public IHttpActionResult GetPolSourceSiteList([FromUri] string lang = "en", [FromUri] int skip  = 0, [FromUri] int take      = 200,
                                               [FromUri] string asc  = "", [FromUri] string desc = "", [FromUri] string where = "", [FromUri] string extra = "")
 {
     using (CSSPDBContext db = new CSSPDBContext(DatabaseType))
     {
         PolSourceSiteService polSourceSiteService = new PolSourceSiteService(new Query()
         {
             Lang = lang
         }, db, ContactID);
 protected override void Initialize(System.Web.Routing.RequestContext requestContext)
 {
     base.Initialize(requestContext);
     _AddressService        = new AddressService(LanguageRequest, User);
     _TVItemLinkService     = new TVItemLinkService(LanguageRequest, User);
     _InfrastructureService = new InfrastructureService(LanguageRequest, User);
     _PolSourceSiteService  = new PolSourceSiteService(LanguageRequest, User);
     _MapInfoService        = new MapInfoService(LanguageRequest, User);
 }
Exemple #3
0
        public void PolSourceSite_Controller_Put_Test()
        {
            foreach (LanguageEnum LanguageRequest in AllowableLanguages)
            {
                foreach (int ContactID in new List <int>()
                {
                    AdminContactID
                })                                                             //, TestEmailValidatedContactID, TestEmailNotValidatedContactID })
                {
                    PolSourceSiteController polSourceSiteController = new PolSourceSiteController(DatabaseTypeEnum.SqlServerTestDB);
                    Assert.IsNotNull(polSourceSiteController);
                    Assert.AreEqual(DatabaseTypeEnum.SqlServerTestDB, polSourceSiteController.DatabaseType);

                    PolSourceSite polSourceSiteLast = new PolSourceSite();
                    using (CSSPDBContext db = new CSSPDBContext(DatabaseType))
                    {
                        Query query = new Query();
                        query.Language = LanguageRequest;

                        PolSourceSiteService polSourceSiteService = new PolSourceSiteService(query, db, ContactID);
                        polSourceSiteLast = (from c in db.PolSourceSites select c).FirstOrDefault();
                    }

                    // ok with PolSourceSite info
                    IHttpActionResult jsonRet = polSourceSiteController.GetPolSourceSiteWithID(polSourceSiteLast.PolSourceSiteID);
                    Assert.IsNotNull(jsonRet);

                    OkNegotiatedContentResult <PolSourceSite> Ret = jsonRet as OkNegotiatedContentResult <PolSourceSite>;
                    PolSourceSite polSourceSiteRet = Ret.Content;
                    Assert.AreEqual(polSourceSiteLast.PolSourceSiteID, polSourceSiteRet.PolSourceSiteID);

                    BadRequestErrorMessageResult badRequest = jsonRet as BadRequestErrorMessageResult;
                    Assert.IsNull(badRequest);

                    // Put to return success
                    IHttpActionResult jsonRet2 = polSourceSiteController.Put(polSourceSiteRet, LanguageRequest.ToString());
                    Assert.IsNotNull(jsonRet2);

                    OkNegotiatedContentResult <PolSourceSite> polSourceSiteRet2 = jsonRet2 as OkNegotiatedContentResult <PolSourceSite>;
                    Assert.IsNotNull(polSourceSiteRet2);

                    BadRequestErrorMessageResult badRequest2 = jsonRet2 as BadRequestErrorMessageResult;
                    Assert.IsNull(badRequest2);

                    // Put to return CSSPError because PolSourceSiteID of 0 does not exist
                    polSourceSiteRet.PolSourceSiteID = 0;
                    IHttpActionResult jsonRet3 = polSourceSiteController.Put(polSourceSiteRet, LanguageRequest.ToString());
                    Assert.IsNotNull(jsonRet3);

                    OkNegotiatedContentResult <PolSourceSite> polSourceSiteRet3 = jsonRet3 as OkNegotiatedContentResult <PolSourceSite>;
                    Assert.IsNull(polSourceSiteRet3);

                    BadRequestErrorMessageResult badRequest3 = jsonRet3 as BadRequestErrorMessageResult;
                    Assert.IsNotNull(badRequest3);
                }
            }
        }
Exemple #4
0
 protected override void Initialize(System.Web.Routing.RequestContext requestContext)
 {
     base.Initialize(requestContext);
     _PolSourceSiteEffectService     = new PolSourceSiteEffectService(LanguageRequest, User);
     _PolSourceSiteEffectTermService = new PolSourceSiteEffectTermService(LanguageRequest, User);
     _PolSourceSiteService           = new PolSourceSiteService(LanguageRequest, User);
     _MWQMSiteService            = new MWQMSiteService(LanguageRequest, User);
     _UseOfSiteService           = new UseOfSiteService(LanguageRequest, User);
     _PolSourceSiteEffectService = new PolSourceSiteEffectService(LanguageRequest, User);
     _BaseEnumService            = new BaseEnumService(LanguageRequest);
 }
 protected override void Initialize(System.Web.Routing.RequestContext requestContext)
 {
     base.Initialize(requestContext);
     _PolSourceSiteService          = new PolSourceSiteService(LanguageRequest, User);
     _PolSourceSiteInputToolService = new PolSourceSiteInputToolService(LanguageRequest, User);
     _MapInfoService      = new MapInfoService(LanguageRequest, User);
     _MapInfoPointService = new MapInfoPointService(LanguageRequest, User);
     _AddressService      = new AddressService(LanguageRequest, User);
     _BaseEnumService     = new BaseEnumService(LanguageRequest);
     _TVFileService       = new TVFileService(LanguageRequest, User);
 }
        public void PolSourceSite_CRUD_Test()
        {
            foreach (CultureInfo culture in AllowableCulture)
            {
                ChangeCulture(culture);

                using (CSSPDBContext dbTestDB = new CSSPDBContext(DatabaseTypeEnum.SqlServerTestDB))
                {
                    PolSourceSiteService polSourceSiteService = new PolSourceSiteService(new Query()
                    {
                        Lang = culture.TwoLetterISOLanguageName
                    }, dbTestDB, ContactID);

                    int count = 0;
                    if (count == 1)
                    {
                        // just so we don't get a warning during compile [The variable 'count' is assigned but its value is never used]
                    }

                    PolSourceSite polSourceSite = GetFilledRandomPolSourceSite("");

                    // -------------------------------
                    // -------------------------------
                    // CRUD testing
                    // -------------------------------
                    // -------------------------------

                    count = polSourceSiteService.GetPolSourceSiteList().Count();

                    Assert.AreEqual(count, (from c in dbTestDB.PolSourceSites select c).Count());

                    polSourceSiteService.Add(polSourceSite);
                    if (polSourceSite.HasErrors)
                    {
                        Assert.AreEqual("", polSourceSite.ValidationResults.FirstOrDefault().ErrorMessage);
                    }
                    Assert.AreEqual(true, polSourceSiteService.GetPolSourceSiteList().Where(c => c == polSourceSite).Any());
                    polSourceSiteService.Update(polSourceSite);
                    if (polSourceSite.HasErrors)
                    {
                        Assert.AreEqual("", polSourceSite.ValidationResults.FirstOrDefault().ErrorMessage);
                    }
                    Assert.AreEqual(count + 1, polSourceSiteService.GetPolSourceSiteList().Count());
                    polSourceSiteService.Delete(polSourceSite);
                    if (polSourceSite.HasErrors)
                    {
                        Assert.AreEqual("", polSourceSite.ValidationResults.FirstOrDefault().ErrorMessage);
                    }
                    Assert.AreEqual(count, polSourceSiteService.GetPolSourceSiteList().Count());
                }
            }
        }
Exemple #7
0
        public IHttpActionResult GetPolSourceSiteWithID([FromUri] int PolSourceSiteID, [FromUri] string lang = "en", [FromUri] string extra = "")
        {
            using (CSSPDBContext db = new CSSPDBContext(DatabaseType))
            {
                PolSourceSiteService polSourceSiteService = new PolSourceSiteService(new Query()
                {
                    Language = (lang == "fr" ? LanguageEnum.fr : LanguageEnum.en)
                }, db, ContactID);

                polSourceSiteService.Query = polSourceSiteService.FillQuery(typeof(PolSourceSite), lang, 0, 1, "", "", extra);

                if (polSourceSiteService.Query.Extra == "A")
                {
                    PolSourceSiteExtraA polSourceSiteExtraA = new PolSourceSiteExtraA();
                    polSourceSiteExtraA = polSourceSiteService.GetPolSourceSiteExtraAWithPolSourceSiteID(PolSourceSiteID);

                    if (polSourceSiteExtraA == null)
                    {
                        return(NotFound());
                    }

                    return(Ok(polSourceSiteExtraA));
                }
                else if (polSourceSiteService.Query.Extra == "B")
                {
                    PolSourceSiteExtraB polSourceSiteExtraB = new PolSourceSiteExtraB();
                    polSourceSiteExtraB = polSourceSiteService.GetPolSourceSiteExtraBWithPolSourceSiteID(PolSourceSiteID);

                    if (polSourceSiteExtraB == null)
                    {
                        return(NotFound());
                    }

                    return(Ok(polSourceSiteExtraB));
                }
                else
                {
                    PolSourceSite polSourceSite = new PolSourceSite();
                    polSourceSite = polSourceSiteService.GetPolSourceSiteWithPolSourceSiteID(PolSourceSiteID);

                    if (polSourceSite == null)
                    {
                        return(NotFound());
                    }

                    return(Ok(polSourceSite));
                }
            }
        }
Exemple #8
0
        public void PolSourceSite_Controller_GetPolSourceSiteWithID_Test()
        {
            foreach (LanguageEnum LanguageRequest in AllowableLanguages)
            {
                foreach (int ContactID in new List <int>()
                {
                    AdminContactID
                })                                                             //, TestEmailValidatedContactID, TestEmailNotValidatedContactID })
                {
                    PolSourceSiteController polSourceSiteController = new PolSourceSiteController(DatabaseTypeEnum.SqlServerTestDB);
                    Assert.IsNotNull(polSourceSiteController);
                    Assert.AreEqual(DatabaseTypeEnum.SqlServerTestDB, polSourceSiteController.DatabaseType);

                    PolSourceSite polSourceSiteFirst = new PolSourceSite();
                    using (CSSPDBContext db = new CSSPDBContext(DatabaseType))
                    {
                        PolSourceSiteService polSourceSiteService = new PolSourceSiteService(new Query(), db, ContactID);
                        polSourceSiteFirst = (from c in db.PolSourceSites select c).FirstOrDefault();
                    }

                    // ok with PolSourceSite info
                    IHttpActionResult jsonRet = polSourceSiteController.GetPolSourceSiteWithID(polSourceSiteFirst.PolSourceSiteID);
                    Assert.IsNotNull(jsonRet);

                    OkNegotiatedContentResult <PolSourceSite> Ret = jsonRet as OkNegotiatedContentResult <PolSourceSite>;
                    PolSourceSite polSourceSiteRet = Ret.Content;
                    Assert.AreEqual(polSourceSiteFirst.PolSourceSiteID, polSourceSiteRet.PolSourceSiteID);

                    BadRequestErrorMessageResult badRequest = jsonRet as BadRequestErrorMessageResult;
                    Assert.IsNull(badRequest);

                    // Not Found
                    IHttpActionResult jsonRet2 = polSourceSiteController.GetPolSourceSiteWithID(0);
                    Assert.IsNotNull(jsonRet2);

                    OkNegotiatedContentResult <PolSourceSite> polSourceSiteRet2 = jsonRet2 as OkNegotiatedContentResult <PolSourceSite>;
                    Assert.IsNull(polSourceSiteRet2);

                    NotFoundResult notFoundRequest = jsonRet2 as NotFoundResult;
                    Assert.IsNotNull(notFoundRequest);
                }
            }
        }
Exemple #9
0
        public IHttpActionResult Delete([FromBody] PolSourceSite polSourceSite, [FromUri] string lang = "en")
        {
            using (CSSPDBContext db = new CSSPDBContext(DatabaseType))
            {
                PolSourceSiteService polSourceSiteService = new PolSourceSiteService(new Query()
                {
                    Language = (lang == "fr" ? LanguageEnum.fr : LanguageEnum.en)
                }, db, ContactID);

                if (!polSourceSiteService.Delete(polSourceSite))
                {
                    return(BadRequest(String.Join("|||", polSourceSite.ValidationResults)));
                }
                else
                {
                    polSourceSite.ValidationResults = null;
                    return(Ok(polSourceSite));
                }
            }
        }
        public void GetPolSourceSiteList_Test()
        {
            foreach (CultureInfo culture in AllowableCulture)
            {
                ChangeCulture(culture);

                using (CSSPDBContext dbTestDB = new CSSPDBContext(DatabaseTypeEnum.SqlServerTestDB))
                {
                    PolSourceSiteService polSourceSiteService = new PolSourceSiteService(new Query()
                    {
                        Lang = culture.TwoLetterISOLanguageName
                    }, dbTestDB, ContactID);
                    PolSourceSite polSourceSite = (from c in dbTestDB.PolSourceSites select c).FirstOrDefault();
                    Assert.IsNotNull(polSourceSite);

                    List <PolSourceSite> polSourceSiteDirectQueryList = new List <PolSourceSite>();
                    polSourceSiteDirectQueryList = (from c in dbTestDB.PolSourceSites select c).Take(200).ToList();

                    foreach (string extra in new List <string>()
                    {
                        null, "A", "B", "C", "D", "E"
                    })
                    {
                        polSourceSiteService.Query.Extra = extra;

                        if (string.IsNullOrWhiteSpace(extra))
                        {
                            List <PolSourceSite> polSourceSiteList = new List <PolSourceSite>();
                            polSourceSiteList = polSourceSiteService.GetPolSourceSiteList().ToList();
                            CheckPolSourceSiteFields(polSourceSiteList);
                        }
                        else
                        {
                            //Assert.AreEqual(true, false);
                        }
                    }
                }
            }
        }
        public void GetPolSourceSiteList_2Where_Test()
        {
            foreach (CultureInfo culture in AllowableCulture)
            {
                ChangeCulture(culture);

                using (CSSPDBContext dbTestDB = new CSSPDBContext(DatabaseTypeEnum.SqlServerTestDB))
                {
                    foreach (string extra in new List <string>()
                    {
                        null, "A", "B", "C", "D", "E"
                    })
                    {
                        PolSourceSiteService polSourceSiteService = new PolSourceSiteService(new Query()
                        {
                            Lang = culture.TwoLetterISOLanguageName
                        }, dbTestDB, ContactID);

                        polSourceSiteService.Query = polSourceSiteService.FillQuery(typeof(PolSourceSite), culture.TwoLetterISOLanguageName, 0, 10000, "", "", "PolSourceSiteID,GT,2|PolSourceSiteID,LT,5", extra);

                        List <PolSourceSite> polSourceSiteDirectQueryList = new List <PolSourceSite>();
                        polSourceSiteDirectQueryList = (from c in dbTestDB.PolSourceSites select c).Where(c => c.PolSourceSiteID > 2 && c.PolSourceSiteID < 5).ToList();

                        if (string.IsNullOrWhiteSpace(extra))
                        {
                            List <PolSourceSite> polSourceSiteList = new List <PolSourceSite>();
                            polSourceSiteList = polSourceSiteService.GetPolSourceSiteList().ToList();
                            CheckPolSourceSiteFields(polSourceSiteList);
                            Assert.AreEqual(polSourceSiteDirectQueryList[0].PolSourceSiteID, polSourceSiteList[0].PolSourceSiteID);
                        }
                        else
                        {
                            //Assert.AreEqual(true, false);
                        }
                    }
                }
            }
        }
Exemple #12
0
        public IHttpActionResult GetPolSourceSiteList([FromUri] string lang = "en", [FromUri] int skip  = 0, [FromUri] int take      = 200,
                                                      [FromUri] string asc  = "", [FromUri] string desc = "", [FromUri] string where = "", [FromUri] string extra = "")
        {
            using (CSSPDBContext db = new CSSPDBContext(DatabaseType))
            {
                PolSourceSiteService polSourceSiteService = new PolSourceSiteService(new Query()
                {
                    Lang = lang
                }, db, ContactID);

                if (extra == "A") // QueryString contains [extra=A]
                {
                    polSourceSiteService.Query = polSourceSiteService.FillQuery(typeof(PolSourceSiteExtraA), lang, skip, take, asc, desc, where, extra);

                    if (polSourceSiteService.Query.HasErrors)
                    {
                        return(Ok(new List <PolSourceSiteExtraA>()
                        {
                            new PolSourceSiteExtraA()
                            {
                                HasErrors = polSourceSiteService.Query.HasErrors,
                                ValidationResults = polSourceSiteService.Query.ValidationResults,
                            },
                        }.ToList()));
                    }
                    else
                    {
                        return(Ok(polSourceSiteService.GetPolSourceSiteExtraAList().ToList()));
                    }
                }
                else if (extra == "B") // QueryString contains [extra=B]
                {
                    polSourceSiteService.Query = polSourceSiteService.FillQuery(typeof(PolSourceSiteExtraB), lang, skip, take, asc, desc, where, extra);

                    if (polSourceSiteService.Query.HasErrors)
                    {
                        return(Ok(new List <PolSourceSiteExtraB>()
                        {
                            new PolSourceSiteExtraB()
                            {
                                HasErrors = polSourceSiteService.Query.HasErrors,
                                ValidationResults = polSourceSiteService.Query.ValidationResults,
                            },
                        }.ToList()));
                    }
                    else
                    {
                        return(Ok(polSourceSiteService.GetPolSourceSiteExtraBList().ToList()));
                    }
                }
                else // QueryString has no parameter [extra] or extra is empty
                {
                    polSourceSiteService.Query = polSourceSiteService.FillQuery(typeof(PolSourceSite), lang, skip, take, asc, desc, where, extra);

                    if (polSourceSiteService.Query.HasErrors)
                    {
                        return(Ok(new List <PolSourceSite>()
                        {
                            new PolSourceSite()
                            {
                                HasErrors = polSourceSiteService.Query.HasErrors,
                                ValidationResults = polSourceSiteService.Query.ValidationResults,
                            },
                        }.ToList()));
                    }
                    else
                    {
                        return(Ok(polSourceSiteService.GetPolSourceSiteList().ToList()));
                    }
                }
            }
        }
        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;
        }
        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);
        }
        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();
        }
        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);
        }
Exemple #17
0
        public void PolSourceSite_Controller_GetPolSourceSiteList_Test()
        {
            foreach (LanguageEnum LanguageRequest in AllowableLanguages)
            {
                foreach (int ContactID in new List <int>()
                {
                    AdminContactID
                })                                                             //, TestEmailValidatedContactID, TestEmailNotValidatedContactID })
                {
                    PolSourceSiteController polSourceSiteController = new PolSourceSiteController(DatabaseTypeEnum.SqlServerTestDB);
                    Assert.IsNotNull(polSourceSiteController);
                    Assert.AreEqual(DatabaseTypeEnum.SqlServerTestDB, polSourceSiteController.DatabaseType);

                    PolSourceSite polSourceSiteFirst = new PolSourceSite();
                    int           count = -1;
                    Query         query = new Query();
                    using (CSSPDBContext db = new CSSPDBContext(DatabaseTypeEnum.SqlServerTestDB))
                    {
                        PolSourceSiteService polSourceSiteService = new PolSourceSiteService(query, db, ContactID);
                        polSourceSiteFirst = (from c in db.PolSourceSites select c).FirstOrDefault();
                        count = (from c in db.PolSourceSites select c).Count();
                        count = (query.Take > count ? count : query.Take);
                    }

                    // ok with PolSourceSite info
                    IHttpActionResult jsonRet = polSourceSiteController.GetPolSourceSiteList();
                    Assert.IsNotNull(jsonRet);

                    OkNegotiatedContentResult <List <PolSourceSite> > ret = jsonRet as OkNegotiatedContentResult <List <PolSourceSite> >;
                    Assert.AreEqual(polSourceSiteFirst.PolSourceSiteID, ret.Content[0].PolSourceSiteID);
                    Assert.AreEqual((count > query.Take ? query.Take : count), ret.Content.Count);

                    List <PolSourceSite> polSourceSiteList = new List <PolSourceSite>();
                    count = -1;
                    query = new Query();
                    using (CSSPDBContext db = new CSSPDBContext(DatabaseTypeEnum.SqlServerTestDB))
                    {
                        PolSourceSiteService polSourceSiteService = new PolSourceSiteService(query, db, ContactID);
                        polSourceSiteList = (from c in db.PolSourceSites select c).OrderBy(c => c.PolSourceSiteID).Skip(0).Take(2).ToList();
                        count             = (from c in db.PolSourceSites select c).Count();
                    }

                    if (count > 0)
                    {
                        query.Skip = 0;
                        query.Take = 5;
                        count      = (query.Take > count ? query.Take : count);

                        // ok with PolSourceSite info
                        jsonRet = polSourceSiteController.GetPolSourceSiteList(query.Language.ToString(), query.Skip, query.Take);
                        Assert.IsNotNull(jsonRet);

                        ret = jsonRet as OkNegotiatedContentResult <List <PolSourceSite> >;
                        Assert.AreEqual(polSourceSiteList[0].PolSourceSiteID, ret.Content[0].PolSourceSiteID);
                        Assert.AreEqual((count > query.Take ? query.Take : count), ret.Content.Count);

                        if (count > 1)
                        {
                            query.Skip = 1;
                            query.Take = 5;
                            count      = (query.Take > count ? query.Take : count);

                            // ok with PolSourceSite info
                            IHttpActionResult jsonRet2 = polSourceSiteController.GetPolSourceSiteList(query.Language.ToString(), query.Skip, query.Take);
                            Assert.IsNotNull(jsonRet2);

                            OkNegotiatedContentResult <List <PolSourceSite> > ret2 = jsonRet2 as OkNegotiatedContentResult <List <PolSourceSite> >;
                            Assert.AreEqual(polSourceSiteList[1].PolSourceSiteID, ret2.Content[0].PolSourceSiteID);
                            Assert.AreEqual((count > query.Take ? query.Take : count), ret2.Content.Count);
                        }
                    }
                }
            }
        }
Exemple #18
0
        public void PolSourceSite_Controller_Post_Test()
        {
            foreach (LanguageEnum LanguageRequest in AllowableLanguages)
            {
                foreach (int ContactID in new List <int>()
                {
                    AdminContactID
                })                                                             //, TestEmailValidatedContactID, TestEmailNotValidatedContactID })
                {
                    PolSourceSiteController polSourceSiteController = new PolSourceSiteController(DatabaseTypeEnum.SqlServerTestDB);
                    Assert.IsNotNull(polSourceSiteController);
                    Assert.AreEqual(DatabaseTypeEnum.SqlServerTestDB, polSourceSiteController.DatabaseType);

                    PolSourceSite polSourceSiteLast = new PolSourceSite();
                    using (CSSPDBContext db = new CSSPDBContext(DatabaseType))
                    {
                        Query query = new Query();
                        query.Language = LanguageRequest;
                        query.Asc      = "";
                        query.Desc     = "";

                        PolSourceSiteService polSourceSiteService = new PolSourceSiteService(query, db, ContactID);
                        polSourceSiteLast = (from c in db.PolSourceSites select c).FirstOrDefault();
                    }

                    // ok with PolSourceSite info
                    IHttpActionResult jsonRet = polSourceSiteController.GetPolSourceSiteWithID(polSourceSiteLast.PolSourceSiteID);
                    Assert.IsNotNull(jsonRet);

                    OkNegotiatedContentResult <PolSourceSite> Ret = jsonRet as OkNegotiatedContentResult <PolSourceSite>;
                    PolSourceSite polSourceSiteRet = Ret.Content;
                    Assert.AreEqual(polSourceSiteLast.PolSourceSiteID, polSourceSiteRet.PolSourceSiteID);

                    BadRequestErrorMessageResult badRequest = jsonRet as BadRequestErrorMessageResult;
                    Assert.IsNull(badRequest);

                    // Post to return CSSPError because PolSourceSiteID exist
                    IHttpActionResult jsonRet2 = polSourceSiteController.Post(polSourceSiteRet, LanguageRequest.ToString());
                    Assert.IsNotNull(jsonRet2);

                    OkNegotiatedContentResult <PolSourceSite> polSourceSiteRet2 = jsonRet2 as OkNegotiatedContentResult <PolSourceSite>;
                    Assert.IsNull(polSourceSiteRet2);

                    BadRequestErrorMessageResult badRequest2 = jsonRet2 as BadRequestErrorMessageResult;
                    Assert.IsNotNull(badRequest2);

                    // Post to return newly added PolSourceSite
                    polSourceSiteRet.PolSourceSiteID           = 0;
                    polSourceSiteController.Request            = new System.Net.Http.HttpRequestMessage();
                    polSourceSiteController.Request.RequestUri = new System.Uri("http://localhost:5000/api/polSourceSite");
                    IHttpActionResult jsonRet3 = polSourceSiteController.Post(polSourceSiteRet, LanguageRequest.ToString());
                    Assert.IsNotNull(jsonRet3);

                    CreatedNegotiatedContentResult <PolSourceSite> polSourceSiteRet3 = jsonRet3 as CreatedNegotiatedContentResult <PolSourceSite>;
                    Assert.IsNotNull(polSourceSiteRet3);

                    BadRequestErrorMessageResult badRequest3 = jsonRet3 as BadRequestErrorMessageResult;
                    Assert.IsNull(badRequest3);

                    IHttpActionResult jsonRet4 = polSourceSiteController.Delete(polSourceSiteRet, LanguageRequest.ToString());
                    Assert.IsNotNull(jsonRet4);

                    OkNegotiatedContentResult <PolSourceSite> polSourceSiteRet4 = jsonRet4 as OkNegotiatedContentResult <PolSourceSite>;
                    Assert.IsNotNull(polSourceSiteRet4);

                    BadRequestErrorMessageResult badRequest4 = jsonRet4 as BadRequestErrorMessageResult;
                    Assert.IsNull(badRequest4);
                }
            }
        }
        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 PolSourceSite_Properties_Test()
        {
            foreach (CultureInfo culture in AllowableCulture)
            {
                ChangeCulture(culture);

                using (CSSPDBContext dbTestDB = new CSSPDBContext(DatabaseTypeEnum.SqlServerTestDB))
                {
                    PolSourceSiteService polSourceSiteService = new PolSourceSiteService(new Query()
                    {
                        Lang = culture.TwoLetterISOLanguageName
                    }, dbTestDB, ContactID);

                    int count = 0;
                    if (count == 1)
                    {
                        // just so we don't get a warning during compile [The variable 'count' is assigned but its value is never used]
                    }

                    count = polSourceSiteService.GetPolSourceSiteList().Count();

                    PolSourceSite polSourceSite = GetFilledRandomPolSourceSite("");

                    // -------------------------------
                    // -------------------------------
                    // Properties testing
                    // -------------------------------
                    // -------------------------------


                    // -----------------------------------
                    // [Key]
                    // Is NOT Nullable
                    // polSourceSite.PolSourceSiteID   (Int32)
                    // -----------------------------------

                    polSourceSite = null;
                    polSourceSite = GetFilledRandomPolSourceSite("");
                    polSourceSite.PolSourceSiteID = 0;
                    polSourceSiteService.Update(polSourceSite);
                    Assert.AreEqual(string.Format(CSSPServicesRes._IsRequired, "PolSourceSiteID"), polSourceSite.ValidationResults.FirstOrDefault().ErrorMessage);

                    polSourceSite = null;
                    polSourceSite = GetFilledRandomPolSourceSite("");
                    polSourceSite.PolSourceSiteID = 10000000;
                    polSourceSiteService.Update(polSourceSite);
                    Assert.AreEqual(string.Format(CSSPServicesRes.CouldNotFind_With_Equal_, "PolSourceSite", "PolSourceSiteID", polSourceSite.PolSourceSiteID.ToString()), polSourceSite.ValidationResults.FirstOrDefault().ErrorMessage);


                    // -----------------------------------
                    // Is NOT Nullable
                    // [CSSPExist(ExistTypeName = "TVItem", ExistPlurial = "s", ExistFieldID = "TVItemID", AllowableTVtypeList = PolSourceSite)]
                    // polSourceSite.PolSourceSiteTVItemID   (Int32)
                    // -----------------------------------

                    polSourceSite = null;
                    polSourceSite = GetFilledRandomPolSourceSite("");
                    polSourceSite.PolSourceSiteTVItemID = 0;
                    polSourceSiteService.Add(polSourceSite);
                    Assert.AreEqual(string.Format(CSSPServicesRes.CouldNotFind_With_Equal_, "TVItem", "PolSourceSiteTVItemID", polSourceSite.PolSourceSiteTVItemID.ToString()), polSourceSite.ValidationResults.FirstOrDefault().ErrorMessage);

                    polSourceSite = null;
                    polSourceSite = GetFilledRandomPolSourceSite("");
                    polSourceSite.PolSourceSiteTVItemID = 1;
                    polSourceSiteService.Add(polSourceSite);
                    Assert.AreEqual(string.Format(CSSPServicesRes._IsNotOfType_, "PolSourceSiteTVItemID", "PolSourceSite"), polSourceSite.ValidationResults.FirstOrDefault().ErrorMessage);


                    // -----------------------------------
                    // Is Nullable
                    // [StringLength(50))]
                    // polSourceSite.Temp_Locator_CanDelete   (String)
                    // -----------------------------------

                    polSourceSite = null;
                    polSourceSite = GetFilledRandomPolSourceSite("");
                    polSourceSite.Temp_Locator_CanDelete = GetRandomString("", 51);
                    Assert.AreEqual(false, polSourceSiteService.Add(polSourceSite));
                    Assert.AreEqual(string.Format(CSSPServicesRes._MaxLengthIs_, "Temp_Locator_CanDelete", "50"), polSourceSite.ValidationResults.FirstOrDefault().ErrorMessage);
                    Assert.AreEqual(count, polSourceSiteService.GetPolSourceSiteList().Count());

                    // -----------------------------------
                    // Is Nullable
                    // [Range(0, 1000)]
                    // polSourceSite.Oldsiteid   (Int32)
                    // -----------------------------------

                    polSourceSite           = null;
                    polSourceSite           = GetFilledRandomPolSourceSite("");
                    polSourceSite.Oldsiteid = -1;
                    Assert.AreEqual(false, polSourceSiteService.Add(polSourceSite));
                    Assert.AreEqual(string.Format(CSSPServicesRes._ValueShouldBeBetween_And_, "Oldsiteid", "0", "1000"), polSourceSite.ValidationResults.FirstOrDefault().ErrorMessage);
                    Assert.AreEqual(count, polSourceSiteService.GetPolSourceSiteList().Count());
                    polSourceSite           = null;
                    polSourceSite           = GetFilledRandomPolSourceSite("");
                    polSourceSite.Oldsiteid = 1001;
                    Assert.AreEqual(false, polSourceSiteService.Add(polSourceSite));
                    Assert.AreEqual(string.Format(CSSPServicesRes._ValueShouldBeBetween_And_, "Oldsiteid", "0", "1000"), polSourceSite.ValidationResults.FirstOrDefault().ErrorMessage);
                    Assert.AreEqual(count, polSourceSiteService.GetPolSourceSiteList().Count());

                    // -----------------------------------
                    // Is Nullable
                    // [Range(0, 1000)]
                    // polSourceSite.Site   (Int32)
                    // -----------------------------------

                    polSourceSite      = null;
                    polSourceSite      = GetFilledRandomPolSourceSite("");
                    polSourceSite.Site = -1;
                    Assert.AreEqual(false, polSourceSiteService.Add(polSourceSite));
                    Assert.AreEqual(string.Format(CSSPServicesRes._ValueShouldBeBetween_And_, "Site", "0", "1000"), polSourceSite.ValidationResults.FirstOrDefault().ErrorMessage);
                    Assert.AreEqual(count, polSourceSiteService.GetPolSourceSiteList().Count());
                    polSourceSite      = null;
                    polSourceSite      = GetFilledRandomPolSourceSite("");
                    polSourceSite.Site = 1001;
                    Assert.AreEqual(false, polSourceSiteService.Add(polSourceSite));
                    Assert.AreEqual(string.Format(CSSPServicesRes._ValueShouldBeBetween_And_, "Site", "0", "1000"), polSourceSite.ValidationResults.FirstOrDefault().ErrorMessage);
                    Assert.AreEqual(count, polSourceSiteService.GetPolSourceSiteList().Count());

                    // -----------------------------------
                    // Is Nullable
                    // [Range(0, 1000)]
                    // polSourceSite.SiteID   (Int32)
                    // -----------------------------------

                    polSourceSite        = null;
                    polSourceSite        = GetFilledRandomPolSourceSite("");
                    polSourceSite.SiteID = -1;
                    Assert.AreEqual(false, polSourceSiteService.Add(polSourceSite));
                    Assert.AreEqual(string.Format(CSSPServicesRes._ValueShouldBeBetween_And_, "SiteID", "0", "1000"), polSourceSite.ValidationResults.FirstOrDefault().ErrorMessage);
                    Assert.AreEqual(count, polSourceSiteService.GetPolSourceSiteList().Count());
                    polSourceSite        = null;
                    polSourceSite        = GetFilledRandomPolSourceSite("");
                    polSourceSite.SiteID = 1001;
                    Assert.AreEqual(false, polSourceSiteService.Add(polSourceSite));
                    Assert.AreEqual(string.Format(CSSPServicesRes._ValueShouldBeBetween_And_, "SiteID", "0", "1000"), polSourceSite.ValidationResults.FirstOrDefault().ErrorMessage);
                    Assert.AreEqual(count, polSourceSiteService.GetPolSourceSiteList().Count());

                    // -----------------------------------
                    // Is NOT Nullable
                    // polSourceSite.IsPointSource   (Boolean)
                    // -----------------------------------


                    // -----------------------------------
                    // Is Nullable
                    // [CSSPEnumType]
                    // polSourceSite.InactiveReason   (PolSourceInactiveReasonEnum)
                    // -----------------------------------

                    polSourceSite = null;
                    polSourceSite = GetFilledRandomPolSourceSite("");
                    polSourceSite.InactiveReason = (PolSourceInactiveReasonEnum)1000000;
                    polSourceSiteService.Add(polSourceSite);
                    Assert.AreEqual(string.Format(CSSPServicesRes._IsRequired, "InactiveReason"), polSourceSite.ValidationResults.FirstOrDefault().ErrorMessage);


                    // -----------------------------------
                    // Is Nullable
                    // [CSSPExist(ExistTypeName = "TVItem", ExistPlurial = "s", ExistFieldID = "TVItemID", AllowableTVtypeList = Address)]
                    // polSourceSite.CivicAddressTVItemID   (Int32)
                    // -----------------------------------

                    polSourceSite = null;
                    polSourceSite = GetFilledRandomPolSourceSite("");
                    polSourceSite.CivicAddressTVItemID = 0;
                    polSourceSiteService.Add(polSourceSite);
                    Assert.AreEqual(string.Format(CSSPServicesRes.CouldNotFind_With_Equal_, "TVItem", "CivicAddressTVItemID", polSourceSite.CivicAddressTVItemID.ToString()), polSourceSite.ValidationResults.FirstOrDefault().ErrorMessage);

                    polSourceSite = null;
                    polSourceSite = GetFilledRandomPolSourceSite("");
                    polSourceSite.CivicAddressTVItemID = 1;
                    polSourceSiteService.Add(polSourceSite);
                    Assert.AreEqual(string.Format(CSSPServicesRes._IsNotOfType_, "CivicAddressTVItemID", "Address"), polSourceSite.ValidationResults.FirstOrDefault().ErrorMessage);


                    // -----------------------------------
                    // Is NOT Nullable
                    // [CSSPAfter(Year = 1980)]
                    // polSourceSite.LastUpdateDate_UTC   (DateTime)
                    // -----------------------------------

                    polSourceSite = null;
                    polSourceSite = GetFilledRandomPolSourceSite("");
                    polSourceSite.LastUpdateDate_UTC = new DateTime();
                    polSourceSiteService.Add(polSourceSite);
                    Assert.AreEqual(string.Format(CSSPServicesRes._IsRequired, "LastUpdateDate_UTC"), polSourceSite.ValidationResults.FirstOrDefault().ErrorMessage);
                    polSourceSite = null;
                    polSourceSite = GetFilledRandomPolSourceSite("");
                    polSourceSite.LastUpdateDate_UTC = new DateTime(1979, 1, 1);
                    polSourceSiteService.Add(polSourceSite);
                    Assert.AreEqual(string.Format(CSSPServicesRes._YearShouldBeBiggerThan_, "LastUpdateDate_UTC", "1980"), polSourceSite.ValidationResults.FirstOrDefault().ErrorMessage);

                    // -----------------------------------
                    // Is NOT Nullable
                    // [CSSPExist(ExistTypeName = "TVItem", ExistPlurial = "s", ExistFieldID = "TVItemID", AllowableTVtypeList = Contact)]
                    // polSourceSite.LastUpdateContactTVItemID   (Int32)
                    // -----------------------------------

                    polSourceSite = null;
                    polSourceSite = GetFilledRandomPolSourceSite("");
                    polSourceSite.LastUpdateContactTVItemID = 0;
                    polSourceSiteService.Add(polSourceSite);
                    Assert.AreEqual(string.Format(CSSPServicesRes.CouldNotFind_With_Equal_, "TVItem", "LastUpdateContactTVItemID", polSourceSite.LastUpdateContactTVItemID.ToString()), polSourceSite.ValidationResults.FirstOrDefault().ErrorMessage);

                    polSourceSite = null;
                    polSourceSite = GetFilledRandomPolSourceSite("");
                    polSourceSite.LastUpdateContactTVItemID = 1;
                    polSourceSiteService.Add(polSourceSite);
                    Assert.AreEqual(string.Format(CSSPServicesRes._IsNotOfType_, "LastUpdateContactTVItemID", "Contact"), polSourceSite.ValidationResults.FirstOrDefault().ErrorMessage);


                    // -----------------------------------
                    // Is NOT Nullable
                    // [NotMapped]
                    // polSourceSite.HasErrors   (Boolean)
                    // -----------------------------------

                    // No testing requied

                    // -----------------------------------
                    // Is NOT Nullable
                    // [NotMapped]
                    // polSourceSite.ValidationResults   (IEnumerable`1)
                    // -----------------------------------

                    // No testing requied
                }
            }
        }