// ////////////////////////////////////////////////////////////////////////
        // EVENTS
        //
        protected void Page_Load(object sender, EventArgs e)
        {
            // Register client scripts
            this.RegisterClientScripts();

            if (!IsPostBack)
            {
                // Security check
                if (!(Convert.ToBoolean(Session["sgLFS_APP_VIEW"]) && Convert.ToBoolean(Session["sgLFS_APP_DELETE"])))
                {
                    Response.Redirect("./../../error_page.aspx?error=" + "You are not authorized to view this page. Contact your system administrator.");
                }

                // Validate query string
                if (((string)Request.QueryString["source_page"] == null) || ((string)Request.QueryString["client"] == null))
                {
                    Response.Redirect("./../../error_page.aspx?error=" + "Invalid query string in jliner_delete.aspx");
                }

                // Tag page
                hdfCurrentClient.Value = (string)Request.QueryString["client"];

                // If coming from
                // ... jliner_navigator2.aspx
                if (Request.QueryString["source_page"] == "jliner_navigator2.aspx")
                {
                    StoreNavigatorState();
                    ViewState["update"] = "no";
                }

                // ... flat_section_jliner_summary.aspx
                if (Request.QueryString["source_page"] == "flat_section_jliner_summary.aspx")
                {
                    StoreNavigatorState();
                    ViewState["update"] = Request.QueryString["update"];
                }

                // Restore datasets
                flatSectionJlinerTDS = (FlatSectionJlinerTDS)Session["flatSectionJlinerTDS"];

                sectionTDS = new SectionTDS();
                Session["sectionTDS"] = sectionTDS;
            }
            else
            {
                // Restore datasets
                flatSectionJlinerTDS = (FlatSectionJlinerTDS)Session["flatSectionJlinerTDS"];
                sectionTDS = (SectionTDS)Session["sectionTDS"];
            }
        }
        /// <summary>
        /// Save to Section and Jliner rows
        /// </summary>
        /// <param name="sectionTDS">sectionTDS</param>
        public void Save(SectionTDS sectionTDS)
        {
            FlatSectionJlinerTDS flatSectionJlinerChanges = (FlatSectionJlinerTDS)Data.GetChanges();
            if (flatSectionJlinerChanges.FlatSectionJliner.Rows.Count > 0)
            {
                SectionGateway sectionGateway = new SectionGateway(sectionTDS);
                LiquiForce.LFSLive.BL.CWP.Section.Section section = new LiquiForce.LFSLive.BL.CWP.Section.Section(sectionTDS);
                JlinerGateway jlinerGateway = new JlinerGateway(sectionTDS);
                Jliner jliner = new Jliner(sectionTDS);
                JlinerCommentGateway jlinerCommentGateway = new JlinerCommentGateway(sectionTDS);
                JlinerComments jlinerComments = new JlinerComments(jlinerCommentGateway.Data);
                JlinerHistoryGateway jlinerHistoryGateway = new JlinerHistoryGateway(sectionTDS);
                JlinerHistory jlinerHistory = new JlinerHistory(jlinerHistoryGateway.Data);

                sectionGateway.ClearBeforeFill = false;
                jlinerGateway.ClearBeforeFill = false;
                jlinerCommentGateway.ClearBeforeFill = false;
                jlinerHistoryGateway.ClearBeforeFill = false;

                foreach (FlatSectionJlinerTDS.FlatSectionJlinerRow flatSectionJlinerRow in (FlatSectionJlinerTDS.FlatSectionJlinerDataTable)flatSectionJlinerChanges.FlatSectionJliner)
                {
                    // Load section and jliner
                    // ... Load section
                    try
                    {
                        //... Search section row
                        sectionGateway.GetRow(flatSectionJlinerRow.ID);
                    }
                    catch
                    {
                        //... Load section and section's jliners
                        sectionGateway.LoadById(flatSectionJlinerRow.ID, flatSectionJlinerRow.COMPANY_ID);
                        jlinerGateway.LoadByIdCompanyId(flatSectionJlinerRow.ID, flatSectionJlinerRow.COMPANY_ID);
                        jlinerCommentGateway.LoadById(flatSectionJlinerRow.ID, flatSectionJlinerRow.COMPANY_ID);
                        jlinerHistoryGateway.LoadById(flatSectionJlinerRow.ID, flatSectionJlinerRow.COMPANY_ID);
                    }

                    // Update

                    // ... Update jliner
                    string address = ""; if (!flatSectionJlinerRow.IsNull("Address")) address = flatSectionJlinerRow.Address;
                    DateTime? pipeLocated = null; if (!flatSectionJlinerRow.IsNull("PipeLocated")) pipeLocated = flatSectionJlinerRow.PipeLocated;
                    DateTime? servicesLocated = null; if (!flatSectionJlinerRow.IsNull("ServicesLocated")) servicesLocated = flatSectionJlinerRow.ServicesLocated;
                    DateTime? coInstalled = null; if (!flatSectionJlinerRow.IsNull("CoInstalled")) coInstalled = flatSectionJlinerRow.CoInstalled;
                    DateTime? backfilledConcrete = null; if (!flatSectionJlinerRow.IsNull("BackfilledConcrete")) backfilledConcrete = flatSectionJlinerRow.BackfilledConcrete;
                    DateTime? backfilledSoil = null; if (!flatSectionJlinerRow.IsNull("BackfilledSoil")) backfilledSoil = flatSectionJlinerRow.BackfilledSoil;
                    DateTime? grouted = null; if (!flatSectionJlinerRow.IsNull("Grouted")) grouted = flatSectionJlinerRow.Grouted;
                    DateTime? cored = null; if (!flatSectionJlinerRow.IsNull("Cored")) cored = flatSectionJlinerRow.Cored;
                    DateTime? prepped = null; if (!flatSectionJlinerRow.IsNull("Prepped")) prepped = flatSectionJlinerRow.Prepped;
                    DateTime? measured = null; if (!flatSectionJlinerRow.IsNull("Measured")) measured = flatSectionJlinerRow.Measured;
                    string linerSize = ""; if (!flatSectionJlinerRow.IsNull("LinerSize")) linerSize = flatSectionJlinerRow.LinerSize;
                    DateTime? inProcess = null; if (!flatSectionJlinerRow.IsNull("Inprocess")) inProcess = flatSectionJlinerRow.InProcess;
                    DateTime? inStock = null; if (!flatSectionJlinerRow.IsNull("InStock")) inStock = flatSectionJlinerRow.InStock;
                    DateTime? delivered = null; if (!flatSectionJlinerRow.IsNull("Delivered")) delivered = flatSectionJlinerRow.Delivered;
                    DateTime? preVideo = null; if (!flatSectionJlinerRow.IsNull("PreVideo")) preVideo = flatSectionJlinerRow.PreVideo;
                    DateTime? linerInstalled = null; if (!flatSectionJlinerRow.IsNull("LinerInstalled")) linerInstalled = flatSectionJlinerRow.LinerInstalled;
                    DateTime? finalVideo = null; if (!flatSectionJlinerRow.IsNull("FinalVideo")) finalVideo = flatSectionJlinerRow.FinalVideo;
                    double? distanceFromUSMH = null; if (!flatSectionJlinerRow.IsNull("DistanceFromUSMH")) distanceFromUSMH = flatSectionJlinerRow.DistanceFromUSMH;
                    double? distanceFromDSMH = null; if (!flatSectionJlinerRow.IsNull("DistanceFromDSMH")) distanceFromDSMH = flatSectionJlinerRow.DistanceFromDSMH;
                    string history = ""; if (!flatSectionJlinerRow.IsNull("History")) history = flatSectionJlinerRow.History;
                    string map = "";
                    string issue = flatSectionJlinerRow.Issue;
                    decimal? cost = null; if (!flatSectionJlinerRow.IsNull("Cost")) cost = flatSectionJlinerRow.Cost;
                    bool deleted = flatSectionJlinerRow.Deleted;

                    // ... Delete all comments and history for a jliner
                    if (deleted)
                    {
                        jlinerComments.DeleteAllCommentsForAJliner(flatSectionJlinerRow.ID, flatSectionJlinerRow.RefID, flatSectionJlinerRow.COMPANY_ID);
                        jlinerHistory.DeleteAllHistoryForAJliner(flatSectionJlinerRow.ID, flatSectionJlinerRow.RefID, flatSectionJlinerRow.COMPANY_ID);
                    }

                    DateTime? videoInspection = null; if (!flatSectionJlinerRow.IsNull("VideoInspection")) videoInspection = flatSectionJlinerRow.VideoInspection;
                    bool coRequired = flatSectionJlinerRow.CoRequired;
                    bool pitRequired = flatSectionJlinerRow.PitRequired;
                    string coPitLocation = ""; if (!flatSectionJlinerRow.IsNull("CoPitLocation")) coPitLocation = flatSectionJlinerRow.CoPitLocation;
                    bool postContractDigRequired = flatSectionJlinerRow.PostContractDigRequired;
                    DateTime? coCutDown = null; if (!flatSectionJlinerRow.IsNull("CoCutDown")) coCutDown = flatSectionJlinerRow.CoCutDown;
                    DateTime? finalRestoration = null; if (!flatSectionJlinerRow.IsNull("FinalRestoration")) finalRestoration = flatSectionJlinerRow.FinalRestoration;
                    string clientLateralId = ""; if (!flatSectionJlinerRow.IsNull("ClientLateralID")) clientLateralId = flatSectionJlinerRow.ClientLateralID;
                    string videoLengthToPropertyLine = ""; if (!flatSectionJlinerRow.IsNull("VideoLengthToPropertyLine")) videoLengthToPropertyLine = flatSectionJlinerRow.VideoLengthToPropertyLine;
                    bool liningThruCo = flatSectionJlinerRow.LiningThruCo;
                    string hamiltonInspectionNumber = ""; if (!flatSectionJlinerRow.IsNull("HamiltonInspectionNumber")) hamiltonInspectionNumber = flatSectionJlinerRow.HamiltonInspectionNumber;
                    DateTime? noticeDelivered = null; if (!flatSectionJlinerRow.IsNull("NoticeDelivered")) noticeDelivered = flatSectionJlinerRow.NoticeDelivered;

                    jliner.Update(flatSectionJlinerRow.ID, flatSectionJlinerRow.RefID, flatSectionJlinerRow.COMPANY_ID, flatSectionJlinerRow.DetailID, address, pipeLocated, servicesLocated, coInstalled, backfilledConcrete, backfilledSoil, grouted, cored, prepped, measured, linerSize, inProcess, inStock, delivered, preVideo, linerInstalled, finalVideo, distanceFromUSMH, distanceFromDSMH,map, issue, cost, deleted, videoInspection, coRequired, pitRequired, coPitLocation, postContractDigRequired, coCutDown, finalRestoration, clientLateralId, videoLengthToPropertyLine, liningThruCo, hamiltonInspectionNumber, noticeDelivered);

                    // ... Update section
                    section.UpdateJliners(flatSectionJlinerRow.ID, flatSectionJlinerRow.COMPANY_ID);
                }
            }
        }
 /// <summary>
 /// InitData
 /// </summary>
 protected override void InitData()
 {
     _data = new SectionTDS();
 }
        private void Save()
        {
            FlatSectionJliner flatSectionJliner = new FlatSectionJliner(flatSectionJlinerTDS);
            DataView dataViewFlatSectionJliner = new DataView(flatSectionJlinerTDS.FlatSectionJliner);
            dataViewFlatSectionJliner.RowFilter = "(Selected = 1) AND (Deleted = 0)";
            string summary = "";
            bool existsDataModificated = false;

            foreach (DataRowView row in dataViewFlatSectionJliner)
            {
                if (row["Issue"].ToString() == "No" || row["Issue"].ToString() == "Dig Required After Lining")
                {
                    string id_ = row["ID_"].ToString();
                    DateTime? value = null; if (tbxDate.Text.ToString() != "") value = DateTime.Parse(tbxDate.Text);

                    // ... Update row
                    flatSectionJliner.UpdateField(id_, ddlFieldToUpdate.SelectedValue, value);

                    existsDataModificated = true;
                }
                else
                {
                    if (summary.Trim().Length == 0)
                    {
                        summary = "The following laterals were not updated:\n\n";
                        summary = summary + "\t - " + row["ID_"].ToString() + "\n";
                    }
                    else
                    {
                        summary = summary + "\t - " + row["ID_"].ToString() + "\n";
                    }
                }
            }

            if (summary.Trim().Length == 0)
            {
                summary = "All the laterals were updated\n\n";
            }

            tbxSummary.Text = summary;

            // Store datasets
            Session["flatSectionJlinerTDS"] = flatSectionJlinerTDS;

            if (existsDataModificated)
            {
                // Update section and jliners
                sectionTDS = new SectionTDS();
                flatSectionJliner.Save(sectionTDS);

                // Update database
                UpdateDatabase();
            }
        }
        // ////////////////////////////////////////////////////////////////////////
        // INITIAL EVENTS
        //
        protected void Page_Load(object sender, EventArgs e)
        {
            // Register client scripts
            this.RegisterClientScripts();

            if (!IsPostBack)
            {
                // Security check
                if (!(Convert.ToBoolean(Session["sgLFS_APP_VIEW"]) && Convert.ToBoolean(Session["sgLFS_APP_ADD"])))
                {
                    Response.Redirect("./../../error_page.aspx?error=" + "You are not authorized to view this page. Contact your system administrator.");
                }

                // Validate query string
                if (((string)Request.QueryString["source_page"] == null) || ((string)Request.QueryString["client"] == null))
                {
                    Response.Redirect("./../../error_page.aspx?error=" + "Invalid query string in jliner_add.aspx");
                }

                // Tag page
                ViewState["client"] = Request.QueryString["client"];

                // Prepare initial data
                jlinerAddTDS = new JlinerAddTDS();
                Session.Remove("masterAreaDummy");
                Session.Remove("jliner2Dummy");

                // ... Initialize viewstate variables
                ViewState["StepFrom"] = "Out";

                // StepSection1In
                wizard.ActiveStepIndex = 0;
                StepSection1In();

                // Create and store datasets
                sectionTDS = new SectionTDS();
                Session["sectionTDSForJlinerAdd"] = sectionTDS;

                Session["jlinerAddTDS"] = jlinerAddTDS;
                masterArea = jlinerAddTDS.MasterArea;
                Session["masterArea"] = masterArea;

                jliner2 = jlinerAddTDS.JunctionLiner2;
                Session["jliner2"] = jliner2;
            }
            else
            {
                // Restore datasets
                sectionTDS = (SectionTDS)Session["sectionTDSForJlinerAdd"];
                jlinerAddTDS = (JlinerAddTDS)Session["jlinerAddTDS"];
            }
        }
        /// <summary>
        /// Save a JL Work
        /// </summary>
        /// <param name="originalId">originalId</param>
        /// <param name="projectId">projectId</param>
        /// <param name="section_assetId">section_assetId</param>
        /// <param name="numLats">numLats</param>
        /// <param name="notLinedYet">notLinedYet</param>
        /// <param name="allMeasured">allMeasured</param>
        /// <param name="issueWithLaterals">issueWithLaterals</param>
        /// <param name="notMeasuredYet">notMeasuredYet</param>
        /// <param name="notDeliveredYet">notDeliveredYet</param>
        /// <param name="countryId">countryId</param>
        /// <param name="provinceId">provinceId</param>
        /// <param name="countyId">countyId</param>
        /// <param name="cityId">cityId</param>
        /// <param name="companyId">companyId</param>
        private void SaveJLWork(Guid originalId, int section_assetId, int numLats, int notLinedYet, bool allMeasured, string issueWithLaterals, int notMeasuredYet, int notDeliveredYet, int projectId, Int64? countryId, Int64? provinceId, Int64? countyId, Int64? cityId, int companyId)
        {
            // Insert Junction Lining Section
            WorkJunctionLiningSection workJunctionLiningSection = new WorkJunctionLiningSection(null);
            int sectionWorkId = workJunctionLiningSection.InsertDirect(projectId, section_assetId, null, numLats, notLinedYet, allMeasured, issueWithLaterals, notMeasuredYet, notDeliveredYet, false, companyId, "", "", "", "", false, "", 0);

            // Insert Junction Lining Laterals
            SectionTDS sectionTDS = new SectionTDS();

            SectionGateway sectionGateway = new SectionGateway(sectionTDS);
            sectionGateway.LoadById(originalId, companyId);

            JlinerGateway jlinerGateway = new JlinerGateway(sectionTDS);
            jlinerGateway.LoadByIdCompanyId(originalId, companyId);

            foreach (SectionTDS.LFS_JUNCTION_LINER2Row row in (SectionTDS.LFS_JUNCTION_LINER2DataTable)jlinerGateway.Table)
            {
                string lateralID = ""; if (!row.IsDetailIDNull()) lateralID = row.DetailID;
                string address = ""; if (!row.IsAddressNull()) address = row.Address;
                string distanceFromUSMH = ""; if (!row.IsDistanceFromUSMHNull()) distanceFromUSMH = row.DistanceFromUSMH.ToString();
                string distanceFromDSMH = ""; if (!row.IsDistanceFromDSMHNull()) distanceFromDSMH = row.DistanceFromDSMH.ToString();
                DateTime? pipeLocated = null; if (!row.IsPipeLocatedNull()) pipeLocated = row.PipeLocated;
                DateTime? servicesLocated = null; if (!row.IsServicesLocatedNull()) servicesLocated = row.ServicesLocated;
                DateTime? coInstalled = null; if (!row.IsCoInstalledNull()) coInstalled = row.CoInstalled;
                DateTime? backfilledConcrete = null; if (!row.IsBackfilledConcreteNull()) backfilledConcrete = row.BackfilledConcrete;
                DateTime? backfilledSoil = null; if (!row.IsBackfilledSoilNull()) backfilledSoil = row.BackfilledSoil;
                DateTime? grouted = null; if (!row.IsGroutedNull()) grouted = row.Grouted;
                DateTime? cored = null; if (!row.IsCoredNull()) cored = row.Cored;
                DateTime? prepped = null; if (!row.IsPreppedNull()) prepped = row.Prepped;
                DateTime? measured = null; if (!row.IsMeasuredNull()) measured = row.Measured;
                string linerSize = ""; if (!row.IsLinerSizeNull()) linerSize = row.LinerSize;
                DateTime? inProcess = null; if (!row.IsInProcessNull()) inProcess = row.InProcess;
                DateTime? inStock = null; if (!row.IsInStockNull()) inStock = row.InStock;
                DateTime? delivered = null; if (!row.IsDeliveredNull()) delivered = row.Delivered;
                int? buildRebuid = null; if (!row.IsBuildRebuildNull()) buildRebuid = row.BuildRebuild;
                DateTime? preVideo = null; if (!row.IsPreVideoNull()) preVideo = row.PreVideo;
                DateTime? linerInstalled = null; if (!row.IsLinerInstalledNull()) linerInstalled = row.LinerInstalled;
                DateTime? finalVideo = null; if (!row.IsFinalVideoNull()) finalVideo = row.FinalVideo;
                string map = ""; if (!row.IsMapNull()) map = row.Map;
                decimal? cost = null; if (!row.IsCostNull()) cost = row.Cost;
                DateTime? videoInspection = null; if (!row.IsVideoInspectionNull()) videoInspection = row.VideoInspection;
                bool coRequired = row.CoRequired;
                bool pitRequired = row.PitRequired;
                string coPitLocation = ""; if (!row.IsCoPitLocationNull()) coPitLocation = row.CoPitLocation;
                bool postContractDigRequired = row.PostContractDigRequired;
                string comments = ""; if (!row.IsCommentsNull()) comments = row.Comments;
                string history = ""; if (!row.IsHistoryNull()) history = row.History;
                DateTime? coCutDown = null; if (!row.IsCoCutDownNull()) coCutDown = row.CoCutDown;
                DateTime? finalRestoration = null; if (!row.IsFinalRestorationNull()) finalRestoration = row.FinalRestoration;
                string clientLateralId = ""; if (!row.IsClientLateralIDNull()) clientLateralId = row.ClientLateralID;
                string videoLengthToPropertyLine = ""; if (!row.IsVideoLengthToPropertyLineNull()) videoLengthToPropertyLine = row.VideoLengthToPropertyLine;
                bool liningThruCo = row.LiningThruCo;
                DateTime? noticeDelivered = null; if (!row.IsNoticeDeliveredNull()) noticeDelivered = row.NoticeDelivered;
                string hamiltonInspectionNumber = ""; if (!row.IsHamiltonInspectionNumberNull()) hamiltonInspectionNumber = row.HamiltonInspectionNumber;
                bool dyeTestReq = row.DyeTestReq;
                DateTime? dyeTestComplete = null; if (!row.IsDyeTestCompleteNull()) dyeTestComplete = row.DyeTestComplete;

                // Fields only presents in new Junction lining
                string flange = "";
                string gasket = "";
                string connectionType = "";
                string depthOfLocated = "";
                bool digRequiredPriorToLining = false;
                DateTime? digRequiredPriorToLiningCompleted = null;
                bool digRequiredAfterLining = false;
                DateTime? digRequiredAfterLiningCompleted = null;
                bool outOfScope = false;
                bool holdClientIssue = false;
                DateTime? holdClientIssueResolved  = null;
                bool holdLFSIssue = false;
                DateTime? holdLFSIssueResolved = null;
                bool requiresRoboticPrep = false;
                DateTime? requiresRoboticPrepCompleted = null;

                ProjectGateway projectGateway = new ProjectGateway();
                projectGateway.LoadByProjectId(projectId);
                int clientId = projectGateway.GetClientID(projectId);

                // Insert into LFS Asset Lateral
                LfsAssetSewerLateral lfsAssetSewerLateral = new LfsAssetSewerLateral(null);
                int lateralAssetId = lfsAssetSewerLateral.InsertDirect(countryId, provinceId, countyId, cityId, section_assetId, address, lateralID, "", "", "", "", "Live", "", distanceFromUSMH, distanceFromDSMH, "", false, companyId, connectionType);

                // Insert into LFS Asset Lateral Client
                LfsAssetSewerLateralClient lfsAssetSewerLateralClient = new LfsAssetSewerLateralClient(null);
                lfsAssetSewerLateralClient.InsertDirect(lateralAssetId, clientId, clientLateralId, false, companyId);

                // Insert into Work Junction Lining Lateral
                WorkJunctionLiningLateral workJunctionLiningLateral = new WorkJunctionLiningLateral(null);
                int workLateral = workJunctionLiningLateral.InsertDirect(projectId, lateralAssetId, sectionWorkId, pipeLocated, servicesLocated, coInstalled, backfilledConcrete, backfilledSoil, grouted, cored, prepped, measured, linerSize, inProcess, inStock, delivered, buildRebuid, preVideo, linerInstalled, finalVideo, cost, videoInspection, coRequired, pitRequired, coPitLocation, postContractDigRequired, coCutDown, finalRestoration, false, companyId, comments, history, videoLengthToPropertyLine, liningThruCo, noticeDelivered, hamiltonInspectionNumber, flange, gasket, depthOfLocated, digRequiredPriorToLining, digRequiredPriorToLiningCompleted, digRequiredAfterLining, digRequiredAfterLiningCompleted, outOfScope, holdClientIssue, holdClientIssueResolved, holdLFSIssue, holdLFSIssueResolved, requiresRoboticPrep, requiresRoboticPrepCompleted, "", "", dyeTestReq, dyeTestComplete, "");

                // Insert into Work Comments
                JlinerCommentGateway jlinerCommentGateway = new JlinerCommentGateway(sectionTDS);
                jlinerCommentGateway.LoadByIdRefId(originalId, row.RefID, companyId);

                foreach (SectionTDS.LFS_JUNCTION_LINER2_COMMENTRow rowComment in (SectionTDS.LFS_JUNCTION_LINER2_COMMENTDataTable)jlinerCommentGateway.Table)
                {
                    int loginId = rowComment.LoginID;
                    DateTime dateTime_ = rowComment.DateTime_;
                    string comment = rowComment.Comment;

                    WorkCommentsGateway workCommentsGateway = new WorkCommentsGateway();
                    workCommentsGateway.LoadByWorkIdWorkType(workLateral, companyId, "Junction Lining Lateral");
                    WorkComments workComments = new WorkComments(workCommentsGateway.Data);
                    workComments.Insert(workLateral, 0, "Junction Lining Lateral", "Bulk Upload Comments", loginId, dateTime_, comment, null, false, companyId, false, "Junction Lining");

                    // Update Comments
                    workCommentsGateway.Update();
                }

                // Insert into Work History
                JlinerHistoryGateway jlinerHistoryGateway = new JlinerHistoryGateway(sectionTDS);
                jlinerHistoryGateway.LoadByIdRefId(originalId, row.RefID, companyId);

                foreach (SectionTDS.LFS_JUNCTION_LINER2_HISTORYRow rowHistory in (SectionTDS.LFS_JUNCTION_LINER2_HISTORYDataTable)jlinerHistoryGateway.Table)
                {
                    int loginId = rowHistory.LoginID;
                    DateTime dateTime_H = rowHistory.DateTime_;
                    string history_ = rowHistory.History;

                    WorkHistoryGateway workHistoryGateway = new WorkHistoryGateway();
                    workHistoryGateway.LoadByWorkIdWorkType(workLateral, companyId, "Junction Lining Lateral");
                    WorkHistory workHistory = new WorkHistory(workHistoryGateway.Data);
                    workHistory.Insert(workLateral, 0, "Junction Lining Lateral", "Bulk Upload History", loginId, dateTime_H, history_, null, false, companyId, false, "Junction Lining");

                    // Update History
                    workHistoryGateway.Update();
                }
            }
        }
        private void Save2()
        {
            Page.Validate();

            if (Page.IsValid)
            {
                FlatSectionJliner flatSectionJliner = new FlatSectionJliner(flatSectionJlinerTDS);

                // Update flatSectionJlinerTDS
                foreach (GridViewRow row in grdvJliner.Rows)
                {
                    // ... Get standard fields
                    Guid id = new Guid(((HiddenField)row.FindControl("hdfId")).Value);
                    int companyId = int.Parse(((HiddenField)row.FindControl("hdfCompanyId")).Value);
                    int refId = int.Parse(((HiddenField)row.FindControl("hdfRefId")).Value);
                    string recordId = ((HiddenField)row.FindControl("hdfRecordId")).Value;
                    string detailId = ((HiddenField)row.FindControl("hdfDetailId")).Value;
                    string id_ = ((TextBox)row.FindControl("tbxId_")).Text.Trim();
                    string address = ((TextBox)row.FindControl("tbxAddress")).Text.Trim();
                    DateTime? pipeLocated = null; if (((TextBox)row.FindControl("tbxPipeLocated")).Text.Trim() != "") pipeLocated = DateTime.Parse(((TextBox)row.FindControl("tbxPipeLocated")).Text.Trim());
                    DateTime? servicesLocated = null; if (((TextBox)row.FindControl("tbxServicesLocated")).Text.Trim() != "") servicesLocated = DateTime.Parse(((TextBox)row.FindControl("tbxServicesLocated")).Text.Trim());
                    DateTime? coInstalled = null; if (((TextBox)row.FindControl("tbxCoInstalled")).Text.Trim() != "") coInstalled = DateTime.Parse(((TextBox)row.FindControl("tbxCoInstalled")).Text.Trim());
                    DateTime? backfilledConcrete = null; if (((TextBox)row.FindControl("tbxBackfilledConcrete")).Text.Trim() != "") backfilledConcrete = DateTime.Parse(((TextBox)row.FindControl("tbxBackfilledConcrete")).Text.Trim());
                    DateTime? backfilledSoil = null; if (((TextBox)row.FindControl("tbxBackfilledSoil")).Text.Trim() != "") backfilledSoil = DateTime.Parse(((TextBox)row.FindControl("tbxBackfilledSoil")).Text.Trim());
                    DateTime? grouted = null; if (((TextBox)row.FindControl("tbxGrouted")).Text.Trim() != "") grouted = DateTime.Parse(((TextBox)row.FindControl("tbxGrouted")).Text.Trim());
                    DateTime? cored = null; if (((TextBox)row.FindControl("tbxCored")).Text.Trim() != "") cored = DateTime.Parse(((TextBox)row.FindControl("tbxCored")).Text.Trim());
                    DateTime? prepped = null; if (((TextBox)row.FindControl("tbxPrepped")).Text.Trim() != "") prepped = DateTime.Parse(((TextBox)row.FindControl("tbxPrepped")).Text.Trim());
                    DateTime? measured = null; if (((TextBox)row.FindControl("tbxMeasured")).Text.Trim() != "") measured = DateTime.Parse(((TextBox)row.FindControl("tbxMeasured")).Text.Trim());
                    string linerSize = ""; if (((TextBox)row.FindControl("tbxLinerSize")).Text.Trim() != "") linerSize = ((TextBox)row.FindControl("tbxLinerSize")).Text.Trim();
                    bool liningThruCo = ((CheckBox)row.FindControl("cbxLiningThruCo")).Checked;
                    DateTime? inProcess = null; if (((TextBox)row.FindControl("tbxInProcess")).Text.Trim() != "") inProcess = DateTime.Parse(((TextBox)row.FindControl("tbxInProcess")).Text.Trim());
                    DateTime? inStock = null; if (((TextBox)row.FindControl("tbxInStock")).Text.Trim() != "") inStock = DateTime.Parse(((TextBox)row.FindControl("tbxInStock")).Text.Trim());
                    DateTime? delivered = null; if (((TextBox)row.FindControl("tbxDelivered")).Text.Trim() != "") delivered = DateTime.Parse(((TextBox)row.FindControl("tbxDelivered")).Text.Trim());
                    DateTime? preVideo = null; if (((TextBox)row.FindControl("tbxPreVideo")).Text.Trim() != "") preVideo = DateTime.Parse(((TextBox)row.FindControl("tbxPreVideo")).Text.Trim());
                    DateTime? linerInstalled = null; if (((TextBox)row.FindControl("tbxLinerInstalled")).Text.Trim() != "") linerInstalled = DateTime.Parse(((TextBox)row.FindControl("tbxLinerInstalled")).Text.Trim());
                    DateTime? finalVideo = null; if (((TextBox)row.FindControl("tbxFinalVideo")).Text.Trim() != "") finalVideo = DateTime.Parse(((TextBox)row.FindControl("tbxFinalVideo")).Text.Trim());
                    double? distanceFromUSMH = null; if (((TextBox)row.FindControl("tbxDistanceFromUSMH")).Text.Trim() != "") distanceFromUSMH = double.Parse(((TextBox)row.FindControl("tbxDistanceFromUSMH")).Text.Trim());
                    string comments = ""; if (((TextBox)row.FindControl("tbxComments")).Text.Trim() != "") comments = ((TextBox)row.FindControl("tbxComments")).Text.Trim();
                    string history = ""; if (((TextBox)row.FindControl("tbxHistory")).Text.Trim() != "") history = ((TextBox)row.FindControl("tbxHistory")).Text.Trim();
                    string issue = ((DropDownList)row.FindControl("ddlIssue")).SelectedValue.Trim();
                    decimal? cost = null; if (((TextBox)row.FindControl("tbxCost")).Text.Trim() != "") cost = decimal.Parse(((TextBox)row.FindControl("tbxCost")).Text.Trim());
                    bool deleted = false;
                    bool selected = true;
                    DateTime? videoInspection = null; if (((TextBox)row.FindControl("tbxVideoInspection")).Text.Trim() != "") videoInspection = DateTime.Parse(((TextBox)row.FindControl("tbxVideoInspection")).Text.Trim());
                    string videoLengthToPropertyLine = ""; if (((TextBox)row.FindControl("tbxVideoLengthToPropertyLine")).Text.Trim() != "") videoLengthToPropertyLine = ((TextBox)row.FindControl("tbxVideoLengthToPropertyLine")).Text.Trim();
                    bool coRequired = ((CheckBox)row.FindControl("cbxCoReq")).Checked;
                    bool pitRequired = ((CheckBox)row.FindControl("cbxPitReq")).Checked;
                    string coPitLocation = ""; coPitLocation = ((DropDownList)row.FindControl("ddlCoPitLocation")).SelectedValue;
                    bool postContractDigRequired = ((CheckBox)row.FindControl("cbxPostContractDigRequired")).Checked;
                    DateTime? coCutDown = null; if (((TextBox)row.FindControl("tbxCoCutDown")).Text.Trim() != "") coCutDown = DateTime.Parse(((TextBox)row.FindControl("tbxCoCutDown")).Text.Trim());
                    DateTime? finalRestoration = null; if (((TextBox)row.FindControl("tbxFinalRestoration")).Text.Trim() != "") finalRestoration = DateTime.Parse(((TextBox)row.FindControl("tbxFinalRestoration")).Text.Trim());
                    string clientLateralId = ""; if (((TextBox)row.FindControl("tbxClientLateralId")).Text.Trim() != "") clientLateralId = ((TextBox)row.FindControl("tbxClientLateralId")).Text.Trim();
                    string hamiltonInspectionNumber = ""; if (((TextBox)row.FindControl("tbxHamiltonInspectionNumber")).Text.Trim() != "") hamiltonInspectionNumber = ((TextBox)row.FindControl("tbxHamiltonInspectionNumber")).Text.Trim();
                    DateTime? noticeDelivered = null; if (((TextBox)row.FindControl("tbxNoticeDelivered")).Text.Trim() != "") noticeDelivered = DateTime.Parse(((TextBox)row.FindControl("tbxNoticeDelivered")).Text.Trim());

                    // ... Calculate fields
                    double? distanceFromDSMH = null;
                    if (distanceFromUSMH.HasValue)
                    {
                        SectionGateway sectionGateway = new SectionGateway();
                        sectionGateway.LoadById(id, companyId);

                        Distance length = new Distance(sectionGateway.GetActualLength(id)) - new Distance(((double)distanceFromUSMH).ToString());
                        distanceFromDSMH = length.ToDoubleInEng3();
                    }

                    // ... Update row
                    flatSectionJliner.Update(id_, id, refId, companyId, recordId, detailId, address, pipeLocated, servicesLocated, coInstalled, backfilledConcrete, backfilledSoil, grouted, cored, prepped, measured, linerSize, inProcess, inStock, delivered, preVideo, linerInstalled, finalVideo, distanceFromUSMH, distanceFromDSMH, comments, history, issue, cost, deleted, selected, videoInspection, coRequired, pitRequired, coPitLocation, postContractDigRequired, coCutDown, finalRestoration, clientLateralId, videoLengthToPropertyLine, liningThruCo, hamiltonInspectionNumber, noticeDelivered);
                }

                // Store datasets
                Session["flatSectionJlinerTDS"] = flatSectionJlinerTDS;

                // Update section and jliners
                sectionTDS = new SectionTDS();
                flatSectionJliner.Save(sectionTDS);
            }
        }
        // ////////////////////////////////////////////////////////////////////////
        // EVENTS
        //
        protected void Page_Load(object sender, EventArgs e)
        {
            // Register client scripts
            this.RegisterClientScripts();

            if (!IsPostBack)
            {
                // Security check
                if (!(Convert.ToBoolean(Session["sgLFS_APP_VIEW"]) && Convert.ToBoolean(Session["sgLFS_APP_EDIT"])))
                {
                    Response.Redirect("./../../error_page.aspx?error=" + "You are not authorized to view this page. Contact your system administrator.");
                }

                // Validate query string
                if (((string)Request.QueryString["source_page"] == null) || ((string)Request.QueryString["client"] == null))
                {
                    Response.Redirect("./../../error_page.aspx?error=" + "Invalid query string in flat_section_jliner_edit.aspx");
                }

                // Tag page
                hdfCurrentClient.Value = (string)Request.QueryString["client"];
                hdfLoginId.Value = Convert.ToInt32(Session["loginID"]).ToString();
                hdfId.Value = Convert.ToString(Request.QueryString["rowId"]);
                hdfRefId.Value = Convert.ToString(Request.QueryString["rowRefId"]);
                hdfCompanyId.Value = Convert.ToString(Request.QueryString["rowCompanyId"]);
                hdfAdminPermission.Value = Convert.ToBoolean(Session["sgLFS_APP_ADMIN"]).ToString();
                hdfUpdate.Value = "yes";

                // Prepare initial data
                Session.Remove("commentsDummy");

                // ... Names for UserList
                int companyId = Int32.Parse(hdfCompanyId.Value);

                LoginGateway loginGateway = new LoginGateway();
                loginGateway.LoadByLoginId(Convert.ToInt32(hdfLoginId.Value), companyId);
                hdfCreatedBy.Value = loginGateway.GetLastName(Convert.ToInt32(hdfLoginId.Value), companyId) + " " + loginGateway.GetFirstName(Convert.ToInt32(hdfLoginId.Value), companyId);
                hdfCreationDateTime.Value = DateTime.Now.ToString();

                // If comming from
                // ... flat_section_jliner_summary.aspx
                if (Request.QueryString["source_page"] == "flat_section_jliner_summary.aspx" || Request.QueryString["source_page"] == "flat_section_jliner_edit.aspx")
                {
                    StoreNavigatorState();
                    ViewState["update"] = Request.QueryString["update"];
                    Session["rowFocus"] = Convert.ToInt32(Request.QueryString["rowFocus"].ToString());

                    // ... Load comments to edit
                    sectionTDS = new SectionTDS();
                    flatSectionJlinerTDS = (FlatSectionJlinerTDS)Session["flatSectionJlinerTDS"];

                    SectionGateway sectionGateway = new SectionGateway(sectionTDS);
                    sectionGateway.LoadById(new Guid(hdfId.Value), Convert.ToInt32(hdfCompanyId.Value));

                    JlinerGateway jlinerGateway = new JlinerGateway(sectionTDS);
                    jlinerGateway.LoadByIdCompanyIdRefId(new Guid(hdfId.Value), Convert.ToInt32(hdfCompanyId.Value), Convert.ToInt32(hdfRefId.Value));

                    FlatSectionJlinerJuntionLiner2CommentGateway flatSectionJlinerJuntionLiner2CommentGateway = new FlatSectionJlinerJuntionLiner2CommentGateway(flatSectionJlinerTDS);
                    flatSectionJlinerJuntionLiner2CommentGateway.LoadAllByIdRefId(new Guid(hdfId.Value), Convert.ToInt32(hdfRefId.Value), Convert.ToInt32(hdfCompanyId.Value));

                    FlatSectionJlinerJuntionLiner2Comment flatSectionJlinerJuntionLiner2Comment = new FlatSectionJlinerJuntionLiner2Comment(flatSectionJlinerJuntionLiner2CommentGateway.Data);
                    flatSectionJlinerJuntionLiner2Comment.UpdateForProcess();

                    // ... Load history for transfers
                    FlatSectionJlinerJuntionLiner2HistoryGateway flatSectionJlinerJuntionLiner2HistoryGateway = new FlatSectionJlinerJuntionLiner2HistoryGateway(flatSectionJlinerTDS);
                    flatSectionJlinerJuntionLiner2HistoryGateway.LoadAllByIdRefId(new Guid(hdfId.Value), Convert.ToInt32(hdfRefId.Value), Convert.ToInt32(hdfCompanyId.Value));

                    // ... Store datasets
                    Session["sectionTDS"] = sectionTDS;
                    Session["flatSectionJlinerTDS"] = flatSectionJlinerTDS;
                    comments = flatSectionJlinerTDS.JuntionLiner2Comment;
                    Session["comments"] = comments;
                }
            }
            else
            {
                // Restore datasets
                sectionTDS = (SectionTDS)Session["sectionTDS"];
                flatSectionJlinerTDS = (FlatSectionJlinerTDS)Session["flatSectionJlinerTDS"];
                Session["flatSectionJlinerTDS"] = flatSectionJlinerTDS;
                comments = flatSectionJlinerTDS.JuntionLiner2Comment;
                Session["comments"] = comments;
            }
        }