protected void Page_Load(object sender, EventArgs e)
        {
            User user = Session["UserObj"] == null ? new User() : (User)Session["UserObj"];

            var title = (HtmlGenericControl)Master.FindControl("pageTitleSpan");
            
            title.InnerText = Title;

            if (user.Rol.ID != (int)Role.TipoRoles.Director
                && user.Rol.ID != (int)Role.TipoRoles.SuperInspector
                && user.Rol.ID != (int)Role.TipoRoles.Admin)
            {
                Response.Redirect("~/Default.aspx", true);
            }

            if (!IsPostBack)
            {
                #region Instanciate company ddl

                companyDDL.Items.Add("Seleccionar");

                LinkedList<Company> companies = new SolicitudesInicialesServicio().GetCompanies();

                for (int i = 0; i < companies.Count; i++)
                {
                    companyDDL.Items.Add(companies.ElementAt(i).Nombre);
                } 

                #endregion
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            var title = (HtmlGenericControl)Master.FindControl("pageTitleSpan");

            title.InnerText = Title;

            User user = Session["UserObj"] == null ? new User() : (User)Session["UserObj"];

            if (string.IsNullOrWhiteSpace(user.Email))
            {
                Response.Redirect("~/Account/Ingresar.aspx", true);
            }

            Operador operador = new SolicitudesInicialesServicio().GetOperadorByName(user.EmpresaID);

            if (operador.OperadorId == 0)
            {
                Response.Redirect("~/Default.aspx", true);
            }

            if (!IsPostBack)
            {
                LinkedList<string> municipios = new SolicitudesInicialesServicio().GetMunicipios();


                if (!Request.Browser.Browser.Equals("InternetExplorer") && !Request.Browser.Browser.Equals("Safari"))
                {
                    ViewState["municipiosCell"] = 2;

                    ViewState["certCell"] = 6;

                    ViewState["croqCell"] = 7;

                    ViewState["numControl"] = 0;
                }

                    //Add one to cells cause select link is added, on the 1st cell, when gv.AutoGenerateSelectButton = true on IE and safari
                else
                {
                    gv.AutoGenerateSelectButton = true;

                    ViewState["municipiosCell"] = 3;

                    ViewState["certCell"] = 7;

                    ViewState["croqCell"] = 8;

                    ViewState["numControlCell"] = 1;
                }

                for (int i = 0; i < municipios.Count; i++)
                {
                    municipiosDDL.Items.Add(municipios.ElementAt(i));
                }
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            User user = Session["UserObj"] == null ? new User() : (User)Session["UserObj"];

            #region Set title

            var title = (HtmlGenericControl)Master.FindControl("pageTitleSpan");

            title.InnerText = Title;

            #endregion

            #region Check role

            if (user.Rol.ID != (int)Role.TipoRoles.Director
                    && user.Rol.ID != (int)Role.TipoRoles.SuperInspector
                    && user.Rol.ID != (int)Role.TipoRoles.Admin)
            {
                Response.Redirect("~/Default.aspx", true);
            }

            #endregion

            if (!IsPostBack)
            {
                #region Instanciate municipio ddl

                LinkedList<string> municipios = new SolicitudesInicialesServicio().GetMunicipios();

                for (int i = 0; i < municipios.Count; i++)
                {
                    municipioDDL.Items.Add(municipios.ElementAt(i));
                }

                #endregion

                LinkedList<Averia> averias = AveriasServicio.GetAverias();

                avisosRadicadosSinFiltroLbl.Text = string.Format("Total de Averias Cometidas: {0}", averias.Count);

                FillSinFiltroGv();
            }
        }
Exemple #4
0
        //private static LinkedList<FileUpload> docRequeridosFileUpload = new LinkedList<FileUpload>(); //Used for doc validations when guardar is pressed

        //private static LinkedList<ImageButton> ImageButtons = new LinkedList<ImageButton>(); //Used to store all imgBtns on doc section

        //private static LinkedList<DropDownList> docAsociadosStatuses = new LinkedList<DropDownList>(); // Used to save doc status on doc object

        //private static LinkedList<RequiredFieldValidator> docAsociadosValidators = new LinkedList<RequiredFieldValidator>(); // Used when I need to disable status RFVs

        //private static LinkedList<DocumentoRequerido> docsRequeridos = new LinkedList<DocumentoRequerido>(); // Just in case I lose data on postbacks

        protected void Page_Load(object sender, EventArgs e)
        {
            User user = Session["UserObj"] == null ? new User() : (User)Session["UserObj"];

            if (!user.Rol.VerExtensiones)
            {
                Response.Redirect("~/Default.aspx");
            }

            var title = (HtmlGenericControl)Master.FindControl("pageTitleSpan");

            title.InnerText = Title;



            #region Populate horario ddl

            horarioDDL.Items.Add("Seleccionar");

            horarioDDL2.Items.Add("Seleccionar");

            for (int i = 0; i < 2; i++)
            {
                string dayTime = "AM";

                if (i == 1)
                {
                    dayTime = "PM";
                }

                for (int h = 1; h < 13; h++)
                {
                    for (int m = 0; m < 4; m += 3)
                    {
                        horarioDDL.Items.Add(h.ToString() + ":" + m.ToString() + "0" + dayTime);

                        horarioDDL2.Items.Add(h.ToString() + ":" + m.ToString() + "0" + dayTime);
                    }
                }
            }
            #endregion

            //CreateDocReqCtrls(tipoAvisoRBtnLst.SelectedIndex);

            //CreateDefaultAveriasGrdVwRow();

            if (!IsPostBack)
            {
                Session.Remove("docAsociadosStatusesExt");

                Session.Remove("docsRequeridos");

                NumeroControl numeroControl = new NumeroControl()
                {
                    NumControlText = Request.QueryString["NumeroControl"]

                    //NumControlText = "2015-0003" // only for testing
                };

                try
                {
                    #region Municipios

                    LinkedList<String> municipios = new SolicitudesInicialesServicio().GetMunicipios();

                    municipioDDL.Items.Add("Seleccionar");

                    municipioSubDDL.Items.Add("Seleccionar");

                    municipioTrabajoDDL.Items.Add("Seleccionar");

                    foreach (var m in municipios)
                    {
                        municipioDDL.Items.Add(m);

                        municipioSubDDL.Items.Add(m);

                        municipioTrabajoDDL.Items.Add(m);
                    }

                    municipioDDL.SelectedIndex = 0;

                    municipioSubDDL.SelectedIndex = 0;

                    municipioTrabajoDDL.SelectedIndex = 0;

                    #endregion

                    SolicitudAviso primeraExtExistente = new PrimerasExtensionesServicio().GetPrimeraExtension(numeroControl);

                    primeraExtExistente.EstatusId = primeraExtExistente.EstatusId.Replace(primeraExtExistente.LetraStatus, string.Empty).Replace("I", string.Empty);

                    SolicitudAviso solicitud = new SolicitudesInicialesServicio().GetSolicitud(numeroControl);

                    if (String.IsNullOrEmpty(primeraExtExistente.NumeroControl.NumControlText))
                    {
                        #region Create

                        #region Set txtbxs con info de aviso inicial

                        #region Poblar campos solicitud

                        #region Info general

                        //Session["userId"] = solicitud.Usuario.Id;

                        numeroControlTxtBx.Text = numeroControl.NumControlText;

                        emergenciaChkBx.Checked = solicitud.Emergencia;

                        if (!user.Rol.EditarAvisoEmergerncia)
                        {
                            emergenciaChkBx.Enabled = false;
                        }

                        tipoAvisoRBtnLst.SelectedIndex = Convert.ToInt32(solicitud.TipoAviso);

                        areaDepartamentoTxtBx.Enabled = tipoAvisoRBtnLst.SelectedIndex != 2;

                        deptRFV.Enabled = tipoAvisoRBtnLst.SelectedIndex != 2;

                        if (!areaDepartamentoTxtBx.Enabled)
                        {
                            deptLbl.Text = deptLbl.Text.Replace("*", string.Empty);
                        }

                        areaDepartamentoSubTxtBx.Enabled = tipoAvisoRBtnLst.SelectedIndex != 2;

                        SetDocsVisibilities();

                        nombreContactoTxtBx.Text = solicitud.NombreContacto;

                        celularContactoTxtBx.Text = solicitud.CelularContacto;

                        direccionPostalContactoTxtBx.Text = solicitud.DireccionPostalContacto;

                        #endregion

                        #region Contratista

                        companyDDL.Items.Add(solicitud.NombreEmpresa);

                        representanteTxtBx.Text = solicitud.RepresentanteAutorizado;

                        if (!solicitud.TipoAviso.Equals(((int)SolicitudAviso.TiposAvisos.Residencial).ToString()))
                        {
                            areaDepartamentoTxtBx.Text = solicitud.AreaDept;

                            //representanteRFV.Enabled = tipoAvisoRBtnLst.SelectedIndex != 2;

                            //deptLbl.Text = deptLbl.Text.Replace("*", string.Empty);
                        }

                        else
                        {
                            deptLbl.Text = deptLbl.Text.Replace("*", string.Empty);

                            areaDepartamentoTxtBx.Enabled = false;

                            deptRFV.Enabled = false;
                        }

                        telOficinaTxtBx.Text = solicitud.TelOficina;

                        telTrabajoTxtBx.Text = solicitud.TelCampoTrabajo;

                        celularTxtBx.Text = solicitud.TelCelular;

                        emailTxtBx.Text = solicitud.CorreoElectronico;

                        direccionTxtBx.Text = solicitud.DireccionPostal;

                        municipioDDL.SelectedIndex = solicitud.MunicipioId;

                        codigoPostalTxtBx.Text = solicitud.CodigoPostal;

                        #endregion

                        #region Sub
                        companySubTxtBx.Text = solicitud.Subcontratista;



                        representanteSubTxtBx.Text = solicitud.RepresentanteAutorizadoSub;

                        if (!solicitud.TipoAviso.Equals(((int)SolicitudAviso.TiposAvisos.Residencial).ToString()))
                        {
                            areaDepartamentoSubTxtBx.Text = solicitud.AreaDeptSub;
                        }

                        else
                        {
                            areaDepartamentoSubTxtBx.Enabled = false;
                        }

                        //representanteSubTxtBx.Text = solicitud.RepresentanteAutorizadoSub;

                        telOficinaSubTxtBx.Text = solicitud.TelOficinaSub;

                        telTrabajoSubTxtBx.Text = solicitud.TelCampoTrabajoSub;

                        celularSubTxtBx.Text = solicitud.TelCelularSub;

                        emailSubTxtBx.Text = solicitud.CorreoElectronicoSub;

                        direccionSubTxtBx.Text = solicitud.DireccionPostalSub;

                        municipioSubDDL.SelectedIndex = solicitud.MunicipioIdSub;

                        codigoPostalSubTxtBx.Text = solicitud.CodigoPostalSub;

                        #endregion

                        #region Info trabajo

                        //Urbana?
                        if (solicitud.Zona)
                        {
                            zonaRBtnLst.SelectedIndex = 1;
                        }

                        else
                        {
                            zonaRBtnLst.SelectedIndex = 0;
                        }

                        boUrbTxtBx.Text = solicitud.BoUrb;

                        sectorCalleTxtBx.Text = solicitud.SectorCalle;

                        carreteraTxtBx.Text = solicitud.Carretera;

                        kmTxtBx.Text = solicitud.KM.ToString();

                        hmTxtBx.Text = solicitud.HM.ToString();

                        municipioTrabajoDDL.SelectedIndex = solicitud.MunicipioIdTrab;

                        referenciasTxtBx.Text = solicitud.Referencias;

                        fechaComienzoPropuestoTxtBx.Text = solicitud.FechaPropuesta.ToShortDateString();

                        fechaComienzoTxtBx.Text = solicitud.FechaComienzo.ToShortDateString();

                        fechaExpiracionTxtBx.Text = solicitud.FechaExpiracion.ToShortDateString();

                        //Duracion se guarda con el guion para evitar tener que usar mas de una variable
                        string[] duracionSplit = solicitud.TiempoDuracion.Split('-');

                        duracionDiaTxtBx.Text = duracionSplit[0];

                        duracionMesTxtBx.Text = duracionSplit[1];

                        duracionYearTxtBx.Text = duracionSplit[2];

                        string[] horSplit = solicitud.Horario.Split('-');

                        horarioDDL.SelectedValue = horSplit[0];

                        horarioDDL2.SelectedValue = horSplit[1];

                        maquinariaChkBx.Checked = solicitud.Maquinaria;

                        tipoMaquinariaTxtBx.Enabled = solicitud.Maquinaria;

                        if (maquinariaChkBx.Checked)
                        {
                            tipoMaquinariaTxtBx.Enabled = true;

                            tipoMaquinariaTxtBx.Text = solicitud.TipoMaquinaria;

                            maquinariaUtilizarLbl.Text += "*";
                        }

                        else
                        {
                            tipoMaquinariaTxtBx.Enabled = false;
                        }

                        explosivoChkBx.Checked = solicitud.Explosivos;

                        licExplosivoTxtBx.Enabled = solicitud.Explosivos;

                        licExplosivoTxtBx.Text = solicitud.LicenciaExplosivo;

                        fechaExpiracionExplosivoTxtBx.Enabled = solicitud.Explosivos;

                        //fechaExpiracionExplosivoTxtBx.Text = solicitud.FechaExpiracionExplosivo.ToShortDateString();

                        if (explosivoChkBx.Checked)
                        {
                            //tipoExplosivoTxtBx.Enabled = true;

                            //tipoExplosivoTxtBx.Text = solicitud.TipoExplosivo;

                            licExplosivoLbl.Text += "*";

                            fechaExpiracionExplosivoLbl.Text += "*";

                            fechaExpiracionExplosivoTxtBx.Text = solicitud.FechaExpiracionExplosivo.ToShortDateString();
                        }

                        areaMarcadaChkBx.Checked = solicitud.AreaMarcada;

                        //Continua?
                        if (solicitud.TipoExcavacion)
                        {
                            tipoExcavacionRBtnLst.SelectedIndex = 0;
                        }

                        else
                        {
                            tipoExcavacionRBtnLst.SelectedIndex = 1;
                        }

                        razonTxtBx.Text = solicitud.RazonTrabajos;

                        profundidadPiesTxtBx.Text = solicitud.ProfundidadPies.ToString();

                        profundidadPulgadasDLL.SelectedIndex = solicitud.ProfundidadPulgadas;

                        longitudPiesTxtBx.Text = solicitud.LongitudPies.ToString();

                        longitudPulgadasDDL.SelectedIndex = solicitud.LongitudPulgadas;

                        coordenadasXTxtBx.Text = solicitud.CoordenadaX.ToString();

                        coordenadasYTxtBx.Text = solicitud.CoordenadaY.ToString();

                        enCasoEmergenciaTxtBx.Text = solicitud.EnCasoEmergencia;
                        #endregion

                        #endregion

                        #region Poblar campos docs requeridos

                        LinkedList<DocumentoRequerido> documentosRequeridos = new DocumentosRequeridosServicio().GetDocumentosAsociados(numeroControl,
                            (int)SolicitudAviso.TiposExtensiones.Inicial);

                        CreateDocReqCtrls(documentosRequeridos);

                        Session["docsRequeridos"] = documentosRequeridos;

                        //CreateDocAsociadosCtrl(documentosRequeridos);

                        //LinkedList<DropDownList> docAsociadosStatuses = (LinkedList<DropDownList>)Session["docAsociadosStatuses"];

                        //foreach (var d in docAsociadosStatuses)
                        //{
                        //    d.Enabled = solicitud.EstatusId.Equals(((int)SolicitudAviso.Estatus.PendienteRevisarCoordinador).ToString());
                        //}

                        //for (int i = 0; i < docRequeridosTxtBxs.Count; i++)
                        //{
                        //    docRequeridosTxtBxs.ElementAt(i).Text = documentosRequeridos.ElementAt(i).Path;
                        //}

                        //Dictionary<TextBox, DropDownList> docControls = new Dictionary<TextBox, DropDownList>();

                        //docControls = GetDocCtrls();

                        //SetDocsRequeridos(docControls, documentosRequeridos, primeraExtExistente);

                        //if (tipoAvisoRBtnLst.Items[0].Selected)
                        //{
                        //    #region Company docs

                        //    docControls = GetDocCtrls();

                        //    SetDocsRequeridos(docControls, documentosRequeridos, primeraExtExistente);

                        //    #endregion
                        //}

                        //else
                        //{
                        //    #region Docs Individuo

                        //    docControls = GetDocCtrls();

                        //    SetDocsRequeridos(docControls, documentosRequeridos, primeraExtExistente);

                        //    #endregion
                        //}

                        solicitud.Documentos = documentosRequeridos;

                        #endregion

                        extensionInicialLink.NavigateUrl = extensionInicialLink.NavigateUrl +
                            "?NumeroControl=" + numeroControl.NumControlText + (string.IsNullOrEmpty(Request.QueryString["CorreoElectronico"]) ? string.Empty
                            : "&CorreoElectronico=" + Request.QueryString["CorreoElectronico"]);

                        #endregion

                        #region Poblar tabla averias
                        LinkedList<Averia> averias = new AveriasServicio().GetAverias(numeroControl, (int)SolicitudAviso.TiposExtensiones.Inicial);

                        Session["averias"] = averias;

                        averiasTxtBx.Text = averias.ElementAt(0).Titulo;

                        //CreateDefaultAveriasGrdVwRow();

                        //    DataTable dtCurrentTable = null;

                        //    DataRow drCurrentRow = null;

                        //    /*En la primera entrada, asigna los valores al row hecho por default. Verifica si hay que crear otro.
                        //     * 
                        //     * En la segunda corrida, asigna los valores al row nuevo.
                        //     * 
                        //     * Para evitar usar una linea que no existe o hacer una linea de mas esta el i + 1
                        //     * 
                        //     * i + 1 si es mayor a la cantidad de filas pues me pase del total y no tengo que hacer una fila nueva
                        //     */
                        //    for (int i = 0; i < averias.Count; i++)
                        //    {
                        //        TextBox averiaTituloTxtBx = (TextBox)averiasGrdVw.Rows[i].Cells[0].FindControl("averiaTituloTxtBx"),
                        //                averiaFechaTxtBx = (TextBox)averiasGrdVw.Rows[i].Cells[1].FindControl("averiaFechaTxtBx"),
                        //                averiaHoraTxtBx = (TextBox)averiasGrdVw.Rows[i].Cells[2].FindControl("averiaHoraTxtBx"),
                        //                averiaInfraAfectadaTxtBx = (TextBox)averiasGrdVw.Rows[i].Cells[3].FindControl("averiaInfraAfectadaTxtBx"),
                        //                averiaLugarTxtBx = (TextBox)averiasGrdVw.Rows[i].Cells[4].FindControl("averiaLugarTxtBx");

                        //        averiaTituloTxtBx.Text = averias.ElementAt(i).Titulo;

                        //        averiaFechaTxtBx.Text = averias.ElementAt(i).Fecha.Year == 1900
                        //            || averias.ElementAt(i).Fecha.Year == 9999 ? string.Empty
                        //            : averias.ElementAt(i).Fecha.ToShortDateString();

                        //        averiaHoraTxtBx.Text = averias.ElementAt(i).Hora;

                        //        averiaInfraAfectadaTxtBx.Text = averias.ElementAt(i).InfraAfectada;

                        //        averiaLugarTxtBx.Text = averias.ElementAt(i).Lugar;

                        //        //Si hay que crear otro row
                        //        if ((i + 1) != averias.Count)
                        //        {
                        //            if (ViewState["averiaTbl"] != null)
                        //            {
                        //                dtCurrentTable = (DataTable)ViewState["averiaTbl"];

                        //                drCurrentRow = dtCurrentTable.NewRow();

                        //                dtCurrentTable.Rows[i]["titulo"] = averiaTituloTxtBx.Text;

                        //                dtCurrentTable.Rows[i]["fecha"] = averiaFechaTxtBx.Text;

                        //                dtCurrentTable.Rows[i]["hora"] = averiaHoraTxtBx.Text;

                        //                dtCurrentTable.Rows[i]["afectada"] = averiaInfraAfectadaTxtBx.Text;

                        //                dtCurrentTable.Rows[i]["lugar"] = averiaLugarTxtBx.Text;

                        //                dtCurrentTable.Rows.Add(drCurrentRow);

                        //                averiasGrdVw.DataSource = dtCurrentTable;

                        //                averiasGrdVw.DataBind();

                        //                SetPreviousData();
                        //            }
                        //        }

                        //        else
                        //        {
                        //            break;
                        //        }
                        //    }

                        #endregion

                        #region Set visibilities

                        fechaComienzoDiv.Visible = false;

                        fechaExpiracionDiv.Visible = false;

                        docsRequeridosHeader.Visible = true;

                        docRequeridosMainDiv.Visible = true;

                        docsAsociadosHeader.Visible = false;

                        docsAsociadosTableTag.Visible = false;

                        fechaComienzoImgBtn.Visible = false;

                        segundaExtensionLink.Visible = false;

                        //individuoDocDiv.Visible = false;
                        #endregion

                        #region Set enabled
                        //tipoMaquinariaTxtBx.Enabled = false;

                        //licExplosivoTxtBx.Enabled = false;

                        //fechaExpiracionExplosivoTxtBx.Enabled = false;

                        fechaComienzoPropuestoTxtBx.Enabled = false;

                        tipoAvisoRBtnLst.Enabled = false;
                        #endregion

                        #endregion
                    }

                    else
                    {
                        #region Edit

                        numeroControl.Year = Convert.ToInt32(numeroControl.NumControlText.Substring(0, 4));

                        numeroControl.NumControl = Convert.ToInt32(numeroControl.NumControlText.Substring(4));

                        #region Set links extensiones

                        extensionInicialLink.NavigateUrl = extensionInicialLink.NavigateUrl + "?NumeroControl="
                            + numeroControl.NumControlText + (string.IsNullOrEmpty(Request.QueryString["CorreoElectronico"]) ? string.Empty
                            : "&CorreoElectronico=" + Request.QueryString["CorreoElectronico"]);

                        segundaExtensionLink.NavigateUrl = segundaExtensionLink.NavigateUrl + "?NumeroControl="
                            + numeroControl.NumControlText + (string.IsNullOrEmpty(Request.QueryString["CorreoElectronico"]) ? string.Empty
                            : "&CorreoElectronico=" + Request.QueryString["CorreoElectronico"]);

                        SolicitudAviso segundaExt = new SegundasExtensionesServicio().GetSegundaExtension(numeroControl);

                        if (!String.IsNullOrEmpty(segundaExt.NumeroControl.NumControlText))
                        {
                            //segundaExtensionLink.NavigateUrl = segundaExtensionLink.NavigateUrl + "?numControl=" + numeroControl.NumControlText;

                            segundaExtensionLink.Text = "Segunda";
                        }

                        else
                        {
                                segundaExtensionLink.Text = "Crear segunda extensión";                            

                            //segundaExtensionLink.Visible = false;
                        }
                        #endregion

                        #region Poblar campos solicitud

                        SolicitudAviso primeraExt =
                            new PrimerasExtensionesServicio().GetPrimeraExtension(numeroControl);

                        #region Info general

                        numeroControlTxtBx.Text = numeroControl.NumControlText;

                        if (!user.Rol.EditarAvisoEmergerncia)
                        {
                            emergenciaChkBx.Enabled = false;
                        }

                        emergenciaChkBx.Checked = primeraExt.Emergencia;

                        tipoAvisoRBtnLst.SelectedIndex = Convert.ToInt32(primeraExt.TipoAviso);

                        areaDepartamentoTxtBx.Enabled = tipoAvisoRBtnLst.SelectedIndex != 2;

                        areaDepartamentoSubTxtBx.Enabled = tipoAvisoRBtnLst.SelectedIndex != 2;

                        if (tipoAvisoRBtnLst.SelectedIndex == 2)
                        {
                            areaDepartamentoTxtBx.Text = string.Empty;

                            areaDepartamentoSubTxtBx.Text = string.Empty;
                        }

                        SetDocsVisibilities();

                        if (!string.IsNullOrWhiteSpace(primeraExt.EstatusId))
                        {
                            //Quitale la letra y brega con el numero solo
                            primeraExt.EstatusId = primeraExt.EstatusId.Replace(solicitud.LetraStatus, string.Empty).Replace(new Inspeccion().LetraStatus, string.Empty);

                            #region Fill status msgs

                            var statusMsgs = new SolicitudesInicialesServicio().GetStatusMsgs();

                            Dictionary<string, System.Drawing.Color> newStatusMsgs = new Dictionary<string, System.Drawing.Color>();

                            newStatusMsgs.Add("filler", System.Drawing.Color.Violet);

                            for (int i = 0; i < solicitud.StatusMsgs.Count; i++)
                            {
                                newStatusMsgs.Add(statusMsgs.ElementAt(i), solicitud.StatusMsgs.ElementAt(i).Value);

                                //solicitud.StatusMsgs.ElementAt(i).Key = statusMsgs.ElementAt(i);
                            }

                            primeraExt.StatusMsgs = newStatusMsgs;

                            #endregion

                            statusLbl.Text = string.Format("EXTENSIÓN {0}", primeraExt.StatusMsgs.Keys.ElementAt(Convert.ToInt32(primeraExt.EstatusId)));

                            statusLbl.ForeColor = primeraExt.StatusMsgs.Values.ElementAt(Convert.ToInt32(primeraExt.EstatusId));

                            statusHF.Value = primeraExt.EstatusId;

                            //if coordinador
                            if (primeraExt.EstatusId.Equals((((int)SolicitudAviso.Estatus.PendienteDocumentosIncompletos).ToString())))
                            {
                                if (user.Rol.ID != (int)Role.TipoRoles.Excavador)
                                {
                                    coordinadorPopup.Show();

                                    //Response.Redirect("~/Default.aspx");
                                }
                            }


                            else if (primeraExt.EstatusId.Equals((((int)SolicitudAviso.Estatus.PendienteRevisarCoordinador).ToString())))
                            {
                                if (user.Rol.ID != (int)Role.TipoRoles.Coordinador
                                    && user.Rol.ID != (int)Role.TipoRoles.Admin
                                    && user.Rol.ID != (int)Role.TipoRoles.SuperInspector
                                    && user.Rol.ID != (int)Role.TipoRoles.Director)
                                {
                                    coordinadorPoPupHeader.InnerText = "Excavador / Demoledor";

                                    coordinadorPopupBodyLbl.Text = "Esperar por revisión de coordinador";

                                    coordinadorPopup.Show();
                                }
                            }

                            //Do not allow update if any of these conditions
                            else if (!primeraExt.EstatusId.Equals(((int)SolicitudAviso.Estatus.PendienteRevisarCoordinador).ToString())
                                    || !primeraExt.EstatusId.Equals(((int)SolicitudAviso.Estatus.PendienteDocumentosIncompletos).ToString()))
                            {
                                if (user.Rol.ID != (int)Role.TipoRoles.Director && user.Rol.ID != (int)Role.TipoRoles.SuperInspector)
                                {
                                    guardarBtn.Enabled = false;
                                }
                            }

                            else
                            {
                                //Esto es un else if preguntado si es empresa o individuo, no se puede guardar
                            }
                        }

                        nombreContactoTxtBx.Text = primeraExt.NombreContacto;

                        celularContactoTxtBx.Text = primeraExt.CelularContacto;

                        direccionPostalContactoTxtBx.Text = primeraExt.DireccionPostalContacto;

                        #endregion

                        #region Contratista

                        companyDDL.Items.Add(primeraExt.NombreEmpresa);

                        representanteTxtBx.Text = primeraExt.RepresentanteAutorizado;



                        if (!primeraExt.TipoAviso.Equals(((int)SolicitudAviso.TiposAvisos.Residencial).ToString()))
                        {
                            areaDepartamentoTxtBx.Text = primeraExt.AreaDept;
                        }

                        else
                        {
                            deptLbl.Text = deptLbl.Text.Replace("*", string.Empty);

                            areaDepartamentoTxtBx.Enabled = false;

                            deptRFV.Enabled = false;
                        }

                        telOficinaTxtBx.Text = primeraExt.TelOficina;

                        telTrabajoTxtBx.Text = primeraExt.TelCampoTrabajo;

                        celularTxtBx.Text = primeraExt.TelCelular;

                        emailTxtBx.Text = primeraExt.CorreoElectronico;

                        direccionTxtBx.Text = primeraExt.DireccionPostal;

                        municipioDDL.SelectedIndex = primeraExt.MunicipioId;

                        codigoPostalTxtBx.Text = primeraExt.CodigoPostal;

                        #endregion

                        #region Sub
                        companySubTxtBx.Text = primeraExt.Subcontratista;

                        representanteSubTxtBx.Text = primeraExt.RepresentanteAutorizadoSub;

                        if (!primeraExt.TipoAviso.Equals(((int)SolicitudAviso.TiposAvisos.Residencial).ToString()))
                        {
                            areaDepartamentoSubTxtBx.Text = primeraExt.AreaDeptSub;
                        }

                        else
                        {
                            areaDepartamentoSubTxtBx.Enabled = false;
                        }

                        //representanteSubTxtBx.Text = primeraExt.RepresentanteAutorizadoSub;

                        telOficinaSubTxtBx.Text = primeraExt.TelOficinaSub;

                        telTrabajoSubTxtBx.Text = primeraExt.TelCampoTrabajoSub;

                        celularSubTxtBx.Text = primeraExt.TelCelularSub;

                        emailSubTxtBx.Text = primeraExt.CorreoElectronicoSub;

                        direccionSubTxtBx.Text = primeraExt.DireccionPostalSub;

                        municipioSubDDL.SelectedIndex = primeraExt.MunicipioIdSub;

                        codigoPostalSubTxtBx.Text = primeraExt.CodigoPostalSub;

                        #endregion

                        #region Info trabajo

                        //Urbana?
                        if (primeraExt.Zona)
                        {
                            zonaRBtnLst.SelectedIndex = 1;
                        }

                        else
                        {
                            zonaRBtnLst.SelectedIndex = 0;
                        }

                        boUrbTxtBx.Text = primeraExt.BoUrb;

                        sectorCalleTxtBx.Text = primeraExt.SectorCalle;

                        carreteraTxtBx.Text = primeraExt.Carretera;

                        kmTxtBx.Text = primeraExt.KM.ToString();

                        hmTxtBx.Text = primeraExt.HM.ToString();

                        municipioTrabajoDDL.SelectedIndex = primeraExt.MunicipioIdTrab;

                        referenciasTxtBx.Text = primeraExt.Referencias;

                        fechaComienzoPropuestoTxtBx.Text = solicitud.FechaPropuesta.ToShortDateString();

                        fechaComienzoTxtBx.Text = primeraExt.FechaComienzo.ToShortDateString();

                        fechaExpiracionTxtBx.Text = primeraExt.FechaExpiracion.ToShortDateString();

                        string[] duracionSplit = solicitud.TiempoDuracion.Split('-');

                        duracionDiaTxtBx.Text = duracionSplit[0];

                        duracionMesTxtBx.Text = duracionSplit[1];

                        duracionYearTxtBx.Text = duracionSplit[2];

                        string[] horSplit = primeraExt.Horario.Split('-');

                        horarioDDL.SelectedValue = horSplit[0];

                        horarioDDL2.SelectedValue = horSplit[1];

                        maquinariaChkBx.Checked = primeraExt.Maquinaria;

                        tipoMaquinariaTxtBx.Enabled = primeraExt.Maquinaria;

                        if (maquinariaChkBx.Checked)
                        {
                            tipoMaquinariaTxtBx.Enabled = true;

                            tipoMaquinariaTxtBx.Text = primeraExt.TipoMaquinaria;

                            maquinariaUtilizarLbl.Text += "*";
                        }

                        else
                        {
                            tipoMaquinariaTxtBx.Enabled = false;
                        }

                        explosivoChkBx.Checked = primeraExt.Explosivos;

                        licExplosivoTxtBx.Enabled = primeraExt.Explosivos;

                        licExplosivoTxtBx.Text = primeraExt.LicenciaExplosivo;

                        fechaExpiracionExplosivoTxtBx.Enabled = primeraExt.Explosivos;

                        //fechaExpiracionExplosivoTxtBx.Text = solicitud.FechaExpiracionExplosivo.ToShortDateString();

                        if (explosivoChkBx.Checked)
                        {
                            //tipoExplosivoTxtBx.Enabled = true;

                            //tipoExplosivoTxtBx.Text = solicitud.TipoExplosivo;

                            licExplosivoLbl.Text += "*";

                            fechaExpiracionExplosivoLbl.Text += "*";

                            fechaExpiracionExplosivoTxtBx.Text = primeraExt.FechaExpiracionExplosivo.ToShortDateString();
                        }

                        areaMarcadaChkBx.Checked = primeraExt.AreaMarcada;

                        //Continua?
                        if (primeraExt.TipoExcavacion)
                        {
                            tipoExcavacionRBtnLst.SelectedIndex = 0;
                        }

                        else
                        {
                            tipoExcavacionRBtnLst.SelectedIndex = 1;
                        }

                        razonTxtBx.Text = primeraExt.RazonTrabajos;

                        profundidadPiesTxtBx.Text = primeraExt.ProfundidadPies.ToString();

                        profundidadPulgadasDLL.SelectedIndex = primeraExt.ProfundidadPulgadas;

                        longitudPiesTxtBx.Text = primeraExt.LongitudPies.ToString();

                        longitudPulgadasDDL.SelectedIndex = primeraExt.LongitudPulgadas;

                        coordenadasXTxtBx.Text = primeraExt.CoordenadaX.ToString();

                        coordenadasYTxtBx.Text = primeraExt.CoordenadaY.ToString();

                        enCasoEmergenciaTxtBx.Text = primeraExt.EnCasoEmergencia;
                        #endregion

                        #endregion

                        #region Poblar campos docs requeridos

                        LinkedList<DocumentoRequerido> documentosRequeridos = new DocumentosRequeridosServicio().GetDocumentosAsociados(numeroControl,
                                                                                                                (int)SolicitudAviso.TiposExtensiones.Primera);

                        Session["docsRequeridos"] = documentosRequeridos;

                        CreateDocReqCtrls(documentosRequeridos);

                        //for (int i = 0; i < docRequeridosTxtBxs.Count; i++)
                        //{
                        //    docRequeridosTxtBxs.ElementAt(i).Text = documentosRequeridos.ElementAt(i).Path;
                        //}

                        CreateDocAsociadosCtrl(documentosRequeridos);

                        LinkedList<DropDownList> docAsociadosStatuses = (LinkedList<DropDownList>)Session["docAsociadosStatusesExt"];

                        foreach (var d in docAsociadosStatuses)
                        {
                            d.Enabled = primeraExt.EstatusId.Equals(((int)SolicitudAviso.Estatus.PendienteRevisarCoordinador).ToString());
                        }

                        //Dictionary<TextBox, DropDownList> docControls = new Dictionary<TextBox, DropDownList>();

                        //docControls = GetDocCtrls();

                        //SetDocsRequeridos(docControls, documentosRequeridos, primeraExtExistente);

                        #region Disable doc status validators if docs incomplete
                        //Asi si el user cambia de tipo de aviso, no dan problemas esos validators

                        LinkedList<RequiredFieldValidator> docAsociadosValidators = (LinkedList<RequiredFieldValidator>)Session["docAsociadosValidatorsExt"];

                        foreach (var v in docAsociadosValidators)
                        {
                            v.Enabled = primeraExt.EstatusId.Equals(((int)SolicitudAviso.Estatus.PendienteRevisarCoordinador).ToString());
                        }

                        #endregion

                        primeraExt.Documentos = documentosRequeridos;

                        //foreach (var d in docAsociadosStatuses)
                        //{
                        //    d.Enabled = solicitud.EstatusId.Equals(((int)SolicitudAviso.Estatus.PendienteRevisarCoordinador).ToString());
                        //}

                        #endregion

                        #region Poblar tabla averias

                        CreateDefaultAveriasGrdVwRow();

                        LinkedList<Averia> averias = new AveriasServicio().GetAverias(numeroControl, (int)SolicitudAviso.TiposExtensiones.Primera);

                        Session["averias"] = averias;

                        averiasTxtBx.Text = averias.ElementAt(0).Titulo;

                        //DataTable dtCurrentTable = null;

                        //DataRow drCurrentRow = null;

                        ///*En la primera entrada, asigna los valores al row hecho por default. Verifica si hay que crear otro.
                        // * 
                        // * En la segunda corrida, asigna los valores al row nuevo.
                        // * 
                        // * Para evitar usar una linea que no existe o hacer una linea de mas esta el i + 1
                        // * 
                        // * i + 1 si es mayor a la cantidad de filas pues me pase del total y no tengo que hacer una fila nueva
                        // */
                        //for (int i = 0; i < averias.Count; i++)
                        //{
                        //    TextBox averiaTituloTxtBx = (TextBox)averiasGrdVw.Rows[i].Cells[0].FindControl("averiaTituloTxtBx"),
                        //            averiaFechaTxtBx = (TextBox)averiasGrdVw.Rows[i].Cells[1].FindControl("averiaFechaTxtBx"),
                        //            averiaHoraTxtBx = (TextBox)averiasGrdVw.Rows[i].Cells[2].FindControl("averiaHoraTxtBx"),
                        //            averiaInfraAfectadaTxtBx = (TextBox)averiasGrdVw.Rows[i].Cells[3].FindControl("averiaInfraAfectadaTxtBx"),
                        //            averiaLugarTxtBx = (TextBox)averiasGrdVw.Rows[i].Cells[4].FindControl("averiaLugarTxtBx");

                        //    averiaTituloTxtBx.Text = averias.ElementAt(i).Titulo;

                        //    averiaFechaTxtBx.Text = averias.ElementAt(i).Fecha.Year == 1900
                        //        || averias.ElementAt(i).Fecha.Year == 9999 ? string.Empty
                        //        : averias.ElementAt(i).Fecha.ToShortDateString();

                        //    averiaHoraTxtBx.Text = averias.ElementAt(i).Hora;

                        //    averiaInfraAfectadaTxtBx.Text = averias.ElementAt(i).InfraAfectada;

                        //    averiaLugarTxtBx.Text = averias.ElementAt(i).Lugar;

                        //    //Si hay que crear otro row
                        //    if ((i + 1) != averias.Count)
                        //    {
                        //        if (ViewState["averiaTbl"] != null)
                        //        {
                        //            dtCurrentTable = (DataTable)ViewState["averiaTbl"];

                        //            drCurrentRow = dtCurrentTable.NewRow();

                        //            dtCurrentTable.Rows[i]["titulo"] = averiaTituloTxtBx.Text;

                        //            dtCurrentTable.Rows[i]["fecha"] = averiaFechaTxtBx.Text;

                        //            dtCurrentTable.Rows[i]["hora"] = averiaHoraTxtBx.Text;

                        //            dtCurrentTable.Rows[i]["afectada"] = averiaInfraAfectadaTxtBx.Text;

                        //            dtCurrentTable.Rows[i]["lugar"] = averiaLugarTxtBx.Text;

                        //            dtCurrentTable.Rows.Add(drCurrentRow);

                        //            averiasGrdVw.DataSource = dtCurrentTable;

                        //            averiasGrdVw.DataBind();

                        //            SetPreviousData();
                        //        }
                        //    }

                        //    else
                        //    {
                        //        break;
                        //    }
                        //}

                        primeraExt.Averias = averias;

                        #endregion

                        #region Set visibilities(role)
                        //fechaComienzoDiv.Visible = true;

                        //fechaExpiracionDiv.Visible = true;

                        //docsRequeridosHeader.Visible = false;

                        //docRequeridosTableTag.Visible = false;

                        //docsAsociadosHeader.Visible = true;

                        //docsAsociadosTableTag.Visible = true;

                        #region Display responsables de la solicitud

                        //User currentUser = new SolicitudesInicialesServicio().GetUser(primeraExt.Usuario.Id);

                        User currentUser = user; //new SolicitudesInicialesServicio().GetUser(solicitud.Usuario.Email);

                        tramitadoLbl.Visible = true;

                        tramitadoLbl.Text += string.Format(" {0}", primeraExt.TramitadoPor);

                        //primeraExt.Coordinador.Id = 1; // only test

                        if (!string.IsNullOrWhiteSpace(primeraExt.Coordinador.Nombre))
                        {
                            //Coordinador coordinador = new SolicitudesInicialesServicio().GetCoordinador(primeraExt.Coordinador.Nombre);

                            procesadoLbl.Visible = true;

                            procesadoLbl.Text += string.Format(" {0}", primeraExt.Coordinador.Nombre);

                            //primeraExt.Inspector.NumeroPlacaID = "001"; // only test

                            if (!string.IsNullOrWhiteSpace(primeraExt.Inspector.Nombre))
                            {
                                //Inspector inspector = new SolicitudesInicialesServicio().GetInspector(primeraExt.Inspector.NumeroPlacaID);

                                inspeccionLbl.Visible = true;

                                inspeccionLbl.Text += string.Format(" {0}", primeraExt.Inspector.Nombre);
                            }
                        }

                        #endregion

                        if (primeraExt.EstatusId.Equals(((int)SolicitudAviso.Estatus.Inactiva).ToString())
                           || primeraExt.EstatusId.Equals(((int)SolicitudAviso.Estatus.InspeccionCompletada).ToString())
                           || primeraExt.EstatusId.Equals(((int)SolicitudAviso.Estatus.PendienteAsignarInspector).ToString())
                           || primeraExt.EstatusId.Equals(((int)SolicitudAviso.Estatus.EnProcesoInspeccion).ToString()))
                        {
                            fechaComienzoDiv.Visible = true;

                            fechaComienzoDiv2.Visible = true;

                            fechaExpiracionDiv.Visible = true;

                            fechaExpiracionDiv2.Visible = true;
                        }

                        #endregion

                        fechaComienzoPropuestoTxtBx.Enabled = false;

                        fechaComienzoImgBtn.Visible = false;

                        tipoAvisoRBtnLst.Enabled = false;

                        ////Si la solicitud es inactiva o denegada, no dejas guardar
                        //if (solicitud.EstatusId.Equals(((int)SolicitudAviso.Estatus.Inactiva).ToString())
                        //    || solicitud.EstatusId.Equals(((int)SolicitudAviso.Estatus.Denegada).ToString())
                        //    || solicitud.EstatusId.Equals(((int)SolicitudAviso.Estatus.PendienteAsignarInspector).ToString()))
                        //{
                        //    guardarBtn.Enabled = false;
                        //}

                        //Allow to view extensions if it's inactive and extensions have already been created
                        if (primeraExt.EstatusId.Equals(((int)SolicitudAviso.Estatus.Inactiva).ToString())
                            || primeraExt.EstatusId.Equals(((int)SolicitudAviso.Estatus.Denegada).ToString()))
                        {
                            if (string.IsNullOrWhiteSpace(segundaExt.NumeroControl.NumControlText))
                            {
                                segundaExtensionLink.Visible = false;
                            }
                        }

                        //Don't allow to create extensions if it ain't aprovada
                        else if (!primeraExt.EstatusId.Equals(((int)SolicitudAviso.Estatus.PendienteAsignarInspector).ToString())
                            & !primeraExt.EstatusId.Equals(((int)SolicitudAviso.Estatus.InspeccionCompletada).ToString())
                            & !primeraExt.EstatusId.Equals(((int)SolicitudAviso.Estatus.EnProcesoInspeccion).ToString()))
                        {
                            segundaExtensionLink.Visible = false;
                        } 

                        #endregion
                    }
                }

                catch (Exception ex)
                {
                    errorLbl2.InnerText = ex.Message;

                    errorPopup.Show();
                }
            }

            else
            {
                if (maquinariaChkBx.Checked)
                {
                    tipoMaquinariaTxtBx.Enabled = true;

                    if (!maquinariaUtilizarLbl.Text.Contains("*"))
                    {
                        maquinariaUtilizarLbl.Text += "*";
                    }
                }

                else
                {
                    tipoMaquinariaTxtBx.Enabled = false;

                    maquinariaUtilizarLbl.Text = maquinariaUtilizarLbl.Text.Replace("*", string.Empty);
                }

                if (explosivoChkBx.Checked)
                {
                    licExplosivoTxtBx.Enabled = true;

                    fechaExpiracionExplosivoTxtBx.Enabled = true;

                    if (!licExplosivoLbl.Text.Contains("*"))
                    {
                        licExplosivoLbl.Text += "*";

                        fechaExpiracionExplosivoLbl.Text += "*";
                    }
                }

                else
                {
                    licExplosivoTxtBx.Enabled = false;

                    fechaExpiracionExplosivoTxtBx.Enabled = false;

                    licExplosivoLbl.Text = licExplosivoLbl.Text.Replace("*", string.Empty);

                    fechaExpiracionExplosivoLbl.Text = fechaExpiracionExplosivoLbl.Text.Replace("*", string.Empty);
                }

                //#region Poblar tabla averias
                //LinkedList<Averia> averias = (LinkedList<Averia>)Session["Averias"];

                ////Session["Averias"] = averias;

                //bool rowWasAdded = Session["newRow"] == null ? false : (bool)Session["newRow"];

                //if (averias.Count > 0)
                //{
                //    if (rowWasAdded)
                //    {
                //        #region Update averia obj after postback

                //        DataTable dtCurrentTable = (DataTable)ViewState["averiaTbl"];

                //        DataRow drCurrentRow = null;

                //        dtCurrentTable = SetAveriaRowData(dtCurrentTable, drCurrentRow, false, true);

                //        averias = (LinkedList<Averia>)Session["Averias"];

                //        #endregion
                //    }

                //    if (averiasGrdVw.Rows.Count < 1)
                //    {
                //        DataTable dtCurrentTable = (DataTable)ViewState["averiaTbl"];

                //        averiasGrdVw.DataSource = dtCurrentTable;

                //        averiasGrdVw.DataBind();

                //        SetPreviousData();
                //    }

                //    /*En la primera entrada, asigna los valores al row hecho por default. Verifica si hay que crear otro.
                //     * 
                //     * En la segunda corrida, asigna los valores al row nuevo.
                //     * 
                //     * Sino hay filas(por un postback) las creo y relleno con la data pasada.
                //     * 
                //     * Si hay filas pues las lleno con el obj de averias
                //     */

                //    else
                //        for (int i = 0; i < averias.Count; i++)
                //        {
                //            TextBox averiaTituloTxtBx = (TextBox)averiasGrdVw.Rows[i].Cells[0].FindControl("averiaTituloTxtBx"),
                //                    averiaFechaTxtBx = (TextBox)averiasGrdVw.Rows[i].Cells[1].FindControl("averiaFechaTxtBx"),
                //                    averiaHoraTxtBx = (TextBox)averiasGrdVw.Rows[i].Cells[2].FindControl("averiaHoraTxtBx"),
                //                    averiaInfraAfectadaTxtBx = (TextBox)averiasGrdVw.Rows[i].Cells[3].FindControl("averiaInfraAfectadaTxtBx"),
                //                    averiaLugarTxtBx = (TextBox)averiasGrdVw.Rows[i].Cells[4].FindControl("averiaLugarTxtBx");

                //            averiaTituloTxtBx.Text = averias.ElementAt(i).Titulo;

                //            averiaFechaTxtBx.Text = averias.ElementAt(i).Fecha.Year == 1900
                //                || averias.ElementAt(i).Fecha.Year == 9999 ? string.Empty
                //                : averias.ElementAt(i).Fecha.ToShortDateString();

                //            averiaHoraTxtBx.Text = averias.ElementAt(i).Hora;

                //            averiaInfraAfectadaTxtBx.Text = averias.ElementAt(i).InfraAfectada;

                //            averiaLugarTxtBx.Text = averias.ElementAt(i).Lugar;

                //            //Si hay que crear otro row
                //            //if ((i + 1) != averias.Count)
                //            //{
                //            //    if (ViewState["averiaTbl"] != null)
                //            //    {
                //            //        dtCurrentTable = (DataTable)ViewState["averiaTbl"];

                //            //        drCurrentRow = dtCurrentTable.NewRow();

                //            //        dtCurrentTable.Rows[i]["titulo"] = averiaTituloTxtBx.Text;

                //            //        dtCurrentTable.Rows[i]["fecha"] = averiaFechaTxtBx.Text;

                //            //        dtCurrentTable.Rows[i]["hora"] = averiaHoraTxtBx.Text;

                //            //        dtCurrentTable.Rows[i]["afectada"] = averiaInfraAfectadaTxtBx.Text;

                //            //        dtCurrentTable.Rows[i]["lugar"] = averiaLugarTxtBx.Text;

                //            //        dtCurrentTable.Rows.Add(drCurrentRow);

                //            //        averiasGrdVw.DataSource = dtCurrentTable;

                //            //        averiasGrdVw.DataBind();

                //            //        SetPreviousData();
                //            //    }
                //            //}

                //            //else
                //            //{
                //            //    break;
                //            //}
                //        }

                //    Session["newRow"] = false;
                //}

                ////solicitud.Averias = averias;

                //#endregion

                #region Set doc controls on postback
                LinkedList<DocumentoRequerido> docsRequeridos = (LinkedList<DocumentoRequerido>)Session["docsRequeridos"];

                if (docsRequeridos != null)
                {
                    CreateDocAsociadosCtrl(docsRequeridos);

                    CreateDocReqCtrls(docsRequeridos);
                }
                #endregion
            }
        }
Exemple #5
0
        protected void GuardarBtnClick(object sender, EventArgs e)
        {
            User user = Session["UserObj"] == null ? new User() : (User)Session["UserObj"];

            string exceptionMsg = string.Empty;

            guardarBtn.Enabled = false;

            NumeroControl exceptionNumControl = new NumeroControl();

            try
            {
                #region Validate controls server side

                /* Los valido desde aca por que algunos controles se vuelven requeridos cuando obtienen input
                 * y seria muy trabajoso hacerle el bind con un rqf a cada uno. Ademas que, algunos no funcionan 
                 * bien con el rqf
                 */

                //Quizas en vez de esta vali, le pongo en requiredfield y si esta checked que se ponga enabled
                if (maquinariaChkBx.Checked)
                {
                    exceptionMsg = ValidateStrings(tipoMaquinariaTxtBx.Text, "Tipo de maquinaria, requerida");
                }

                if (explosivoChkBx.Checked)
                {
                    exceptionMsg += ValidateStrings(licExplosivoTxtBx.Text, "Licencia explosivo, requerida");

                    exceptionMsg += ValidateStrings(fechaExpiracionExplosivoTxtBx.Text, "Fecha expiración Licencia explosivo, requerida");
                }

                if (string.IsNullOrEmpty(duracionDiaTxtBx.Text)
                    && string.IsNullOrEmpty(duracionMesTxtBx.Text)
                    && string.IsNullOrEmpty(duracionYearTxtBx.Text))
                {
                    //throw new Exception("Duración, requerida");

                    exceptionMsg += "Duración, requerida \r\n";
                }

                //#region Docs

                //foreach (var t in docRequeridosTxtBxs)
                //{
                //    if (string.IsNullOrWhiteSpace(t.Text))
                //    {
                //        exceptionMsg += t.ID.Replace("TxtBx", string.Empty) + ", requerido </br>";
                //    }
                //}

                //#endregion

                //if (!string.IsNullOrWhiteSpace(exceptionMsg))
                //{
                //    throw new Exception(exceptionMsg);
                //}

                #endregion

                #region Genera numero Control

                NumeroControl numeroControlExistente = new NumerosControlServicio().GetNumeroControl(DateTime.Now.Year),
                    numeroControl = new NumeroControl()
                    {
                        //NumControlText = "2015-0016" // only for testing

                        NumControlText = Request.QueryString["NumeroControl"]
                    };

                #endregion

                Boolean zona = zonaRBtnLst.SelectedValue.Equals("Urbana"),
                    tipoExcavacion = tipoExcavacionRBtnLst.SelectedValue.Equals("Continua");

                #region Poblar averias
                LinkedList<Averia> averias = new LinkedList<Averia>(),
                    averiasExistentes = new AveriasServicio().GetAverias(numeroControl, (int)SolicitudAviso.TiposExtensiones.Primera);

                averias.AddLast(new Averia()
                {
                    Titulo = averiasTxtBx.Text,

                    ExtensionId = (int)SolicitudAviso.TiposExtensiones.Primera
                });

                //for (int i = 0; i < averiasGrdVw.Rows.Count; i++)
                //{
                //    TextBox averiaTituloTxtBx = (TextBox)averiasGrdVw.Rows[i].Cells[0].FindControl("averiaTituloTxtBx"),
                //                averiaFechaTxtBx = (TextBox)averiasGrdVw.Rows[i].Cells[1].FindControl("averiaFechaTxtBx"),
                //                averiaHoraTxtBx = (TextBox)averiasGrdVw.Rows[i].Cells[2].FindControl("averiaHoraTxtBx"),
                //                averiaInfraAfectadaTxtBx = (TextBox)averiasGrdVw.Rows[i].Cells[3].FindControl("averiaInfraAfectadaTxtBx"),
                //                averiaLugarTxtBx = (TextBox)averiasGrdVw.Rows[i].Cells[4].FindControl("averiaLugarTxtBx");


                //}

                #endregion

                #region Poblar docs

                LinkedList<DocumentoRequerido> documentos = new LinkedList<DocumentoRequerido>(),
                    docsExistentes = new DocumentosRequeridosServicio().GetDocumentosAsociados(numeroControl, (int)SolicitudAviso.TiposExtensiones.Primera);

                Dictionary<TextBox, DropDownList> docControls = new Dictionary<TextBox, DropDownList>();

                docControls = GetDocCtrls();

                //#region Docs

                //for (int i = 0; i < docRequeridosTxtBxs.Count; i++)
                //{
                //    DocumentoRequerido docReq = new DocumentoRequerido()
                //    {
                //        Nombre = docRequeridosTxtBxs.ElementAt(i).ID.Replace("TxtBx", string.Empty),

                //        NumeroControl = numeroControl,

                //        Path = docRequeridosTxtBxs.ElementAt(i).Text,

                //        Tipo = tipoAvisoRBtnLst.SelectedIndex,

                //        ExtensionId = (int)SolicitudAviso.TiposExtensiones.Primera
                //    };

                //    if (docAsociadosStatuses.Count() > 0)
                //    {
                //        docReq.Status = docAsociadosStatuses.ElementAt(i).SelectedIndex;
                //    }

                //    documentos.AddLast(docReq);
                //}

                //#endregion

                #endregion

                //User currentUser = new SolicitudesInicialesServicio().GetUser(Convert.ToInt32(Request.QueryString["userId"])); 

                //User currentUser = new SolicitudesInicialesServicio().GetUser(Request.QueryString["CorreoElectronico"].Replace("%40", "@")); 

                //User currentUser = user; // only for testinng

                User currentUser = new SolicitudesInicialesServicio().GetUser(user.Email);

                SolicitudAviso primeraExtExistente = new PrimerasExtensionesServicio().GetPrimeraExtension(numeroControl);

                #region Poblar solicitud

                SolicitudAviso solicitud
                        = new SolicitudAviso()
                        {
                            #region Info general

                            NumeroControl = numeroControl,

                            Emergencia = emergenciaChkBx.Checked,

                            TipoAviso = tipoAvisoRBtnLst.SelectedIndex.ToString(),

                            //EstatusId = statusHF.Value,

                            NombreContacto = nombreContactoTxtBx.Text.ToUpper(),

                            CelularContacto = celularContactoTxtBx.Text.ToUpper(),

                            DireccionPostalContacto = direccionPostalContactoTxtBx.Text.ToUpper(),

                            #endregion

                            #region Contratista

                            NombreEmpresa = companyDDL.SelectedValue,

                            AreaDept = areaDepartamentoTxtBx.Text.ToUpper(),

                            RepresentanteAutorizado = representanteTxtBx.Text.ToUpper(),

                            TelOficina = telOficinaTxtBx.Text.ToUpper(),

                            TelCampoTrabajo = telTrabajoTxtBx.Text.ToUpper(),

                            TelCelular = celularTxtBx.Text.ToUpper(),

                            CorreoElectronico = emailTxtBx.Text.ToUpper(),

                            DireccionPostal = direccionTxtBx.Text,

                            MunicipioId = municipioDDL.SelectedIndex,

                            CodigoPostal = codigoPostalTxtBx.Text.ToUpper(),

                            #endregion

                            #region Sub

                            Subcontratista = companySubTxtBx.Text,

                            AreaDeptSub = areaDepartamentoSubTxtBx.Text.ToUpper(),

                            RepresentanteAutorizadoSub = representanteSubTxtBx.Text.ToUpper(),

                            TelOficinaSub = telOficinaSubTxtBx.Text.ToUpper(),

                            TelCampoTrabajoSub = telTrabajoSubTxtBx.Text.ToUpper(),

                            TelCelularSub = celularSubTxtBx.Text.ToUpper(),

                            CorreoElectronicoSub = emailSubTxtBx.Text,

                            DireccionPostalSub = direccionSubTxtBx.Text.ToUpper(),

                            MunicipioIdSub = municipioSubDDL.SelectedIndex,

                            CodigoPostalSub = codigoPostalSubTxtBx.Text.ToUpper(),

                            #endregion

                            #region Info trabajo

                            Zona = zona,

                            BoUrb = boUrbTxtBx.Text.ToUpper(),

                            SectorCalle = sectorCalleTxtBx.Text.ToUpper(),

                            Carretera = carreteraTxtBx.Text.ToUpper(),

                            MunicipioIdTrab = municipioTrabajoDDL.SelectedIndex,

                            KM = Convert.ToInt32(kmTxtBx.Text),

                            HM = Convert.ToInt32(hmTxtBx.Text),

                            Referencias = referenciasTxtBx.Text.ToUpper(),

                            RazonTrabajos = razonTxtBx.Text.ToUpper(),

                            FechaPropuesta = Convert.ToDateTime(fechaComienzoPropuestoTxtBx.Text),

                            FechaComienzo = string.IsNullOrWhiteSpace(fechaComienzoTxtBx.Text)
                    ? new DateTime(1900, 01, 01) : Convert.ToDateTime(fechaComienzoTxtBx.Text),

                            FechaExpiracion = string.IsNullOrWhiteSpace(fechaExpiracionTxtBx.Text)
                            ? new DateTime(1900, 01, 01) : Convert.ToDateTime(fechaExpiracionTxtBx.Text),

                            TiempoDuracion = string.Format("{0}-{1}-{2}", duracionDiaTxtBx.Text
                                                          , duracionMesTxtBx.Text, duracionYearTxtBx.Text),

                            Horario = string.Format("{0}-{1}", horarioDDL.SelectedValue, horarioDDL2.SelectedValue),

                            Maquinaria = maquinariaChkBx.Checked,

                            TipoMaquinaria = tipoMaquinariaTxtBx.Text.ToUpper(),

                            Explosivos = explosivoChkBx.Checked,

                            LicenciaExplosivo = licExplosivoTxtBx.Text.ToUpper(),

                            FechaExpiracionExplosivo = !string.IsNullOrWhiteSpace(fechaExpiracionExplosivoTxtBx.Text)
                            ? Convert.ToDateTime(fechaExpiracionExplosivoTxtBx.Text)
                            : Convert.ToDateTime(@"01/01/1900"),

                            AreaMarcada = areaMarcadaChkBx.Checked,

                            TipoExcavacion = tipoExcavacion,

                            ProfundidadPies = Convert.ToInt32(profundidadPiesTxtBx.Text),

                            ProfundidadPulgadas = profundidadPulgadasDLL.SelectedIndex,

                            LongitudPies = Convert.ToInt32(longitudPiesTxtBx.Text),

                            LongitudPulgadas = longitudPulgadasDDL.SelectedIndex,

                            CoordenadaX = decimal.Parse(coordenadasXTxtBx.Text),

                            CoordenadaY = decimal.Parse(coordenadasYTxtBx.Text),

                            EnCasoEmergencia = enCasoEmergenciaTxtBx.Text.ToUpper(),

                            //TramitadoPor = currentUser.NombreCompleto,

                            //FechaTramite = DateTime.Now,

                            #endregion

                            Documentos = documentos,

                            ExtensionID = (int)SolicitudAviso.TiposExtensiones.Primera                         

                            //Usuario = new User()
                            //{
                            //    Email = currentUser.Email,

                            ////    NombreCompleto = currentUser.Nombre + " " + currentUser.Inicial + " "
                            ////    + currentUser.ApellidoPaterno + " " + currentUser.ApellidoMaterno
                            //}
                        };

                solicitud.EstatusId = string.Format("{0}{1}", solicitud.LetraStatus, statusHF.Value);

                #endregion

                LinkedList<Mail> mails = new MailServicio().GetMailMsgs();

                #region Create / Edit

                if (String.IsNullOrEmpty(primeraExtExistente.NumeroControl.NumControlText))
                {
                    #region Create

                    #region validate docs

                    LinkedList<FileUpload> _docRequeridosFileUpload = new LinkedList<FileUpload>();

                    var files = Request.Files;

                    LinkedList<FileUpload> docRequeridosFileUpload = (LinkedList<FileUpload>)Session["docRequeridosFileUpload"];

                    foreach (var t in docRequeridosFileUpload)
                    {
                        _docRequeridosFileUpload.AddLast((FileUpload)docRequeridosMainDiv.FindControl(t.ID));

                        //if (!t.HasFile)
                        //{
                        //    exceptionMsg += t.ID.Replace("fileUp", string.Empty) + ", requerido </br>";
                        //}
                    }

                    foreach (var d in _docRequeridosFileUpload)
                    {
                        if (!d.HasFile)
                        {
                            exceptionMsg += d.ID.Replace("fileUp", string.Empty) + ", requerido </br>";
                        }
                    }

                    if (!string.IsNullOrWhiteSpace(exceptionMsg))
                    {
                        throw new Exception(exceptionMsg);
                    }

                    #endregion

                    #region Docs

                    for (int i = 0; i < _docRequeridosFileUpload.Count; i++)
                    {
                        DocumentoRequerido docReq = new DocumentoRequerido()
                        {
                            Nombre = _docRequeridosFileUpload.ElementAt(i).ID.Replace("fileUp", string.Empty),

                            NumeroControl = numeroControl,

                            Path = string.Format("{0}/{1}/{2}_{3}", new DocumentoRequerido().DocumentosPrimerasSavePath, user.Email
                            , numeroControl.NumControlText, Path.GetFileName(_docRequeridosFileUpload.ElementAt(i).PostedFile.FileName)),

                            Tipo = tipoAvisoRBtnLst.SelectedIndex,

                            ExtensionId = (int)SolicitudAviso.TiposExtensiones.Primera
                        };

                        //LinkedList<DropDownList> docAsociadosStatuses = (LinkedList<DropDownList>)Session["docAsociadosStatusesExt"];

                        //if (docAsociadosStatuses != null)
                        //{
                        //    docReq.Status = docAsociadosStatuses.ElementAt(i).SelectedIndex;
                        //}

                        documentos.AddLast(docReq);

                        #region Create aviso dir

                        ////DirectoryInfo dirInfo = new DirectoryInfo(string.Format("{0}/{1}", documentos.ElementAt(i).Path
                        ////, numeroControl.NumControlText));

                        //DirectoryInfo dirInfo = new DirectoryInfo(documentos.ElementAt(i).Path),
                        //    subDirInfo = new DirectoryInfo(string.Format("{0}/{1}", documentos.ElementAt(i).Path, numeroControl.NumControlText));

                        //if (!subDirInfo.Exists)
                        //{
                        //    dirInfo.CreateSubdirectory(string.Format("{0}/{1}", documentos.ElementAt(i).Path, numeroControl.NumControlText));
                        //}
                        #endregion
                    }

                    #endregion

                    exceptionNumControl = solicitud.NumeroControl;

                    averias = SetAveriasNumControl(averias, numeroControl);

                    documentos = SetDocumentsNumControl(documentos, numeroControl);

                    solicitud.EstatusId = string.Format("{0}{1}", solicitud.LetraStatus, ((int)SolicitudAviso.Estatus.PendienteRevisarCoordinador).ToString());

                    //info de la empresa
                    solicitud.Usuario = new User()
                    {
                        Email = currentUser.Email,

                        NombreCompleto = currentUser.Nombre + " " + currentUser.Inicial + " "
                    + currentUser.ApellidoPaterno + " " + currentUser.ApellidoMaterno
                    };

                    solicitud.TramitadoPor = solicitud.Usuario.NombreCompleto;

                    solicitud.FechaTramite = DateTime.Now;

                    new DocumentosRequeridosServicio().TryCreate(documentos);

                    new AveriasServicio().TryCreate(averias);

                    new PrimerasExtensionesServicio().TryCreate(solicitud);

                    SaveDocs(_docRequeridosFileUpload, documentos);

                    #region Email coordinadores
                    LinkedList<string> to = new LinkedList<string>();

                    LinkedList<User> coordinadores = new SolicitudesInicialesServicio().GetCoordinadores(),
                    superInspectores = new SolicitudesInicialesServicio().GetSuperInspectores(),
                        directores = new SolicitudesInicialesServicio().GetDirectores();

                    for (int i = 0; i < coordinadores.Count; i++)
                    {
                        to.AddLast(coordinadores.ElementAt(i).Email);
                    }

                    for (int i = 0; i < superInspectores.Count; i++)
                    {
                        to.AddLast(superInspectores.ElementAt(i).Email);
                    }

                    for (int i = 0; i < directores.Count; i++)
                    {
                        to.AddLast(directores.ElementAt(i).Email);
                    }

                    //to = new LinkedList<string>();

                    //Uncomment when intergrating

                    //to.AddLast(currentUser.Email);

                    //SendEmail(to, "", "", ""); 

                    //to.AddLast("*****@*****.**"); //only test

                    try
                    {
                        if (CheckForInternetConnection())
                            SendEmail(to, "*****@*****.**",
                            mails.ElementAt((int)Mail.Notifications.ExtensionNueva).Subject,
                            mails.ElementAt((int)Mail.Notifications.ExtensionNueva).Body.Replace(
                            "@NumControl", numeroControl.NumControlText).Replace("@NombreEmpresa", solicitud.NombreEmpresa), new LinkedList<string>()); // only test
                    }

                    catch (Exception ex)
                    { } 
                    #endregion

                    #endregion
                }

                else
                {
                    #region Edit

                    exceptionNumControl = solicitud.NumeroControl;

                    //Remove estatus letra
                    solicitud.EstatusId = solicitud.EstatusId.Replace(solicitud.LetraStatus, string.Empty).Replace(new Inspeccion().LetraStatus, string.Empty);

                    LinkedList<string> to = new LinkedList<string>();

                    //to.AddLast("*****@*****.**"); //only test

                    to.AddLast(user.Email);

                    #region Actualiza status solicitud

                    if ((Convert.ToInt32(solicitud.EstatusId)) == ((int)SolicitudAviso.Estatus.PendienteRevisarCoordinador))
                    {
                        if (string.IsNullOrWhiteSpace(solicitud.Coordinador.Nombre))
                        {
                            solicitud.Coordinador.Nombre = string.Format("{0} {1} {2}", currentUser.Nombre, currentUser.ApellidoPaterno, currentUser.ApellidoMaterno);
                        }

                        solicitud.EstatusId = GenerateStatus(ref docsExistentes).ToString();

                        documentos = docsExistentes;

                        if (solicitud.EstatusId.Equals(((int)SolicitudAviso.Estatus.PendienteAsignarInspector).ToString()))
                        {
                            //solicitud.FechaRespuestaSolicitadas = DateTime.Now.ToShortDateString();

                            SolicitudAviso solicitudIncial = new SolicitudesInicialesServicio().GetSolicitud(numeroControl);

                            solicitud.FechaComienzo = ValidarFecha(solicitudIncial.FechaComienzo);

                            solicitud.FechaExpiracion = solicitud.FechaComienzo.AddDays(60);

                            Company company = new SolicitudesInicialesServicio().GetCompany(companyDDL.SelectedValue);

                            #region Poblar hoja inspeccion

                            Inspeccion inspeccion = new Inspeccion()
                            {
                                EstatusInspeccionID = "1",

                                TipoInspeccionID = "1",

                                NumeroInspeccion = solicitud.NumeroControl.NumControlText,

                                //ExtensionID = (int)SolicitudAviso.TiposExtensiones.Primera,

                                NumeroPlacaID = "000",

                                NumeroControl = new NumeroControl()
                                {
                                    NumControl = solicitud.NumeroControl.NumControl,

                                    Year = solicitud.NumeroControl.Year,

                                    NumControlText = solicitud.NumeroControl.NumControlText
                                },

                                NombreEmpresa = solicitud.NombreEmpresa,

                                RepresentateAutorizado = solicitud.RepresentanteAutorizado,

                                CorreoElectronico = solicitud.CorreoElectronico,

                                DireccionPostal = solicitud.DireccionPostal,

                                DireccionFisica = company.DireccionFisica,

                                TelOficina = solicitud.TelOficina,

                                TelTrabajo = solicitud.TelCampoTrabajo,

                                Celular = solicitud.TelCelular,

                                TipoAviso = ((int)SolicitudAviso.TiposExtensiones.Primera).ToString(),

                                TipoTrabajo = solicitud.TipoAviso,

                                FechaComienzo = solicitud.FechaComienzo,

                                FechaExpiracion = solicitud.FechaExpiracion,

                                LongitudPies = solicitud.LongitudPies,

                                LongitudPulgadas = solicitud.LongitudPulgadas,

                                ProfundidadPies = solicitud.ProfundidadPies,

                                ProfundidadPulgadas = solicitud.ProfundidadPulgadas,

                                CoordenadaX = float.Parse(solicitud.CoordenadaX.ToString()),

                                CoordenadaY = float.Parse(solicitud.CoordenadaY.ToString()),

                                RazonTrabajos = solicitud.RazonTrabajos,

                                Zona = solicitud.Zona,

                                BoUrbT = solicitud.BoUrb,

                                SectorCalleT = solicitud.SectorCalle,

                                CarreteraT = solicitud.Carretera,

                                KM = solicitud.KM,

                                HM = solicitud.HM,

                                MunicipioT = municipioTrabajoDDL.SelectedValue,
                            };

                            #endregion

                            new InspeccionesServicio().TryCrear(inspeccion);

                            ViewState["justCreatedInspeccion"] = true;

                            //throw new Exception("inspeccion error test");

                            #region Enviar email excavador
                            //currentUser = new SolicitudesInicialesServicio().GetUser(solicitud.Usuario.Id);

                            // User currentUser = new SolicitudesInicialesServicio().GetUser(solicitud.Usuario.Email);

                            //to = new LinkedList<string>();

                            //to.AddLast(currentUser.Email);

                            //SendEmail(to, "", "", ""); LinkedList<string> attachment = new LinkedList<string>();

                            LinkedList<string> attachment = new LinkedList<string>();

                            #region pdf stuff

                            Document doc = new Document(PageSize.LETTER, 0f, 0f, 0f, 0f);

                            String Fecha = DateTime.Now.ToString();

                            iTextSharp.text.Font NormalFont = FontFactory.GetFont("Arial", 12, Font.NORMAL, Color.BLACK);
                            using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
                            {
                                PdfWriter writer = PdfWriter.GetInstance(doc, memoryStream);
                                Phrase phrase = null;
                                PdfPCell cell = null;
                                PdfPCell b = new PdfPCell(new Phrase(" "));
                                PdfPTable table = null;
                                //Color color = null;
                                //PdfPCell imageCell = new PdfPCell(Check);
                                PdfPCell uncheck = ImageCell("~/Images/uncheck4.png", 2f, PdfPCell.ALIGN_CENTER);
                                PdfPCell check = ImageCell("~/Images/Check4.png", 2f, PdfPCell.ALIGN_CENTER);
                                PdfPCell cbox = check,
                                         signatureImgCell = ImageCell(string.Format("~/Images/Documentos/Firmas/{0}_Firma.png", user.Email), 50f, PdfPCell.ALIGN_CENTER);
                                DateTime datevalue = (Convert.ToDateTime(Fecha.ToString()));
                                Fecha = datevalue.ToString("MM/dd/yyyy");

                                String[] mes = { "ENERO", "FEBRERO", "MARZO", "ABRIL", "MAYO", "JUNIO", "JULIO", "AGOSTO", "SEPTIEMBRE", "OCTUBRE", "NOVIEMBRE", "DICIEMBRE" };
                                String FechaLetras = datevalue.Day.ToString() + " DE " + mes[datevalue.Month - 1] + " DE " + datevalue.Year.ToString();

                                doc.Open();

                                #region Header
                                Paragraph p = new Paragraph("DTOP-          09/15                                              \n\n", FontFactory.GetFont("Arial", 8, Font.NORMAL, Color.BLACK));
                                p.Alignment = Element.ALIGN_RIGHT;
                                doc.Add(p);

                                //Header Table
                                table = new PdfPTable(3);

                                //Header Data
                                cell = ImageCell("~/images/EscudoPR.png", 40f, PdfPCell.ALIGN_LEFT);
                                cell.Border = 0;
                                table.AddCell(cell);
                                cell = new PdfPCell(new Phrase(" "));
                                cell.Border = 0;
                                table.AddCell(cell);
                                phrase = new Phrase();
                                phrase.Add(new Chunk("\n\nNÚMERO DE AVISO:\n", FontFactory.GetFont("Arial", 8, Font.NORMAL, Color.BLACK)));
                                phrase.Add(new Chunk("DEDT-" + solicitud.NumeroControl.NumControlText, FontFactory.GetFont("Arial", 16, Font.BOLD, Color.RED)));

                                cell = PhraseCell(phrase, PdfPCell.ALIGN_CENTER);
                                cell.BorderColorLeft = Color.BLACK;
                                cell.BorderColorRight = Color.BLACK;
                                cell.BorderColorTop = Color.BLACK;
                                cell.BorderColorBottom = Color.BLACK;
                                cell.BorderWidthLeft = 1f;
                                cell.BorderWidthRight = 1f;
                                cell.BorderWidthTop = 1f;
                                cell.BorderWidthBottom = 1f;
                                cell.Border = Rectangle.BOX;
                                table.AddCell(cell);

                                cell = new PdfPCell(new Phrase(" "));
                                cell.Colspan = 3;
                                SetBorder(cell, false, false, false, false);
                                table.AddCell(cell);

                                doc.Add(table);

                                p = new Paragraph("DIRECTORÍA DE EXCAVACIONES, DEMOLICIONES Y TUBERÍAS", FontFactory.GetFont("Arial", 14, Font.NORMAL, Color.BLACK));
                                p.Alignment = Element.ALIGN_CENTER;
                                doc.Add(p);

                                p = new Paragraph("CENTRO DE COORDINACIÓN DE EXCAVACIONES Y DEMOLICIONES", FontFactory.GetFont("Arial", 14, Font.NORMAL, Color.BLACK));
                                p.Alignment = Element.ALIGN_CENTER;
                                doc.Add(p);

                                p = new Paragraph("CERTIFICACIÓN DE TRÁMITE DE AVISO DE EXCAVACIÓN Y/O DEMOLICIÓN\n\n", FontFactory.GetFont("Arial", 14, Font.BOLD, Color.BLACK));
                                p.Alignment = Element.ALIGN_CENTER;
                                doc.Add(p);

                                /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                                table = new PdfPTable(7);
                                table.SetWidths(new float[] { 1.0f, 0.5f, 3.5f, 1.5f, 0.2f, 0.4f, 0.1f });

                                cell = new PdfPCell(new Phrase(""));
                                cell.Colspan = 7;
                                SetBorder(cell, true, true, true, false);
                                table.AddCell(cell);
                                ////////////////////
                                cell = new PdfPCell(new Phrase("EMERGENCIA", FontFactory.GetFont("Arial", 9, Font.NORMAL, Color.BLACK)));
                                SetBorder(cell, true, false, false, false);
                                table.AddCell(cell);

                                cbox = uncheck;
                                if (solicitud.Emergencia)
                                    cbox = check;
                                SetBorder(cell, false, false, false, false);
                                table.AddCell(cbox);

                                cell = new PdfPCell(new Phrase("FECHA DE PRESENTACIÓN:", FontFactory.GetFont("Arial", 9, Font.NORMAL, Color.BLACK)));
                                cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                                SetBorder(cell, false, false, false, false);
                                table.AddCell(cell);

                                cell = new PdfPCell(new Phrase("AVISO INICIAL", FontFactory.GetFont("Arial", 9, Font.NORMAL, Color.BLACK)));
                                cell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                                SetBorder(cell, false, false, false, false);
                                table.AddCell(cell);

                                cell = new PdfPCell(new Phrase(""));
                                SetBorder(cell, false, false, false, false);
                                table.AddCell(cell);

                                cbox = uncheck;
                                if (solicitud.ExtensionID == (int)SolicitudAviso.TiposExtensiones.Inicial)
                                    cbox = check;
                                SetBorder(cell, false, false, false, false);
                                table.AddCell(cbox);

                                cell = new PdfPCell(new Phrase(""));
                                SetBorder(cell, false, false, true, false);
                                table.AddCell(cell);

                                //////////////////////////////////////////

                                cell = new PdfPCell(new Phrase("EXCAVACIÓN", FontFactory.GetFont("Arial", 9, Font.NORMAL, Color.BLACK)));
                                SetBorder(cell, true, false, false, false);
                                table.AddCell(cell);

                                cbox = uncheck;
                                if (solicitud.TipoAviso.Equals(((int)SolicitudAviso.TiposAvisos.Excavacion).ToString()))
                                    cbox = check;
                                SetBorder(cell, false, false, false, false);
                                table.AddCell(cbox);

                                cell = new PdfPCell(new Phrase(FechaLetras, FontFactory.GetFont("Arial", 12, Font.BOLD, Color.BLACK)));
                                cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                                SetBorder(cell, false, false, false, false);
                                table.AddCell(cell);

                                cell = new PdfPCell(new Phrase("1RA EXTENSIÓN", FontFactory.GetFont("Arial", 9, Font.NORMAL, Color.BLACK)));
                                cell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                                SetBorder(cell, false, false, false, false);
                                table.AddCell(cell);

                                cell = new PdfPCell(new Phrase(""));
                                SetBorder(cell, false, false, false, false);
                                table.AddCell(cell);

                                cbox = uncheck;
                                if (solicitud.ExtensionID == (int)SolicitudAviso.TiposExtensiones.Primera)
                                    cbox = check;
                                SetBorder(cell, false, false, false, false);
                                table.AddCell(cbox);

                                cell = new PdfPCell(new Phrase(""));
                                SetBorder(cell, false, false, true, false);
                                table.AddCell(cell);

                                ///////////////////

                                cell = new PdfPCell(new Phrase("DEMOLICIÓN", FontFactory.GetFont("Arial", 9, Font.NORMAL, Color.BLACK)));
                                SetBorder(cell, true, false, false, false);
                                table.AddCell(cell);

                                cbox = uncheck;
                                if (solicitud.TipoAviso.Equals(((int)SolicitudAviso.TiposAvisos.Demolicion).ToString()))
                                    cbox = check;
                                SetBorder(cell, false, false, false, false);
                                table.AddCell(cbox);

                                cell = new PdfPCell(new Phrase(" "));
                                SetBorder(cell, false, false, false, false);
                                table.AddCell(cell);

                                cell = new PdfPCell(new Phrase("2RA EXTENSIÓN", FontFactory.GetFont("Arial", 9, Font.NORMAL, Color.BLACK)));
                                cell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                                SetBorder(cell, false, false, false, false);
                                table.AddCell(cell);

                                cell = new PdfPCell(new Phrase(" "));
                                SetBorder(cell, false, false, false, false);
                                table.AddCell(cell);

                                cbox = uncheck;
                                if (solicitud.ExtensionID == (int)SolicitudAviso.TiposExtensiones.Segunda)
                                    cbox = check;
                                SetBorder(cell, false, false, false, false);
                                table.AddCell(cbox);

                                cell = new PdfPCell(new Phrase(" "));
                                SetBorder(cell, false, false, true, false);
                                table.AddCell(cell);

                                //////////////////

                                cell = new PdfPCell(new Phrase("RESIDENCIAL", FontFactory.GetFont("Arial", 9, Font.NORMAL, Color.BLACK)));
                                SetBorder(cell, true, false, false, false);
                                table.AddCell(cell);

                                cbox = uncheck;
                                if (solicitud.TipoAviso.Equals(((int)SolicitudAviso.TiposAvisos.Residencial).ToString()))
                                    cbox = check;
                                SetBorder(cell, false, false, false, false);
                                table.AddCell(cbox);

                                //cell = new PdfPCell(new Phrase("", FontFactory.GetFont("Arial", 9, Font.NORMAL, Color.BLACK)));
                                //cell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                                //SetBorder(cell, false, false, false, false);
                                //table.AddCell(cell);

                                cell = new PdfPCell(new Phrase(" "));
                                SetBorder(cell, false, false, false, false);
                                table.AddCell(cell);

                                cell = new PdfPCell(new Phrase(" "));
                                SetBorder(cell, false, false, false, false);
                                table.AddCell(cell);

                                /////////////////////////

                                cell = new PdfPCell(new Phrase(""));
                                cell.Colspan = 7;
                                SetBorder(cell, true, false, true, true);
                                table.AddCell(cell);

                                cell = new PdfPCell(new Phrase(""));
                                cell.Colspan = 7;
                                SetBorder(cell, false, false, false, false);
                                table.AddCell(cell);

                                doc.Add(table);
                                #endregion

                                //Información del Solicitante----------------------------------------------------------------------------------------------------------
                                #region Info solicitante
                                table = new PdfPTable(20);

                                cell = new PdfPCell(new Phrase("INFORMACIÓN DEL SOLICITANTE:", FontFactory.GetFont("Arial", 11, Font.BOLD, Color.BLACK)));
                                cell.Colspan = 20;
                                SetBorder(cell, true, true, true, false);
                                table.AddCell(cell);

                                cell = new PdfPCell(new Phrase(""));
                                cell.Colspan = 20;
                                SetBorder(cell, true, false, true, false);
                                table.AddCell(cell);

                                cell = new PdfPCell(new Phrase("NOMBRE DE LA COMPAÑÍA:", FontFactory.GetFont("Arial", 9, Font.BOLD, Color.BLACK)));
                                cell.Colspan = 6;
                                SetBorder(cell, true, false, false, false);
                                table.AddCell(cell);
                                cell = new PdfPCell(new Phrase(solicitud.NombreEmpresa, FontFactory.GetFont("Arial", 9, Font.NORMAL, Color.BLACK)));
                                cell.Colspan = 14;
                                SetBorder(cell, false, false, true, false);
                                table.AddCell(cell);

                                cell = new PdfPCell(new Phrase("PERSONA CONTACTO:", FontFactory.GetFont("Arial", 9, Font.BOLD, Color.BLACK)));
                                cell.Colspan = 5;
                                SetBorder(cell, true, false, false, false);
                                table.AddCell(cell);
                                cell = new PdfPCell(new Phrase(solicitud.NombreContacto, FontFactory.GetFont("Arial", 9, Font.NORMAL, Color.BLACK)));
                                cell.Colspan = 8;
                                SetBorder(cell, false, false, false, false);
                                table.AddCell(cell);

                                cell = new PdfPCell(new Phrase("TEL / CELULAR:", FontFactory.GetFont("Arial", 9, Font.BOLD, Color.BLACK)));
                                cell.Colspan = 4;
                                SetBorder(cell, false, false, false, false);
                                table.AddCell(cell);
                                cell = new PdfPCell(new Phrase(solicitud.CelularContacto, FontFactory.GetFont("Arial", 9, Font.NORMAL, Color.BLACK)));
                                cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                                cell.Colspan = 3;
                                SetBorder(cell, false, false, true, false);
                                table.AddCell(cell);

                                cell = new PdfPCell(new Phrase(""));
                                cell.Colspan = 20;
                                SetBorder(cell, true, false, true, false);
                                table.AddCell(cell);

                                cell = new PdfPCell(new Phrase("DIRECCIÓN DONDE SE REALIZARÁ LA EXCAVACIÓN Y/O DEMOLICIÓN:", FontFactory.GetFont("Arial", 9, Font.BOLD, Color.BLACK)));
                                cell.Colspan = 20;
                                SetBorder(cell, true, false, true, false);
                                table.AddCell(cell);

                                cell = new PdfPCell(new Phrase(solicitud.BoUrb + ", " + solicitud.SectorCalle + ", " + solicitud.Carretera + ", "
                                    + solicitud.MunicipioId, FontFactory.GetFont("Arial", 9, Font.NORMAL, Color.BLACK)));
                                cell.Colspan = 20;
                                SetBorder(cell, true, false, true, false);
                                table.AddCell(cell);
                                cell = new PdfPCell(new Phrase(" "));
                                cell.Colspan = 20;
                                SetBorder(cell, true, false, true, false);
                                table.AddCell(cell);
                                cell.Colspan = 20;
                                SetBorder(cell, true, false, true, true);
                                table.AddCell(cell);

                                cell = new PdfPCell(new Phrase(""));
                                cell.Colspan = 20;
                                SetBorder(cell, false, false, false, false);
                                table.AddCell(cell);

                                doc.Add(table);

                                #endregion

                                //----Información del Subcontratista---------------------------------------------------------------------------------------------------------------------------------------------------
                                #region Info Sub
                                table = new PdfPTable(20);

                                cell = new PdfPCell(new Phrase("INFORMACIÓN DEL SUBCONTRATISTA:", FontFactory.GetFont("Arial", 11, Font.BOLD, Color.BLACK)));
                                cell.Colspan = 20;
                                SetBorder(cell, true, true, true, false);
                                table.AddCell(cell);

                                cell = new PdfPCell(new Phrase(""));
                                cell.Colspan = 20;
                                SetBorder(cell, true, false, true, false);
                                table.AddCell(cell);

                                cell = new PdfPCell(new Phrase("NOMBRE DE LA COMPAÑÍA:", FontFactory.GetFont("Arial", 9, Font.BOLD, Color.BLACK)));
                                cell.Colspan = 6;
                                SetBorder(cell, true, false, false, false);
                                table.AddCell(cell);
                                cell = new PdfPCell(new Phrase(solicitud.Subcontratista, FontFactory.GetFont("Arial", 9, Font.NORMAL, Color.BLACK)));
                                cell.Colspan = 14;
                                SetBorder(cell, false, false, true, false);
                                table.AddCell(cell);

                                cell = new PdfPCell(new Phrase("PERSONA CONTACTO:", FontFactory.GetFont("Arial", 9, Font.BOLD, Color.BLACK)));
                                cell.Colspan = 5;
                                SetBorder(cell, true, false, false, false);
                                table.AddCell(cell);
                                cell = new PdfPCell(new Phrase(solicitud.NombreContacto, FontFactory.GetFont("Arial", 9, Font.NORMAL, Color.BLACK)));
                                cell.Colspan = 8;
                                SetBorder(cell, false, false, false, false);
                                table.AddCell(cell);
                                cell = new PdfPCell(new Phrase("TEL / CELULAR:", FontFactory.GetFont("Arial", 9, Font.BOLD, Color.BLACK)));
                                cell.Colspan = 4;
                                SetBorder(cell, false, false, false, false);
                                table.AddCell(cell);
                                cell = new PdfPCell(new Phrase(solicitud.TelCelularSub, FontFactory.GetFont("Arial", 9, Font.NORMAL, Color.BLACK)));
                                cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                                cell.Colspan = 3;
                                SetBorder(cell, false, false, true, false);
                                table.AddCell(cell);

                                cell = new PdfPCell(new Phrase(" "));
                                cell.Colspan = 20;
                                SetBorder(cell, true, false, true, true);
                                table.AddCell(cell);

                                cell = new PdfPCell(new Phrase(""));
                                cell.Colspan = 20;
                                SetBorder(cell, false, false, false, false);
                                table.AddCell(cell);

                                doc.Add(table);
                                #endregion

                                //Información de los Trabajos a Realizar//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                                #region Info trabajos
                                table = new PdfPTable(20);
                                cell = new PdfPCell(new Phrase("INFORMACIÓN DE LOS TRABAJOS A REALIZAR:", FontFactory.GetFont("Arial", 9, Font.BOLD, Color.BLACK)));
                                cell.Colspan = 20;
                                SetBorder(cell, true, true, true, false);
                                table.AddCell(cell);

                                cell = new PdfPCell(new Phrase(""));
                                cell.Colspan = 20;
                                SetBorder(cell, true, false, true, false);
                                table.AddCell(cell);

                                cell = new PdfPCell(new Phrase("FECHA DE COMIENZO:", FontFactory.GetFont("Arial", 9, Font.BOLD, Color.BLACK)));
                                cell.Colspan = 5;
                                SetBorder(cell, true, false, false, false);
                                table.AddCell(cell);
                                cell = new PdfPCell(new Phrase(solicitud.FechaComienzo.ToShortDateString(), FontFactory.GetFont("Arial", 9, Font.NORMAL, Color.BLACK)));
                                cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                                cell.Colspan = 3;
                                SetBorder(cell, false, false, false, false);
                                table.AddCell(cell);
                                cell = new PdfPCell(new Phrase(" "));
                                cell.Colspan = 4;
                                SetBorder(cell, false, false, false, false);
                                table.AddCell(cell);
                                cell = new PdfPCell(new Phrase("FECHA DE EXPIRACIÓN:", FontFactory.GetFont("Arial", 9, Font.BOLD, Color.BLACK)));
                                cell.Colspan = 5;
                                SetBorder(cell, false, false, false, false);
                                table.AddCell(cell);
                                cell = new PdfPCell(new Phrase(solicitud.FechaExpiracion.ToShortDateString(), FontFactory.GetFont("Arial", 9, Font.NORMAL, Color.BLACK)));
                                cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                                cell.Colspan = 3;
                                SetBorder(cell, false, false, true, false);

                                table.AddCell(cell);

                                cell = new PdfPCell(new Phrase("HORARIO EN QUE SE REALIZARÁ LA(S) EXCAVACIÓN Y/O DEMOLICIÓN", FontFactory.GetFont("Arial", 9, Font.BOLD, Color.BLACK)));
                                cell.Colspan = 6;
                                SetBorder(cell, true, false, false, false);
                                table.AddCell(cell);
                                cell = new PdfPCell(new Phrase(solicitud.Horario, FontFactory.GetFont("Arial", 9, Font.NORMAL, Color.BLACK)));
                                cell.Colspan = 14;
                                SetBorder(cell, false, false, true, false);
                                table.AddCell(cell);

                                cell = new PdfPCell(new Phrase(""));
                                cell.Colspan = 20;
                                SetBorder(cell, true, false, true, false);
                                table.AddCell(cell);

                                cell = new PdfPCell(new Phrase("MAQUINARIA", FontFactory.GetFont("Arial", 9, Font.BOLD, Color.BLACK)));
                                cell.Colspan = 3;
                                SetBorder(cell, true, false, false, false);
                                table.AddCell(cell);

                                cell.Colspan = 1;
                                cbox = uncheck;
                                if (solicitud.Maquinaria)
                                    cbox = check;
                                SetBorder(cell, false, false, false, false);
                                table.AddCell(cbox);

                                cell = new PdfPCell(new Phrase("SI", FontFactory.GetFont("Arial", 9, Font.BOLD, Color.BLACK)));
                                cell.Colspan = 1;
                                SetBorder(cell, false, false, false, false);
                                table.AddCell(cell);

                                cell.Colspan = 1;
                                cbox = uncheck;
                                if (!solicitud.Maquinaria)
                                    cbox = check;
                                SetBorder(cell, false, false, false, false);
                                table.AddCell(cbox);

                                cell = new PdfPCell(new Phrase("NO", FontFactory.GetFont("Arial", 9, Font.BOLD, Color.BLACK)));
                                cell.Colspan = 1;
                                SetBorder(cell, false, false, false, false);
                                table.AddCell(cell);
                                cell = new PdfPCell(new Phrase("DESCRIPCIÓN MAQUINARIA:", FontFactory.GetFont("Arial", 9, Font.BOLD, Color.BLACK)));
                                cell.Colspan = 6;
                                SetBorder(cell, false, false, false, false);
                                table.AddCell(cell);
                                cell = new PdfPCell(new Phrase(solicitud.TipoMaquinaria, FontFactory.GetFont("Arial", 9, Font.NORMAL, Color.BLACK)));
                                cell.Colspan = 7;
                                SetBorder(cell, false, false, true, false);
                                table.AddCell(cell);

                                cell = new PdfPCell(new Phrase("EXPLOSIVOS", FontFactory.GetFont("Arial", 9, Font.BOLD, Color.BLACK)));
                                cell.Colspan = 3;
                                SetBorder(cell, true, false, false, false);
                                table.AddCell(cell);

                                cbox = uncheck;
                                if (solicitud.Explosivos)
                                    cbox = check;
                                cell.Colspan = 1;
                                SetBorder(cell, false, false, false, false);
                                table.AddCell(cbox);

                                cell = new PdfPCell(new Phrase("SI", FontFactory.GetFont("Arial", 9, Font.BOLD, Color.BLACK)));
                                cell.Colspan = 1;
                                SetBorder(cell, false, false, false, false);
                                table.AddCell(cell);

                                cbox = uncheck;
                                if (!solicitud.Explosivos)
                                    cbox = check;
                                cell.Colspan = 1;
                                SetBorder(cell, false, false, false, false);
                                table.AddCell(cbox);

                                cell = new PdfPCell(new Phrase("NO", FontFactory.GetFont("Arial", 9, Font.BOLD, Color.BLACK)));
                                cell.Colspan = 1;
                                SetBorder(cell, false, false, false, false);
                                table.AddCell(cell);

                                cell = new PdfPCell(new Phrase("NÚMERO LICENCIA EXPLOSIVOS:", FontFactory.GetFont("Arial", 9, Font.BOLD, Color.BLACK)));
                                cell.Colspan = 7;
                                SetBorder(cell, false, false, false, false);
                                table.AddCell(cell);
                                cell = new PdfPCell(new Phrase(solicitud.LicenciaExplosivo, FontFactory.GetFont("Arial", 9, Font.NORMAL, Color.BLACK)));
                                cell.Colspan = 6;
                                SetBorder(cell, false, false, true, false);
                                table.AddCell(cell);
                                ///////////////////////////////////////////
                                cell = new PdfPCell(new Phrase(""));
                                cell.Colspan = 20;
                                SetBorder(cell, true, false, true, false);
                                table.AddCell(cell);

                                cell = new PdfPCell(new Phrase("DESCRIPCIÓN DE LOS TRABAJOS A REALIZAR:", FontFactory.GetFont("Arial", 9, Font.BOLD, Color.BLACK)));
                                cell.Colspan = 20;
                                SetBorder(cell, true, false, true, false);
                                table.AddCell(cell);
                                cell = new PdfPCell(new Phrase(solicitud.RazonTrabajos, FontFactory.GetFont("Arial", 9, Font.NORMAL, Color.BLACK)));
                                cell.Colspan = 20;
                                SetBorder(cell, true, false, true, false);
                                table.AddCell(cell);
                                cell = new PdfPCell(new Phrase("COMENTARIOS:", FontFactory.GetFont("Arial", 9, Font.BOLD, Color.BLACK)));
                                cell.Colspan = 4;
                                SetBorder(cell, true, false, false, false);
                                table.AddCell(cell);
                                cell = new PdfPCell(new Phrase(" ", FontFactory.GetFont("Arial", 9, Font.NORMAL, Color.BLACK)));
                                cell.Colspan = 17;
                                SetBorder(cell, false, false, true, false);
                                table.AddCell(cell);
                                cell = new PdfPCell(new Phrase(" "));
                                cell.Colspan = 20;
                                SetBorder(cell, true, false, true, false);
                                table.AddCell(cell);
                                cell = new PdfPCell(new Phrase(" "));
                                cell.Colspan = 20;
                                SetBorder(cell, true, false, true, true);
                                table.AddCell(cell);

                                doc.Add(table);
                                #endregion


                                #region Footer
                                table = new PdfPTable(6);

                                //cell = signatureImgCell;

                                //cell.Colspan = 2;

                                //cell.Border = 0;

                                //cell.PaddingTop = 20f;

                                //table.AddCell(cell);

                                //p = new Paragraph("\n\n" + /*solicitud.Coordinador.Nombre +*/"\n___________________________________________________\n" +
                                //"  FIRMA DEL COORDINADOR QUE AUTORIZÓ EL AVISO\n\n" +
                                //"                             FECHA: " + Fecha + "\n\n", FontFactory.GetFont("Arial", 9, Font.BOLD, Color.BLACK));

                                //p.Alignment = Element.ALIGN_TOP;

                                //p = new Paragraph();

                                //var phr = new Phrase("\n\n\n___________________________________________________\n" +
                                //"  FIRMA DEL COORDINADOR QUE AUTORIZÓ EL AVISO\n\n");

                                //phr.Font = FontFactory.GetFont("Arial", 9, Font.BOLD, Color.BLACK);

                                //p.Alignment = Element.ALIGN_LEFT;

                                //p.Font = FontFactory.GetFont("Arial", 9, Font.BOLD, Color.BLACK);


                                //cell = new PdfPCell(new Phrase(p));
                                cell = new PdfPCell();

                                var firmaImg = iTextSharp.text.Image.GetInstance(Server.MapPath(
                                    string.Format("~/Images/Documentos/Firmas/{0}_Firma.png", user.Email)));

                                firmaImg.ScalePercent(50f);

                                firmaImg.SpacingBefore = 100f;

                                //p.Add( new Chunk(firmaImg, 0, 100));

                                //p.Add(phr);

                                //firmaImg.Alignment = Element.ALIGN_BOTTOM;

                                //firmaImg.SetAbsolutePosition(0f, 200f);

                                cell.AddElement(firmaImg);

                                //cell.AddElement(phr);


                                //cell.AddElement(p);

                                //cell.HorizontalAlignment = Element.ALIGN_BOTTOM;
                                cell.Colspan = 4;
                                cell.Border = 0;
                                //cell.Image = iTextSharp.text.Image.GetInstance("~/Images/Documentos/Firmas/firma1.png");
                                table.AddCell(cell);

                                cell = ImageCell("~/images/SelloOficialCertificacion.png", 10f, PdfPCell.ALIGN_RIGHT);
                                cell.Colspan = 2;
                                cell.Border = 0;
                                table.AddCell(cell);

                                p = new Paragraph("FECHA: " + Fecha + "\n\nAdvertencia: Esta certificación no constituye un permiso para excavar o demoler dentro de la jurisdicción del \n" +
                                "Estado Libre Asociado de Puerto Rico. La misma deberá  ser mostrada a solicitud de la Policía de Puerto Rico,\n" +
                                "Policía Municipal, Cuerpo de Bomberos, Oficiales del COT, Inspectores de DTOP y CSP y cualquier funcionario\n" +
                                "del DTOP que asi lo solicite.", FontFactory.GetFont("Arial", 6, Font.NORMAL, Color.BLACK));
                                p.Alignment = Element.ALIGN_JUSTIFIED;
                                cell = new PdfPCell(new Phrase(p));
                                cell.Border = 0;
                                cell.Colspan = 4;
                                table.AddCell(cell);

                                p = new Paragraph("                     SELLO          OFICIAL", FontFactory.GetFont("Arial", 10, Font.NORMAL, Color.BLACK));
                                p.Alignment = Element.ALIGN_RIGHT;
                                cell = new PdfPCell(new Phrase(p));
                                cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                                cell.Border = 0;
                                cell.Colspan = 2;
                                table.AddCell(cell);


                                doc.Add(table);
                                #endregion

                                doc.Close();
                                byte[] bytes = memoryStream.ToArray();
                                memoryStream.Close();

                                //File.WriteAllBytes(string.Format(@"{0}/{1}/Cert_{2}_Inicial.pdf", new DocumentoRequerido().DocumentosInicialesSavePath,
                                //    solicitud.Usuario.Email, solicitud.NumeroControl.NumControlText), bytes);



                                //File.WriteAllBytes(string.Format(@"C:\inetpub\wwwroot\EXC\Certificaciones\Cert_{0}_Inicial.pdf", solicitud.NumeroControl.NumControlText), bytes);

                                File.WriteAllBytes(Server.MapPath(string.Format(@"~/Certificaciones/Cert_{0}_EXT1.pdf", solicitud.NumeroControl.NumControlText)), bytes);

                                //File.WriteAllBytes(string.Format(@"C:\Users\devilsLap\Downloads\{0}.pdf", solicitud.NumeroControl.NumControlText), bytes);

                                //File.WriteAllBytes(string.Format(@"C:\Users\Administrator\Downloads\{0}.pdf", solicitud.NumeroControl.NumControlText), bytes);

                                //    //Response.Clear();
                                //    //Response.ContentType = "application/pdf";
                                //    //Response.AddHeader("Content-Disposition", "attachment; filename=" + NumeroControl + ".pdf");
                                //    //Response.ContentType = "application/pdf";
                                //    //Response.Buffer = true;
                                //    //Response.Cache.SetCacheability(HttpCacheability.NoCache);
                                //    //Response.BinaryWrite(bytes);
                                //    //Response.End();
                                //    //Response.Close();
                            }

                            #endregion

                            attachment.AddLast(string.Format(@"C:\inetpub\wwwroot\EXC\Certificaciones\Cert_{0}_EXT1.pdf", solicitud.NumeroControl.NumControlText));

                            //attachment.AddLast(Server.MapPath(string.Format(@"{0}/{1}/Cert_{2}_EXT1.pdf", new DocumentoRequerido().DocumentosPrimerasSavePath,
                            //        solicitud.Usuario.Email, solicitud.NumeroControl.NumControlText)));

                            //attachment.AddLast(string.Format(@"C:\Users\Administrator\Downloads\{0}.pdf", solicitud.NumeroControl.NumControlText));

                            //SendEmail(to, "*****@*****.**", new Mail().NotificationMsgs.Keys.ElementAt((int)Mail.Notifications.SolicitudAprovada),
                            //    new Mail().NotificationMsgs.Values.ElementAt((int)Mail.Notifications.SolicitudAprovada), attachment); //only foor test

                            //SendEmail(to, "*****@*****.**", "With cert", "body", attachment);

                            try
                            {
                                if (CheckForInternetConnection())
                                    SendEmail(to, "*****@*****.**",
                            mails.ElementAt((int)Mail.Notifications.SolicitudAprovada).Subject,
                            mails.ElementAt((int)Mail.Notifications.SolicitudAprovada).Body.Replace(
                            "@NumControl", numeroControl.NumControlText).Replace("@NombreEmpresa", solicitud.NombreEmpresa), attachment); // only test
                            }

                            catch (Exception ex)
                            { }
                            #endregion

                            #region Enviar email a operadores
                            LinkedList<string> from = new LinkedList<string>();

                            //to = new LinkedList<string>();

                            //LinkedList<Operador> operadores = new SolicitudesInicialesServicio().GetOperadores();

                            //foreach (var o in operadores)
                            //{
                            //    if (!currentUser.Email.Equals(o.Email))
                            //    {
                            //        to.AddLast(o.Email);
                            //    }
                            //}

                            //
                            //(to, "", "", "");

                            //SendEmail(to, "*****@*****.**", "Aviso", "Aviso de excavacion a operador", new LinkedList<string>()); // only test

                            //    if (CheckForInternetConnection())
                            //    SendEmail(to, "*****@*****.**",
                            //mails.ElementAt((int)Mail.Notifications.ExtensionNueva).Subject,
                            //mails.ElementAt((int)Mail.Notifications.ExtensionNueva).Body.Replace(
                            //"@NumControl", numeroControl.NumControlText).Replace("@NombreEmpresa", solicitud.NombreEmpresa), new LinkedList<string>()); // only test

                            #endregion
                        }

                        else
                        {
                            //Notifica excavador que tiene docs incompletos
                            //to = new LinkedList<string>();//user email

                            solicitud.FechaDocsIncompletos = DateTime.Now;

                            try
                            {
                                if (CheckForInternetConnection())
                                    SendEmail(to, "*****@*****.**",
                            mails.ElementAt((int)Mail.Notifications.ExtensionDocsIncompletos).Subject,
                            mails.ElementAt((int)Mail.Notifications.ExtensionDocsIncompletos).Body.Replace(
                            "@NumControl", numeroControl.NumControlText).Replace("@NombreEmpresa", solicitud.NombreEmpresa), new LinkedList<string>()); // only test
                            }

                            catch (Exception ex)
                            { }

                            //SendEmail(to, "*****@*****.**", "Aviso", "Docs incompletos", new LinkedList<string>()); //only foor test

                            //SendEmail(to, "", "", "");
                        }
                    }

                    else if ((Convert.ToInt32(solicitud.EstatusId)) == ((int)SolicitudAviso.Estatus.PendienteDocumentosIncompletos))
                    {
                        LinkedList<FileUpload> _docRequeridosFileUpload = new LinkedList<FileUpload>();

                        #region Validate docs requeridos

                        LinkedList<FileUpload> docRequeridosFileUpload = (LinkedList<FileUpload>)Session["docRequeridosFileUpload"];

                        foreach (var t in docRequeridosFileUpload)
                        {
                            _docRequeridosFileUpload.AddLast((FileUpload)docRequeridosMainDiv.FindControl(t.ID));

                            //if (!t.HasFile)
                            //{
                            //    exceptionMsg += t.ID.Replace("fileUp", string.Empty) + ", requerido </br>";
                            //}
                        }

                        foreach (var d in _docRequeridosFileUpload)
                        {
                            if (!d.HasFile)
                            {
                                exceptionMsg += d.ID.Replace("fileUp", string.Empty) + ", requerido </br>";
                            }
                        }

                        if (!string.IsNullOrWhiteSpace(exceptionMsg))
                        {
                            throw new Exception(exceptionMsg);
                        }

                        #endregion

                        #region Docs

                        for (int i = 0; i < _docRequeridosFileUpload.Count; i++)
                        {
                            DocumentoRequerido docReq = new DocumentoRequerido()
                            {
                                Nombre = _docRequeridosFileUpload.ElementAt(i).ID.Replace("fileUp", string.Empty),

                                NumeroControl = numeroControl,

                                Path = string.Format("{0}/{1}/{2}_{3}", new DocumentoRequerido().DocumentosPrimerasSavePath, user.Email
                                , solicitud.NumeroControl.NumControlText, Path.GetFileName(_docRequeridosFileUpload.ElementAt(i).PostedFile.FileName)),

                                Tipo = tipoAvisoRBtnLst.SelectedIndex,

                                ExtensionId = (int)SolicitudAviso.TiposExtensiones.Primera
                            };

                            LinkedList<DropDownList> docAsociadosStatuses = (LinkedList<DropDownList>)Session["docAsociadosStatusesExt"];


                            docReq.Status = docAsociadosStatuses.ElementAt(i).SelectedIndex;


                            documentos.AddLast(docReq);
                        }

                        #endregion

                        //documentos = SetDocumentsNumControl(documentos, numeroControl);

                        #region Set docs id

                        for (int i = 0; i < documentos.Count; i++)
                        {
                            documentos.ElementAt(i).DocumentoId = docsExistentes.ElementAt(i).DocumentoId;

                            //documentos.ElementAt(i).Status = docsExistentes.ElementAt(i).Status;
                        }

                        #endregion

                        SaveDocs(_docRequeridosFileUpload, documentos);

                        solicitud.EstatusId = ((int)SolicitudAviso.Estatus.PendienteRevisarCoordinador).ToString();

                        solicitud.FechaDocsIncompletos = Convert.ToDateTime(@"01/01/1900");

                        try
                        {
                            if (CheckForInternetConnection())
                                SendEmail(to, "*****@*****.**",
                            mails.ElementAt((int)Mail.Notifications.ExtensionRevisada).Subject,
                            mails.ElementAt((int)Mail.Notifications.ExtensionRevisada).Body.Replace(
                            "@NumControl", numeroControl.NumControlText).Replace("@NombreEmpresa", solicitud.NombreEmpresa), new LinkedList<string>()); // only test
                        }

                        catch (Exception ex)
                        { }
                    }

                    //else if ((solicitud.EstatusId.Equals(((int)SolicitudAviso.Estatus.PendienteAsignarInspector).ToString())))
                    //{
                    //    if (solicitud.Inspector.NumeroPlacaID.Equals("0"))
                    //    {
                    //        //solicitud.Inspector.NumeroPlacaID = Request.QueryString["inspectorId"];
                    //    }

                    //    solicitud.EstatusId = ((int)SolicitudAviso.Estatus.EnProcesoInspeccion).ToString();
                    //}

                    #endregion

                    solicitud.NumeroControl.NumControl = Convert.ToInt32(solicitud.NumeroControl.NumControlText.Substring(4));

                    //Agrega letra al status id
                    solicitud.EstatusId = string.Format("{0}{1}", solicitud.LetraStatus, solicitud.EstatusId);

                    solicitud.FechaTramite = primeraExtExistente.FechaTramite;

                    solicitud.TramitadoPor = primeraExtExistente.TramitadoPor;

                    solicitud.Usuario = primeraExtExistente.Usuario;

                    //documentos = SetDocumentsNumControl(documentos, numeroControl);

                    averias = SetAveriasNumControl(averias, numeroControl);

                    #region Set averias & docs Ids
                    for (int i = 0; i < averiasExistentes.Count; i++)
                    {
                        averias.ElementAt(i).ID = averiasExistentes.ElementAt(i).ID;
                    }

                    //for (int i = 0; i < documentos.Count; i++)
                    //{
                    //    documentos.ElementAt(i).DocumentoId = docsExistentes.ElementAt(i).DocumentoId;
                    //}
                    #endregion

                    new DocumentosRequeridosServicio().TryUpdate(documentos);

                    new AveriasServicio().TryCreate(averias);

                    new PrimerasExtensionesServicio().TryUpdate(solicitud);

                    #endregion
                }

                #endregion

                guardarBtn.Enabled = true;

                Response.Redirect("~/Default.aspx", false);
            }

            catch (Exception ex)
            {
                if (string.IsNullOrWhiteSpace(exceptionMsg))
                {
                    guardarBtn.Enabled = true;

                    errorLbl2.InnerText = ex.Message;
                }

                else
                {
                    guardarBtn.Enabled = true;

                    errorLbl2.InnerHtml = exceptionMsg;
                }

                if (ViewState["justCreatedInspeccion"] != null)
                {
                    new InspeccionesServicio().TryDelete(exceptionNumControl, ((int)SolicitudAviso.TiposExtensiones.Primera).ToString());
                }

                String errorLog = "Date: " + DateTime.Now.ToLongDateString() + "\r\n NumeroControl:" + exceptionNumControl.NumControlText
                            + "\r\n Message: " + ex.Message + "\r\n Source: "
                            + ex.Source + "\r\n Stacktrace: " + ex.StackTrace + "\r\n TargetSite: " + ex.TargetSite.ToString() + "\r\n\r\n";

                //File.WriteAllText(Server.MapPath(Inspeccion.ErrorLogDir + "Ext1Log.txt"), errorLog);

                Page.DataBind();

                errorPopup.Show();
            }
        }
        protected void GuardarBtnClick(object sender, EventArgs e)
        {
            string exceptionMsg = string.Empty;

            User user = Session["UserObj"] == null ? new User() : (User)Session["UserObj"];

            guardarBtn.Enabled = false;

            LinkedList<HtmlInputFile> uploadFilesWithFile = new LinkedList<HtmlInputFile>();

            NumeroControl exceptionNumControl = new NumeroControl();

            #region Set comentario txtBx if empty

            /*Por alguna razon, no importa si el rfv esta disable o si el txtbx tiene causevalidation falso, el rfv, tira el msg de que esta vacio cuando se presiona guardar.
             Al reemplaza un blank txtbx con )_+, cuando el status sea completo, evito que tire el msg de vacio, Cuando se guarda enn el obj de documentos, se reemplaza )_+
             con blank text*/
            LinkedList<DropDownList> docAsociadosStatusesPostValidation = (LinkedList<DropDownList>)Session["docAsociadosStatuses"] == null
                ? new LinkedList<DropDownList>() : (LinkedList<DropDownList>)Session["docAsociadosStatuses"];

            foreach (var d in docAsociadosStatusesPostValidation)
            {
                TextBox txtBx = (TextBox)docsAsociadosTableTag.FindControl(d.ID.Replace("DDL", "TxtBx"));

                if ((d.SelectedIndex == (int)DocumentoRequerido.Estatus.Completo) && txtBx != null)
                {
                    txtBx.Text = string.IsNullOrEmpty(txtBx.Text) ? ")_+" : txtBx.Text;
                }
            } 
            #endregion

            try
            {
                //Some validators don't validate if this isn't invoked
                Page.Validate();

                //Some rfv won't validate after becoming enabled when being disabled
                if (Page.IsValid)
                {
                    //throw new Exception("Errores fueron encontrados");

                    #region Validate controls server side

                    //Quizas en vez de esta vali, le pongo en requiredfield y si esta checked que se ponga enabled
                    #region maq/expl
                    if (maquinariaChkBx.Checked)
                    {
                        exceptionMsg = ValidateStrings(tipoMaquinariaTxtBx.Text, "<b>Tipo de Maquinaria:</b> Requerida  ");
                    }

                    if (explosivoChkBx.Checked)
                    {
                        exceptionMsg += ValidateStrings(licExplosivoTxtBx.Text, "<b>Licencia Explosivo:</b> Requerida  ");

                        exceptionMsg += ValidateStrings(fechaExpiracionExplosivoTxtBx.Text, "<b>Fecha Expiración de Licencia Explosivo:</b> Requerida  ");
                    }
                    #endregion

                    if (string.IsNullOrEmpty(duracionDiaTxtBx.Text)
                        && string.IsNullOrEmpty(duracionMesTxtBx.Text)
                        && string.IsNullOrEmpty(duracionYearTxtBx.Text))
                    {
                        //throw new Exception("Duración, requerida");

                        exceptionMsg += "<b>Duración:</b> Requerida <br />";
                    }

                    #endregion

                    #region Genera numero Control

                    NumeroControl numeroControlExistente = new NumerosControlServicio().GetNumeroControl(DateTime.Now.Year),
                        numeroControl = new NumeroControl()
                        {
                            Year = DateTime.Now.Year,

                            //NumControlText = "2015-0016" // only for testing

                            NumControlText = Request.QueryString["NumeroControl"]
                        };

                    #endregion

                    Boolean zona = zonaRBtnLst.SelectedValue.Equals("Urbana"),
                        tipoExcavacion = tipoExcavacionRBtnLst.SelectedValue.Equals("Continua");

                    #region Poblar averias
                    //LinkedList<Averia> averias = new LinkedList<Averia>(),
                    //    averiasExistentes = new AveriasServicio().GetAverias(numeroControl, (int)SolicitudAviso.TiposExtensiones.Inicial);

                    //averias.AddLast(new Averia()
                    //    {
                    //        Titulo = averiasTxtBx.Text,

                    //        ExtensionId = (int)SolicitudAviso.TiposExtensiones.Inicial
                    //    });

                    #endregion

                    #region Poblar docs

                    LinkedList<DocumentoRequerido> documentos = new LinkedList<DocumentoRequerido>(),
                        docsExistentes = new DocumentosRequeridosServicio().GetDocumentosAsociados(numeroControl, (int)SolicitudAviso.TiposExtensiones.Inicial);

                    Dictionary<TextBox, DropDownList> docControls = new Dictionary<TextBox, DropDownList>();

                    docControls = GetDocCtrls();



                    #endregion

                    User currentUser = new SolicitudesInicialesServicio().GetUser(user.Email);

                    #region Poblar solicitud

                    SolicitudAviso solicitud = new SolicitudAviso()
                    {
                        #region Info general

                        NumeroControl = numeroControl,

                        Emergencia = emergenciaChkBx.Checked,

                        TipoAviso = tipoAvisoRBtnLst.SelectedIndex.ToString().ToUpper(),

                        NombreContacto = nombreContactoTxtBx.Text.ToUpper(),

                        CelularContacto = celularContactoTxtBx.Text.ToUpper(),

                        DireccionPostalContacto = direccionPostalContactoTxtBx.Text.ToUpper(),

                        #endregion

                        #region Contratista

                        NombreEmpresa = companyDDL.SelectedValue,

                        AreaDept = areaDepartamentoTxtBx.Text.ToUpper(),

                        RepresentanteAutorizado = representanteTxtBx.Text.ToUpper(),

                        TelOficina = telOficinaTxtBx.Text.ToUpper(),

                        TelCampoTrabajo = telTrabajoTxtBx.Text.ToUpper(),

                        TelCelular = celularTxtBx.Text.ToUpper(),

                        CorreoElectronico = emailTxtBx.Text,

                        DireccionPostal = direccionTxtBx.Text.ToUpper(),

                        MunicipioId = municipioDDL.SelectedIndex,

                        CodigoPostal = codigoPostalTxtBx.Text.ToUpper(),

                        #endregion

                        #region Sub

                        Subcontratista = companySubTxtBx.Text,

                        AreaDeptSub = areaDepartamentoSubTxtBx.Text.ToUpper(),

                        RepresentanteAutorizadoSub = representanteSubTxtBx.Text.ToUpper(),

                        TelOficinaSub = telOficinaSubTxtBx.Text.ToUpper(),

                        TelCampoTrabajoSub = telTrabajoSubTxtBx.Text.ToUpper(),

                        TelCelularSub = celularSubTxtBx.Text.ToUpper(),

                        CorreoElectronicoSub = emailSubTxtBx.Text,

                        DireccionPostalSub = direccionSubTxtBx.Text.ToUpper(),

                        MunicipioIdSub = municipioSubDDL.SelectedIndex,

                        CodigoPostalSub = codigoPostalSubTxtBx.Text.ToUpper(),

                        #endregion

                        #region Info trabajo

                        Zona = zona,

                        BoUrb = boUrbTxtBx.Text.ToUpper(),

                        SectorCalle = sectorCalleTxtBx.Text.ToUpper(),

                        Carretera = carreteraTxtBx.Text.ToUpper(),

                        MunicipioIdTrab = municipioTrabajoDDL.SelectedIndex,

                        KM = Convert.ToInt32(kmTxtBx.Text),

                        HM = Convert.ToInt32(hmTxtBx.Text),

                        Referencias = referenciasTxtBx.Text.ToUpper(),

                        RazonTrabajos = razonTxtBx.Text.ToUpper(),

                        FechaPropuesta = Convert.ToDateTime(fechaComienzoPropuestoTxtBx.Text),

                        FechaComienzo = string.IsNullOrWhiteSpace(fechaComienzoTxtBx.Text)
                        ? new DateTime(1900, 01, 01) : Convert.ToDateTime(fechaComienzoTxtBx.Text),

                        FechaExpiracion = string.IsNullOrWhiteSpace(fechaExpiracionTxtBx.Text)
                        ? new DateTime(1900, 01, 01) : Convert.ToDateTime(fechaExpiracionTxtBx.Text),

                        TiempoDuracion = string.Format("{0}-{1}-{2}", duracionDiaTxtBx.Text
                                                      , duracionMesTxtBx.Text, duracionYearTxtBx.Text),

                        Horario = string.Format("{0}-{1}", horarioDDL.SelectedValue, horarioDDL2.SelectedValue),

                        Maquinaria = maquinariaChkBx.Checked,

                        TipoMaquinaria = tipoMaquinariaTxtBx.Text.ToUpper(),

                        Explosivos = explosivoChkBx.Checked,

                        LicenciaExplosivo = licExplosivoTxtBx.Text.ToUpper(),

                        FechaExpiracionExplosivo = !string.IsNullOrWhiteSpace(fechaExpiracionExplosivoTxtBx.Text)
                        ? Convert.ToDateTime(fechaExpiracionExplosivoTxtBx.Text)
                        : Convert.ToDateTime(@"1/1/1900"),

                        AreaMarcada = areaMarcadaChkBx.Checked,

                        TipoExcavacion = tipoExcavacion,

                        ProfundidadPies = Convert.ToInt32(profundidadPiesTxtBx.Text),

                        ProfundidadPulgadas = profundidadPulgadasDLL.SelectedIndex,

                        LongitudPies = Convert.ToInt32(longitudPiesTxtBx.Text),

                        LongitudPulgadas = longitudPulgadasDDL.SelectedIndex,

                        CoordenadaX = decimal.Parse(coordenadasXTxtBx.Text),

                        CoordenadaY = decimal.Parse(coordenadasYTxtBx.Text),

                        EnCasoEmergencia = enCasoEmergenciaTxtBx.Text.ToUpper(),

                        #endregion

                        Documentos = documentos,

                        //Averias = averias,

                        ExtensionID = (int)SolicitudAviso.TiposExtensiones.Inicial
                    };

                    solicitud.EstatusId = string.Format("{0}{1}", solicitud.LetraStatus, statusHF.Value);

                    #endregion

                    LinkedList<Mail> mails = new MailServicio().GetMailMsgs();

                    #region Create / Edit

                    if (String.IsNullOrEmpty(numeroControl.NumControlText))
                    {
                        #region Create

                        #region validate docs

                        LinkedList<FileUpload> _docRequeridosFileUpload = new LinkedList<FileUpload>();

                        var files = Request.Files;

                        LinkedList<FileUpload> docRequeridosFileUpload = (LinkedList<FileUpload>)Session["docRequeridosFileUpload"];

                        foreach (var t in docRequeridosFileUpload)
                        {
                            _docRequeridosFileUpload.AddLast((FileUpload)docRequeridosMainDiv.FindControl(t.ID));
                        }

                        foreach (var d in _docRequeridosFileUpload)
                        {
                            if (d.PostedFile.ContentLength < 1)
                            {
                                exceptionMsg += string.Format("<b>{0}:</b> Requerido <br />", d.ID.Replace("fileUp", string.Empty));
                            }
                        }

                        if (!string.IsNullOrWhiteSpace(exceptionMsg))
                        {
                            throw new Exception(exceptionMsg);
                        }

                        #endregion

                        #region Set up num control
                        numeroControl.NumControl = numeroControlExistente.NumControl + 1;

                        string numTxt = numeroControl.NumControl.ToString();

                        numTxt = numTxt.PadLeft(4, '0');

                        numeroControl.NumControlText = string.Format("{0}-{1}", numeroControl.Year.ToString(), numTxt);

                        exceptionNumControl = numeroControl;
                        #endregion

                        #region Docs

                        for (int i = 0; i < _docRequeridosFileUpload.Count; i++)
                        {
                            DocumentoRequerido docReq = new DocumentoRequerido()
                            {
                                Nombre = _docRequeridosFileUpload.ElementAt(i).ID.Replace("fileUp", string.Empty),

                                NumeroControl = numeroControl,

                                Path = string.Format("{0}/{1}/{2}_{3}", new DocumentoRequerido().DocumentosInicialesSavePath, user.Email
                                , numeroControl.NumControlText, Path.GetFileName(_docRequeridosFileUpload.ElementAt(i).PostedFile.FileName.Replace(
                                "#", string.Empty).Replace("&", string.Empty))),

                                Tipo = tipoAvisoRBtnLst.SelectedIndex
                            };

                            LinkedList<DropDownList> docAsociadosStatuses = (LinkedList<DropDownList>)Session["docAsociadosStatuses"];

                            if (docAsociadosStatuses != null)
                            {
                                docReq.Status = docAsociadosStatuses.ElementAt(i).SelectedIndex;
                            }

                            documentos.AddLast(docReq);
                        }

                        #endregion

                        documentos = SetDocumentsNumControl(documentos, numeroControl);

                        solicitud.NumeroControl = numeroControl;

                        numControlPopupLbl.Text = numeroControl.NumControlText;

                        //info de la empresa
                        solicitud.Usuario = new User()
                        {
                            Email = currentUser.Email,

                            NombreCompleto = currentUser.Nombre + " " + currentUser.Inicial + " "
                        + currentUser.ApellidoPaterno + " " + currentUser.ApellidoMaterno
                        };

                        solicitud.TramitadoPor = solicitud.Usuario.NombreCompleto;

                        solicitud.FechaTramite = DateTime.Now;

                        solicitud.EstatusId = string.Format("{0}{1}", solicitud.LetraStatus, ((int)SolicitudAviso.Estatus.PendienteRevisarCoordinador).ToString());

                        new NumerosControlServicio().Create(numeroControl);

                        new DocumentosRequeridosServicio().TryCreate(documentos);

                        //new AveriasServicio().TryCreate(averias);

                        new SolicitudesInicialesServicio().TryCreate(solicitud);

                        SaveDocs(_docRequeridosFileUpload, documentos);

                        #region Email coordinadores
                        LinkedList<string> to = new LinkedList<string>();

                        LinkedList<User> coordinadores = new SolicitudesInicialesServicio().GetCoordinadores(),
                            superInspectores = new SolicitudesInicialesServicio().GetSuperInspectores(),
                            directores = new SolicitudesInicialesServicio().GetDirectores();

                        for (int i = 0; i < coordinadores.Count; i++)
                        {
                            to.AddLast(coordinadores.ElementAt(i).Email);
                        }

                        for (int i = 0; i < superInspectores.Count; i++)
                        {
                            to.AddLast(superInspectores.ElementAt(i).Email);
                        }

                        for (int i = 0; i < directores.Count; i++)
                        {
                            to.AddLast(directores.ElementAt(i).Email);
                        }

                        numControlPopupTriggerBtn_Click(numControlPopupTriggerBtn, EventArgs.Empty);

                        try
                        {
                            if (CheckForInternetConnection())
                                SendEmail(to, "*****@*****.**",
                                mails.ElementAt((int)Mail.Notifications.SolicitudNueva).Subject,
                                mails.ElementAt((int)Mail.Notifications.SolicitudNueva).Body.Replace(
                                "@NumControl", numeroControl.NumControlText).Replace("@NombreEmpresa", solicitud.NombreEmpresa), new LinkedList<string>());
                        }

                        catch (Exception ex)
                        {
                            if (ex.Message == "")
                            {

                            }
                        }
                        #endregion

                        Page.DataBind();

                        #endregion
                    }

                    else
                    {
                        #region Edit

                        SolicitudAviso solicitudExistente = new SolicitudesInicialesServicio().GetSolicitud(numeroControl);

                        exceptionNumControl = numeroControl;

                        solicitud.FechaTramite = solicitudExistente.FechaTramite;

                        solicitud.TramitadoPor = solicitudExistente.TramitadoPor;

                        solicitud.Usuario = solicitudExistente.Usuario;

                        solicitud.SolicitudStatusID = solicitudStatusDDL.SelectedIndex;

                        solicitud.Observaciones = observacionesTxtBx.Text.ToUpper();

                        #region Set docs comentario
                        for (int i = 0; i < docsExistentes.Count; i++)
                        {
                            TextBox txtBx = (TextBox)docsAsociadosTableTag.FindControl(string.Format("{0}TxtBx", docsExistentes.ElementAt(i).Nombre));

                            docsExistentes.ElementAt(i).Comentario = txtBx.Visible ? txtBx.Text.Replace(")_+", string.Empty).ToUpper() : string.Empty;
                        }
                        #endregion

                        #region Actualiza status solicitud

                        LinkedList<string> to = new LinkedList<string>();

                        to.AddLast(user.Email);

                        //Remove estatus letra
                        solicitud.EstatusId = solicitud.EstatusId.Replace(solicitud.LetraStatus, string.Empty).Replace(new Inspeccion().LetraStatus, string.Empty);

                        //Pend coordinador
                        if ((Convert.ToInt32(solicitud.EstatusId)) == ((int)SolicitudAviso.Estatus.PendienteRevisarCoordinador))
                        {
                            if (string.IsNullOrWhiteSpace(solicitud.Coordinador.Nombre))
                            {
                                solicitud.Coordinador.Nombre = string.Format("{0} {1} {2}", currentUser.Nombre, currentUser.ApellidoPaterno, currentUser.ApellidoMaterno);
                            }

                            solicitud.EstatusId = GenerateStatus(ref docsExistentes).ToString();

                            documentos = docsExistentes;

                            if (solicitud.EstatusId.Equals(((int)SolicitudAviso.Estatus.PendienteAsignarInspector).ToString()))
                            {
                                #region Se aprobo despues de pend coordinador
                                solicitud.FechaRespuestaSolicitadas = DateTime.Now.ToShortDateString();

                                if (emergenciaChkBx.Checked)
                                {
                                    solicitud.FechaComienzo = DateTime.Now.Date;
                                }

                                else
                                {
                                    solicitud.FechaComienzo = ValidarFecha(5);
                                }

                                solicitud.FechaExpiracion = solicitud.FechaComienzo.AddDays(60);

                                Company company = new SolicitudesInicialesServicio().GetCompany(companyDDL.SelectedValue);

                                #region Poblar hoja inspeccion

                                Inspeccion inspeccion = new Inspeccion()
                                {
                                    NumeroInspeccion = solicitud.NumeroControl.NumControlText,

                                    NumeroPlacaID = string.IsNullOrWhiteSpace(solicitud.Inspector.NumeroPlacaID) ? "000"
                                    : solicitud.Inspector.NumeroPlacaID,

                                    DireccionFisica = company.DireccionFisica,

                                    EstatusInspeccionID = "1",

                                    TipoInspeccionID = "1",

                                    //ExtensionID = (int)SolicitudAviso.TiposExtensiones.Inicial,

                                    NumeroControl = new NumeroControl()
                                    {
                                        NumControl = solicitud.NumeroControl.NumControl,

                                        Year = solicitud.NumeroControl.Year,

                                        NumControlText = solicitud.NumeroControl.NumControlText
                                    },

                                    NombreEmpresa = solicitud.NombreEmpresa,

                                    RepresentateAutorizado = solicitud.RepresentanteAutorizado,

                                    CorreoElectronico = solicitud.CorreoElectronico,

                                    TelOficina = solicitud.TelOficina,

                                    TelTrabajo = solicitud.TelCampoTrabajo,

                                    Celular = solicitud.TelCelular,

                                    TipoAviso = solicitud.ExtensionID.ToString(),

                                    FechaComienzo = solicitud.FechaComienzo,

                                    FechaExpiracion = solicitud.FechaExpiracion,

                                    LongitudPies = solicitud.LongitudPies,

                                    LongitudPulgadas = solicitud.LongitudPulgadas,

                                    ProfundidadPies = solicitud.ProfundidadPies,

                                    ProfundidadPulgadas = solicitud.ProfundidadPulgadas,

                                    CoordenadaX = float.Parse(solicitud.CoordenadaX.ToString()),

                                    CoordenadaY = float.Parse(solicitud.CoordenadaY.ToString()),

                                    RazonTrabajos = solicitud.RazonTrabajos,

                                    Zona = solicitud.Zona,

                                    BoUrbT = solicitud.BoUrb,

                                    SectorCalleT = solicitud.SectorCalle,

                                    CarreteraT = solicitud.Carretera,

                                    KM = solicitud.KM,

                                    HM = solicitud.HM,

                                    MunicipioT = municipioTrabajoDDL.SelectedValue,
                                };

                                #endregion

                                new InspeccionesServicio().TryCrear(inspeccion);

                                ViewState["justCreatedInspeccion"] = true;

                                //throw new Exception("delete inpeccion test");

                                #region Enviar email excavador

                                //currentUser = new SolicitudesInicialesServicio().GetUser(solicitud.Usuario.Id);

                                //User solicitudUser = new SolicitudesInicialesServicio().GetUser(solicitud.Usuario.Email);

                                to = new LinkedList<string>();

                                //Uncomment when intergrating

                                to.AddLast(solicitud.Usuario.Email);

                                //SendEmail(to, "", "", ""); 

                                LinkedList<string> attachment = new LinkedList<string>();

                                #region pdf stuff

                                #region Init

                                Document doc = new Document(PageSize.LETTER, 0f, 0f, 0f, 0f);

                                //String Fecha = DateTime.Now.ToString();

                                string Fecha = solicitud.FechaTramite.ToString();

                                iTextSharp.text.Font NormalFont = FontFactory.GetFont("Arial", 12, Font.NORMAL, Color.BLACK);

                                using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
                                {
                                    PdfWriter writer = PdfWriter.GetInstance(doc, memoryStream);

                                    Phrase phrase = null;

                                    PdfPCell cell = null;

                                    PdfPCell b = new PdfPCell(new Phrase(" "));

                                    PdfPTable table = null;

                                    PdfPCell uncheck = ImageCell("~/Images/uncheck4.png", 2f, PdfPCell.ALIGN_CENTER);

                                    PdfPCell check = ImageCell("~/Images/Check4.png", 2f, PdfPCell.ALIGN_CENTER);

                                    PdfPCell cbox = check,
                                             signatureImgCell = ImageCell(string.Format("~/Images/Documentos/Firmas/{0}_Firma.png", user.Email), 50f, PdfPCell.ALIGN_CENTER);

                                    DateTime datevalue = (Convert.ToDateTime(Fecha.ToString()));

                                    Fecha = datevalue.ToString("MM/dd/yyyy");

                                    String[] mes = { "ENERO", "FEBRERO", "MARZO", "ABRIL", "MAYO", "JUNIO", "JULIO", "AGOSTO", "SEPTIEMBRE", "OCTUBRE", "NOVIEMBRE", "DICIEMBRE" };

                                    String FechaLetras = datevalue.Day.ToString() + " DE " + mes[datevalue.Month - 1] + " DE " + datevalue.Year.ToString();

                                    doc.Open();

                                #endregion

                                    #region Header
                                    Paragraph p = new Paragraph("DTOP-          09/15                                              \n\n", FontFactory.GetFont("Arial", 8, Font.NORMAL, Color.BLACK));
                                    p.Alignment = Element.ALIGN_RIGHT;
                                    doc.Add(p);

                                    //Header Table
                                    table = new PdfPTable(3);

                                    //Header Data
                                    cell = ImageCell("~/images/EscudoPR.png", 40f, PdfPCell.ALIGN_LEFT);
                                    cell.Border = 0;
                                    table.AddCell(cell);
                                    cell = new PdfPCell(new Phrase(" "));
                                    cell.Border = 0;
                                    table.AddCell(cell);
                                    phrase = new Phrase();
                                    phrase.Add(new Chunk("\n\nNÚMERO DE AVISO:\n", FontFactory.GetFont("Arial", 8, Font.NORMAL, Color.BLACK)));
                                    phrase.Add(new Chunk("DEDT-" + solicitud.NumeroControl.NumControlText, FontFactory.GetFont("Arial", 16, Font.BOLD, Color.RED)));

                                    cell = PhraseCell(phrase, PdfPCell.ALIGN_CENTER);
                                    cell.BorderColorLeft = Color.BLACK;
                                    cell.BorderColorRight = Color.BLACK;
                                    cell.BorderColorTop = Color.BLACK;
                                    cell.BorderColorBottom = Color.BLACK;
                                    cell.BorderWidthLeft = 1f;
                                    cell.BorderWidthRight = 1f;
                                    cell.BorderWidthTop = 1f;
                                    cell.BorderWidthBottom = 1f;
                                    cell.Border = Rectangle.BOX;
                                    table.AddCell(cell);

                                    cell = new PdfPCell(new Phrase(" "));
                                    cell.Colspan = 3;
                                    SetBorder(cell, false, false, false, false);
                                    table.AddCell(cell);

                                    doc.Add(table);

                                    p = new Paragraph("DIRECTORÍA DE EXCAVACIONES, DEMOLICIONES Y TUBERÍAS", FontFactory.GetFont("Arial", 14, Font.NORMAL, Color.BLACK));
                                    p.Alignment = Element.ALIGN_CENTER;
                                    doc.Add(p);

                                    p = new Paragraph("CENTRO DE COORDINACIÓN DE EXCAVACIONES Y DEMOLICIONES", FontFactory.GetFont("Arial", 14, Font.NORMAL, Color.BLACK));
                                    p.Alignment = Element.ALIGN_CENTER;
                                    doc.Add(p);

                                    p = new Paragraph("CERTIFICACIÓN DE TRÁMITE DE AVISO DE EXCAVACIÓN Y/O DEMOLICIÓN\n\n", FontFactory.GetFont("Arial", 14, Font.BOLD, Color.BLACK));
                                    p.Alignment = Element.ALIGN_CENTER;
                                    doc.Add(p);

                                    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                                    table = new PdfPTable(7);
                                    table.SetWidths(new float[] { 1.0f, 0.5f, 3.5f, 1.5f, 0.2f, 0.4f, 0.1f });

                                    cell = new PdfPCell(new Phrase(""));
                                    cell.Colspan = 7;
                                    SetBorder(cell, true, true, true, false);
                                    table.AddCell(cell);
                                    ////////////////////
                                    cell = new PdfPCell(new Phrase("EMERGENCIA", FontFactory.GetFont("Arial", 9, Font.NORMAL, Color.BLACK)));
                                    SetBorder(cell, true, false, false, false);
                                    table.AddCell(cell);

                                    cbox = uncheck;
                                    if (solicitud.Emergencia)
                                        cbox = check;
                                    SetBorder(cell, false, false, false, false);
                                    table.AddCell(cbox);

                                    cell = new PdfPCell(new Phrase("FECHA DE PRESENTACIÓN:", FontFactory.GetFont("Arial", 9, Font.NORMAL, Color.BLACK)));
                                    cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                                    SetBorder(cell, false, false, false, false);
                                    table.AddCell(cell);

                                    cell = new PdfPCell(new Phrase("AVISO INICIAL", FontFactory.GetFont("Arial", 9, Font.NORMAL, Color.BLACK)));
                                    cell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                                    SetBorder(cell, false, false, false, false);
                                    table.AddCell(cell);

                                    cell = new PdfPCell(new Phrase(""));
                                    SetBorder(cell, false, false, false, false);
                                    table.AddCell(cell);

                                    cbox = uncheck;
                                    if (solicitud.ExtensionID == (int)SolicitudAviso.TiposExtensiones.Inicial)
                                        cbox = check;
                                    SetBorder(cell, false, false, false, false);
                                    table.AddCell(cbox);

                                    cell = new PdfPCell(new Phrase(""));
                                    SetBorder(cell, false, false, true, false);
                                    table.AddCell(cell);

                                    //////////////////////////////////////////

                                    cell = new PdfPCell(new Phrase("EXCAVACIÓN", FontFactory.GetFont("Arial", 9, Font.NORMAL, Color.BLACK)));
                                    SetBorder(cell, true, false, false, false);
                                    table.AddCell(cell);

                                    cbox = uncheck;
                                    if (solicitud.TipoAviso.Equals(((int)SolicitudAviso.TiposAvisos.Excavacion).ToString()))
                                        cbox = check;
                                    SetBorder(cell, false, false, false, false);
                                    table.AddCell(cbox);

                                    cell = new PdfPCell(new Phrase(FechaLetras, FontFactory.GetFont("Arial", 12, Font.BOLD, Color.BLACK)));
                                    cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                                    SetBorder(cell, false, false, false, false);
                                    table.AddCell(cell);

                                    cell = new PdfPCell(new Phrase("1RA EXTENSIÓN", FontFactory.GetFont("Arial", 9, Font.NORMAL, Color.BLACK)));
                                    cell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                                    SetBorder(cell, false, false, false, false);
                                    table.AddCell(cell);

                                    cell = new PdfPCell(new Phrase(""));
                                    SetBorder(cell, false, false, false, false);
                                    table.AddCell(cell);

                                    cbox = uncheck;
                                    if (solicitud.ExtensionID == (int)SolicitudAviso.TiposExtensiones.Primera)
                                        cbox = check;
                                    SetBorder(cell, false, false, false, false);
                                    table.AddCell(cbox);

                                    cell = new PdfPCell(new Phrase(""));
                                    SetBorder(cell, false, false, true, false);
                                    table.AddCell(cell);

                                    ///////////////////

                                    cell = new PdfPCell(new Phrase("DEMOLICIÓN", FontFactory.GetFont("Arial", 9, Font.NORMAL, Color.BLACK)));
                                    SetBorder(cell, true, false, false, false);
                                    table.AddCell(cell);

                                    cbox = uncheck;
                                    if (solicitud.TipoAviso.Equals(((int)SolicitudAviso.TiposAvisos.Demolicion).ToString()))
                                        cbox = check;
                                    SetBorder(cell, false, false, false, false);
                                    table.AddCell(cbox);

                                    cell = new PdfPCell(new Phrase(" "));
                                    SetBorder(cell, false, false, false, false);
                                    table.AddCell(cell);

                                    cell = new PdfPCell(new Phrase("2RA EXTENSIÓN", FontFactory.GetFont("Arial", 9, Font.NORMAL, Color.BLACK)));
                                    cell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                                    SetBorder(cell, false, false, false, false);
                                    table.AddCell(cell);

                                    cell = new PdfPCell(new Phrase(" "));
                                    SetBorder(cell, false, false, false, false);
                                    table.AddCell(cell);

                                    cbox = uncheck;
                                    if (solicitud.ExtensionID == (int)SolicitudAviso.TiposExtensiones.Segunda)
                                        cbox = check;
                                    SetBorder(cell, false, false, false, false);
                                    table.AddCell(cbox);

                                    cell = new PdfPCell(new Phrase(" "));
                                    SetBorder(cell, false, false, true, false);
                                    table.AddCell(cell);

                                    //////////////////

                                    cell = new PdfPCell(new Phrase("RESIDENCIAL", FontFactory.GetFont("Arial", 9, Font.NORMAL, Color.BLACK)));
                                    SetBorder(cell, true, false, false, false);
                                    table.AddCell(cell);

                                    cbox = uncheck;
                                    if (solicitud.TipoAviso.Equals(((int)SolicitudAviso.TiposAvisos.Residencial).ToString()))
                                        cbox = check;
                                    SetBorder(cell, false, false, false, false);
                                    table.AddCell(cbox);

                                    //cell = new PdfPCell(new Phrase("", FontFactory.GetFont("Arial", 9, Font.NORMAL, Color.BLACK)));
                                    //cell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                                    //SetBorder(cell, false, false, false, false);
                                    //table.AddCell(cell);

                                    cell = new PdfPCell(new Phrase(" "));
                                    SetBorder(cell, false, false, false, false);
                                    table.AddCell(cell);

                                    cell = new PdfPCell(new Phrase(" "));
                                    SetBorder(cell, false, false, false, false);
                                    table.AddCell(cell);

                                    /////////////////////////

                                    cell = new PdfPCell(new Phrase(""));
                                    cell.Colspan = 7;
                                    SetBorder(cell, true, false, true, true);
                                    table.AddCell(cell);

                                    cell = new PdfPCell(new Phrase(""));
                                    cell.Colspan = 7;
                                    SetBorder(cell, false, false, false, false);
                                    table.AddCell(cell);

                                    doc.Add(table);
                                    #endregion

                                    //Información del Solicitante----------------------------------------------------------------------------------------------------------
                                    #region Info solicitante
                                    table = new PdfPTable(20);

                                    cell = new PdfPCell(new Phrase("INFORMACIÓN DEL SOLICITANTE:", FontFactory.GetFont("Arial", 11, Font.BOLD, Color.BLACK)));
                                    cell.Colspan = 20;
                                    SetBorder(cell, true, true, true, false);
                                    table.AddCell(cell);

                                    cell = new PdfPCell(new Phrase(""));
                                    cell.Colspan = 20;
                                    SetBorder(cell, true, false, true, false);
                                    table.AddCell(cell);

                                    cell = new PdfPCell(new Phrase("NOMBRE DE LA ENTIDAD:", FontFactory.GetFont("Arial", 9, Font.BOLD, Color.BLACK)));
                                    cell.Colspan = 6;
                                    SetBorder(cell, true, false, false, false);
                                    table.AddCell(cell);
                                    cell = new PdfPCell(new Phrase(solicitud.NombreEmpresa, FontFactory.GetFont("Arial", 9, Font.NORMAL, Color.BLACK)));
                                    cell.Colspan = 14;
                                    SetBorder(cell, false, false, true, false);
                                    table.AddCell(cell);

                                    cell = new PdfPCell(new Phrase("PERSONA CONTACTO:", FontFactory.GetFont("Arial", 9, Font.BOLD, Color.BLACK)));
                                    cell.Colspan = 5;
                                    SetBorder(cell, true, false, false, false);
                                    table.AddCell(cell);
                                    cell = new PdfPCell(new Phrase(solicitud.RepresentanteAutorizado, FontFactory.GetFont("Arial", 9, Font.NORMAL, Color.BLACK)));
                                    cell.Colspan = 8;
                                    SetBorder(cell, false, false, false, false);
                                    table.AddCell(cell);

                                    cell = new PdfPCell(new Phrase("TEL / CELULAR:", FontFactory.GetFont("Arial", 9, Font.BOLD, Color.BLACK)));
                                    cell.Colspan = 4;
                                    SetBorder(cell, false, false, false, false);
                                    table.AddCell(cell);
                                    cell = new PdfPCell(new Phrase(string.Format("{0} / {1}", solicitud.TelOficina, solicitud.TelCelular),
                                        FontFactory.GetFont("Arial", 9, Font.NORMAL, Color.BLACK)));
                                    cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                                    cell.Colspan = 3;
                                    SetBorder(cell, false, false, true, false);
                                    table.AddCell(cell);

                                    cell = new PdfPCell(new Phrase(""));
                                    cell.Colspan = 20;
                                    SetBorder(cell, true, false, true, false);
                                    table.AddCell(cell);

                                    cell = new PdfPCell(new Phrase("DIRECCIÓN DONDE SE REALIZARÁ LA EXCAVACIÓN Y/O DEMOLICIÓN:", FontFactory.GetFont("Arial", 9, Font.BOLD, Color.BLACK)));
                                    cell.Colspan = 20;
                                    SetBorder(cell, true, false, true, false);
                                    table.AddCell(cell);


                                    cell = new PdfPCell(new Phrase(solicitud.BoUrb + ", " + solicitud.SectorCalle + ", " + solicitud.Carretera + ", "
                                        + municipioTrabajoDDL.SelectedValue + " KM:" + solicitud.KM.ToString() + " HM:" + solicitud.HM.ToString()
                                        , FontFactory.GetFont("Arial", 9, Font.NORMAL, Color.BLACK)));
                                    cell.Colspan = 20;
                                    SetBorder(cell, true, false, true, false);
                                    table.AddCell(cell);
                                    cell = new PdfPCell(new Phrase(" "));
                                    cell.Colspan = 20;
                                    SetBorder(cell, true, false, true, false);
                                    table.AddCell(cell);
                                    cell.Colspan = 20;
                                    SetBorder(cell, true, false, true, true);
                                    table.AddCell(cell);

                                    cell = new PdfPCell(new Phrase(""));
                                    cell.Colspan = 20;
                                    SetBorder(cell, false, false, false, false);
                                    table.AddCell(cell);

                                    doc.Add(table);

                                    #endregion

                                    //----Información del Subcontratista---------------------------------------------------------------------------------------------------------------------------------------------------
                                    #region Info Sub
                                    table = new PdfPTable(20);

                                    cell = new PdfPCell(new Phrase("INFORMACIÓN DEL SUBCONTRATISTA:", FontFactory.GetFont("Arial", 11, Font.BOLD, Color.BLACK)));
                                    cell.Colspan = 20;
                                    SetBorder(cell, true, true, true, false);
                                    table.AddCell(cell);

                                    cell = new PdfPCell(new Phrase(""));
                                    cell.Colspan = 20;
                                    SetBorder(cell, true, false, true, false);
                                    table.AddCell(cell);

                                    cell = new PdfPCell(new Phrase("NOMBRE DE LA ENTIDAD:", FontFactory.GetFont("Arial", 9, Font.BOLD, Color.BLACK)));
                                    cell.Colspan = 6;
                                    SetBorder(cell, true, false, false, false);
                                    table.AddCell(cell);
                                    cell = new PdfPCell(new Phrase(solicitud.Subcontratista, FontFactory.GetFont("Arial", 9, Font.NORMAL, Color.BLACK)));
                                    cell.Colspan = 14;
                                    SetBorder(cell, false, false, true, false);
                                    table.AddCell(cell);

                                    cell = new PdfPCell(new Phrase("PERSONA CONTACTO:", FontFactory.GetFont("Arial", 9, Font.BOLD, Color.BLACK)));
                                    cell.Colspan = 5;
                                    SetBorder(cell, true, false, false, false);
                                    table.AddCell(cell);
                                    cell = new PdfPCell(new Phrase(solicitud.RepresentanteAutorizadoSub, FontFactory.GetFont("Arial", 9, Font.NORMAL, Color.BLACK)));
                                    cell.Colspan = 8;
                                    SetBorder(cell, false, false, false, false);
                                    table.AddCell(cell);
                                    cell = new PdfPCell(new Phrase("TEL / CELULAR:", FontFactory.GetFont("Arial", 9, Font.BOLD, Color.BLACK)));
                                    cell.Colspan = 4;
                                    SetBorder(cell, false, false, false, false);
                                    table.AddCell(cell);
                                    cell = new PdfPCell(new Phrase(string.Format("{0} / {1}", solicitud.TelOficinaSub, solicitud.TelCelularSub),
                                        FontFactory.GetFont("Arial", 9, Font.NORMAL, Color.BLACK)));
                                    cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                                    cell.Colspan = 3;
                                    SetBorder(cell, false, false, true, false);
                                    table.AddCell(cell);

                                    cell = new PdfPCell(new Phrase(" "));
                                    cell.Colspan = 20;
                                    SetBorder(cell, true, false, true, true);
                                    table.AddCell(cell);

                                    cell = new PdfPCell(new Phrase(""));
                                    cell.Colspan = 20;
                                    SetBorder(cell, false, false, false, false);
                                    table.AddCell(cell);

                                    doc.Add(table);
                                    #endregion

                                    //Información de los Trabajos a Realizar//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                                    #region Info trabajos
                                    table = new PdfPTable(20);
                                    cell = new PdfPCell(new Phrase("INFORMACIÓN DE LOS TRABAJOS A REALIZAR:", FontFactory.GetFont("Arial", 11, Font.BOLD, Color.BLACK)));
                                    cell.Colspan = 20;
                                    SetBorder(cell, true, true, true, false);
                                    table.AddCell(cell);

                                    cell = new PdfPCell(new Phrase(""));
                                    cell.Colspan = 20;
                                    SetBorder(cell, true, false, true, false);
                                    table.AddCell(cell);

                                    cell = new PdfPCell(new Phrase("FECHA DE COMIENZO:", FontFactory.GetFont("Arial", 9, Font.BOLD, Color.BLACK)));
                                    cell.Colspan = 5;
                                    SetBorder(cell, true, false, false, false);
                                    table.AddCell(cell);
                                    cell = new PdfPCell(new Phrase(solicitud.FechaComienzo.ToShortDateString(), FontFactory.GetFont("Arial", 9, Font.NORMAL, Color.BLACK)));
                                    cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                                    cell.Colspan = 3;
                                    SetBorder(cell, false, false, false, false);
                                    table.AddCell(cell);
                                    cell = new PdfPCell(new Phrase(" "));
                                    cell.Colspan = 4;
                                    SetBorder(cell, false, false, false, false);
                                    table.AddCell(cell);
                                    cell = new PdfPCell(new Phrase("FECHA DE EXPIRACIÓN:", FontFactory.GetFont("Arial", 9, Font.BOLD, Color.BLACK)));
                                    cell.Colspan = 5;
                                    SetBorder(cell, false, false, false, false);
                                    table.AddCell(cell);
                                    cell = new PdfPCell(new Phrase(solicitud.FechaExpiracion.ToShortDateString(), FontFactory.GetFont("Arial", 9, Font.NORMAL, Color.BLACK)));
                                    cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                                    cell.Colspan = 3;
                                    SetBorder(cell, false, false, true, false);

                                    table.AddCell(cell);

                                    cell = new PdfPCell(new Phrase("HORARIO EN QUE SE REALIZARÁ LA(S) EXCAVACIÓN Y/O DEMOLICIÓN", FontFactory.GetFont("Arial", 9, Font.BOLD, Color.BLACK)));
                                    cell.Colspan = 6;
                                    SetBorder(cell, true, false, false, false);
                                    table.AddCell(cell);
                                    cell = new PdfPCell(new Phrase(solicitud.Horario, FontFactory.GetFont("Arial", 9, Font.NORMAL, Color.BLACK)));
                                    cell.Colspan = 14;
                                    SetBorder(cell, false, false, true, false);
                                    table.AddCell(cell);

                                    cell = new PdfPCell(new Phrase(""));
                                    cell.Colspan = 20;
                                    SetBorder(cell, true, false, true, false);
                                    table.AddCell(cell);

                                    cell = new PdfPCell(new Phrase("MAQUINARIA", FontFactory.GetFont("Arial", 9, Font.BOLD, Color.BLACK)));
                                    cell.Colspan = 3;
                                    SetBorder(cell, true, false, false, false);
                                    table.AddCell(cell);

                                    cell.Colspan = 1;
                                    cbox = uncheck;
                                    if (solicitud.Maquinaria)
                                        cbox = check;
                                    SetBorder(cell, false, false, false, false);
                                    table.AddCell(cbox);

                                    cell = new PdfPCell(new Phrase("SI", FontFactory.GetFont("Arial", 9, Font.BOLD, Color.BLACK)));
                                    cell.Colspan = 1;
                                    SetBorder(cell, false, false, false, false);
                                    table.AddCell(cell);

                                    cell.Colspan = 1;
                                    cbox = uncheck;
                                    if (!solicitud.Maquinaria)
                                        cbox = check;
                                    SetBorder(cell, false, false, false, false);
                                    table.AddCell(cbox);

                                    cell = new PdfPCell(new Phrase("NO", FontFactory.GetFont("Arial", 9, Font.BOLD, Color.BLACK)));
                                    cell.Colspan = 1;
                                    SetBorder(cell, false, false, false, false);
                                    table.AddCell(cell);
                                    cell = new PdfPCell(new Phrase("DESCRIPCIÓN MAQUINARIA:", FontFactory.GetFont("Arial", 9, Font.BOLD, Color.BLACK)));
                                    cell.Colspan = 6;
                                    SetBorder(cell, false, false, false, false);
                                    table.AddCell(cell);
                                    cell = new PdfPCell(new Phrase(solicitud.TipoMaquinaria, FontFactory.GetFont("Arial", 9, Font.NORMAL, Color.BLACK)));
                                    cell.Colspan = 7;
                                    SetBorder(cell, false, false, true, false);
                                    table.AddCell(cell);

                                    cell = new PdfPCell(new Phrase("EXPLOSIVOS", FontFactory.GetFont("Arial", 9, Font.BOLD, Color.BLACK)));
                                    cell.Colspan = 3;
                                    SetBorder(cell, true, false, false, false);
                                    table.AddCell(cell);

                                    cbox = uncheck;
                                    if (solicitud.Explosivos)
                                        cbox = check;
                                    cell.Colspan = 1;
                                    SetBorder(cell, false, false, false, false);
                                    table.AddCell(cbox);

                                    cell = new PdfPCell(new Phrase("SI", FontFactory.GetFont("Arial", 9, Font.BOLD, Color.BLACK)));
                                    cell.Colspan = 1;
                                    SetBorder(cell, false, false, false, false);
                                    table.AddCell(cell);

                                    cbox = uncheck;
                                    if (!solicitud.Explosivos)
                                        cbox = check;
                                    cell.Colspan = 1;
                                    SetBorder(cell, false, false, false, false);
                                    table.AddCell(cbox);

                                    cell = new PdfPCell(new Phrase("NO", FontFactory.GetFont("Arial", 9, Font.BOLD, Color.BLACK)));
                                    cell.Colspan = 1;
                                    SetBorder(cell, false, false, false, false);
                                    table.AddCell(cell);

                                    cell = new PdfPCell(new Phrase("NÚMERO LICENCIA EXPLOSIVOS:", FontFactory.GetFont("Arial", 9, Font.BOLD, Color.BLACK)));
                                    cell.Colspan = 7;
                                    SetBorder(cell, false, false, false, false);
                                    table.AddCell(cell);
                                    cell = new PdfPCell(new Phrase(solicitud.LicenciaExplosivo, FontFactory.GetFont("Arial", 9, Font.NORMAL, Color.BLACK)));
                                    cell.Colspan = 6;
                                    SetBorder(cell, false, false, true, false);
                                    table.AddCell(cell);
                                    ///////////////////////////////////////////
                                    cell = new PdfPCell(new Phrase(""));
                                    cell.Colspan = 20;
                                    SetBorder(cell, true, false, true, false);
                                    table.AddCell(cell);

                                    cell = new PdfPCell(new Phrase("DESCRIPCIÓN DE LOS TRABAJOS A REALIZAR:", FontFactory.GetFont("Arial", 9, Font.BOLD, Color.BLACK)));
                                    cell.Colspan = 20;
                                    SetBorder(cell, true, false, true, false);
                                    table.AddCell(cell);
                                    cell = new PdfPCell(new Phrase(solicitud.RazonTrabajos, FontFactory.GetFont("Arial", 9, Font.NORMAL, Color.BLACK)));
                                    cell.Colspan = 20;
                                    SetBorder(cell, true, false, true, false);
                                    table.AddCell(cell);
                                    cell = new PdfPCell(new Phrase("REFERENCIAS:", FontFactory.GetFont("Arial", 9, Font.BOLD, Color.BLACK)));
                                    cell.Colspan = 4;
                                    SetBorder(cell, true, false, false, false);
                                    table.AddCell(cell);
                                    cell = new PdfPCell(new Phrase(solicitud.Referencias, FontFactory.GetFont("Arial", 9, Font.NORMAL, Color.BLACK)));
                                    cell.Colspan = 17;
                                    SetBorder(cell, false, false, true, false);
                                    table.AddCell(cell);
                                    cell = new PdfPCell(new Phrase(" "));
                                    cell.Colspan = 20;
                                    SetBorder(cell, true, false, true, false);
                                    table.AddCell(cell);
                                    cell = new PdfPCell(new Phrase(" "));
                                    cell.Colspan = 20;
                                    SetBorder(cell, true, false, true, true);
                                    table.AddCell(cell);

                                    doc.Add(table);
                                    #endregion

                                    #region Footer
                                    table = new PdfPTable(6);

                                    //cell = signatureImgCell;

                                    //cell.Colspan = 2;

                                    //cell.Border = 0;

                                    //cell.PaddingTop = 20f;

                                    //table.AddCell(cell);

                                    //p = new Paragraph("\n\n" + /*solicitud.Coordinador.Nombre +*/"\n___________________________________________________\n" +
                                    //"  FIRMA DEL COORDINADOR QUE AUTORIZÓ EL AVISO\n\n" +
                                    //"                             FECHA: " + Fecha + "\n\n", FontFactory.GetFont("Arial", 9, Font.BOLD, Color.BLACK));

                                    //p.Alignment = Element.ALIGN_TOP;

                                    //p = new Paragraph();

                                    //var phr = new Phrase("\n\n\n___________________________________________________\n" +
                                    //"  FIRMA DEL COORDINADOR QUE AUTORIZÓ EL AVISO\n\n");

                                    //phr.Font = FontFactory.GetFont("Arial", 9, Font.BOLD, Color.BLACK);

                                    //p.Alignment = Element.ALIGN_LEFT;

                                    //p.Font = FontFactory.GetFont("Arial", 9, Font.BOLD, Color.BLACK);


                                    //cell = new PdfPCell(new Phrase(p));
                                    cell = new PdfPCell();

                                    var firmaImg = iTextSharp.text.Image.GetInstance(Server.MapPath(
                                        string.Format("~/Images/Documentos/Firmas/{0}_Firma.png", user.Email)));

                                    firmaImg.ScalePercent(50f);

                                    firmaImg.SpacingBefore = 100f;

                                    //p.Add( new Chunk(firmaImg, 0, 100));

                                    //p.Add(phr);

                                    //firmaImg.Alignment = Element.ALIGN_BOTTOM;

                                    //firmaImg.SetAbsolutePosition(0f, 200f);

                                    cell.AddElement(firmaImg);

                                    //cell.AddElement(phr);


                                    //cell.AddElement(p);

                                    //cell.HorizontalAlignment = Element.ALIGN_BOTTOM;
                                    cell.Colspan = 4;
                                    cell.Border = 0;
                                    //cell.Image = iTextSharp.text.Image.GetInstance("~/Images/Documentos/Firmas/firma1.png");
                                    table.AddCell(cell);

                                    cell = ImageCell("~/images/SelloOficialCertificacion.png", 10f, PdfPCell.ALIGN_RIGHT);
                                    cell.Colspan = 2;
                                    cell.Border = 0;
                                    table.AddCell(cell);

                                    p = new Paragraph("FECHA: " + Fecha + "\n\nAdvertencia: Esta certificación no constituye un permiso para excavar o demoler dentro de la jurisdicción del \n" +
                                    "Estado Libre Asociado de Puerto Rico. La misma deberá  ser mostrada a solicitud de la Policía de Puerto Rico,\n" +
                                    "Policía Municipal, Cuerpo de Bomberos, Oficiales del COT, Inspectores de DTOP y CSP y cualquier funcionario\n" +
                                    "del DTOP que asi lo solicite.", FontFactory.GetFont("Arial", 6, Font.NORMAL, Color.BLACK));
                                    p.Alignment = Element.ALIGN_JUSTIFIED;
                                    cell = new PdfPCell(new Phrase(p));
                                    cell.Border = 0;
                                    cell.Colspan = 4;
                                    table.AddCell(cell);

                                    p = new Paragraph("                     SELLO          OFICIAL", FontFactory.GetFont("Arial", 10, Font.NORMAL, Color.BLACK));
                                    p.Alignment = Element.ALIGN_RIGHT;
                                    cell = new PdfPCell(new Phrase(p));
                                    cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                                    cell.Border = 0;
                                    cell.Colspan = 2;
                                    table.AddCell(cell);


                                    doc.Add(table);
                                    #endregion

                                    doc.Close();
                                    byte[] bytes = memoryStream.ToArray();
                                    memoryStream.Close();

                                    //File.WriteAllBytes(string.Format(@"{0}/{1}/Cert_{2}_Inicial.pdf", new DocumentoRequerido().DocumentosInicialesSavePath,
                                    //    solicitud.Usuario.Email, solicitud.NumeroControl.NumControlText), bytes);



                                    //File.WriteAllBytes(string.Format(@"C:\inetpub\wwwroot\EXC\Certificaciones\Cert_{0}_Inicial.pdf", solicitud.NumeroControl.NumControlText), bytes);

                                    File.WriteAllBytes(Server.MapPath(string.Format(@"~/Certificaciones/Cert_{0}_Inicial.pdf", solicitud.NumeroControl.NumControlText)), bytes);
                                }

                                #endregion

                                attachment.AddLast(Server.MapPath(string.Format(@"~/Certificaciones/Cert_{0}_Inicial.pdf", solicitud.NumeroControl.NumControlText)));

                                try
                                {
                                    if (CheckForInternetConnection())
                                        SendEmail(to, "*****@*****.**",
                                mails.ElementAt((int)Mail.Notifications.SolicitudAprovada).Subject,
                                mails.ElementAt((int)Mail.Notifications.SolicitudAprovada).Body.Replace(
                                "@NumControl", numeroControl.NumControlText).Replace("@NombreEmpresa", solicitud.NombreEmpresa), attachment); // only test
                                }

                                catch (Exception ex)
                                {
                                    if (ex.Message == "")
                                    {

                                    }
                                }
                                #endregion


                                #region Enviar email a operadores

                                //to = new LinkedList<string>();

                                LinkedList<Operador> operadores = new SolicitudesInicialesServicio().GetOperadores();

                                Entidad.User solicitudUser = new SolicitudesInicialesServicio().GetUser(solicitud.Usuario.Email);

                                to = new LinkedList<string>();

                                //No se lo envies al mismo que la sometio, si es operador
                                foreach (var o in operadores)
                                {
                                    if (!solicitudUser.EmpresaID.Equals(o.Nombre) /*!currentUser.Email.Equals(o.Email)*/)
                                    {
                                        to.AddLast(o.Email);
                                    }
                                }

                                //SendEmail(to, "", "", "");                            

                                //SendEmail(to, "*****@*****.**", "Operador", "Aviso de excavacion a operador", new LinkedList<string>()); //only foor test

                                #region Add croquis to email

                                string croquisPath = ViewState["croquisPath"] == null
                                    ? string.Empty : (string)ViewState["croquisPath"];

                                if (croquisPath != null)
                                {
                                    attachment.AddLast(croquisPath);
                                }

                                //LinkedList<ImageButton> ImageButtons = (LinkedList<ImageButton>)Session["ImageButtons"];

                                //    //Path del image es el mismo path que esta ene l objeto de docs, pero no tengo acceso a docs desde aqui
                                //    foreach (var i in ImageButtons)
                                //    {
                                //        if (i.ID.ToUpper().Contains("CROQUIS"))
                                //        {
                                //            attachment.AddLast((i.ImageUrl).Replace("~", ".."));

                                //            break;
                                //        }
                                //    }

                                #endregion

                                try
                                {
                                    if (CheckForInternetConnection())
                                        SendEmail(to, "*****@*****.**",
                                mails.ElementAt((int)Mail.Notifications.OperadorNuevaSolicitud).Subject.Replace("@Pueblo", string.Format("{0}", municipioTrabajoDDL.SelectedValue)),
                                mails.ElementAt((int)Mail.Notifications.OperadorNuevaSolicitud).Body.Replace("@NumControl", numeroControl.NumControlText), attachment);

                                }

                                catch (Exception ex)
                                {
                                    if (ex.Message == "")
                                    {

                                    }
                                }
                                #endregion
                                #endregion
                            }

                            else
                            {
                                #region Docs incompletos
                                //Notifica excavador que tiene docs incompletos
                                to = new LinkedList<string>();//user email

                                to.AddLast(solicitud.Usuario.Email);

                                solicitud.FechaDocsIncompletos = DateTime.Now;

                                try
                                {
                                    if (CheckForInternetConnection())
                                    {
                                        #region Build razones por devolucion

                                        string razonesMsg = string.Empty;

                                        if (solicitud.SolicitudStatusID == (int)SolicitudAviso.SolicitudStatuses.INCOMPLETO)
                                            razonesMsg = string.Format("Observaciones : {0} \r\n\r\n", solicitud.Observaciones);

                                        for (int i = 0; i < documentos.Count; i++)
                                        {
                                            if (!string.IsNullOrEmpty(documentos.ElementAt(i).Comentario))
                                            {
                                                razonesMsg += string.Format("{0} : {1} \r\n\r\n", documentos.ElementAt(i).Nombre.Replace("_", " "),
                                                    documentos.ElementAt(i).Comentario);
                                            }
                                        }

                                        #endregion

                                        SendEmail(to, "*****@*****.**",
                                        mails.ElementAt((int)Mail.Notifications.DocsIncompletos).Subject,
                                        mails.ElementAt((int)Mail.Notifications.DocsIncompletos).Body.Replace(
                                        "@NumControl", numeroControl.NumControlText).Replace("@NombreEmpresa", solicitud.NombreEmpresa).Replace("@Razones", razonesMsg),
                                        new LinkedList<string>());
                                    }
                                }

                                catch (Exception)
                                {
                                }
                                #endregion
                            }
                        }

                        //docs inc 
                        else if ((Convert.ToInt32(solicitud.EstatusId)) == ((int)SolicitudAviso.Estatus.PendienteDocumentosIncompletos))
                        {
                            #region sometio despues de estar docs incompletos
                            LinkedList<FileUpload> _docRequeridosFileUpload = new LinkedList<FileUpload>();

                            #region Validate docs requeridos

                            LinkedList<FileUpload> docRequeridosFileUpload = (LinkedList<FileUpload>)Session["docRequeridosFileUpload"];

                            foreach (var t in docRequeridosFileUpload)
                            {
                                _docRequeridosFileUpload.AddLast((FileUpload)docRequeridosMainDiv.FindControl(t.ID));
                            }

                            foreach (var d in _docRequeridosFileUpload)
                            {
                                if (!d.HasFile)
                                {
                                    exceptionMsg += string.Format("<b>{0}:</b> Requerido <br />", d.ID.Replace("fileUp", string.Empty));
                                }
                            }

                            if (!string.IsNullOrWhiteSpace(exceptionMsg))
                            {
                                throw new Exception(exceptionMsg);
                            }

                            #endregion

                            #region Docs
                            
                            for (int i = 0; i < _docRequeridosFileUpload.Count; i++)
                            {
                                DocumentoRequerido docReq = new DocumentoRequerido()
                                {
                                    Nombre = _docRequeridosFileUpload.ElementAt(i).ID.Replace("fileUp", string.Empty),

                                    NumeroControl = numeroControl,

                                    Path = string.Format("{0}/{1}/{2}_{3}", new DocumentoRequerido().DocumentosInicialesSavePath, user.Email
                                    , solicitud.NumeroControl.NumControlText, Path.GetFileName(_docRequeridosFileUpload.ElementAt(i).PostedFile.FileName.Replace(
                                "#", string.Empty).Replace("&", string.Empty))),

                                    Tipo = tipoAvisoRBtnLst.SelectedIndex
                                };

                                LinkedList<DropDownList> docAsociadosStatuses = (LinkedList<DropDownList>)Session["docAsociadosStatuses"];

                                docReq.Status = docAsociadosStatuses.ElementAt(i).SelectedIndex;

                                documentos.AddLast(docReq);
                            }

                            #endregion

                            #region Update documentos con data de documentosExistentes

                            for (int i = 0; i < documentos.Count; i++)
                            {
                                documentos.ElementAt(i).DocumentoId = docsExistentes.ElementAt(i).DocumentoId;

                                documentos.ElementAt(i).Comentario = docsExistentes.ElementAt(i).Comentario;
                            }

                            #endregion

                            SaveDocs(_docRequeridosFileUpload, documentos);

                            solicitud.EstatusId = ((int)SolicitudAviso.Estatus.PendienteRevisarCoordinador).ToString();

                            solicitud.FechaDocsIncompletos = Convert.ToDateTime(@"1/1/1900");

                            #region Email coordinadores

                            to = new LinkedList<string>();

                            LinkedList<User> coordinadores = new SolicitudesInicialesServicio().GetCoordinadores(),
                                superInspectores = new SolicitudesInicialesServicio().GetSuperInspectores(),
                                directores = new SolicitudesInicialesServicio().GetDirectores();

                            for (int i = 0; i < coordinadores.Count; i++)
                            {
                                to.AddLast(coordinadores.ElementAt(i).Email);
                            }

                            for (int i = 0; i < superInspectores.Count; i++)
                            {
                                to.AddLast(superInspectores.ElementAt(i).Email);
                            }

                            for (int i = 0; i < directores.Count; i++)
                            {
                                to.AddLast(directores.ElementAt(i).Email);
                            }

                            try
                            {
                                if (CheckForInternetConnection())
                                    SendEmail(to, "*****@*****.**",
                                    mails.ElementAt((int)Mail.Notifications.SolicitudRevisada).Subject,
                                    mails.ElementAt((int)Mail.Notifications.SolicitudRevisada).Body.Replace(
                                    "@NumControl", numeroControl.NumControlText).Replace("@NombreEmpresa", solicitud.NombreEmpresa), new LinkedList<string>()); // only test
                            }

                            catch (Exception ex)
                            {
                                if (ex.Message == "")
                                {

                                }
                            }

                            #endregion

                            #endregion

                        }

                        else if ((Convert.ToInt32(solicitud.EstatusId)) == ((int)SolicitudAviso.Estatus.EnProcesoInspeccion)
                            || (Convert.ToInt32(solicitud.EstatusId)) == ((int)SolicitudAviso.Estatus.InspeccionCompletada)
                            || (Convert.ToInt32(solicitud.EstatusId)) == ((int)SolicitudAviso.Estatus.PendienteAsignarInspector))
                        {
                            documentos = docsExistentes;

                            solicitud.EstatusId = solicitudExistente.EstatusId;

                            solicitud.FechaRespuestaSolicitadas = solicitudExistente.FechaRespuestaSolicitadas;
                        }

                        #endregion

                        solicitud.NumeroControl.NumControl = Convert.ToInt32(solicitud.NumeroControl.NumControlText.Substring(4));

                        //Agrega letra al status id
                        solicitud.EstatusId = !solicitud.EstatusId.Contains('S') ? string.Format("{0}{1}", solicitud.LetraStatus, solicitud.EstatusId)
                            : solicitud.EstatusId;

                        //documentos = SetDocumentsNumControl(documentos, numeroControl);

                        //averias = SetAveriasNumControl(averias, numeroControl);

                        #region Set averias & docs ids
                        //for (int i = 0; i < averiasExistentes.Count; i++)
                        //{
                        //    averias.ElementAt(i).ID = averiasExistentes.ElementAt(i).ID;
                        //}

                        //for (int i = 0; i < documentos.Count; i++)
                        //{
                        //    documentos.ElementAt(i).DocumentoId = docsExistentes.ElementAt(i).DocumentoId;

                        //    documentos.ElementAt(i).Status = docsExistentes.ElementAt(i).Status;
                        //}
                        #endregion

                        new DocumentosRequeridosServicio().TryUpdate(documentos);

                        new SolicitudesInicialesServicio().TryUpdate(solicitud);

                        Session.Remove("Respuesta");

                        Session.Remove("RespuestaVisibility");

                        Response.Redirect("~/Default.aspx", false);

                        #endregion
                    }

                    #endregion

                }
            }

            catch (Exception ex)
            {
                if (string.IsNullOrWhiteSpace(exceptionMsg))
                {
                    errorLbl2.InnerText = ex.Message;
                }

                else
                {
                    errorLbl2.InnerHtml = exceptionMsg;
                }

                if (ViewState["justCreatedInspeccion"] != null)
                {
                    new InspeccionesServicio().TryDelete(exceptionNumControl, ((int)SolicitudAviso.TiposExtensiones.Inicial).ToString());
                }

                String errorLog = "Date: " + DateTime.Now.ToLongDateString() + "\r\n NumeroControl:" + exceptionNumControl.NumControlText
                            + "\r\n Message: " + ex.Message + "\r\n Source: "
                            + ex.Source + "\r\n Stacktrace: " + ex.StackTrace + "\r\n TargetSite: " + ex.TargetSite.ToString() + "\r\n\r\n";

                //File.WriteAllText(Server.MapPath(Inspeccion.ErrorLogDir + "SolicitudInicLog.txt"), errorLog);

                //transaction.Rollback();

                Page.DataBind();

                errorPopup.Show();
            }

            

            guardarBtn.Enabled = true;
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            guardarBtn.Enabled = true;

            User user = Session["UserObj"] == null ? new User() : (User)Session["UserObj"];

            if (!user.Rol.VerAvisoInicial)
            {
                Response.Redirect("~/Default.aspx");
            }

            var title = (HtmlGenericControl)Master.FindControl("pageTitleSpan");

            title.InnerText = Title;            

            CreateDocReqCtrls(tipoAvisoRBtnLst.SelectedIndex);

            if (!IsPostBack)
            {
                #region Populate horario ddl

                horarioDDL.Items.Clear();

                horarioDDL2.Items.Clear();

                horarioDDL.Items.Add("Seleccionar");

                horarioDDL2.Items.Add("Seleccionar");

                for (int i = 0; i < 2; i++)
                {
                    string dayTime = "AM";

                    if (i == 1)
                    {
                        dayTime = "PM";
                    }

                    for (int h = 1; h < 13; h++)
                    {
                        for (int m = 0; m < 4; m += 3)
                        {
                            horarioDDL.Items.Add(h.ToString() + ":" + m.ToString() + "0" + dayTime);

                            horarioDDL2.Items.Add(h.ToString() + ":" + m.ToString() + "0" + dayTime);
                        }
                    }
                }
                #endregion

                #region Clean up session

                Session.Remove("Respuesta");

                Session.Remove("RespuestaVisibility");

                Session.Remove("docAsociadosStatuses");

                Session.Remove("docsRequeridos");

                Session.Remove("croquisPath"); 

                #endregion

                Page.Form.Attributes.Add("enctype", "multipart/form-data");

                NumeroControl numeroControl = new NumeroControl()
                {
                    NumControlText = Request.QueryString["NumeroControl"]
                };

                try
                {
                    #region Set Municipios

                    LinkedList<String> municipios = new SolicitudesInicialesServicio().GetMunicipios();

                    municipioDDL.Items.Add("Seleccionar");

                    municipioSubDDL.Items.Add("Seleccionar");

                    municipioTrabajoDDL.Items.Add("Seleccionar");

                    foreach (var m in municipios)
                    {
                        municipioDDL.Items.Add(m);

                        municipioSubDDL.Items.Add(m);

                        municipioTrabajoDDL.Items.Add(m);
                    }

                    municipioDDL.SelectedIndex = 0;

                    municipioSubDDL.SelectedIndex = 0;

                    municipioTrabajoDDL.SelectedIndex = 0;

                    #endregion

                    #region Set multi line txtbx maxlength cause clieent side max length doesn't work

                    direccionPostalContactoTxtBx.Attributes["maxlength"] = Convert.ToString(400);

                    direccionTxtBx.Attributes["maxlength"] = Convert.ToString(400);

                    direccionSubTxtBx.Attributes["maxlength"] = Convert.ToString(400);

                    referenciasTxtBx.Attributes["maxlength"] = Convert.ToString(600);

                    razonTxtBx.Attributes["maxlength"] = Convert.ToString(600);

                    tipoMaquinariaTxtBx.Attributes["maxlength"] = Convert.ToString(400);

                    observacionesTxtBx.Attributes["maxlength"] = Convert.ToString(400);

                    enCasoEmergenciaTxtBx.Attributes["maxlength"] = Convert.ToString(100); 

                    #endregion

                    //if numcontrol exist, get data. Else setup controls for creation
                    if (String.IsNullOrEmpty(numeroControl.NumControlText))
                    {
                        #region Create

                        if(user.Rol.ID != ((int)Role.TipoRoles.Excavador))
                            Response.Redirect("~/Default.aspx", true);

                        #region Set visibilities

                        SolicitudStatusLbl.Visible = false;

                        solicitudStatusCol.Visible = false;

                        solicitudStatusLblCol.Visible = false;

                        fechaComienzoDiv.Visible = false;

                        fechaComienzoDiv2.Visible = false;

                        fechaExpiracionDiv.Visible = false;

                        fechaExpiracionDiv2.Visible = false;

                        docsRequeridosHeader.Visible = true;

                        docRequeridosMainDiv.Visible = true;

                        docsAsociadosHeader.Visible = false;

                        docsAsociadosTableTag.Visible = false;

                        respuestasDiv.Visible = false;

                        #endregion

                        tipoMaquinariaTxtBx.Enabled = false;

                        licExplosivoTxtBx.Enabled = false;

                        fechaExpiracionExplosivoTxtBx.Enabled = false;

                        fechaComienzoPropuestoTxtBx.Enabled = true;

                        fechaComienzoImgBtn.Visible = true;

                        primeraExtensionLink.NavigateUrl = String.Empty;

                        primeraExtensionLink.Text = "No hay extensiones disponibles";

                        segundaExtensionLink.Visible = false;

                        #region Poblar campos contratista

                        #region Company

                        companyDDL.Items.Add("Seleccionar");

                        Company company = new SolicitudesInicialesServicio().GetCompany(user);

                        companyDDL.Items.Add(company.Nombre);

                        companyDDL.SelectedIndex = 1;

                        #endregion

                        representanteTxtBx.Text = company.RepresentanteAutorizado;

                        telOficinaTxtBx.Text = company.TelOficina;

                        telTrabajoTxtBx.Text = company.TelTrabajo;

                        celularTxtBx.Text = company.Celular;

                        emailTxtBx.Text = company.CorreoElectronico;

                        direccionTxtBx.Text = company.DireccionPostal.Replace(",", string.Empty);

                        codigoPostalTxtBx.Text = company.CodigoPostal;

                        municipioDDL.SelectedValue = company.Municipio;

                        #endregion

                        #endregion
                    }

                    else
                    {
                        #region Edit

                        numeroControl.Year = Convert.ToInt32(numeroControl.NumControlText.Substring(0, 4));

                        numeroControl.NumControl = Convert.ToInt32(numeroControl.NumControlText.Substring(4));

                        SolicitudAviso solicitud =
                            new SolicitudesInicialesServicio().GetSolicitud(numeroControl);

                        //Don't allow regular user to view other user's aviso
                        if (user.Rol.ID == (int)Role.TipoRoles.Excavador && !solicitud.Usuario.Email.Equals(user.Email))
                        {
                            Response.Redirect("~/Default.aspx", true);
                        }

                        #region Set links extensiones

                        SolicitudAviso primeraExt = new PrimerasExtensionesServicio().GetPrimeraExtension(numeroControl),
                                        segundaExt = new SegundasExtensionesServicio().GetSegundaExtension(numeroControl);

                        primeraExtensionLink.NavigateUrl = primeraExtensionLink.NavigateUrl + "?NumeroControl=" + numeroControl.NumControlText;

                        segundaExtensionLink.NavigateUrl = segundaExtensionLink.NavigateUrl + "?NumeroControl=" + numeroControl.NumControlText;

                        //Si tiene la primera ext
                        if (!String.IsNullOrEmpty(primeraExt.NumeroControl.NumControlText))
                        {
                            primeraExtensionLink.Text = "Ver Primera";

                            //Si tiene la segunda ext
                            if (!String.IsNullOrEmpty(segundaExt.NumeroControl.NumControlText))
                            {
                                segundaExtensionLink.Text = "Ver Segunda";
                            }

                            else
                            {
                                //Si puede crear ext
                                if (solicitud.PuedeCrearSegundaExt)
                                    segundaExtensionLink.Text = "Crear Segunda";

                                else
                                {
                                    segundaExtensionLink.Visible = false;

                                    //Para que no pase a la ext si le da al link
                                    segundaExtensionLink.NavigateUrl = string.Empty;
                                }

                            }
                        }

                        else
                        {
                            //Si puede crear ext
                            if (solicitud.PuedeCrearPrimeraExt)
                                primeraExtensionLink.Text = "Crear Primera";

                            else
                            {
                                primeraExtensionLink.Text = "No hay extensiones disponibles";

                                //Para que no pase a la ext si le da al link
                                primeraExtensionLink.NavigateUrl = string.Empty;
                            }

                            segundaExtensionLink.Visible = false;
                        }
                        #endregion

                        #region Poblar campos solicitud

                        #region Info general

                        numeroControlTxtBx.Text = numeroControl.NumControlText;

                        emergenciaChkBx.Checked = solicitud.Emergencia;

                        if (!user.Rol.EditarAvisoEmergerncia)
                        {
                            emergenciaChkBx.Enabled = false;
                        }

                        areaDepartamentoTxtBx.Enabled = tipoAvisoRBtnLst.SelectedIndex != 2;

                        areaDepartamentoTxtBx.Enabled = tipoAvisoRBtnLst.SelectedIndex != 2;                     

                        if (tipoAvisoRBtnLst.SelectedIndex == 2)
                        {
                            areaDepartamentoTxtBx.Text = string.Empty;

                            areaDepartamentoTxtBx.Text = string.Empty;
                        }

                        tipoAvisoRBtnLst.SelectedIndex = Convert.ToInt32(solicitud.TipoAviso);

                        SetDocsVisibilities();

                        if (!string.IsNullOrWhiteSpace(solicitud.EstatusId))
                        {
                            //Quitale la letra y brega con el numero solo
                            solicitud.EstatusId = solicitud.EstatusId.Replace(solicitud.LetraStatus, string.Empty).Replace(new Inspeccion().LetraStatus, string.Empty);

                            #region Fill status msgs

                            var statusMsgs = new SolicitudesInicialesServicio().GetStatusMsgs();

                            Dictionary<string, System.Drawing.Color> newStatusMsgs = new Dictionary<string, System.Drawing.Color>();

                            if (Convert.ToInt32(solicitud.EstatusId) < 8)
                            {
                                newStatusMsgs.Add("filler", System.Drawing.Color.Violet);

                                for (int i = 0; i < solicitud.StatusMsgs.Count; i++)
                                {
                                    newStatusMsgs.Add(statusMsgs.ElementAt(i), solicitud.StatusMsgs.ElementAt(i).Value);
                                }

                                solicitud.StatusMsgs = newStatusMsgs;

                                statusLbl.Text = solicitud.StatusMsgs.Keys.ElementAt(Convert.ToInt32(solicitud.EstatusId));

                                statusLbl.ForeColor = solicitud.StatusMsgs.Values.ElementAt(Convert.ToInt32(solicitud.EstatusId));
                            }

                                //Eliminada
                            else
                            {
                                newStatusMsgs.Add("Eliminada", System.Drawing.Color.White);

                                solicitud.StatusMsgs = newStatusMsgs;

                                statusLbl.Text = solicitud.StatusMsgs.Keys.ElementAt(0);

                                statusLbl.ForeColor = solicitud.StatusMsgs.Values.ElementAt(0);
                            }

                            

                            #endregion

                            statusHF.Value = solicitud.EstatusId;

                            if (solicitud.EstatusId.Equals((((int)SolicitudAviso.Estatus.PendienteDocumentosIncompletos).ToString())))
                            {
                                if (user.Rol.ID != (int)Role.TipoRoles.Excavador)
                                {
                                    coordinadorPopup.Show();
                                }

                                else
                                {
                                    solicitudStatusDDL.Enabled = false;

                                    observacionesTxtBx.ReadOnly = true;
                                }
                            }

                            else if (solicitud.EstatusId.Equals((((int)SolicitudAviso.Estatus.PendienteRevisarCoordinador).ToString())))
                            {
                                //si es empresa(exc/demole)
                                if (user.Rol.ID != (int)Role.TipoRoles.Coordinador
                                    && user.Rol.ID != (int)Role.TipoRoles.Admin
                                    && user.Rol.ID != (int)Role.TipoRoles.SuperInspector
                                    && user.Rol.ID != (int)Role.TipoRoles.Director)
                                {
                                    coordinadorPoPupHeader.InnerText = "Excavador / Demoledor";

                                    coordinadorPopupBodyLbl.Text = "Esperar por revisión de coordinador";

                                    coordinadorPopup.Show();
                                }
                            }

                            //Do not allow update if any of these conditions
                            else if (!solicitud.EstatusId.Equals(((int)SolicitudAviso.Estatus.PendienteRevisarCoordinador).ToString())
                                    || !solicitud.EstatusId.Equals(((int)SolicitudAviso.Estatus.PendienteDocumentosIncompletos).ToString()))
                            {
                                if (user.Rol.ID != (int)Role.TipoRoles.Director && user.Rol.ID != (int)Role.TipoRoles.SuperInspector)
                                {
                                    guardarBtn.Enabled = false;
                                }
                            }

                            //Allow to view extensions if it's inactive and extensions have already been created
                            if (solicitud.EstatusId.Equals(((int)SolicitudAviso.Estatus.Inactiva).ToString())
                                || solicitud.EstatusId.Equals(((int)SolicitudAviso.Estatus.Denegada).ToString()))
                            {
                                if (string.IsNullOrWhiteSpace(primeraExt.NumeroControl.NumControlText))
                                {
                                    primeraExtensionLink.Visible = false;
                                }

                                if (string.IsNullOrWhiteSpace(segundaExt.NumeroControl.NumControlText))
                                {
                                    segundaExtensionLink.Visible = false;
                                }
                            }

                            //Don't allow to create extensions if it ain't aprovada
                            else if (!solicitud.EstatusId.Equals(((int)SolicitudAviso.Estatus.PendienteAsignarInspector).ToString())
                                & !solicitud.EstatusId.Equals(((int)SolicitudAviso.Estatus.InspeccionCompletada).ToString())
                                & !solicitud.EstatusId.Equals(((int)SolicitudAviso.Estatus.EnProcesoInspeccion).ToString()))
                            {
                                primeraExtensionLink.Visible = false;

                                segundaExtensionLink.Visible = false;
                            }                            
                        }

                        #region Set solicitud status

                        solicitudStatusDDL.SelectedIndex = solicitud.SolicitudStatusID;

                        solicitudStatusDDL_SelectedIndexChanged(sender, EventArgs.Empty);

                        observacionesTxtBx.Text = solicitud.Observaciones;

                        #endregion

                        nombreContactoTxtBx.Text = solicitud.NombreContacto;

                        celularContactoTxtBx.Text = solicitud.CelularContacto;

                        direccionPostalContactoTxtBx.Text = solicitud.DireccionPostalContacto;

                        #endregion

                        #region Contratista

                        companyDDL.Items.Add(solicitud.NombreEmpresa);

                        companyDDL.SelectedValue = solicitud.NombreEmpresa;

                        representanteTxtBx.Text = solicitud.RepresentanteAutorizado;

                        if (!solicitud.TipoAviso.Equals(((int)SolicitudAviso.TiposAvisos.Residencial).ToString()))
                        {
                            areaDepartamentoTxtBx.Text = solicitud.AreaDept;
                        }

                        else
                        {
                            deptLbl.Text = deptLbl.Text.Replace("*", string.Empty);

                            areaDepartamentoTxtBx.Enabled = false;

                            deptRFV.Enabled = false;
                        }

                        telOficinaTxtBx.Text = solicitud.TelOficina;

                        telTrabajoTxtBx.Text = solicitud.TelCampoTrabajo;

                        celularTxtBx.Text = solicitud.TelCelular;

                        emailTxtBx.Text = solicitud.CorreoElectronico;

                        direccionTxtBx.Text = solicitud.DireccionPostal;

                        municipioDDL.SelectedIndex = solicitud.MunicipioId;

                        codigoPostalTxtBx.Text = solicitud.CodigoPostal;

                        #endregion

                        #region Sub
                        companySubTxtBx.Text = solicitud.Subcontratista;

                        representanteSubTxtBx.Text = solicitud.RepresentanteAutorizadoSub;

                        if (!solicitud.TipoAviso.Equals(((int)SolicitudAviso.TiposAvisos.Residencial).ToString()))
                        {
                            areaDepartamentoSubTxtBx.Text = solicitud.AreaDeptSub;
                        }

                        else
                        {
                            areaDepartamentoSubTxtBx.Enabled = false;

                            //deptRFV.Enabled = false;
                        }

                        //representanteSubTxtBx.Text = solicitud.RepresentanteAutorizadoSub;

                        telOficinaSubTxtBx.Text = solicitud.TelOficinaSub;

                        telTrabajoSubTxtBx.Text = solicitud.TelCampoTrabajoSub;

                        celularSubTxtBx.Text = solicitud.TelCelularSub;

                        emailSubTxtBx.Text = solicitud.CorreoElectronicoSub;

                        direccionSubTxtBx.Text = solicitud.DireccionPostalSub;

                        municipioSubDDL.SelectedIndex = solicitud.MunicipioIdSub;

                        codigoPostalSubTxtBx.Text = solicitud.CodigoPostalSub;

                        #endregion

                        #region Info trabajo

                        //Es urbana?
                        if (solicitud.Zona)
                        {
                            zonaRBtnLst.SelectedIndex = 1;
                        }

                        else
                        {
                            zonaRBtnLst.SelectedIndex = 0;
                        }

                        boUrbTxtBx.Text = solicitud.BoUrb;

                        sectorCalleTxtBx.Text = solicitud.SectorCalle;

                        carreteraTxtBx.Text = solicitud.Carretera;

                        kmTxtBx.Text = solicitud.KM.ToString();

                        hmTxtBx.Text = solicitud.HM.ToString();

                        municipioTrabajoDDL.SelectedIndex = solicitud.MunicipioIdTrab;

                        referenciasTxtBx.Text = solicitud.Referencias;

                        fechaComienzoPropuestoTxtBx.Text = solicitud.FechaPropuesta.ToShortDateString();

                        fechaComienzoTxtBx.Text = solicitud.FechaComienzo.ToShortDateString();

                        fechaExpiracionTxtBx.Text = solicitud.FechaExpiracion.ToShortDateString();

                        string[] duracionSplit = solicitud.TiempoDuracion.Split('-');

                        duracionDiaTxtBx.Text = duracionSplit[0];

                        duracionMesTxtBx.Text = duracionSplit[1];

                        duracionYearTxtBx.Text = duracionSplit[2];

                        string[] horSplit = solicitud.Horario.Split('-');

                        horarioDDL.SelectedValue = horSplit[0];

                        horarioDDL2.SelectedValue = horSplit[1];


                        maquinariaChkBx.Checked = solicitud.Maquinaria;

                        tipoMaquinariaTxtBx.Enabled = solicitud.Maquinaria;

                        if (maquinariaChkBx.Checked)
                        {
                            tipoMaquinariaTxtBx.Enabled = true;

                            tipoMaquinariaTxtBx.Text = solicitud.TipoMaquinaria;

                            maquinariaUtilizarLbl.Text += "*";
                        }

                        else
                        {
                            tipoMaquinariaTxtBx.Enabled = false;
                        }

                        explosivoChkBx.Checked = solicitud.Explosivos;

                        licExplosivoTxtBx.Enabled = solicitud.Explosivos;

                        licExplosivoTxtBx.Text = solicitud.LicenciaExplosivo;

                        fechaExpiracionExplosivoTxtBx.Enabled = solicitud.Explosivos;

                        //fechaExpiracionExplosivoTxtBx.Text = solicitud.FechaExpiracionExplosivo.ToShortDateString();

                        if (explosivoChkBx.Checked)
                        {
                            //tipoExplosivoTxtBx.Enabled = true;

                            //tipoExplosivoTxtBx.Text = solicitud.TipoExplosivo;

                            licExplosivoLbl.Text += "*";

                            fechaExpiracionExplosivoLbl.Text += "*";

                            fechaExpiracionExplosivoTxtBx.Text = solicitud.FechaExpiracionExplosivo.ToShortDateString();
                        }

                        areaMarcadaChkBx.Checked = solicitud.AreaMarcada;

                        //Es continua?
                        if (solicitud.TipoExcavacion)
                        {
                            tipoExcavacionRBtnLst.SelectedIndex = 0;
                        }

                        else
                        {
                            tipoExcavacionRBtnLst.SelectedIndex = 1;
                        }

                        razonTxtBx.Text = solicitud.RazonTrabajos;

                        profundidadPiesTxtBx.Text = solicitud.ProfundidadPies.ToString();

                        profundidadPulgadasDLL.SelectedIndex = solicitud.ProfundidadPulgadas;

                        longitudPiesTxtBx.Text = solicitud.LongitudPies.ToString();

                        longitudPulgadasDDL.SelectedIndex = solicitud.LongitudPulgadas;

                        coordenadasXTxtBx.Text = solicitud.CoordenadaX.ToString();

                        coordenadasYTxtBx.Text = solicitud.CoordenadaY.ToString();

                        enCasoEmergenciaTxtBx.Text = solicitud.EnCasoEmergencia;
                        #endregion

                        #endregion

                        #region Poblar tabla averias
                        //LinkedList<Averia> averias = new AveriasServicio().GetAverias(numeroControl, (int)SolicitudAviso.TiposExtensiones.Inicial);

                        //averiasTxtBx.Text = averias.ElementAt(0).Titulo;

                        //solicitud.Averias = averias;

                        #endregion

                        #region Poblar campos docs requeridos

                        LinkedList<DocumentoRequerido> documentosRequeridos = new DocumentosRequeridosServicio().GetDocumentosAsociados(numeroControl,
                            (int)SolicitudAviso.TiposExtensiones.Inicial);

                        Session["docsRequeridos"] = documentosRequeridos;

                        //User docs
                        CreateDocReqCtrls(documentosRequeridos);

                        solicitud.Documentos = documentosRequeridos;

                        //Employee docs
                        CreateDocAsociadosCtrl(documentosRequeridos);

                        #region Build devolucion popUp

                        if (solicitud.EstatusId.Equals((((int)SolicitudAviso.Estatus.PendienteDocumentosIncompletos).ToString())))
                        {
                            if (user.Rol.ID == (int)Role.TipoRoles.Excavador)
                            {
                                coordinadorPoPupHeader.InnerText = "Razón por devolución";

                                coordinadorPopupBodyLbl.Text = string.Empty;

                                if (solicitud.SolicitudStatusID == (int)SolicitudAviso.SolicitudStatuses.INCOMPLETO)
                                    coordinadorPopupBodyLbl.Text = string.Format("<b>Observaciones:</b> {0} <br />", solicitud.Observaciones);

                                for (int i = 0; i < documentosRequeridos.Count; i++)
                                {
                                    if (!string.IsNullOrEmpty(documentosRequeridos.ElementAt(i).Comentario))
                                        coordinadorPopupBodyLbl.Text += string.Format("<b>{0}:</b> {1} <br />", documentosRequeridos.ElementAt(i).Nombre.Replace("_", " "),
                                        documentosRequeridos.ElementAt(i).Comentario);
                                }

                                ViewState["Redirect"] = true;

                                coordinadorPopup.Show();
                            }
                        } 
                        #endregion

                        LinkedList<DropDownList> docAsociadosStatuses = (LinkedList<DropDownList>)Session["docAsociadosStatuses"];

                        #region Enable/ disable image controls

                        foreach (var d in docAsociadosStatuses)
                        {
                            d.Enabled = solicitud.EstatusId.Equals(((int)SolicitudAviso.Estatus.PendienteRevisarCoordinador).ToString());

                            TextBox txtBx = (TextBox)docsAsociadosTableTag.FindControl(d.ID.Replace("DDL", "TxtBx"));

                            if ((d.SelectedIndex != (int)DocumentoRequerido.Estatus.Completo && d.SelectedIndex != 0) && txtBx != null
                                && (user.Rol.ID == (int)Role.TipoRoles.Excavador))
                            {
                                txtBx.ReadOnly = true;
                            }
                        } 

                        #endregion

                        #region Disable doc status validators if docs incomplete
                        //Asi si el user cambia de tipo de aviso, no dan problemas esos validators

                        LinkedList<RequiredFieldValidator> docAsociadosValidators = (LinkedList<RequiredFieldValidator>)Session["docAsociadosValidators"];

                        foreach (var v in docAsociadosValidators)
                        {
                            v.Enabled = solicitud.EstatusId.Equals(((int)SolicitudAviso.Estatus.PendienteRevisarCoordinador).ToString());
                        }

                        #endregion

                        #endregion

                        #region poblar respuestas
                        if (!solicitud.EstatusId.Equals(((int)SolicitudAviso.Estatus.PendienteRevisarCoordinador).ToString())
                            && !solicitud.EstatusId.Equals(((int)SolicitudAviso.Estatus.PendienteDocumentosIncompletos).ToString()))
                        {
                            Session["RespuestaVisibility"] = true;

                            respuestasDiv.Visible = true;

                            LinkedList<Respuesta> respuestas = new RespuestasServicio().GetRespuestasResumen(numeroControl,
                                            new SolicitudesInicialesServicio().GetOperadores());

                            Session["Respuesta"] = respuestas;

                            SetRespuestasRowData(respuestas);
                        }

                        #endregion

                        #region Poblar multas

                        if (!solicitud.EstatusId.Equals(((int)SolicitudAviso.Estatus.PendienteRevisarCoordinador).ToString())
                           && !solicitud.EstatusId.Equals(((int)SolicitudAviso.Estatus.PendienteDocumentosIncompletos).ToString()))
                        {
                            multasDiv.Visible = true;

                            multasGv.Visible = multasDiv.Visible;
                        }

                        #endregion

                        #region Set visibilities(role)

                        #region Display responsables de la solicitud

                        //User currentUser = new SolicitudesInicialesServicio().GetUser(solicitud.Usuario.Id);

                        User currentUser = new SolicitudesInicialesServicio().GetUser(solicitud.Usuario.Email);

                        tramitadoLbl.Visible = true;

                        tramitadoLbl.Text += string.Format(" {0}", solicitud.TramitadoPor);

                        //solicitud.Coordinador.Id = 1; // only test

                        if (!string.IsNullOrWhiteSpace(solicitud.Coordinador.Nombre))
                        {
                            //Coordinador coordinador = new SolicitudesInicialesServicio().GetCoordinador(solicitud.Coordinador.Nombre);

                            procesadoLbl.Visible = true;

                            procesadoLbl.Text += string.Format(" {0}", solicitud.Coordinador.Nombre);

                            //solicitud.Inspector.NumeroPlacaID = "001";

                            if (!string.IsNullOrWhiteSpace(solicitud.Inspector.Nombre))
                            {
                                //Inspector inspector = new SolicitudesInicialesServicio().GetInspector(solicitud.Inspector.NumeroPlacaID);

                                inspeccionLbl.Visible = true;

                                inspeccionLbl.Text += string.Format(" {0}", solicitud.Inspector.Nombre);
                            }
                        }

                        #endregion

                        if (solicitud.EstatusId.Equals(((int)SolicitudAviso.Estatus.Inactiva).ToString())
                            || solicitud.EstatusId.Equals(((int)SolicitudAviso.Estatus.InspeccionCompletada).ToString())
                            || solicitud.EstatusId.Equals(((int)SolicitudAviso.Estatus.PendienteAsignarInspector).ToString())
                            || solicitud.EstatusId.Equals(((int)SolicitudAviso.Estatus.EnProcesoInspeccion).ToString())
                            || solicitud.EstatusId.Equals(((int)SolicitudAviso.Estatus.Eliminada).ToString()))
                        {
                            fechaComienzoDiv.Visible = true;

                            fechaComienzoDiv2.Visible = true;

                            fechaExpiracionDiv.Visible = true;

                            fechaExpiracionDiv2.Visible = true;

                            #region Setup certificacion btn

                            if (!string.IsNullOrEmpty(solicitud.Coordinador.Nombre))
                            {
                                certificacionBtn.Visible = true;

                                certificacionBtn.OnClientClick = string.Format("window.open('/EXC/Certificaciones/Cert_{0}_Inicial.pdf','_blank')",
                                    solicitud.NumeroControl.NumControlText);
                            }
                            #endregion
                        }

                        #endregion

                        #region Set visibilities

                        fechaComienzoImgBtn.Visible = false; 

                        #endregion
                        
                        fechaComienzoPropuestoTxtBx.Enabled = false;                        

                        /*
                         * Para que no puedan cambiar de residente a excavacion si ya se guardo.
                         * Esto evita error al update docs
                         */
                        if (tipoAvisoRBtnLst.Items[2].Selected)
                        {
                            tipoAvisoRBtnLst.Items[0].Enabled = false;

                            tipoAvisoRBtnLst.Items[1].Enabled = false;
                        }

                        else
                        tipoAvisoRBtnLst.Items[2].Enabled = false;

                        #endregion
                    }
                }

                catch (Exception ex)
                {
                    errorLbl2.InnerText = ex.Message;

                    errorPopup.Show();
                }
            }

                //tipo de aviso si hace postback
            else
            {
                #region OnPostBack

                if (maquinariaChkBx.Checked)
                {
                    tipoMaquinariaTxtBx.Enabled = true;

                    if (!maquinariaUtilizarLbl.Text.Contains("*"))
                    {
                        maquinariaUtilizarLbl.Text += "*";
                    }
                }

                else
                {
                    tipoMaquinariaTxtBx.Enabled = false;

                    maquinariaUtilizarLbl.Text = maquinariaUtilizarLbl.Text.Replace("*", string.Empty);
                }

                if (explosivoChkBx.Checked)
                {
                    licExplosivoTxtBx.Enabled = true;

                    fechaExpiracionExplosivoTxtBx.Enabled = true;

                    if (!licExplosivoLbl.Text.Contains("*"))
                    {
                        licExplosivoLbl.Text += "*";

                        fechaExpiracionExplosivoLbl.Text += "*";
                    }
                }

                else
                {
                    licExplosivoTxtBx.Enabled = false;

                    fechaExpiracionExplosivoTxtBx.Enabled = false;

                    licExplosivoLbl.Text = licExplosivoLbl.Text.Replace("*", string.Empty);

                    fechaExpiracionExplosivoLbl.Text = fechaExpiracionExplosivoLbl.Text.Replace("*", string.Empty);
                }

                #region Set respuesta
                LinkedList<Respuesta> respuestas = (LinkedList<Respuesta>)Session["Respuesta"];

                //= respuestas;

                if (respuestas != null)
                {
                    SetRespuestasRowData(respuestas);
                }
                #endregion

                #region Set doc controls on postback
                LinkedList<DocumentoRequerido> docsRequeridos = (LinkedList<DocumentoRequerido>)Session["docsRequeridos"];

                if (docsRequeridos != null)
                {
                    CreateDocAsociadosCtrl(docsRequeridos);
                }
                #endregion 

                #endregion
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            User user = Session["UserObj"] == null ? new User() : (User)Session["UserObj"];

            #region Set title

            var title = (HtmlGenericControl)Master.FindControl("pageTitleSpan");

            title.InnerText = Title; 

            #endregion

            #region Check role

            if (user.Rol.ID != (int)Role.TipoRoles.Director
                    && user.Rol.ID != (int)Role.TipoRoles.SuperInspector
                    && user.Rol.ID != (int)Role.TipoRoles.Admin)
            {
                Response.Redirect("~/Default.aspx", true);
            } 

            #endregion

            if (!IsPostBack)
            {
                #region Instanciate municipio ddl

                LinkedList<string> municipios = new SolicitudesInicialesServicio().GetMunicipios();

                for (int i = 0; i < municipios.Count; i++)
                {
                    municipioDDL.Items.Add(municipios.ElementAt(i));
                }

                #endregion

                string from = string.Empty;

                LinkedList<SolicitudAviso> solicitudes = new LinkedList<SolicitudAviso>();

                GetFromAndSolicitudes(ref from, ref solicitudes, 0);

                avisosRadicadosSinFiltroLbl.Text = string.Format("Total de Avisos Iniciales Radicados: {0}", solicitudes.Count);

                if (solicitudes.Count > 0)
                {
                    FillAvisosSinFiltroGv(from);
                }

                GetFromAndSolicitudes(ref from, ref solicitudes, 1);

                ext1Lbl.Text = string.Format("Total de Primeras Extensiones Radicadas: {0}", solicitudes.Count);

                if (solicitudes.Count > 0)
                {
                    FillAvisosSinFiltroGv(from);
                }

                GetFromAndSolicitudes(ref from, ref solicitudes, 2);

                ext2Lbl.Text = string.Format("Total de Segundas Extensiones Radicadas: {0}", solicitudes.Count);

                if (solicitudes.Count > 0)
                {
                    FillAvisosSinFiltroGv(from);
                }
            }
        }
        protected void searchFilterDDL_SelectedIndexChanged(object sender, EventArgs e)
        {
            searchBtn.Visible = true;

            seachDDL.Visible = searchFilterDDL.SelectedValue.Equals("Inspector") || searchFilterDDL.SelectedValue.Equals("Municipio");

            searchTxtBx.Visible = !seachDDL.Visible;

            if (searchTxtBx.Visible)
            {
                searchTxtBx.Text = string.Empty;
            }

            if (searchFilterDDL.SelectedValue.Equals("Inspector"))
            {
                User user = Session["UserObj"] == null ? new User() : (User)Session["UserObj"];

                #region Fill inspector DDL

                //seachDDL = new DropDownList();

                seachDDL.Items.Clear();

                LinkedList<Inspector> inspectores = new SolicitudesInicialesServicio().GetInspectores();

                for (int i = 1; i < inspectores.Count; i++)
                {
                    seachDDL.Items.Add(inspectores.ElementAt(i).Nombre.ToUpper());
                } 

                #endregion

                if (user.Rol.ID == ((int)Role.TipoRoles.Inspector))
                {
                    seachDDL.Items.FindByValue(user.NombreCompleto).Selected = true;

                    seachDDL.Enabled = false;
                }
            }

            else if (searchFilterDDL.SelectedValue.Contains("Sin"))
            {
                searchBtn.Visible = !searchBtn.Visible;

                searchTxtBx.Visible = !searchTxtBx.Visible;

                averiasGv.DataBind();
            }

            else if (searchFilterDDL.SelectedValue.Equals("Municipio"))
            {
                //seachDDL = new DropDownList();

                seachDDL.Enabled = true;

                seachDDL.Items.Clear();

                LinkedList<string> municipios = new SolicitudesInicialesServicio().GetMunicipios();

                for (int i = 0; i < municipios.Count; i++)
                {
                    seachDDL.Items.Add(municipios.ElementAt(i));
                }
            }
        }
Exemple #10
0
        protected void Guardar_Click(object sender, EventArgs e)
        {
            #region Evita issue donde deja crear user sin entidad

            entidadRFV.Enabled = true;

            Page.Validate(); 

            #endregion

            User user = Session["UserObj"] == null ? new User() : (User)Session["UserObj"];

            if (user == null)
            {
                user = new User();
            }

            Page.Validate();

            if(Page.IsValid)
            {
                emailHF.Value = CorreoElectronico.Text;

                int[] err = new int[12];

                err[0] = 0; ////////////////////////////// EAF ///////////////////////////////////

                if (err[0] == 0)
                {
                    string cs = ConfigurationManager.ConnectionStrings["EXC"].ConnectionString;

                    using (SqlConnection conn = new SqlConnection(cs))
                    {
                        using (SqlCommand command = new SqlCommand())
                        {
                            command.Connection = conn;
                            command.CommandType = CommandType.Text;

                            var role = roles.Where(x => x.Nombre == roleDDL.SelectedValue).First();

                            var inspectores = new LinkedList<Inspector>();

                           
                            if (string.IsNullOrWhiteSpace(Request.QueryString["Email"]))
                            {
                                #region Create

                                command.CommandText += @"INSERT INTO Usuarios VALUES (@NombreUsuario, @Inicial, @ApellidoPaterno, @ApellidoMaterno,
                                                       @CorreoElectronico, @ConfirmarCorreoElectronico, @Contrasena, @ConfirmarContrasena, @PreguntaSeguridad, 
                                                       @RespuestaSeguridad, @Telefono, @UsuarioInterno, @EmpresaID, @Rol, @Activo);";

                                if (user.Rol.ID == (int)Role.TipoRoles.Admin)
                                {
                                    if (role.ID == (int)Role.TipoRoles.Inspector || role.ID == (int)Role.TipoRoles.SuperInspector)
                                    {
                                        inspectores = new SolicitudesInicialesServicio().GetInspectores();

                                        int ultimaPlaca = Convert.ToInt32(inspectores.ElementAt(inspectores.Count - 1).NumeroPlacaID);

                                        command.CommandText += @"INSERT INTO Inspectores VALUES (@PlacaInspector, @NombreCompleto, @CorreoElectronico);";

                                        command.Parameters.AddWithValue("@PlacaInspector", (ultimaPlaca + 1).ToString("D3"));

                                        command.Parameters.AddWithValue("@NombreCompleto", NombreUsuario.Text + " " + ApellidoPaterno.Text + " " + ApellidoMaterno.Text);

                                        command.Parameters.AddWithValue("@UsuarioInterno", true);
                                    }

                                    else if (role.ID == (int)Role.TipoRoles.Coordinador)
                                    {
                                        command.CommandText += @"INSERT INTO Coordinadores VALUES (@NombreCompleto);";

                                        command.Parameters.AddWithValue("@NombreCompleto", NombreUsuario.Text + " " + ApellidoPaterno.Text + " " + ApellidoMaterno.Text);

                                        command.Parameters.AddWithValue("@UsuarioInterno", true);
                                    }

                                    else if (role.ID == (int)Role.TipoRoles.Admin 
                                        || role.ID == (int)Role.TipoRoles.SuperInspector
                                        || role.ID == (int)Role.TipoRoles.Director)
                                    {
                                        command.Parameters.AddWithValue("@UsuarioInterno", true);
                                    }

                                    else
                                    {
                                        command.Parameters.AddWithValue("@UsuarioInterno", false);
                                    }
                                }

                                else
                                {
                                    command.Parameters.AddWithValue("@UsuarioInterno", false);
                                }

                                #endregion
                            }                             

                            else
                            {
                                #region Edit
                                command.CommandText += @"UPDATE Usuarios SET NombreUsuario = @NombreUsuario,
                                                                             Inicial = @Inicial,
                                                                             ApellidoPaterno = @ApellidoPaterno,
                                                                            ApellidoMaterno = @ApellidoMaterno,
                                                                            CorreoElectronico = @CorreoElectronico,
                                                                            ConfirmarCorreoElectronico = @ConfirmarCorreoElectronico,
                                                                            Contrasena = @Contrasena,
                                                                            ConfirmarContrasena = @ConfirmarContrasena,
                                                                            PreguntaSeguridad = @PreguntaSeguridad, 
                                                                            RespuestaSeguridad = @RespuestaSeguridad,
                                                                            Telefono = @Telefono,
                                                                            UsuarioInterno = @UsuarioInterno,
                                                                            EmpresaID = @EmpresaID,
                                                                            Rol = @Rol,
                                                                            Activo = @Activo
                                                                            WHERE CorreoElectronico = @OldEmail;";

                                command.Parameters.AddWithValue("@OldEmail", (string)ViewState["UserEmail"]);

                                if (role.ID == (int)Role.TipoRoles.Inspector || role.ID == (int)Role.TipoRoles.SuperInspector)
                                {
                                    inspectores = new SolicitudesInicialesServicio().GetInspectores();

                                    string placaInspector = inspectores.Where(x => x.CorreoElectronico.Equals((string)ViewState["UserEmail"])).First().NumeroPlacaID;

                                    command.CommandText += @"UPDATE Inspectores SET NombreInspector = @NombreCompleto
                                                                                    , CorreoElectronico = @CorreoElectronico 
                                                                WHERE PlacaInspector = @PlacaInspector;";

                                    command.Parameters.AddWithValue("@PlacaInspector", placaInspector);

                                    command.Parameters.AddWithValue("@NombreCompleto", NombreUsuario.Text + " " + ApellidoPaterno.Text + " " + ApellidoMaterno.Text);

                                    command.Parameters.AddWithValue("@UsuarioInterno", true);
                                }

                                else if (role.ID == (int)Role.TipoRoles.Coordinador)
                                {
                                    command.CommandText += @"UPDATE Coordinadores SET NombreCoordinador = @NombreCompleto WHERE NombreCoordinador = @NombreCoordinador;";

                                    command.Parameters.AddWithValue("@NombreCoordinador", (string)Session["Username"]);

                                    command.Parameters.AddWithValue("@NombreCompleto", NombreUsuario.Text + " " + ApellidoPaterno.Text + " " + ApellidoMaterno.Text);

                                    command.Parameters.AddWithValue("@UsuarioInterno", true);
                                }

                                else if (role.ID == (int)Role.TipoRoles.Admin
                                        || role.ID == (int)Role.TipoRoles.SuperInspector
                                        || role.ID == (int)Role.TipoRoles.Director)
                                {
                                    command.Parameters.AddWithValue("@UsuarioInterno", true);
                                }

                                else
                                {
                                    command.Parameters.AddWithValue("@UsuarioInterno", false);
                                }

                                #endregion
                            }

                            command.Parameters.AddWithValue("@Rol", role.ID);

                            command.Parameters.AddWithValue("@Activo", true); 

                            command.Parameters.AddWithValue("@NombreUsuario", NombreUsuario.Text.ToUpper());                                                  

                            command.Parameters.AddWithValue("@Inicial", Inicial.Text.ToUpper());
                            command.Parameters.AddWithValue("@ApellidoPaterno", ApellidoPaterno.Text.ToUpper());
                            command.Parameters.AddWithValue("@ApellidoMaterno", ApellidoMaterno.Text.ToUpper()); ;
                            command.Parameters.AddWithValue("@CorreoElectronico", CorreoElectronico.Text.ToLower());
                            command.Parameters.AddWithValue("@ConfirmarCorreoElectronico", ConfirmarCorreoElectronico.Text.ToLower());

                            //Si el pass es empty y el logged user esta updating su profile then use pass from logged user
                            if (string.IsNullOrWhiteSpace(ConfirmarContrasena.Value))
                            {
                                string oldEmail = (string)ViewState["UserEmail"];

                                if(oldEmail.Equals(user.Email))
                                {                                
                                    command.Parameters.AddWithValue("@Contrasena", user.Password );

                                    command.Parameters.AddWithValue("@ConfirmarContrasena", user.Password);
                                }

                                    //No uses pass del logged user sino, Get pass del user que se esta updating
                                else
                                {
                                    User selectedUser = new SolicitudesInicialesServicio().GetUser(Request.QueryString["Email"].Replace("%40", "@"));

                                    command.Parameters.AddWithValue("@Contrasena", selectedUser.Password);

                                    command.Parameters.AddWithValue("@ConfirmarContrasena", selectedUser.Password);
                                }
                            }

                            else
                            {
                                command.Parameters.AddWithValue("@Contrasena", Contrasena.Value);

                                command.Parameters.AddWithValue("@ConfirmarContrasena", Contrasena.Value);
                            }

                            command.Parameters.AddWithValue("@PreguntaSeguridad", PreguntaSeguridad.SelectedValue.ToString());
                            command.Parameters.AddWithValue("@RespuestaSeguridad", RespuestaSeguridad.Text.ToUpper());
                            command.Parameters.AddWithValue("@Telefono", Telefono.Text);
                            command.Parameters.AddWithValue("@EmpresaID", ddlEmpresas.SelectedValue);

                            try
                            {
                                conn.Open();
                                int recordsAffected = command.ExecuteNonQuery();

                                if (string.IsNullOrWhiteSpace(Request.QueryString["Email"]))
                                {
                                    CreateUserDir(role, CorreoElectronico.Text);

                                    Response.Redirect("~/Account/Ingresar.aspx");
                                }                                    

                                else
                                {
                                    string oldEmail = (string)ViewState["UserEmail"];

                                    #region Update user dir

                                    if (!oldEmail.Equals(CorreoElectronico.Text))
                                    {
                                        Directory.Move(Server.MapPath(string.Format("{0}/{1}",
                                                                           new DocumentoRequerido().DocumentosInicialesSavePath, oldEmail)),
                                                                           Server.MapPath(string.Format("{0}/{1}", new DocumentoRequerido().DocumentosInicialesSavePath,
                                                                           CorreoElectronico.Text)));

                                        Directory.Move(Server.MapPath(string.Format("{0}/{1}",
                                            new DocumentoRequerido().DocumentosPrimerasSavePath, oldEmail)),
                                            Server.MapPath(string.Format("{0}/{1}", new DocumentoRequerido().DocumentosPrimerasSavePath,
                                            CorreoElectronico.Text)));

                                        Directory.Move(Server.MapPath(string.Format("{0}/{1}",
                                            new DocumentoRequerido().DocumentosSegundasSavePath, oldEmail)),
                                            Server.MapPath(string.Format("{0}/{1}", new DocumentoRequerido().DocumentosSegundasSavePath,
                                            CorreoElectronico.Text)));

                                        if (role.ID == (int)Role.TipoRoles.Inspector || role.ID == (int)Role.TipoRoles.SuperInspector)
                                        {
                                            Directory.Move(Server.MapPath(string.Format("{0}/{1}",
                                                new DocumentoRequerido().DocumentosInspeccionesSavePath, oldEmail)),
                                                Server.MapPath(string.Format("{0}/{1}", new DocumentoRequerido().DocumentosInspeccionesSavePath,
                                                CorreoElectronico.Text)));
                                        }
                                    }
 
                                    #endregion

                                    #region Update current user variable

                                    if (oldEmail.Equals(user.Email))
                                    {
                                        foreach (var r in roles)
                                        {
                                            if (r.ID == (user.Rol.Tipo))
                                            {
                                                user.Rol = r;

                                                user.Email = CorreoElectronico.Text;

                                                user.EmpresaID = ddlEmpresas.SelectedValue;

                                                Session["UserObj"] = user;

                                                break;
                                            }
                                        }
                                    }
                                    #endregion

                                    Response.Redirect("~/Default.aspx");
                                }
                            }
                            catch (Exception)
                            {
                                ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "sqlerr()", true);
                            }
                            finally
                            {
                                conn.Close();
                            }
                        }
                    }
                }
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            var title = (HtmlGenericControl)Master.FindControl("pageTitleSpan");

            title.InnerText = Title;

            #region Fill num control ddl

            LinkedList<SolicitudAviso> solicitudes = new SolicitudesInicialesServicio().GetSolicitudes();

            for (int i = 0; i < solicitudes.Count; i++)
            {
                numControlDDL.Items.Add(solicitudes.ElementAt(i).NumeroControl.NumControlText);

                operadorDDL.Items.Add(solicitudes.ElementAt(i).NombreEmpresa);
            }

            if (!IsPostBack)
            {
                #region Fill averia controls

                if (!string.IsNullOrEmpty(Request.QueryString["NumeroControl"]))
                {
                    NumeroControl numControl = new NumeroControl()
                    {
                        NumControlText = Request.QueryString["NumeroControl"]
                    };

                    var averiasExistentes = new AveriasServicio().GetAverias(numControl);

                    if (averiasExistentes.Count > 0)
                    {
                        #region Get existing

                        if (string.IsNullOrEmpty(averiasExistentes.ElementAt(0).NumeroControl.NumControlText))
                        {
                            numControlDDL.SelectedIndex = 0;
                        }

                        else
                        {
                            numControlDDL.SelectedValue = averiasExistentes.ElementAt(0).NumeroControl.NumControlText;
                        }

                        fechaTxtBx.Text = averiasExistentes.ElementAt(0).Fecha.ToShortDateString();

                        if (string.IsNullOrEmpty(averiasExistentes.ElementAt(0)._Operador.Nombre))
                        {
                            operadorDDL.SelectedIndex = 0;
                        }

                        else
                        {
                            operadorDDL.SelectedValue = averiasExistentes.ElementAt(0)._Operador.Nombre;
                        }

                        direccionTxtBx.Text = averiasExistentes.ElementAt(0).Lugar;

                        commentTxtBx.Text = averiasExistentes.ElementAt(0).Comentario;

                        #endregion
                    }
                } 

                #endregion
            }

            #endregion
        }
        protected void BuscaPorDDL_SelectedIndexChanged(object sender, EventArgs e)
        {
            btnBuscar.Visible = true;

            busca1.Text = string.Empty;

            switch (BuscaPorDDL.SelectedIndex)
            {
                //num control
                case 1:
                    busca1.Visible = true;

                    estatusDDL.Visible = false;

                    desdeTxtbx.Visible = false;

                    hastaTxtBx.Visible = false;

                    hastaRFV.Enabled = false;

                    desdeRFV.Enabled = false;

                    break;

                //Company
                case 2:
                    busca1.Visible = true;

                    estatusDDL.Visible = false;

                    desdeTxtbx.Visible = false;

                    hastaTxtBx.Visible = false;
                    
                    hastaRFV.Enabled = false;

                    desdeRFV.Enabled = false;

                    break;

                //Fecha
                case 3:
                    busca1.Visible = false;

                    estatusDDL.Visible = false;

                    desdeTxtbx.Visible = true;

                    hastaTxtBx.Visible = true;

                    hastaRFV.Enabled = true;

                    desdeRFV.Enabled = true;

                    break;

                //Status
                case 4:
                    busca1.Visible = false;

                    estatusDDL.Visible = true;

                     estatusDDL.Items.Clear();

                     estatusDDL.Items.Add("Sin filtro");

                     LinkedList<string> estatus = new SolicitudesInicialesServicio().GetStatusMsgs();

                     for (int i = 0; i < estatus.Count; i++)
                     {
                         estatusDDL.Items.Add(estatus.ElementAt(i));
                     }

                    desdeTxtbx.Visible = false;

                    hastaTxtBx.Visible = false;

                    hastaRFV.Enabled = false;

                    desdeRFV.Enabled = false;

                    break;

                default:

                    busca1.Visible = false;

                    estatusDDL.Visible = false;

                    desdeTxtbx.Visible = false;

                    hastaTxtBx.Visible = false;

                    hastaRFV.Enabled = false;

                    desdeRFV.Enabled = false;

                    break;
            }
        }
Exemple #13
0
        //private static LinkedList<FileUpload> docRequeridosFileUpload = new LinkedList<FileUpload>(); //Used for doc validations when guardar is pressed

        //private static LinkedList<ImageButton> ImageButtons = new LinkedList<ImageButton>(); //Used to store all imgBtns on doc section

        //private static LinkedList<DropDownList> docAsociadosStatuses = new LinkedList<DropDownList>(); // Used to save doc status on doc object

        //private static LinkedList<RequiredFieldValidator> docAsociadosValidators = new LinkedList<RequiredFieldValidator>(); // Used when I need to disable status RFVs

        //private static LinkedList<DocumentoRequerido> docsRequeridos = new LinkedList<DocumentoRequerido>(); // Just in case I lose data on postbacks

        protected void Page_Load(object sender, EventArgs e)
        {
            User user = Session["UserObj"] == null ? new User() : (User)Session["UserObj"];

            if (!user.Rol.VerAvisoInicial)
            {
                Response.Redirect("~/Default.aspx");
            }

            var title = (HtmlGenericControl)Master.FindControl("pageTitleSpan");

            title.InnerText = Title;

            #region Populate horario ddl

            horarioDDL.Items.Add("Seleccionar");

            horarioDDL2.Items.Add("Seleccionar");

            for (int i = 0; i < 2; i++)
            {
                string dayTime = "AM";

                if (i == 1)
                {
                    dayTime = "PM";
                }

                for (int h = 1; h < 13; h++)
                {
                    for (int m = 0; m < 4; m += 3)
                    {
                        horarioDDL.Items.Add(h.ToString() + ":" + m.ToString() + "0" + dayTime);

                        horarioDDL2.Items.Add(h.ToString() + ":" + m.ToString() + "0" + dayTime);
                    }
                }
            }
            #endregion

            CreateDocReqCtrls(tipoAvisoRBtnLst.SelectedIndex);

            if (!IsPostBack)
            {
                #region Clean up session

                Session.Remove("Respuesta");

                Session.Remove("RespuestaVisibility");

                Session.Remove("docAsociadosStatuses");

                Session.Remove("docsRequeridos");

                Session.Remove("croquisPath"); 

                #endregion

                Page.Form.Attributes.Add("enctype", "multipart/form-data");

                NumeroControl numeroControl = new NumeroControl()
                {
                    NumControlText = Request.QueryString["NumeroControl"]

                    //NumControlText = "20150000" // only for testing

                    //NumControlText = "2015-0015" // only for testing

                    //NumControlText = "2015-0016" // only for testing

                    //NumControlText = "2015-0017" // only for testing

                    //NumControlText = "2015-10" // only for testing

                    //NumControlText = "2015-0002" // only for testing
                };

                try
                {
                    #region Set Municipios

                    LinkedList<String> municipios = new SolicitudesInicialesServicio().GetMunicipios();

                    municipioDDL.Items.Add("Seleccionar");

                    municipioSubDDL.Items.Add("Seleccionar");

                    municipioTrabajoDDL.Items.Add("Seleccionar");

                    foreach (var m in municipios)
                    {
                        municipioDDL.Items.Add(m);

                        municipioSubDDL.Items.Add(m);

                        municipioTrabajoDDL.Items.Add(m);
                    }

                    municipioDDL.SelectedIndex = 0;

                    municipioSubDDL.SelectedIndex = 0;

                    municipioTrabajoDDL.SelectedIndex = 0;

                    #endregion

                    //var _user = ((SiteMaster)Master).user.Email;

                    //var s = ((SiteMaster)this.Master)

                    CreateDefaultAveriasGrdVwRow();

                    //if numcontrol exist, get data. Else setup controls for creation
                    if (String.IsNullOrEmpty(numeroControl.NumControlText))
                    {
                        #region Create

                        #region Set visibilities
                        fechaComienzoDiv.Visible = false;

                        fechaComienzoDiv2.Visible = false;

                        fechaExpiracionDiv.Visible = false;

                        fechaExpiracionDiv2.Visible = false;

                        docsRequeridosHeader.Visible = true;

                        docRequeridosMainDiv.Visible = true;

                        docsAsociadosHeader.Visible = false;

                        docsAsociadosTableTag.Visible = false;

                        //individuoDocDiv.Visible = false;

                        respuestasDiv.Visible = false;

                        averiasDiv.Visible = false;

                        averiasTxtBx.Visible = false;

                        //averiaDS.Visible = false;

                        //averiasGrdVw.Visible = false;
                        #endregion

                        tipoMaquinariaTxtBx.Enabled = false;

                        licExplosivoTxtBx.Enabled = false;

                        fechaExpiracionExplosivoTxtBx.Enabled = false;

                        fechaComienzoPropuestoTxtBx.Enabled = true;

                        fechaComienzoImgBtn.Visible = true;

                        primeraExtensionLink.NavigateUrl = String.Empty;

                        primeraExtensionLink.Text = "No disponibles";

                        segundaExtensionLink.Visible = false;

                        #region Poblar campos contratista

                        //User currentUser = new SolicitudesInicialesServicio().GetUser(Request.QueryString["CorreoElectronico"]);

                        //User currentUser = new SolicitudesInicialesServicio().GetUser("*****@*****.**"); // only test

                        #region Company

                        companyDDL.Items.Add("Seleccionar");

                        Company company = new SolicitudesInicialesServicio().GetCompany(user);

                        companyDDL.Items.Add(company.NombreEmpresa);

                        companyDDL.SelectedIndex = 1;

                        #endregion

                        representanteTxtBx.Text = company.RepresentanteAutorizado;

                        telOficinaTxtBx.Text = company.TelOficina;

                        telTrabajoTxtBx.Text = company.TelTrabajo;

                        celularTxtBx.Text = company.Celular;

                        emailTxtBx.Text = company.CorreoElectronico;

                        direccionTxtBx.Text = company.DireccionPostal.Replace(",", string.Empty);

                        codigoPostalTxtBx.Text = company.CodigoPostal;

                        municipioDDL.SelectedValue = company.Municipio;

                        #endregion

                        //CreateDocReqCtrls(tipoAvisoRBtnLst.SelectedIndex);

                        //                        #region Generar controles para docs requeridos

                        //                        LinkedList<DocumentoRequerido> docsRequeridos = new DocumentosRequeridosServicio().GetDocumentosRequeridos();

                        //                        for (int i = 0; i < docsRequeridos.Count; i++)
                        //                        {
                        //                            string script = @"<script>";

                        //                            LiteralControl uploadLit = new LiteralControl();

                        //                            uploadLit.Text += "<div>";

                        //                            #region Create controls

                        //                            Label lbl = new Label();

                        //                            lbl.ID = docsRequeridos.ElementAt(i).Nombre + "Lbl";

                        //                            lbl.Text = docsRequeridos.ElementAt(i).Nombre;

                        //                            TextBox txtBx = new TextBox();

                        //                            txtBx.ReadOnly = true;

                        //                            txtBx.ID = docsRequeridos.ElementAt(i).Nombre + "TxtBx";

                        //                            txtBx.Width = 250;

                        //                            //Set onclick function
                        //                            txtBx.Attributes["onclick"] = docsRequeridos.ElementAt(i).Nombre + "TxtBxClick()";

                        //                            txtBx.Attributes["placeholder"] = "Presionar aqui, para anejar";

                        //                            docRequeridosMainDiv.Controls.Add(lbl);

                        //                            docRequeridosMainDiv.Controls.Add(txtBx); 

                        //                            #endregion

                        //                            #region Add properties and attr

                        //                            HtmlGenericControl input = new HtmlGenericControl(),
                        //                                                    btn = new HtmlGenericControl();


                        //                            script += @"function " + docsRequeridos.ElementAt(i).Nombre + @"FileSelected() 
                        //                                        {        
                        //                                            txtBx = document.getElementById('" + txtBx.ClientID + @"');
                        //
                        //                                            var fileUpload = document.getElementById('" + lbl.Text + @"File');
                        //
                        //                                            txtBx.value = fileUpload.files[0].name;
                        //                                        }";

                        //                            script += @" function " + docsRequeridos.ElementAt(i).Nombre + @"TxtBxClick() 
                        //                                        {                                           
                        //                                            var fileUp = $('#" + lbl.Text + @"File');
                        //
                        //                                            fileUp.trigger('click');
                        //                                        }";

                        //                            script += @"</script>";

                        //                            ClientScript.RegisterClientScriptBlock(GetType(), docsRequeridos.ElementAt(i).Nombre + "Script", script);

                        //                            //Attach inivisible input type file
                        //                            uploadLit.Text += string.Format(@"<input type='file' id='{0}File' style='display: none;' 
                        //                                                            onchange='" + docsRequeridos.ElementAt(i).Nombre + @"FileSelected()' /></div>", lbl.Text);

                        //                            docRequeridosMainDiv.Controls.Add(uploadLit); 

                        //                            #endregion

                        //                            docRequeridosTxtBxs.AddLast(txtBx);
                        //                        }

                        //                        #endregion

                        #endregion
                    }

                    else
                    {
                        #region Edit

                        numeroControl.Year = Convert.ToInt32(numeroControl.NumControlText.Substring(0, 4));

                        numeroControl.NumControl = Convert.ToInt32(numeroControl.NumControlText.Substring(4));

                        SolicitudAviso solicitud =
                            new SolicitudesInicialesServicio().GetSolicitud(numeroControl);

                        #region Set links extensiones
                        SolicitudAviso primeraExt = new PrimerasExtensionesServicio().GetPrimeraExtension(numeroControl),
                                        segundaExt = new SegundasExtensionesServicio().GetSegundaExtension(numeroControl);

                        primeraExtensionLink.NavigateUrl = primeraExtensionLink.NavigateUrl + "?NumeroControl=" + numeroControl.NumControlText;

                        segundaExtensionLink.NavigateUrl = segundaExtensionLink.NavigateUrl + "?NumeroControl=" + numeroControl.NumControlText;

                        if (!String.IsNullOrEmpty(primeraExt.NumeroControl.NumControlText))
                        {
                            //primeraExtensionLink.NavigateUrl = primeraExtensionLink.NavigateUrl + "?numControl=" + numeroControl.NumControlText;

                            primeraExtensionLink.Text = "Primera";

                            if (!String.IsNullOrEmpty(segundaExt.NumeroControl.NumControlText))
                            {
                                //segundaExtensionLink.NavigateUrl = segundaExtensionLink.NavigateUrl + "?numControl=" + numeroControl.NumControlText;

                                segundaExtensionLink.Text = "Segunda";
                            }

                            else
                            {
                                //segundaExtensionLink.NavigateUrl = segundaExtensionLink.NavigateUrl + "?numControl=" + numeroControl.NumControlText;

                                
                                    segundaExtensionLink.Text = "Crear segunda extensión";
                                
                            }
                        }

                        else
                        {
                            //primeraExtensionLink.NavigateUrl = primeraExtensionLink.NavigateUrl + "?numControl=" + numeroControl.NumControlText;

                                primeraExtensionLink.Text = "Crear primera extensión";                            

                            segundaExtensionLink.Visible = false;
                        }
                        #endregion

                        #region Poblar campos solicitud

                        #region Info general

                        numeroControlTxtBx.Text = numeroControl.NumControlText;

                        emergenciaChkBx.Checked = solicitud.Emergencia;

                        if (!user.Rol.EditarAvisoEmergerncia)
                        {
                            emergenciaChkBx.Enabled = false;
                        }

                        areaDepartamentoTxtBx.Enabled = tipoAvisoRBtnLst.SelectedIndex != 2;

                        areaDepartamentoTxtBx.Enabled = tipoAvisoRBtnLst.SelectedIndex != 2;

                        //representanteSubTxtBx.Enabled = 

                        //representanteTxtBx.Enabled = tipoAvisoRBtnLst.SelectedIndex != 2;                        

                        if (tipoAvisoRBtnLst.SelectedIndex == 2)
                        {
                            //representanteTxtBx.Text = string.Empty;

                            areaDepartamentoTxtBx.Text = string.Empty;

                            areaDepartamentoTxtBx.Text = string.Empty;

                            //representanteSubTxtBx.Text = string.Empty;
                        }

                        tipoAvisoRBtnLst.SelectedIndex = Convert.ToInt32(solicitud.TipoAviso);

                        //representanteDiv.Visible = tipoAvisoRBtnLst.SelectedIndex != 2;

                        //representanteDiv2.Visible = tipoAvisoRBtnLst.SelectedIndex != 2;

                        //representanteSubDiv.Visible = tipoAvisoRBtnLst.SelectedIndex != 2;

                        //representanteSubDiv2.Visible = tipoAvisoRBtnLst.SelectedIndex != 2;

                        SetDocsVisibilities();

                        if (!string.IsNullOrWhiteSpace(solicitud.EstatusId))
                        {
                            //Quitale la letra y brega con el numero solo
                            solicitud.EstatusId = solicitud.EstatusId.Replace(solicitud.LetraStatus, string.Empty).Replace(new Inspeccion().LetraStatus, string.Empty);

                            #region Fill status msgs

                            var statusMsgs = new SolicitudesInicialesServicio().GetStatusMsgs();

                            Dictionary<string, System.Drawing.Color> newStatusMsgs = new Dictionary<string, System.Drawing.Color>();

                            if (Convert.ToInt32(solicitud.EstatusId) < 8)
                            {
                                newStatusMsgs.Add("filler", System.Drawing.Color.Violet);

                                for (int i = 0; i < solicitud.StatusMsgs.Count; i++)
                                {
                                    newStatusMsgs.Add(statusMsgs.ElementAt(i), solicitud.StatusMsgs.ElementAt(i).Value);

                                    //solicitud.StatusMsgs.ElementAt(i).Key = statusMsgs.ElementAt(i);
                                }

                                solicitud.StatusMsgs = newStatusMsgs;

                                statusLbl.Text = solicitud.StatusMsgs.Keys.ElementAt(Convert.ToInt32(solicitud.EstatusId));

                                statusLbl.ForeColor = solicitud.StatusMsgs.Values.ElementAt(Convert.ToInt32(solicitud.EstatusId));
                            }

                                //Eliminada
                            else
                            {
                                newStatusMsgs.Add("Eliminada", System.Drawing.Color.White);

                                solicitud.StatusMsgs = newStatusMsgs;

                                statusLbl.Text = solicitud.StatusMsgs.Keys.ElementAt(0);

                                statusLbl.ForeColor = solicitud.StatusMsgs.Values.ElementAt(0);
                            }

                            

                            #endregion

                            //statusLbl.Text = solicitud.StatusMsgs.Keys.ElementAt(Convert.ToInt32(solicitud.EstatusId));

                            //statusLbl.ForeColor = solicitud.StatusMsgs.Values.ElementAt(Convert.ToInt32(solicitud.EstatusId));

                            statusHF.Value = solicitud.EstatusId;

                            if (solicitud.EstatusId.Equals((((int)SolicitudAviso.Estatus.PendienteDocumentosIncompletos).ToString())))
                            {
                                if (user.Rol.ID != (int)Role.TipoRoles.Excavador)
                                {
                                    coordinadorPopup.Show();
                                }
                            }

                            else if (solicitud.EstatusId.Equals((((int)SolicitudAviso.Estatus.PendienteRevisarCoordinador).ToString())))
                            {
                                //si es empresa(exc/demole)
                                if (user.Rol.ID != (int)Role.TipoRoles.Coordinador
                                    && user.Rol.ID != (int)Role.TipoRoles.Admin
                                    && user.Rol.ID != (int)Role.TipoRoles.SuperInspector
                                    && user.Rol.ID != (int)Role.TipoRoles.Director)
                                {
                                    coordinadorPoPupHeader.InnerText = "Excavador / Demoledor";

                                    coordinadorPopupBodyLbl.Text = "Esperar por revisión de coordinador";

                                    coordinadorPopup.Show();
                                }
                            }

                            //Do not allow update if any of these conditions
                            else if (!solicitud.EstatusId.Equals(((int)SolicitudAviso.Estatus.PendienteRevisarCoordinador).ToString())
                                    || !solicitud.EstatusId.Equals(((int)SolicitudAviso.Estatus.PendienteDocumentosIncompletos).ToString()))
                            {
                                if (user.Rol.ID != (int)Role.TipoRoles.Director && user.Rol.ID != (int)Role.TipoRoles.SuperInspector)
                                {
                                    guardarBtn.Enabled = false;
                                }
                            }

                            //Allow to view extensions if it's inactive and extensions have already been created
                            if (solicitud.EstatusId.Equals(((int)SolicitudAviso.Estatus.Inactiva).ToString())
                                || solicitud.EstatusId.Equals(((int)SolicitudAviso.Estatus.Denegada).ToString()))
                            {
                                if (string.IsNullOrWhiteSpace(primeraExt.NumeroControl.NumControlText))
                                {
                                    primeraExtensionLink.Visible = false;
                                }

                                if (string.IsNullOrWhiteSpace(segundaExt.NumeroControl.NumControlText))
                                {
                                    segundaExtensionLink.Visible = false;
                                }
                            }

                            //Don't allow to create extensions if it ain't aprovada
                            else if (!solicitud.EstatusId.Equals(((int)SolicitudAviso.Estatus.PendienteAsignarInspector).ToString())
                                & !solicitud.EstatusId.Equals(((int)SolicitudAviso.Estatus.InspeccionCompletada).ToString())
                                & !solicitud.EstatusId.Equals(((int)SolicitudAviso.Estatus.EnProcesoInspeccion).ToString()))
                            {
                                primeraExtensionLink.Visible = false;

                                segundaExtensionLink.Visible = false;
                            }                            
                        }

                        nombreContactoTxtBx.Text = solicitud.NombreContacto;

                        celularContactoTxtBx.Text = solicitud.CelularContacto;

                        direccionPostalContactoTxtBx.Text = solicitud.DireccionPostalContacto;

                        #endregion

                        #region Contratista

                        companyDDL.Items.Add(solicitud.NombreEmpresa);

                        companyDDL.SelectedValue = solicitud.NombreEmpresa;

                        representanteTxtBx.Text = solicitud.RepresentanteAutorizado;

                        if (!solicitud.TipoAviso.Equals(((int)SolicitudAviso.TiposAvisos.Residencial).ToString()))
                        {
                            areaDepartamentoTxtBx.Text = solicitud.AreaDept;
                        }

                        else
                        {
                            deptLbl.Text = deptLbl.Text.Replace("*", string.Empty);

                            areaDepartamentoTxtBx.Enabled = false;

                            deptRFV.Enabled = false;
                        }

                        telOficinaTxtBx.Text = solicitud.TelOficina;

                        telTrabajoTxtBx.Text = solicitud.TelCampoTrabajo;

                        celularTxtBx.Text = solicitud.TelCelular;

                        emailTxtBx.Text = solicitud.CorreoElectronico;

                        direccionTxtBx.Text = solicitud.DireccionPostal;

                        municipioDDL.SelectedIndex = solicitud.MunicipioId;

                        codigoPostalTxtBx.Text = solicitud.CodigoPostal;

                        #endregion

                        #region Sub
                        companySubTxtBx.Text = solicitud.Subcontratista;

                        representanteSubTxtBx.Text = solicitud.RepresentanteAutorizadoSub;

                        if (!solicitud.TipoAviso.Equals(((int)SolicitudAviso.TiposAvisos.Residencial).ToString()))
                        {
                            areaDepartamentoSubTxtBx.Text = solicitud.AreaDeptSub;
                        }

                        else
                        {
                            areaDepartamentoSubTxtBx.Enabled = false;

                            //deptRFV.Enabled = false;
                        }

                        //representanteSubTxtBx.Text = solicitud.RepresentanteAutorizadoSub;

                        telOficinaSubTxtBx.Text = solicitud.TelOficinaSub;

                        telTrabajoSubTxtBx.Text = solicitud.TelCampoTrabajoSub;

                        celularSubTxtBx.Text = solicitud.TelCelularSub;

                        emailSubTxtBx.Text = solicitud.CorreoElectronicoSub;

                        direccionSubTxtBx.Text = solicitud.DireccionPostalSub;

                        municipioSubDDL.SelectedIndex = solicitud.MunicipioIdSub;

                        codigoPostalSubTxtBx.Text = solicitud.CodigoPostalSub;

                        #endregion

                        #region Info trabajo

                        //Es urbana?
                        if (solicitud.Zona)
                        {
                            zonaRBtnLst.SelectedIndex = 1;
                        }

                        else
                        {
                            zonaRBtnLst.SelectedIndex = 0;
                        }

                        boUrbTxtBx.Text = solicitud.BoUrb;

                        sectorCalleTxtBx.Text = solicitud.SectorCalle;

                        carreteraTxtBx.Text = solicitud.Carretera;

                        kmTxtBx.Text = solicitud.KM.ToString();

                        hmTxtBx.Text = solicitud.HM.ToString();

                        municipioTrabajoDDL.SelectedIndex = solicitud.MunicipioIdTrab;

                        referenciasTxtBx.Text = solicitud.Referencias;

                        fechaComienzoPropuestoTxtBx.Text = solicitud.FechaPropuesta.ToShortDateString();

                        fechaComienzoTxtBx.Text = solicitud.FechaComienzo.ToShortDateString();

                        fechaExpiracionTxtBx.Text = solicitud.FechaExpiracion.ToShortDateString();

                        string[] duracionSplit = solicitud.TiempoDuracion.Split('-');

                        duracionDiaTxtBx.Text = duracionSplit[0];

                        duracionMesTxtBx.Text = duracionSplit[1];

                        duracionYearTxtBx.Text = duracionSplit[2];

                        string[] horSplit = solicitud.Horario.Split('-');

                        horarioDDL.SelectedValue = horSplit[0];

                        horarioDDL2.SelectedValue = horSplit[1];


                        maquinariaChkBx.Checked = solicitud.Maquinaria;

                        tipoMaquinariaTxtBx.Enabled = solicitud.Maquinaria;

                        if (maquinariaChkBx.Checked)
                        {
                            tipoMaquinariaTxtBx.Enabled = true;

                            tipoMaquinariaTxtBx.Text = solicitud.TipoMaquinaria;

                            maquinariaUtilizarLbl.Text += "*";
                        }

                        else
                        {
                            tipoMaquinariaTxtBx.Enabled = false;
                        }

                        explosivoChkBx.Checked = solicitud.Explosivos;

                        licExplosivoTxtBx.Enabled = solicitud.Explosivos;

                        licExplosivoTxtBx.Text = solicitud.LicenciaExplosivo;

                        fechaExpiracionExplosivoTxtBx.Enabled = solicitud.Explosivos;

                        //fechaExpiracionExplosivoTxtBx.Text = solicitud.FechaExpiracionExplosivo.ToShortDateString();

                        if (explosivoChkBx.Checked)
                        {
                            //tipoExplosivoTxtBx.Enabled = true;

                            //tipoExplosivoTxtBx.Text = solicitud.TipoExplosivo;

                            licExplosivoLbl.Text += "*";

                            fechaExpiracionExplosivoLbl.Text += "*";

                            fechaExpiracionExplosivoTxtBx.Text = solicitud.FechaExpiracionExplosivo.ToShortDateString();
                        }

                        areaMarcadaChkBx.Checked = solicitud.AreaMarcada;

                        //Es continua?
                        if (solicitud.TipoExcavacion)
                        {
                            tipoExcavacionRBtnLst.SelectedIndex = 0;
                        }

                        else
                        {
                            tipoExcavacionRBtnLst.SelectedIndex = 1;
                        }

                        razonTxtBx.Text = solicitud.RazonTrabajos;

                        profundidadPiesTxtBx.Text = solicitud.ProfundidadPies.ToString();

                        profundidadPulgadasDLL.SelectedIndex = solicitud.ProfundidadPulgadas;

                        longitudPiesTxtBx.Text = solicitud.LongitudPies.ToString();

                        longitudPulgadasDDL.SelectedIndex = solicitud.LongitudPulgadas;

                        coordenadasXTxtBx.Text = solicitud.CoordenadaX.ToString();

                        coordenadasYTxtBx.Text = solicitud.CoordenadaY.ToString();

                        enCasoEmergenciaTxtBx.Text = solicitud.EnCasoEmergencia;
                        #endregion

                        #endregion

                        #region Poblar tabla averias
                        LinkedList<Averia> averias = new AveriasServicio().GetAverias(numeroControl, (int)SolicitudAviso.TiposExtensiones.Inicial);

                        averiasTxtBx.Text = averias.ElementAt(0).Titulo;

                        //Session["Averias"] = averias;

                        //DataTable dtCurrentTable = null;

                        //DataRow drCurrentRow = null;

                        ///*En la primera entrada, asigna los valores al row hecho por default. Verifica si hay que crear otro.
                        // * 
                        // * En la segunda corrida, asigna los valores al row nuevo.
                        // * 
                        // * Para evitar usar una linea que no existe o hacer una linea de mas esta el i + 1
                        // * 
                        // * i + 1 si es mayor a la cantidad de filas pues me pase del total y no tengo que hacer una fila nueva
                        // */
                        //for (int i = 0; i < averias.Count; i++)
                        //{
                        //    TextBox averiaTituloTxtBx = (TextBox)averiasGrdVw.Rows[i].Cells[0].FindControl("averiaTituloTxtBx"),
                        //            averiaFechaTxtBx = (TextBox)averiasGrdVw.Rows[i].Cells[1].FindControl("averiaFechaTxtBx"),
                        //            averiaHoraTxtBx = (TextBox)averiasGrdVw.Rows[i].Cells[2].FindControl("averiaHoraTxtBx"),
                        //            averiaInfraAfectadaTxtBx = (TextBox)averiasGrdVw.Rows[i].Cells[3].FindControl("averiaInfraAfectadaTxtBx"),
                        //            averiaLugarTxtBx = (TextBox)averiasGrdVw.Rows[i].Cells[4].FindControl("averiaLugarTxtBx");

                        //    averiaTituloTxtBx.Text = averias.ElementAt(i).Titulo;

                        //    if (true)
                        //    {

                        //    }

                        //    averiaFechaTxtBx.Text = averias.ElementAt(i).Fecha.Year == 1900 
                        //        || averias.ElementAt(i).Fecha.Year == 9999 ? string.Empty
                        //        : averias.ElementAt(i).Fecha.ToShortDateString();

                        //    averiaHoraTxtBx.Text = averias.ElementAt(i).Hora;

                        //    averiaInfraAfectadaTxtBx.Text = averias.ElementAt(i).InfraAfectada;

                        //    averiaLugarTxtBx.Text = averias.ElementAt(i).Lugar;

                        //    //Si hay que crear otro row
                        //    if ((i + 1) != averias.Count)
                        //    {
                        //        if (ViewState["averiaTbl"] != null)
                        //        {
                        //            dtCurrentTable = (DataTable)ViewState["averiaTbl"];

                        //            drCurrentRow = dtCurrentTable.NewRow();

                        //            dtCurrentTable.Rows[i]["titulo"] = averiaTituloTxtBx.Text;

                        //            dtCurrentTable.Rows[i]["fecha"] = averiaFechaTxtBx.Text;

                        //            dtCurrentTable.Rows[i]["hora"] = averiaHoraTxtBx.Text;

                        //            dtCurrentTable.Rows[i]["afectada"] = averiaInfraAfectadaTxtBx.Text;

                        //            dtCurrentTable.Rows[i]["lugar"] = averiaLugarTxtBx.Text;

                        //            dtCurrentTable.Rows.Add(drCurrentRow);

                        //            averiasGrdVw.DataSource = dtCurrentTable;

                        //            averiasGrdVw.DataBind();

                        //            SetPreviousData();
                        //        }
                        //    }

                        //    else
                        //    {
                        //        break;
                        //    }
                        //}

                        solicitud.Averias = averias;

                        #endregion

                        #region Poblar campos docs requeridos

                        LinkedList<DocumentoRequerido> documentosRequeridos = new DocumentosRequeridosServicio().GetDocumentosAsociados(numeroControl,
                            (int)SolicitudAviso.TiposExtensiones.Inicial);

                        Session["docsRequeridos"] = documentosRequeridos;

                        //docsRequeridos = documentosRequeridos;

                        //Dictionary<TextBox, DropDownList> docControls = new Dictionary<TextBox, DropDownList>();

                        //docControls = GetDocCtrls();

                        //SetDocsRequeridos(docControls, documentosRequeridos, solicitud.EstatusId);

                        CreateDocReqCtrls(documentosRequeridos);

                        //for (int i = 0; i < docRequeridosFileUpload.Count; i++)
                        //{
                        //    docRequeridosFileUpload.ElementAt(i).Text = documentosRequeridos.ElementAt(i).Path;
                        //}

                        solicitud.Documentos = documentosRequeridos;

                        CreateDocAsociadosCtrl(documentosRequeridos);

                        LinkedList<DropDownList> docAsociadosStatuses = (LinkedList<DropDownList>)Session["docAsociadosStatuses"];


                        foreach (var d in docAsociadosStatuses)
                        {
                            d.Enabled = solicitud.EstatusId.Equals(((int)SolicitudAviso.Estatus.PendienteRevisarCoordinador).ToString());
                        }


                        #region Disable doc status validators if docs incomplete
                        //Asi si el user cambia de tipo de aviso, no dan problemas esos validators

                        LinkedList<RequiredFieldValidator> docAsociadosValidators = (LinkedList<RequiredFieldValidator>)Session["docAsociadosValidators"];


                        foreach (var v in docAsociadosValidators)
                        {
                            v.Enabled = solicitud.EstatusId.Equals(((int)SolicitudAviso.Estatus.PendienteRevisarCoordinador).ToString());
                        }


                        //propiedadStatusRFV.Enabled = solicitud.EstatusId.Equals(((int)SolicitudAviso.Estatus.PendienteDocumentosIncompletos).ToString());

                        //idStatusRFV.Enabled = solicitud.EstatusId.Equals(((int)SolicitudAviso.Estatus.PendienteDocumentosIncompletos).ToString());

                        //recivoStatusRFV.Enabled = solicitud.EstatusId.Equals(((int)SolicitudAviso.Estatus.PendienteDocumentosIncompletos).ToString());

                        //ajudiStatusRFV.Enabled = solicitud.EstatusId.Equals(((int)SolicitudAviso.Estatus.PendienteDocumentosIncompletos).ToString());

                        //regAgpStatusRFV.Enabled = solicitud.EstatusId.Equals(((int)SolicitudAviso.Estatus.PendienteDocumentosIncompletos).ToString());

                        //regComStatusRFV.Enabled = solicitud.EstatusId.Equals(((int)SolicitudAviso.Estatus.PendienteDocumentosIncompletos).ToString());

                        #endregion

                        #endregion

                        #region poblar respuestas
                        if (!solicitud.EstatusId.Equals(((int)SolicitudAviso.Estatus.PendienteRevisarCoordinador).ToString())
                            && !solicitud.EstatusId.Equals(((int)SolicitudAviso.Estatus.PendienteDocumentosIncompletos).ToString()))
                        {
                            Session["RespuestaVisibility"] = true;

                            respuestasDiv.Visible = true;

                            LinkedList<Respuesta> respuestas = new RespuestasServicio().GetRespuestasResumen(numeroControl,
                                            new SolicitudesInicialesServicio().GetOperadores());

                            Session["Respuesta"] = respuestas;

                            SetRespuestasRowData(respuestas);
                        }

                        #endregion

                        #region Set visibilities(role)
                        //fechaComienzoDiv.Visible = true;

                        //fechaExpiracionDiv.Visible = true;

                        //docsRequeridosHeader.Visible = false;

                        //docRequeridosTableTag.Visible = false;

                        //docsAsociadosHeader.Visible = true;

                        //docsAsociadosTableTag.Visible = true;

                        #region Display responsables de la solicitud

                        //User currentUser = new SolicitudesInicialesServicio().GetUser(solicitud.Usuario.Id);

                        User currentUser = new SolicitudesInicialesServicio().GetUser(solicitud.Usuario.Email);

                        tramitadoLbl.Visible = true;

                        tramitadoLbl.Text += string.Format(" {0}", solicitud.TramitadoPor);

                        //solicitud.Coordinador.Id = 1; // only test

                        if (!string.IsNullOrWhiteSpace(solicitud.Coordinador.Nombre))
                        {
                            //Coordinador coordinador = new SolicitudesInicialesServicio().GetCoordinador(solicitud.Coordinador.Nombre);

                            procesadoLbl.Visible = true;

                            procesadoLbl.Text += string.Format(" {0}", solicitud.Coordinador.Nombre);

                            //solicitud.Inspector.NumeroPlacaID = "001";

                            if (!string.IsNullOrWhiteSpace(solicitud.Inspector.Nombre))
                            {
                                //Inspector inspector = new SolicitudesInicialesServicio().GetInspector(solicitud.Inspector.NumeroPlacaID);

                                inspeccionLbl.Visible = true;

                                inspeccionLbl.Text += string.Format(" {0}", solicitud.Inspector.Nombre);
                            }
                        }

                        #endregion

                        if (solicitud.EstatusId.Equals(((int)SolicitudAviso.Estatus.Inactiva).ToString())
                            || solicitud.EstatusId.Equals(((int)SolicitudAviso.Estatus.InspeccionCompletada).ToString())
                            || solicitud.EstatusId.Equals(((int)SolicitudAviso.Estatus.PendienteAsignarInspector).ToString())
                            || solicitud.EstatusId.Equals(((int)SolicitudAviso.Estatus.EnProcesoInspeccion).ToString()))
                        {
                            fechaComienzoDiv.Visible = true;

                            fechaComienzoDiv2.Visible = true;

                            fechaExpiracionDiv.Visible = true;

                            fechaExpiracionDiv2.Visible = true;
                        }

                        #endregion

                        fechaComienzoPropuestoTxtBx.Enabled = false;

                        fechaComienzoImgBtn.Visible = false;

                        tipoAvisoRBtnLst.Enabled = false;

                        ////Do not allow update if any of these conditions
                        //if (solicitud.EstatusId.Equals(((int)SolicitudAviso.Estatus.Inactiva).ToString())
                        //    || solicitud.EstatusId.Equals(((int)SolicitudAviso.Estatus.Denegada).ToString()))
                        //{
                        //    guardarBtn.Enabled = false;
                        //}

                        //Add validacion de role. Sino es 
                        //else if (!solicitud.EstatusId.Equals(((int)SolicitudAviso.Estatus.PendienteDocumentosIncompletos).ToString())
                        //        && !solicitud.EstatusId.Equals(((int)SolicitudAviso.Estatus.PendienteRevisarCoordinador).ToString()))
                        //{
                        //    guardarBtn.Enabled = false;
                        //}

                        #endregion
                    }
                }

                catch (Exception ex)
                {
                    errorLbl2.InnerText = ex.Message;

                    errorPopup.Show();
                }
            }

                //tipo de aviso si hace postback
            else
            {

                if (maquinariaChkBx.Checked)
                {
                    tipoMaquinariaTxtBx.Enabled = true;

                    if (!maquinariaUtilizarLbl.Text.Contains("*"))
                    {
                        maquinariaUtilizarLbl.Text += "*";
                    }
                }

                else
                {
                    tipoMaquinariaTxtBx.Enabled = false;

                    maquinariaUtilizarLbl.Text = maquinariaUtilizarLbl.Text.Replace("*", string.Empty);
                }

                if (explosivoChkBx.Checked)
                {
                    licExplosivoTxtBx.Enabled = true;

                    fechaExpiracionExplosivoTxtBx.Enabled = true;

                    //tipoExplosivoTxtBx.Text = solicitud.TipoExplosivo;

                    if (!licExplosivoLbl.Text.Contains("*"))
                    {
                        licExplosivoLbl.Text += "*";

                        fechaExpiracionExplosivoLbl.Text += "*";
                    }
                }

                else
                {
                    licExplosivoTxtBx.Enabled = false;

                    fechaExpiracionExplosivoTxtBx.Enabled = false;

                    licExplosivoLbl.Text = licExplosivoLbl.Text.Replace("*", string.Empty);

                    fechaExpiracionExplosivoLbl.Text = fechaExpiracionExplosivoLbl.Text.Replace("*", string.Empty);
                }

                //#region Poblar tabla averias
                //LinkedList<Averia> averias = (LinkedList<Averia>)Session["Averias"];

                ////Session["Averias"] = averias;

                //bool rowWasAdded = Session["newRow"] == null ? false : (bool)Session["newRow"];

                //if (averias.Count > 0)
                //{
                //    if (rowWasAdded)
                //    {
                //        #region Update averia obj after postback

                //        DataTable dtCurrentTable = (DataTable)ViewState["averiaTbl"];

                //        DataRow drCurrentRow = null;

                //        dtCurrentTable = SetAveriaRowData(dtCurrentTable, drCurrentRow, false, true);

                //        averias = (LinkedList<Averia>)Session["Averias"];

                //        #endregion
                //    }

                //if (averiasGrdVw.Rows.Count < 1)
                //{
                //    DataTable dtCurrentTable = (DataTable)ViewState["averiaTbl"];

                //    averiasGrdVw.DataSource = dtCurrentTable;

                //    averiasGrdVw.DataBind();

                //    SetPreviousData();
                //}

                /*En la primera entrada, asigna los valores al row hecho por default. Verifica si hay que crear otro.
                 * 
                 * En la segunda corrida, asigna los valores al row nuevo.
                 * 
                 * Sino hay filas(por un postback) las creo y relleno con la data pasada.
                 * 
                 * Si hay filas pues las lleno con el obj de averias
                 */

                //else
                //for (int i = 0; i < averias.Count; i++)
                //{
                //    TextBox averiaTituloTxtBx = (TextBox)averiasGrdVw.Rows[i].Cells[0].FindControl("averiaTituloTxtBx"),
                //            averiaFechaTxtBx = (TextBox)averiasGrdVw.Rows[i].Cells[1].FindControl("averiaFechaTxtBx"),
                //            averiaHoraTxtBx = (TextBox)averiasGrdVw.Rows[i].Cells[2].FindControl("averiaHoraTxtBx"),
                //            averiaInfraAfectadaTxtBx = (TextBox)averiasGrdVw.Rows[i].Cells[3].FindControl("averiaInfraAfectadaTxtBx"),
                //            averiaLugarTxtBx = (TextBox)averiasGrdVw.Rows[i].Cells[4].FindControl("averiaLugarTxtBx");

                //    averiaTituloTxtBx.Text = averias.ElementAt(i).Titulo;

                //    averiaFechaTxtBx.Text = averias.ElementAt(i).Fecha.Year == 1900
                //        || averias.ElementAt(i).Fecha.Year == 9999 ? string.Empty
                //        : averias.ElementAt(i).Fecha.ToShortDateString();

                //    averiaHoraTxtBx.Text = averias.ElementAt(i).Hora;

                //    averiaInfraAfectadaTxtBx.Text = averias.ElementAt(i).InfraAfectada;

                //    averiaLugarTxtBx.Text = averias.ElementAt(i).Lugar;

                //    //Si hay que crear otro row
                //    //if ((i + 1) != averias.Count)
                //    //{
                //    //    if (ViewState["averiaTbl"] != null)
                //    //    {
                //    //        dtCurrentTable = (DataTable)ViewState["averiaTbl"];

                //    //        drCurrentRow = dtCurrentTable.NewRow();

                //    //        dtCurrentTable.Rows[i]["titulo"] = averiaTituloTxtBx.Text;

                //    //        dtCurrentTable.Rows[i]["fecha"] = averiaFechaTxtBx.Text;

                //    //        dtCurrentTable.Rows[i]["hora"] = averiaHoraTxtBx.Text;

                //    //        dtCurrentTable.Rows[i]["afectada"] = averiaInfraAfectadaTxtBx.Text;

                //    //        dtCurrentTable.Rows[i]["lugar"] = averiaLugarTxtBx.Text;

                //    //        dtCurrentTable.Rows.Add(drCurrentRow);

                //    //        averiasGrdVw.DataSource = dtCurrentTable;

                //    //        averiasGrdVw.DataBind();

                //    //        SetPreviousData();
                //    //    }
                //    //}

                //    //else
                //    //{
                //    //    break;
                //    //}
                //}

                //Session["newRow"] = false;
                //}

                //solicitud.Averias = averias;

                //#endregion

                #region Set respuesta
                LinkedList<Respuesta> respuestas = (LinkedList<Respuesta>)Session["Respuesta"];

                //= respuestas;

                if (respuestas != null)
                {
                    SetRespuestasRowData(respuestas);
                }
                #endregion

                #region Set doc controls on postback
                LinkedList<DocumentoRequerido> docsRequeridos = (LinkedList<DocumentoRequerido>)Session["docsRequeridos"];

                if (docsRequeridos != null)
                {
                    CreateDocAsociadosCtrl(docsRequeridos);
                }
                #endregion
            }
        }
        protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                int municipioCell = Convert.ToInt32(ViewState["municipiosCell"]),
                    certCell = Convert.ToInt32(ViewState["certCell"]),
                    croqCell = Convert.ToInt32(ViewState["croqCell"]),
                    numControlCell = Convert.ToInt32(ViewState["numControlCell"]);

                #region Config row selection

                //On IE and safari, When clicking a btnfield it also invokes this. 
                if (!Request.Browser.Browser.Equals("InternetExplorer") && !Request.Browser.Browser.Equals("Safari"))
                    e.Row.Attributes["onclick"] = Page.ClientScript.GetPostBackClientHyperlink(
                         gv, "Select$" + e.Row.RowIndex);

                e.Row.ToolTip = "Para responder aviso oprima 'Click'.";

                if (e.Row.Cells.Count > 1)
                {
                    try
                    {
                        //To avoid the btn field issue I allowed the gv to generate the select btn instead of adding it every row's attributes. 
                        //That way btn field event and select event are handled seperatly.
                        LinkButton selectLinkBtn = (LinkButton)e.Row.Cells[0].Controls[0];

                        selectLinkBtn.Text = "Seleccionar fila";
                    }

                    catch (Exception)
                    {
                    }

                    //Minus 1 cause on municipios get is the same get from avisos and there the ddl starts in 2 and here starts in 1
                    int index = Math.Abs((Convert.ToInt32(e.Row.Cells[municipioCell].Text)) - 1);

                    e.Row.Cells[municipioCell].Text = municipiosDDL.Items[index].Text;
                } 

                #endregion

                #region Config cert and croquis btn depending on browser. Also, set status

                if (e.Row.Cells.Count > 5)
                {
                    LinkedList<string> statuses = new SolicitudesInicialesServicio().GetStatusMsgs();

                    ButtonField btnCert,
                        btnCroquis;

                    if (!Request.Browser.Browser.Equals("InternetExplorer") && !Request.Browser.Browser.Equals("Safari"))
                    {
                        btnCert = (ButtonField)gv.Columns[certCell];

                        btnCroquis = (ButtonField)gv.Columns[croqCell];

                        //Set status
                        e.Row.Cells[5].Text = statuses.ElementAt((Convert.ToInt32(e.Row.Cells[5].Text.Replace("S", string.Empty))) - 1);
                    }

                        //Minus 1 cause going through e.Row.Cells includes select cell and going through gv.Columns doesn't include select link
                    else
                    {
                        btnCert = (ButtonField)gv.Columns[Math.Abs(certCell - 1)];

                        btnCroquis = (ButtonField)gv.Columns[Math.Abs(croqCell - 1)];

                        //Set status
                        e.Row.Cells[6].Text = statuses.ElementAt((Convert.ToInt32(e.Row.Cells[6].Text.Replace("S", string.Empty))) - 1);
                    }

                    if (!Request.Browser.Browser.Equals("Chrome"))
                    {
                        btnCert.ButtonType = ButtonType.Button;

                        btnCroquis.ButtonType = ButtonType.Button;
                    }
                } 

                #endregion
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            var title = (HtmlGenericControl)Master.FindControl("pageTitleSpan");

            title.InnerText = Title;

            User user = Session["UserObj"] == null ? new User() : (User)Session["UserObj"];

            NumeroControl numControl = new NumeroControl();

            #region Re-register imgsBtns clientscripts

            if (ViewState["SetImgsClientScript"] != null)
            {
                string script = @"<script>
                                          function  @TITLE
                                          {
                                            var img = document.getElementById('@CONTROLID');

                                            var url = img.getAttribute('src');

                                            window.open(url, '_blank');
                                         }

                                </script>";

                #region Evidencia general
                ClientScript.RegisterClientScriptBlock(GetType(), "Primera", script.Replace("@TITLE", primeraEvidenciaImgBtn.OnClientClick.Replace(
                                ";", string.Empty)).Replace("@CONTROLID", primeraEvidenciaImgBtn.ClientID));

                ClientScript.RegisterClientScriptBlock(GetType(), "Segunda", script.Replace("@TITLE", segundaEvidenciaImgBtn.OnClientClick.Replace(
                        ";", string.Empty)).Replace("@CONTROLID", segundaEvidenciaImgBtn.ClientID));

                ClientScript.RegisterClientScriptBlock(GetType(), "Tercera", script.Replace("@TITLE", terceraEvidenciaImgBtn.OnClientClick.Replace(
                        ";", string.Empty)).Replace("@CONTROLID", terceraEvidenciaImgBtn.ClientID));

                ClientScript.RegisterClientScriptBlock(GetType(), "Cuarta", script.Replace("@TITLE", cuartaEvidenciaImgBtn.OnClientClick.Replace(
                        ";", string.Empty)).Replace("@CONTROLID", cuartaEvidenciaImgBtn.ClientID)); 
                #endregion

                #region Evidencia inspector
                ClientScript.RegisterClientScriptBlock(GetType(), "Inspector", script.Replace("@TITLE", inspectorEvidenciaImgBtn.OnClientClick.Replace(
                                    ";", string.Empty)).Replace("@CONTROLID", inspectorEvidenciaImgBtn.ClientID));

                ClientScript.RegisterClientScriptBlock(GetType(), "Inspector2", script.Replace("@TITLE", inspectorEvidenciaImgBtn2.OnClientClick.Replace(
                           ";", string.Empty)).Replace("@CONTROLID", inspectorEvidenciaImgBtn2.ClientID));

                ClientScript.RegisterClientScriptBlock(GetType(), "Inspector3", script.Replace("@TITLE", inspectorEvidenciaImgBtn3.OnClientClick.Replace(
                            ";", string.Empty)).Replace("@CONTROLID", inspectorEvidenciaImgBtn3.ClientID));

                ClientScript.RegisterClientScriptBlock(GetType(), "Inspector4", script.Replace("@TITLE", inspectorEvidenciaImgBtn4.OnClientClick.Replace(
                            ";", string.Empty)).Replace("@CONTROLID", inspectorEvidenciaImgBtn4.ClientID)); 
                #endregion

            } 

            #endregion

            if (!IsPostBack)
            {
                #region Fill ddls

                #region fill inspector ddl

                LinkedList<Inspector> inspectores = new SolicitudesInicialesServicio().GetInspectores();

                for (int i = 1; i < inspectores.Count; i++)
                {
                    inspectoresDDL.Items.Add(inspectores.ElementAt(i).Nombre);
                }

                #endregion

                #region Fill municipio ddl

                LinkedList<string> municipios = new SolicitudesInicialesServicio().GetMunicipios();

                for (int i = 0; i < municipios.Count; i++)
                {
                    municipioDDL.Items.Add(municipios.ElementAt(i));
                }

                #endregion

                #region fill operador afectado ddl

                LinkedList<Operador> operadores = new SolicitudesInicialesServicio().GetOperadores();

                for (int i = 0; i < operadores.Count; i++)
                {
                    operadorAfectadoDDL.Items.Add(operadores.ElementAt(i).Nombre);
                }

                #endregion 

                #endregion

                #region Set multi line txtbx maxlength cause clieent side max length doesn't work

                direccionTxtBx.Attributes["maxlength"] = Convert.ToString(300);

                descTxtBx.Attributes["maxlength"] = Convert.ToString(300);

                causaTxtBx.Attributes["maxlength"] = Convert.ToString(300);

                AccionTxtBx.Attributes["maxlength"] = Convert.ToString(300);

                informeTxtBx.Attributes["maxlength"] = Convert.ToString(500);

                operadoresTxtBx.Attributes["maxlength"] = Convert.ToString(600); 

                #endregion

                if (Request.QueryString["Id"] == null)
                {
                    #region Create

                    #region Set automatic values

                    fechaTxtBx.Text = DateTime.Now.ToShortDateString();

                    horaTxtBx.Text = DateTime.Now.ToString("hh:mm tt"); 

                    #endregion

                    #region Set visibilities

                    primeraEvidenciaImgBtn.Visible = false;

                    segundaEvidenciaImgBtn.Visible = false;

                    terceraEvidenciaImgBtn.Visible = false;

                    cuartaEvidenciaImgBtn.Visible = false;

                    #endregion

                    #endregion
                }

                else
                {
                    #region Edit

                    Averia averia = AveriasServicio.GetAveriaById(Convert.ToInt32(Request.QueryString["Id"]));

                    ViewState["NumControl"] = averia.NumeroControl.NumControlText;

                    ViewState["Evidencias"] = averia.EvidenciasPath;

                    ViewState["EvidenciasInspector"] = averia.InspectorEvidenciasPath;

                    #region Set control generales data

                    numAvisoTxtBx.Text = averia.NumeroControl.NumControlText;

                    municipioDDL.SelectedValue = averia.Municipio;

                    sinAvisoChkBx.Checked = averia.TieneAviso;

                    if (sinAvisoChkBx.Checked)
                        numAvisoLbl.Text = numAvisoLbl.Text.Replace("*", string.Empty);

                    numAvisoREV.Enabled = !sinAvisoChkBx.Checked;

                    fechaTxtBx.Text = averia.FechaNotificacion.ToShortDateString();

                    fechaAveriaTxtBx.Text = averia.FechaAveria.ToShortDateString();

                    horaTxtBx.Text = averia.Hora;

                    reportingCompanyTxtBx.Text = averia.Reportante;

                    causingCompanyTxtBx.Text = averia.Causante;

                    usuariosAfectadosTxtBx.Text = averia.UsuariosAfectados;

                    serviciosAfectadosTxtBx.Text = averia.ServiciosAfectados;

                    direccionTxtBx.Text = averia.Direccion;

                    descTxtBx.Text = averia.Descripcion;

                    causaTxtBx.Text = averia.Causa;

                    AccionTxtBx.Text = averia.AccionTomada;

                    contactEmpTxtBx.Text = averia.EmpleadoContactar;

                    operadoresTxtBx.Text = averia.OperadorAfectado;

                    #endregion

                    #region Set evidencia imgs

                    //Se pierden los clientscript on post this indicates if the should be re-registered
                    ViewState["SetImgsClientScript"] = true;

                    string script = @"<script>
                                          function  @TITLE
                                          {
                                            var img = document.getElementById('@CONTROLID');

                                            var url = img.getAttribute('src');

                                            window.open(url, '_blank');
                                         }

                                </script>";
                    #region Primera

                    if (!string.IsNullOrEmpty(averia.EvidenciasPath.ElementAt(0)))
                    {
                        primeraEvidenciaImgBtn.ImageUrl = averia.EvidenciasPath.ElementAt(0);

                        primeraEvidenciaImgBtn.OnClientClick = "PrimeraImgClick();";

                        ClientScript.RegisterClientScriptBlock(GetType(), "Primera", script.Replace("@TITLE", primeraEvidenciaImgBtn.OnClientClick.Replace(
                            ";", string.Empty)).Replace("@CONTROLID", primeraEvidenciaImgBtn.ClientID));
                    }

                    #endregion

                    #region Segunda

                    if (!string.IsNullOrEmpty(averia.EvidenciasPath.ElementAt(1)))
                    {
                        segundaEvidenciaImgBtn.ImageUrl = averia.EvidenciasPath.ElementAt(1);

                        segundaEvidenciaImgBtn.OnClientClick = "SegundaImgClick();";

                        ClientScript.RegisterClientScriptBlock(GetType(), "Segunda", script.Replace("@TITLE", segundaEvidenciaImgBtn.OnClientClick.Replace(
                            ";", string.Empty)).Replace("@CONTROLID", segundaEvidenciaImgBtn.ClientID));
                    }
 
                    #endregion

                    #region Tercera

                    if (!string.IsNullOrEmpty(averia.EvidenciasPath.ElementAt(2)))
                    {
                        terceraEvidenciaImgBtn.ImageUrl = averia.EvidenciasPath.ElementAt(2);

                        terceraEvidenciaImgBtn.OnClientClick = "TerceraImgClick();";

                        ClientScript.RegisterClientScriptBlock(GetType(), "Tercera", script.Replace("@TITLE", terceraEvidenciaImgBtn.OnClientClick.Replace(
                            ";", string.Empty)).Replace("@CONTROLID", terceraEvidenciaImgBtn.ClientID));
                    }

                    #endregion

                    #region Cuarta

                    if (!string.IsNullOrEmpty(averia.EvidenciasPath.ElementAt(3)))
                    {
                        cuartaEvidenciaImgBtn.ImageUrl = averia.EvidenciasPath.ElementAt(3);

                        cuartaEvidenciaImgBtn.OnClientClick = "CuartaImgClick();";

                        ClientScript.RegisterClientScriptBlock(GetType(), "Cuarta", script.Replace("@TITLE", cuartaEvidenciaImgBtn.OnClientClick.Replace(
                            ";", string.Empty)).Replace("@CONTROLID", cuartaEvidenciaImgBtn.ClientID));
                    }

                    ViewState["EvidenciasPath"] = averia.EvidenciasPath;
  
                    #endregion

                    #endregion

                    #region Set uso oficial

                    if (string.IsNullOrEmpty(averia.Inspector))
                    {
                        fechaUsoOficialTxtBx.Text = DateTime.Now.ToShortDateString();
                    }

                    else
                    {
                        inspectoresDDL.Items.FindByValue(averia.Inspector).Selected = true;

                        fechaUsoOficialTxtBx.Text = averia.FechaUsoOficial.ToShortDateString();
                    }

                    autorizadoTxtBx.Text = averia.AutorizadoPor;

                    informeTxtBx.Text = averia.Informe;

                    #region Inspector evidencias

                    #region 1ra

                    if (!string.IsNullOrEmpty(averia.InspectorEvidenciasPath.ElementAt(0)))
                    {
                        inspectorEvidenciaImgBtn.ImageUrl = averia.InspectorEvidenciasPath.ElementAt(0);

                        inspectorEvidenciaImgBtn.OnClientClick = "InspectorImgClick();";

                        ClientScript.RegisterClientScriptBlock(GetType(), "Inspector", script.Replace("@TITLE", inspectorEvidenciaImgBtn.OnClientClick.Replace(
                            ";", string.Empty)).Replace("@CONTROLID", inspectorEvidenciaImgBtn.ClientID));
                    }

                    #endregion

                    #region 2da

                    if (!string.IsNullOrEmpty(averia.InspectorEvidenciasPath.ElementAt(1)))
                    {
                        inspectorEvidenciaImgBtn2.ImageUrl = averia.InspectorEvidenciasPath.ElementAt(1);

                        inspectorEvidenciaImgBtn2.OnClientClick = "InspectorImgClick2();";

                        ClientScript.RegisterClientScriptBlock(GetType(), "Inspector2", script.Replace("@TITLE", inspectorEvidenciaImgBtn2.OnClientClick.Replace(
                            ";", string.Empty)).Replace("@CONTROLID", inspectorEvidenciaImgBtn2.ClientID));
                    }

                    #endregion

                    #region 3ra

                    if (!string.IsNullOrEmpty(averia.InspectorEvidenciasPath.ElementAt(2)))
                    {
                        inspectorEvidenciaImgBtn3.ImageUrl = averia.InspectorEvidenciasPath.ElementAt(2);

                        inspectorEvidenciaImgBtn3.OnClientClick = "InspectorImgClick3();";

                        ClientScript.RegisterClientScriptBlock(GetType(), "Inspector3", script.Replace("@TITLE", inspectorEvidenciaImgBtn3.OnClientClick.Replace(
                            ";", string.Empty)).Replace("@CONTROLID", inspectorEvidenciaImgBtn3.ClientID));
                    }

                    #endregion

                    #region 4ta

                    if (!string.IsNullOrEmpty(averia.InspectorEvidenciasPath.ElementAt(3)))
                    {
                        inspectorEvidenciaImgBtn4.ImageUrl = averia.InspectorEvidenciasPath.ElementAt(3);

                        inspectorEvidenciaImgBtn4.OnClientClick = "InspectorImgClick4();";

                        ClientScript.RegisterClientScriptBlock(GetType(), "Inspector4", script.Replace("@TITLE", inspectorEvidenciaImgBtn4.OnClientClick.Replace(
                            ";", string.Empty)).Replace("@CONTROLID", inspectorEvidenciaImgBtn4.ClientID));
                    }

                    #endregion

                    #endregion

                    #endregion

                    #region Config inspector controls according to role

                    if (user.Rol.ID != ((int)Role.TipoRoles.Director)
                                && user.Rol.ID != ((int)Role.TipoRoles.SuperInspector)
                                && user.Rol.ID != (int)Role.TipoRoles.Admin)
                        inspectoresDDL.Enabled = false;

                    informeRFV.Enabled = user.Rol.ID == (int)Role.TipoRoles.Inspector;

                    if (user.Rol.ID != ((int)Role.TipoRoles.Inspector))
                    {
                        informeLbl.Text = informeLbl.Text.Replace("*", string.Empty);
                    } 

                    #endregion

                    if (!string.IsNullOrEmpty(averia.Informe) && (user.Rol.ID != ((int)Role.TipoRoles.Excavador) && user.Rol.ID != ((int)Role.TipoRoles.Operador)))
                    {
                        averiaPdfBtn.Visible = true;

                        averiaPdfBtn.OnClientClick = string.Format("window.open('/EXC/Images/Documentos/Averias/Documentos/Averia_{0}.pdf','_blank')",
                                    averia.NumeroControl.NumControlText);
                    }

                    #endregion
                }

                #region Set uso oficial visibility

                if (user.Rol.ID == ((int)Role.TipoRoles.Excavador)
                    || user.Rol.ID == ((int)Role.TipoRoles.Operador)
                    || user.Rol.ID == 0)
                {
                    usoOficialTbl.Visible = false;

                    informeDiv.Visible = usoOficialTbl.Visible;

                    inspectorEvidenciaTbl.Visible = false;
                }

                #endregion
            }
        }
Exemple #16
0
        protected void Guardar_Click(object sender, EventArgs e)
        {
            entidadRFV.Enabled = true;

            Page.Validate();


            User user = Session["UserObj"] == null ? new User() : (User)Session["UserObj"];

            if (user == null)
            {
                user = new User();
            }

            //entidadRFV.Enabled = true;

            //Page.Validate();

            if(Page.IsValid)
            {
                emailHF.Value = CorreoElectronico.Text;

                //string allTextBoxValues = ""};
                //foreach (Control c in Page.Controls)
                //{
                //    foreach (Control childc in c.Controls)
                //    {
                //        if (childc is TextBox)
                //        {
                //            allTextBoxValues += ((TextBox)childc).Text + ","};
                //        }
                //    }
                //}
                //if (allTextBoxValues != "")
                //{
                //    // Label1.Text = allTextBoxValues};
                //}


                int[] err = new int[12];

                //string Contrasena = Page.Request.Form["Contrasena"];
                //string ConfirmarContrasena = Page.Request.Form["ConfirmarContrasena"];

                //if (NombreUsuario.Text.Equals("")) { err[1] = 1; err[0] = 1; }
                //if (Inicial.Text.Equals("")) { err[2] = 1; err[0] = 1; }
                //if (ApellidoPaterno.Text.Equals("")) { err[3] = 1; err[0] = 1; }
                //if (ApellidoMaterno.Text.Equals("")) { err[4] = 1; err[0] = 1; }
                //if (CorreoElectronico.Text.Equals("")) { err[5] = 1; err[0] = 1; }
                //if (ConfirmarCorreoElectronico.Text.Equals("")) { err[6] = 1; err[0] = 1; }
                //if (Contrasena.Equals("")) { err[7] = 1; err[0] = 1; }
                //if (ConfirmarContrasena.Equals("")) { err[8] = 1; err[0] = 1; }
                //if (PreguntaSeguridad.SelectedIndex == 0) { err[9] = 1; err[0] = 1; }
                //if (RespuestaSeguridad.Text.Equals("")) { err[10] = 1; err[0] = 1; }
                //if (Telefono.Text.Equals("")) { err[11] = 1; err[0] = 1; }

                err[0] = 0; ////////////////////////////// EAF ///////////////////////////////////
                if (err[0] == 0)
                {
                    string cs = ConfigurationManager.ConnectionStrings["EXC"].ConnectionString;
                    using (SqlConnection conn = new SqlConnection(cs))
                    {
                        using (SqlCommand command = new SqlCommand())
                        {
                            command.Connection = conn;
                            command.CommandType = CommandType.Text;

                            var role = roles.Where(x => x.Nombre == roleDDL.SelectedValue).First();

                            var inspectores = new LinkedList<Inspector>();

                           
                            if (string.IsNullOrWhiteSpace(Request.QueryString["Email"]))
                            {
                                #region Create

                                //command.CommandText = @"DELETE FROM Usuarios WHERE CorreoElectronico = @CorreoElectronico;";

                                command.CommandText += @"INSERT INTO Usuarios VALUES (@NombreUsuario, @Inicial, @ApellidoPaterno, @ApellidoMaterno,
                                                       @CorreoElectronico, @ConfirmarCorreoElectronico, @Contrasena, @ConfirmarContrasena, @PreguntaSeguridad, 
                                                       @RespuestaSeguridad, @Telefono, @UsuarioInterno, @EmpresaID, @Rol);";

                                if (user.Rol.ID == (int)Role.TipoRoles.Admin)
                                {
                                    if (role.ID == (int)Role.TipoRoles.Inspector || role.ID == (int)Role.TipoRoles.SuperInspector)
                                    {
                                        inspectores = new SolicitudesInicialesServicio().GetInspectores();

                                        int ultimaPlaca = Convert.ToInt32(inspectores.ElementAt(inspectores.Count - 1).NumeroPlacaID);

                                        command.CommandText += @"INSERT INTO Inspectores VALUES (@PlacaInspector, @NombreCompleto, @CorreoElectronico);";

                                        command.Parameters.AddWithValue("@PlacaInspector", (ultimaPlaca + 1).ToString("D3"));

                                        command.Parameters.AddWithValue("@NombreCompleto", NombreUsuario.Text + " " + ApellidoPaterno.Text + " " + ApellidoMaterno.Text);

                                        command.Parameters.AddWithValue("@UsuarioInterno", true);
                                    }

                                    else if (role.ID == (int)Role.TipoRoles.Coordinador)
                                    {
                                        command.CommandText += @"INSERT INTO Coordinadores VALUES (@NombreCompleto);";

                                        command.Parameters.AddWithValue("@NombreCompleto", NombreUsuario.Text + " " + ApellidoPaterno.Text + " " + ApellidoMaterno.Text);

                                        command.Parameters.AddWithValue("@UsuarioInterno", true);
                                    }

                                    else if (role.ID == (int)Role.TipoRoles.Admin 
                                        || role.ID == (int)Role.TipoRoles.SuperInspector
                                        || role.ID == (int)Role.TipoRoles.Director)
                                    {
                                        command.Parameters.AddWithValue("@UsuarioInterno", true);
                                    }

                                    else
                                    {
                                        command.Parameters.AddWithValue("@UsuarioInterno", false);
                                    }

                                    //command.Parameters.AddWithValue("@Rol", role.ID);
                                }

                                else
                                {
                                    //command.Parameters.AddWithValue("@Rol", ((int)Role.TipoRoles.Excavador - 1));

                                    command.Parameters.AddWithValue("@UsuarioInterno", false);
                                }

                                #endregion
                            }                             

                            else
                            {
                                #region Edit
                                command.CommandText += @"UPDATE Usuarios SET NombreUsuario = @NombreUsuario,
                                                                             Inicial = @Inicial,
                                                                             ApellidoPaterno = @ApellidoPaterno,
                                                                            ApellidoMaterno = @ApellidoMaterno,
                                                                            CorreoElectronico = @CorreoElectronico,
                                                                            ConfirmarCorreoElectronico = @ConfirmarCorreoElectronico,
                                                                            Contrasena = @Contrasena,
                                                                            ConfirmarContrasena = @ConfirmarContrasena,
                                                                            PreguntaSeguridad = @PreguntaSeguridad, 
                                                                            RespuestaSeguridad = @RespuestaSeguridad,
                                                                            Telefono = @Telefono,
                                                                            UsuarioInterno = @UsuarioInterno,
                                                                            EmpresaID = @EmpresaID,
                                                                            Rol = @Rol
                                                                            WHERE CorreoElectronico = @OldEmail;";

                                command.Parameters.AddWithValue("@OldEmail", (string)Session["UserEmail"]);

                                if (role.ID == (int)Role.TipoRoles.Inspector || role.ID == (int)Role.TipoRoles.SuperInspector)
                                {
                                    inspectores = new SolicitudesInicialesServicio().GetInspectores();

                                    string placaInspector = inspectores.Where(x => x.CorreoElectronico.Equals((string)Session["UserEmail"])).First().NumeroPlacaID;

                                    command.CommandText += @"UPDATE Inspectores SET NombreInspector = @NombreCompleto
                                                                                    , CorreoElectronico = @CorreoElectronico 
                                                                WHERE PlacaInspector = @PlacaInspector;";

                                    command.Parameters.AddWithValue("@PlacaInspector", placaInspector);

                                    command.Parameters.AddWithValue("@NombreCompleto", NombreUsuario.Text + " " + ApellidoPaterno.Text + " " + ApellidoMaterno.Text);

                                    command.Parameters.AddWithValue("@UsuarioInterno", true);
                                }

                                else if (role.ID == (int)Role.TipoRoles.Coordinador)
                                {
                                    command.CommandText += @"UPDATE Coordinadores SET NombreCoordinador = @NombreCompleto WHERE NombreCoordinador = @NombreCoordinador;";

                                    command.Parameters.AddWithValue("@NombreCoordinador", (string)Session["Username"]);

                                    command.Parameters.AddWithValue("@NombreCompleto", NombreUsuario.Text + " " + ApellidoPaterno.Text + " " + ApellidoMaterno.Text);

                                    command.Parameters.AddWithValue("@UsuarioInterno", true);
                                }

                                else if (role.ID == (int)Role.TipoRoles.Admin
                                        || role.ID == (int)Role.TipoRoles.SuperInspector
                                        || role.ID == (int)Role.TipoRoles.Director)
                                {
                                    command.Parameters.AddWithValue("@UsuarioInterno", true);
                                }

                                else
                                {
                                    command.Parameters.AddWithValue("@UsuarioInterno", false);
                                }

                                #endregion
                            }

                            command.Parameters.AddWithValue("@Rol", role.ID);  

                            command.Parameters.AddWithValue("@NombreUsuario", NombreUsuario.Text.ToUpper());                                                  

                            command.Parameters.AddWithValue("@Inicial", Inicial.Text.ToUpper());
                            command.Parameters.AddWithValue("@ApellidoPaterno", ApellidoPaterno.Text.ToUpper());
                            command.Parameters.AddWithValue("@ApellidoMaterno", ApellidoMaterno.Text.ToUpper()); ;
                            command.Parameters.AddWithValue("@CorreoElectronico", CorreoElectronico.Text.ToLower());
                            command.Parameters.AddWithValue("@ConfirmarCorreoElectronico", ConfirmarCorreoElectronico.Text.ToLower());

                            if (string.IsNullOrWhiteSpace(ConfirmarContrasena.Value))
                            {
                                string oldEmail = (string)Session["UserEmail"];

                                if(oldEmail.Equals(user.Email))
                                {                                
                                    command.Parameters.AddWithValue("@Contrasena", user.Password );

                                    command.Parameters.AddWithValue("@ConfirmarContrasena", user.Password);
                                }

                                else
                                {
                                    User selectedUser = new SolicitudesInicialesServicio().GetUser(Request.QueryString["Email"].Replace("%40", "@"));

                                    command.Parameters.AddWithValue("@Contrasena", selectedUser.Password);

                                    command.Parameters.AddWithValue("@ConfirmarContrasena", selectedUser.Password);
                                }
                            }

                            else
                            {
                                command.Parameters.AddWithValue("@Contrasena", Contrasena.Value);

                                command.Parameters.AddWithValue("@ConfirmarContrasena", Contrasena.Value);
                            }

                            //command.Parameters.AddWithValue("@Contrasena", string.IsNullOrWhiteSpace(ConfirmarContrasena.Value) 
                            //    ? user.Password : Contrasena.Value );
                            //command.Parameters.AddWithValue("@ConfirmarContrasena", string.IsNullOrWhiteSpace(ConfirmarContrasena.Value)
                            //    ? user.Password : Contrasena.Value);
                            command.Parameters.AddWithValue("@PreguntaSeguridad", PreguntaSeguridad.SelectedValue.ToString());
                            command.Parameters.AddWithValue("@RespuestaSeguridad", RespuestaSeguridad.Text.ToUpper());
                            command.Parameters.AddWithValue("@Telefono", Telefono.Text);
                            //command.Parameters.AddWithValue("@UsuarioInterno", false);
                            command.Parameters.AddWithValue("@EmpresaID", ddlEmpresas.SelectedValue);

                            try
                            {
                                conn.Open();
                                int recordsAffected = command.ExecuteNonQuery();

                                if (string.IsNullOrWhiteSpace(Request.QueryString["Email"]))
                                {   
                                    #region Create user document directories

                                    Directory.CreateDirectory(Server.MapPath(string.Format("{0}/{1}",
                                                                    new DocumentoRequerido().DocumentosInicialesSavePath, CorreoElectronico.Text)));

                                    if (role.ID == (int)Role.TipoRoles.Inspector || role.ID == (int)Role.TipoRoles.SuperInspector)
                                    {
                                        Directory.CreateDirectory(Server.MapPath(string.Format("{0}/{1}",
                                        new DocumentoRequerido().DocumentosInspeccionesSavePath, CorreoElectronico.Text)));
                                    } 

                                    Directory.CreateDirectory(Server.MapPath(string.Format("{0}/{1}",
                                        new DocumentoRequerido().DocumentosPrimerasSavePath, CorreoElectronico.Text)));

                                    Directory.CreateDirectory(Server.MapPath(string.Format("{0}/{1}",
                                        new DocumentoRequerido().DocumentosSegundasSavePath, CorreoElectronico.Text)));

                                    #endregion

                                    Response.Redirect("~/Account/Ingresar.aspx");

                                    //Cancelar_Click(sender, e);
                                }                                    

                                else
                                {
                                    Entidad.User updatedUser = new SolicitudesInicialesServicio().GetUser(CorreoElectronico.Text);

                                    #region Update current user variable

                                    if (updatedUser.Email.Equals(user.Email))
                                    {
                                        foreach (var r in roles)
                                        {
                                            if (r.ID == (user.Rol.Tipo))
                                            {
                                                user.Rol = r;

                                                Session["UserObj"] = user;

                                                break;
                                            }
                                        }
                                    }
                                    #endregion

                                    Response.Redirect("~/Default.aspx");
                                }

                                //command.ExecuteNonQuery();

                                //if (recordsAffected == 1)
                                //{
                                
                                //}

                                //else
                                //{
                                //    throw new Exception();
                                //}
                            }
                            catch (Exception ex)
                            {
                                ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "sqlerr()", true);
                            }
                            finally
                            {
                                conn.Close();
                            }
                        }
                    }
                }
            }
        }
Exemple #17
0
        protected void Page_Load(object sender, EventArgs e)
        {
            User user = Session["UserObj"] == null ? new User() : (User)Session["UserObj"];

            if (!user.Rol.VerMensajero)
            {
                Response.Redirect("~/Default.aspx");
            }

            var title = (HtmlGenericControl)Master.FindControl("pageTitleSpan");

            

            title.InnerText = Title;

            if (!IsPostBack)
            {
                if (string.IsNullOrEmpty(Request.QueryString["ShouldNotExecute"]))
                {
                    #region Execute mensajero

                    LinkedList<SolicitudAviso> solicitudesIniciales = new SolicitudesInicialesServicio().GetSolicitudes(),
                                ext1 = new PrimerasExtensionesServicio().GetPrimerasExtensiones(),
                                ext2 = new SegundasExtensionesServicio().GetSegundasExtensiones();

                    int denegadasCounter = 0,
                        solicitudesAExpirarCounter = 0,
                        solicitudesRecienExpiradasCounter = 0,
                        denegadasExt1Counter = 0,
                        ext1AExpirarCounter = 0,
                        ext1RecienExpiradasCounter = 0,
                        denegadasExt2Counter = 0,
                        ext2AExpirarCounter = 0,
                        ext2RecienExpiradasCounter = 0;
                    //operadoresSinResponderCincoDiasCounter = 0,
                    //operadoresSinResponderSieteDiasCounter = 0;

                    LinkedList<string> to = new LinkedList<string>();

                    //to.AddLast("*****@*****.**"); //only test

                    LinkedList<Mail> mails = new MailServicio().GetMailMsgs();

                    #region Inicial

                    Messenger mesInicial = new Messenger();

                    foreach (var s in solicitudesIniciales)
                    {
                        s.EstatusId = s.EstatusId.Replace(s.LetraStatus, string.Empty);

                        to = new LinkedList<string>();

                        to.AddLast(s.Usuario.Email);

                        #region Docs still incompletos after 48hrs

                        DateTime fechaDocsIncompletos = s.FechaDocsIncompletos;
                        //fechaDenegarDocsIncompletos = fechaDocsIncompletos.AddHours(48);

                        if (s.FechaDocsIncompletos.Date.AddHours(48) <= DateTime.Now.Date
                                && s.EstatusId.Equals(((int)SolicitudAviso.Estatus.PendienteDocumentosIncompletos).ToString()))
                        {
                            s.EstatusId = s.LetraStatus + ((int)SolicitudAviso.Estatus.Denegada).ToString();

                            new SolicitudesInicialesServicio().TryUpdate(s);

                            denegadasCounter++;

                            //to.AddLast(currentUser.Email);

                            numControlDenegadasTxtBx.Text += string.Format("{0} ", s.NumeroControl.NumControlText);                            

                            //to = new LinkedList<string>();

                            //SendEmail(to, "", "", "");

                            //SendEmail(to, "*****@*****.**", "Aviso", "Aviso fue denegado, pasaron 48 dias"); //only foor test

                            try
                            {
                                if (CheckForInternetConnection())
                                    SendEmail(to, "*****@*****.**",
                            mails.ElementAt((int)Mail.Notifications.SolicitudDenegada).Subject,
                            mails.ElementAt((int)Mail.Notifications.SolicitudDenegada).Body.Replace(
                            "@NumControl", s.NumeroControl.NumControlText).Replace("@NombreEmpresa", s.NombreEmpresa));
                            }// only test

                            catch (Exception ex)
                            { }

                            mesInicial.NumerosControlSolicitudesDenegadas += string.Format("{0},", numControlDenegadasTxtBx.Text);

                            mesInicial.SolicitudesDenegadas = denegadasCounter;
                        }

                        #endregion

                        SolicitudAviso primeraExt = new PrimerasExtensionesServicio().GetPrimeraExtension(s.NumeroControl);

                        #region Verifica solicitudes apuntos de expirar sin extensiones
                        //var fechaExpiracion = s.FechaExpiracion.AddDays(-4);

                        if (s.FechaExpiracion.Date.AddDays(-5).Equals(DateTime.Now.Date))
                        {
                            if (string.IsNullOrEmpty(primeraExt.NumeroControl.NumControlText))
                            {
                                //to = new LinkedList<string>();

                                //SendEmail(to, "", "", "");

                                //SendEmail(to, "*****@*****.**", "Aviso", "Aviso apunto de expirar sin extension"); //only foor test

                                try
                                {
                                    if (CheckForInternetConnection())
                                        SendEmail(to, "*****@*****.**",
                            mails.ElementAt((int)Mail.Notifications.SolicitudExpira5).Subject,
                            mails.ElementAt((int)Mail.Notifications.SolicitudExpira5).Body.Replace(
                            "@NumControl", s.NumeroControl.NumControlText).Replace("@NombreEmpresa", s.NombreEmpresa));
                                }// only test

                                catch (Exception ex)
                                { }

                                numControlEnRangoExpTxtBx.Text += string.Format("{0} ", s.NumeroControl.NumControlText);

                                solicitudesAExpirarCounter++;

                                mesInicial.NumerosControlSolicitudesAExpirar += string.Format("{0},", s.NumeroControl.NumControlText);

                                mesInicial.SolicitudesAExpirar = solicitudesAExpirarCounter;
                            }
                        }
                        #endregion

                        #region Verifica solicitudes recien expiradas
                        if (s.FechaExpiracion.Date == (DateTime.Now.Date)
                            && (!s.EstatusId.Equals(((int)SolicitudAviso.Estatus.Inactiva).ToString())
                            && !s.EstatusId.Equals(((int)SolicitudAviso.Estatus.InspeccionCompletada).ToString())))
                        {
                            s.EstatusId = s.LetraStatus + ((int)SolicitudAviso.Estatus.Inactiva).ToString();

                            new SolicitudesInicialesServicio().TryUpdate(s);

                            numControlRecienExpTxtBx.Text += string.Format("{0} ", s.NumeroControl.NumControlText);

                            solicitudesRecienExpiradasCounter++;

                            mesInicial.NumerosControlSolicitudesExpiradas += string.Format("{0},", s.NumeroControl.NumControlText);

                            mesInicial.SolicitudesExpiradas = solicitudesRecienExpiradasCounter;
                        }
                        #endregion

                        #region Verificar por operadores sin responder

                        var operadores = new SolicitudesInicialesServicio().GetOperadores();

                        var respuestas = new RespuestasServicio().GetRespuestas(s.NumeroControl);

                        var municipios = new SolicitudesInicialesServicio().GetMunicipios();

                        string municipio = municipios.ElementAt(s.MunicipioIdTrab - 1);                        

                        int respuestaCounter = 0;

                        foreach (var o in operadores)
                        {
                            respuestaCounter = 0;

                            //Check si respondio
                            foreach (var r in respuestas)
                            {
                                if (o.OperadorId == r.Operador.OperadorId)
                                {
                                    respuestaCounter = 1;

                                    break;
                                }
                            }

                            if (respuestaCounter == 0)
                            {
                                if (!string.IsNullOrWhiteSpace(s.FechaRespuestaSolicitadas))
                                {
                                    to = new LinkedList<string>();

                                    to.AddLast(o.Email); 

                                    //DateTime fechaRespuestaSolicitadasCinco = Convert.ToDateTime(s.FechaRespuestaSolicitadas).AddDays(-5),
                                    //         fechaRespuestaSolicitadasSiete = Convert.ToDateTime(s.FechaRespuestaSolicitadas).AddDays(-7);

                                    //var daysPast = DateTime.Now.Date - DateTime.Now.Date;

                                    DateTime fechaAResponder5 = ValidarFecha(5, Convert.ToDateTime(s.FechaRespuestaSolicitadas)).Date, //Se usa para comparacion de fecha con la del aviso aprobado. 
                                        fechaAResponder7 = ValidarFecha(7, Convert.ToDateTime(s.FechaRespuestaSolicitadas)).Date;

                                    if (DateTime.Now.Date.Equals(fechaAResponder5))
                                    {
                                        //to = new LinkedList<string>();

                                        //SendEmail(to, "", "", "");

                                        //SendEmail(to, "*****@*****.**", "Aviso", "Pasaron 5 dias desde que se envio aviso, Sr. operador"); //only foor test

                                        try
                                        {
                                            if (CheckForInternetConnection())
                                                SendEmail(to, "*****@*****.**",
                            mails.ElementAt((int)Mail.Notifications.OperadorSinRespuesta5).Subject.Replace("@Pueblo", municipio),
                            mails.ElementAt((int)Mail.Notifications.OperadorSinRespuesta5).Body.Replace(
                            "@NumControl", s.NumeroControl.NumControlText).Replace("@NombreEmpresa", s.NombreEmpresa).Replace(
                            "@Link", "cced.dtop.gov.pr/exc/Logic/RespuestasAvisos.aspx?RespuestaNumControl=" + s.NumeroControl.NumControlText));
                                        }

                                        catch (Exception ex)
                                        {
                                            if (ex.Message == "")
                                            {
                                                
                                            }
                                        }// only test

                                        //operadoresSinResponderCincoDiasCounter++;

                                        //mesInicial.OperadoresSinResponder5 = operadoresSinResponderCincoDiasCounter;

                                        //Don't duplicate same value on txtbx
                                        if (!numControlRangoCincoNRespuestasTxtBx.Text.Contains(s.NumeroControl.NumControlText))
                                        {
                                            numControlRangoCincoNRespuestasTxtBx.Text += string.Format("{0} ", s.NumeroControl.NumControlText);

                                            mesInicial.NumerosControlSolicitudesOperadoresSinResponder5 = string.Format("{0},", s.NumeroControl.NumControlText);
                                        }
                                    }

                                    else if (DateTime.Now.Date.Equals(fechaAResponder7))
                                    {
                                        //to = new LinkedList<string>();

                                        //SendEmail(to, "", "", "");

                                        //SendEmail(to, "*****@*****.**", "Aviso", "Pasaron 7 dias desde que se envio aviso, Sr. operador"); //only foor test

                                        try
                                        {
                                            if (CheckForInternetConnection())
                                                SendEmail(to, "*****@*****.**",
                            mails.ElementAt((int)Mail.Notifications.OperadorSinRespuesta48).Subject.Replace("@Pueblo", municipio),
                            mails.ElementAt((int)Mail.Notifications.OperadorSinRespuesta48).Body.Replace(
                            "@NumControl", s.NumeroControl.NumControlText).Replace("@NombreEmpresa", s.NombreEmpresa).Replace(
                            "@Link", "cced.dtop.gov.pr/exc/Logic/RespuestasAvisos.aspx?RespuestaNumControl=" + s.NumeroControl.NumControlText)); // only test
                                        }

                                        catch (Exception ex)
                                        { }
                                        //operadoresSinResponderSieteDiasCounter++;

                                        //mesInicial.OperadoresSinResponder7 = operadoresSinResponderSieteDiasCounter;

                                        //Don't duplicate same value on txtbx
                                        if (!numControlRangoSieteNRespuestasTxtBx.Text.Contains(s.NumeroControl.NumControlText))
                                        {
                                            numControlRangoSieteNRespuestasTxtBx.Text += string.Format("{0} ", s.NumeroControl.NumControlText);

                                            mesInicial.NumerosControlSolicitudesOperadoresSinResponder7 += string.Format("{0},", s.NumeroControl.NumControlText);
                                        }
                                    }
                                }

                                else
                                {

                                }
                            }
                        }

                        #endregion
                    }

                    denegadasTxtBx.Text = denegadasCounter.ToString();

                    enRangoExpiracionTxtBx.Text = solicitudesAExpirarCounter.ToString();

                    recienExpiradasTxtBx.Text = solicitudesRecienExpiradasCounter.ToString();

                    //enRangocincoNoRespuestasTxtBx.Text = operadoresSinResponderCincoDiasCounter.ToString();

                    //enRangoSieteNoRespuestasTxtBx.Text = operadoresSinResponderSieteDiasCounter.ToString();

                    mesInicial.FechaEjecucion = DateTime.Now.Date;

                    mesInicial.ExtensionID = (int)SolicitudAviso.TiposExtensiones.Inicial;

                    try
                    {
                        new MensajeroServicio().TryCreate(mesInicial);
                    }

                    catch (Exception ex)
                    {
                    }

                    #endregion

                    #region Ext1

                    Messenger mesExt1 = new Messenger();

                    foreach (var ex in ext1)
                    {
                        to = new LinkedList<string>();

                        ex.EstatusId = ex.EstatusId.Replace(ex.LetraStatus, string.Empty);

                        to.AddLast(ex.Usuario.Email);

                        //LinkedList<string> to = new LinkedList<string>();

                        //User currentUser = new SolicitudesInicialesServicio().GetUser(ex.Usuario.Id);

                        User currentUser = new SolicitudesInicialesServicio().GetUser(ex.Usuario.Email);

                        #region Docs still incompletos after 48hrs

                        DateTime fechaDocsIncompletos = ex.FechaDocsIncompletos;
                        //fechaDenegarDocsIncompletos = fechaDocsIncompletos.AddHours(48);

                        if (ex.FechaDocsIncompletos.Date >= (DateTime.Now.Date.AddHours(48))
                                && ex.EstatusId.Equals(((int)SolicitudAviso.Estatus.PendienteDocumentosIncompletos).ToString()))
                        {
                            ex.EstatusId = ex.LetraStatus + ((int)SolicitudAviso.Estatus.Denegada).ToString();

                            new SolicitudesInicialesServicio().TryUpdate(ex);

                            denegadasExt1Counter++;

                            mesExt1.SolicitudesDenegadas = denegadasExt1Counter;

                            //to.AddLast(currentUser.Email);

                            numControlDenegadasExt1TxtBx.Text += string.Format("{0} ", ex.NumeroControl.NumControlText);

                            mesExt1.NumerosControlSolicitudesDenegadas += string.Format("{0},", ex.NumeroControl.NumControlText);

                            //to = new LinkedList<string>();

                            //SendEmail(to, "", "", "");

                            //SendEmail(to, "*****@*****.**", "Aviso", "Aviso fue denegado, pasaron 48 dias"); //only foor test

                            try
                            {
                                if (CheckForInternetConnection())
                                    SendEmail(to, "*****@*****.**",
                            mails.ElementAt((int)Mail.Notifications.ExtensionDenegada).Subject,
                            mails.ElementAt((int)Mail.Notifications.ExtensionDenegada).Body.Replace(
                            "@NumControl", ex.NumeroControl.NumControlText).Replace("@NombreEmpresa", ex.NombreEmpresa)); // only test
                            }

                            catch (Exception exc)
                            { }

                        }

                        #endregion

                        SolicitudAviso segundaExtExistente = new SegundasExtensionesServicio().GetSegundaExtension(ex.NumeroControl);

                        #region Verifica solicitudes apuntos de expirar sin extensiones
                        //var fechaExpiracion = s.FechaExpiracion.AddDays(-4);

                        if (ex.FechaExpiracion.Date.Equals(DateTime.Now.Date.AddDays(-5)))
                        {
                            if (string.IsNullOrEmpty(segundaExtExistente.NumeroControl.NumControlText))
                            {
                                //to = new LinkedList<string>();

                                //SendEmail(to, "", "", "");

                                //SendEmail(to, "*****@*****.**", "Aviso", "Aviso apunto de expirar sin extension"); //only foor test

                                try
                                {
                                    if (CheckForInternetConnection())
                                        SendEmail(to, "*****@*****.**",
                            mails.ElementAt((int)Mail.Notifications.ExtensionExpira5).Subject,
                            mails.ElementAt((int)Mail.Notifications.ExtensionExpira5).Body.Replace(
                            "@NumControl", ex.NumeroControl.NumControlText).Replace("@NombreEmpresa", ex.NombreEmpresa)); // only test
                                }

                                catch (Exception exc)
                                { }

                                numControlAExpirarExt1TxtBx.Text += string.Format("{0} ", ex.NumeroControl.NumControlText);

                                mesExt1.NumerosControlSolicitudesAExpirar += string.Format("{0}, ", ex.NumeroControl.NumControlText);

                                mesExt1.SolicitudesAExpirar = ext1AExpirarCounter;

                                ext1AExpirarCounter++;


                            }
                        }
                        #endregion

                        #region Verifica solicitudes recien expiradas
                        if (ex.FechaExpiracion.Date == (DateTime.Now.Date)
                            && (!ex.EstatusId.Equals(((int)SolicitudAviso.Estatus.Inactiva).ToString())
                            && !ex.EstatusId.Equals(((int)SolicitudAviso.Estatus.InspeccionCompletada).ToString())))
                        {
                            ex.EstatusId = ex.LetraStatus + ((int)SolicitudAviso.Estatus.Inactiva).ToString();

                            new SolicitudesInicialesServicio().TryUpdate(ex);

                            numControlRecienExpiradasExt1TxtBx.Text += string.Format("{0} ", ex.NumeroControl.NumControlText);

                            ext1RecienExpiradasCounter++;

                            mesExt1.SolicitudesExpiradas = ext1RecienExpiradasCounter;

                            mesExt1.NumerosControlSolicitudesAExpirar += string.Format("{0}, ", ex.NumeroControl.NumControlText);

                        }
                        #endregion
                    }

                    denegadasExt1TxtBx.Text = denegadasExt1Counter.ToString();

                    aExpirarExt1TxtBx.Text = ext1AExpirarCounter.ToString();

                    recienExpiradasExt1TxtBx.Text = ext1RecienExpiradasCounter.ToString();

                    mesExt1.FechaEjecucion = DateTime.Now.Date;

                    mesExt1.ExtensionID = (int)SolicitudAviso.TiposExtensiones.Primera;

                    try
                    {
                        new MensajeroServicio().TryCreate(mesExt1);
                    }

                    catch (Exception exc)
                    {
                    }

                    #endregion

                    #region Ext2

                    Messenger mesExt2 = new Messenger();

                    foreach (var ex in ext2)
                    {
                        to = new LinkedList<string>();

                        ex.EstatusId = ex.EstatusId.Replace(ex.LetraStatus, string.Empty);

                        to.AddLast(ex.Usuario.Email);

                        //LinkedList<string> to = new LinkedList<string>();

                        //User currentUser = new SolicitudesInicialesServicio().GetUser(ex.Usuario.Id);

                        User currentUser = new SolicitudesInicialesServicio().GetUser(ex.Usuario.Email);

                        #region Docs still incompletos after 48hrs

                        DateTime fechaDocsIncompletos = ex.FechaDocsIncompletos;
                        //fechaDenegarDocsIncompletos = fechaDocsIncompletos.AddHours(48);

                        if (ex.FechaDocsIncompletos.Date >= (DateTime.Now.Date.AddHours(48))
                                && ex.EstatusId.Equals(((int)SolicitudAviso.Estatus.PendienteDocumentosIncompletos).ToString()))
                        {
                            ex.EstatusId = ex.LetraStatus + ((int)SolicitudAviso.Estatus.Denegada).ToString();

                            new SolicitudesInicialesServicio().TryUpdate(ex);

                            denegadasExt2Counter++;

                            mesExt2.SolicitudesDenegadas = denegadasExt2Counter;

                            //to.AddLast(currentUser.Email);

                            numControlDenegadasExt2TxtBx.Text += string.Format("{0} ", ex.NumeroControl.NumControlText);

                            mesExt2.NumerosControlSolicitudesDenegadas = string.Format("{0} ", ex.NumeroControl.NumControlText);

                            //to = new LinkedList<string>();

                            //SendEmail(to, "", "", "");

                            //SendEmail(to, "*****@*****.**", "Aviso", "Aviso fue denegado, pasaron 48 dias"); //only foor test

                            try
                            {
                                if (CheckForInternetConnection())
                                    SendEmail(to, "*****@*****.**",
                            mails.ElementAt((int)Mail.Notifications.ExtensionDenegada).Subject,
                            mails.ElementAt((int)Mail.Notifications.ExtensionDenegada).Body.Replace(
                            "@NumControl", ex.NumeroControl.NumControlText).Replace("@NombreEmpresa", ex.NombreEmpresa)); // only test
                            }

                            catch (Exception exc)
                            { }
                        }

                        #endregion

                        #region Verifica solicitudes apuntos de expirar
                        //var fechaExpiracion = s.FechaExpiracion.AddDays(-4);

                        if (ex.FechaExpiracion.Date.Equals(DateTime.Now.Date.AddDays(-5)))
                        {
                            //to = new LinkedList<string>();

                            //SendEmail(to, "", "", "");

                            //SendEmail(to, "*****@*****.**", "Aviso", "Aviso apunto de expirar sin extension"); //only foor test

                            try
                            {
                                if (CheckForInternetConnection())
                                    SendEmail(to, "*****@*****.**",
                            mails.ElementAt((int)Mail.Notifications.ExtensionExpira5).Subject,
                            mails.ElementAt((int)Mail.Notifications.ExtensionExpira5).Body.Replace(
                            "@NumControl", ex.NumeroControl.NumControlText).Replace("@NombreEmpresa", ex.NombreEmpresa)); // only test
                            }

                            catch (Exception exc)
                            { }

                            numControlAExpirarExt2TxtBx.Text += string.Format("{0} ", ex.NumeroControl.NumControlText);

                            mesExt2.NumerosControlSolicitudesAExpirar = string.Format("{0}, ", ex.NumeroControl.NumControlText);

                            ext2AExpirarCounter++;

                        }
                        #endregion

                        #region Verifica solicitudes recien expiradas
                        if (ex.FechaExpiracion.Date == (DateTime.Now.Date)
                            && (!ex.EstatusId.Equals(((int)SolicitudAviso.Estatus.Inactiva).ToString())
                            && !ex.EstatusId.Equals(((int)SolicitudAviso.Estatus.InspeccionCompletada).ToString())))
                        {
                            ex.EstatusId = ex.LetraStatus + ((int)SolicitudAviso.Estatus.Inactiva).ToString();

                            new SolicitudesInicialesServicio().TryUpdate(ex);

                            numControlRecienExpiradasExt2TxtBx.Text += string.Format("{0} ", ex.NumeroControl.NumControlText);

                            mesExt2.NumerosControlSolicitudesExpiradas += string.Format("{0}, ", ex.NumeroControl.NumControlText);

                            ext2RecienExpiradasCounter++;

                            mesExt2.SolicitudesExpiradas = ext2AExpirarCounter;
                        }
                        #endregion
                    }

                    denegadasExt2TxtBx.Text = denegadasExt2Counter.ToString();

                    aExpirarExt2TxtBx.Text = ext2AExpirarCounter.ToString();

                    recienExpiradasExt2TxtBx.Text = ext2RecienExpiradasCounter.ToString();

                    mesExt2.FechaEjecucion = DateTime.Now.Date;

                    mesExt2.ExtensionID = (int)SolicitudAviso.TiposExtensiones.Primera;

                    try
                    {
                        new MensajeroServicio().TryCreate(mesExt2);
                    }

                    catch (Exception exc)
                    {
                    }

                    #endregion

                    #endregion
                }
            }

            else
            {
                //DateTime fechaExe = Convert.ToDateTime(Request.QueryString["fechaExe"].Replace("%2f", "/"));

                //fechaEjecucionTxtBx.Text = fechaExe.ToShortDateString();

                //DateTime fecha = new DateTime(1900,1,1);

                if (!string.IsNullOrWhiteSpace(fechaEjecucionTxtBx.Text))
                {
                    //fecha = Convert.ToDateTime(fechaEjecucionTxtBx.Text);

                    LinkedList<Messenger> messengerExistente = new MensajeroServicio().GetMessengerData(Convert.ToDateTime(fechaEjecucionTxtBx.Text));

                    if (messengerExistente.Count > 0)
                    {
                        #region Get data and fill
                        foreach (var m in messengerExistente)
                        {
                            switch (m.ExtensionID)
                            {
                                case (int)SolicitudAviso.TiposExtensiones.Segunda:

                                    aExpirarExt2TxtBx.Text = m.SolicitudesAExpirar.ToString();

                                    denegadasExt2TxtBx.Text = m.SolicitudesDenegadas.ToString();

                                    numControlAExpirarExt2TxtBx.Text = m.NumerosControlSolicitudesAExpirar;

                                    numControlDenegadasExt2TxtBx.Text = m.NumerosControlSolicitudesDenegadas;

                                    numControlRecienExpiradasExt2TxtBx.Text = m.NumerosControlSolicitudesExpiradas;

                                    recienExpiradasExt2TxtBx.Text = m.SolicitudesExpiradas.ToString();

                                    break;

                                case (int)SolicitudAviso.TiposExtensiones.Primera:

                                    aExpirarExt1TxtBx.Text = m.SolicitudesAExpirar.ToString();

                                    denegadasExt1TxtBx.Text = m.SolicitudesDenegadas.ToString();

                                    numControlAExpirarExt1TxtBx.Text = m.NumerosControlSolicitudesAExpirar;

                                    numControlDenegadasExt1TxtBx.Text = m.NumerosControlSolicitudesDenegadas;

                                    numControlRecienExpiradasExt1TxtBx.Text = m.NumerosControlSolicitudesExpiradas;

                                    recienExpiradasExt1TxtBx.Text = m.SolicitudesExpiradas.ToString();

                                    break;

                                default:

                                    recienExpiradasTxtBx.Text = m.SolicitudesExpiradas.ToString();

                                    numControlRecienExpTxtBx.Text = m.NumerosControlSolicitudesExpiradas;

                                    denegadasTxtBx.Text = m.SolicitudesDenegadas.ToString();

                                    numControlDenegadasTxtBx.Text = m.NumerosControlSolicitudesDenegadas;

                                    enRangoExpiracionTxtBx.Text = m.SolicitudesAExpirar.ToString();

                                    numControlEnRangoExpTxtBx.Text = m.NumerosControlSolicitudesAExpirar;

                                    //enRangocincoNoRespuestasTxtBx.Text = m.OperadoresSinResponder5.ToString();

                                    numControlRangoCincoNRespuestasTxtBx.Text = m.NumerosControlSolicitudesOperadoresSinResponder5;

                                    numControlRangoSieteNRespuestasTxtBx.Text = m.NumerosControlSolicitudesOperadoresSinResponder7;

                                    //enRangoSieteNoRespuestasTxtBx.Text = m.OperadoresSinResponder7.ToString();

                                    break;
                            }
                        }
                        #endregion
                    }

                    else
                    {
                        Response.Redirect("Mensajero.aspx?ShouldNotExecute=false");
                    }
                }
            }

        }