예제 #1
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
            }
        }
예제 #2
0
        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
            }
        }
예제 #3
0
        protected void numControlTxtBx_TextChanged(object sender, EventArgs e)
        {
            try
            {
                NumeroControl numeroControl = new NumeroControl()
                {
                    NumControlText = numControlTxtBx.Text
                }; 

                Respuesta respuesta = new Respuesta()
                        {
                            Operador = (Operador)ViewState["operador"]
                        },
                        respuestaExitente = new RespuestasServicio().GetRespuesta(respuesta.Operador.OperadorId, numeroControl);                          

                //Create
                if (respuestaExitente.Operador.OperadorId == 0)
                {
                    #region Poblar Respuesta campos con info de solicitud

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

                    operadorDDL.Items.Add(respuesta.Operador.Nombre);

                    companyDDL.Items.Add(solicitud.NombreEmpresa);

                    representanteTxtBx.Text = solicitud.RepresentanteAutorizado;

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

                    else
                    {
                        zonaRBtnLst.SelectedIndex = 0;
                    }

                    urbTxtBx.Text = solicitud.BoUrb;

                    calleTxtBx.Text = solicitud.SectorCalle;

                    carreteraTxtBx.Text = solicitud.Carretera;

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

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

                    municipioDDL.SelectedIndex = solicitud.MunicipioIdTrab;

                    codigoPostalTxtBx.Text = solicitud.CodigoPostal;

                    #endregion
                }

                //Edit
                else
                {
                    #region Poblar Respuesta campos

                    companyDDL.Items.Add(respuestaExitente.company.Nombre);

                    representanteTxtBx.Text = respuestaExitente.RepresentanteAutorizado;

                    operadorDDL.Items.Add(SolicitudesInicialesServicio.GetOperadorById(respuestaExitente.Operador.OperadorId).Nombre);

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

                    else
                    {
                        zonaRBtnLst.SelectedIndex = 0;
                    }

                    urbTxtBx.Text = respuestaExitente.Urb;

                    calleTxtBx.Text = respuestaExitente.Calle;

                    carreteraTxtBx.Text = respuestaExitente.Carretera;

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

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

                    municipioDDL.SelectedIndex = respuestaExitente.MunicipioId;

                    codigoPostalTxtBx.Text = respuestaExitente.CodigoPostal;

                    comentarioTxtBx.Text = respuestaExitente.Comentarios;

                    contactarTxtBx.Text = respuestaExitente.PersonaContactar;

                    accionesRBtnLst.SelectedIndex = respuestaExitente.Accion;

                    #region Set evidencia imgs

                    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(respuestaExitente.EvidenciaMarcadoPaths.ElementAt(0)))
                    {
                        evidenciaImgBtn.Visible = true;

                        evidenciaImgBtn.ImageUrl = respuestaExitente.EvidenciaMarcadoPaths.ElementAt(0);

                        evidenciaImgBtn.OnClientClick = "PrimeraImgClick();";

                        ClientScript.RegisterClientScriptBlock(GetType(), "Primera", script.Replace("@TITLE", evidenciaImgBtn.OnClientClick.Replace(
                            ";", string.Empty)).Replace("@CONTROLID", evidenciaImgBtn.ClientID));
                    } 

                    #endregion

                    #region Segunda

                    if (!string.IsNullOrEmpty(respuestaExitente.EvidenciaMarcadoPaths.ElementAt(1)))
                    {
                        evidencia2ImgBtn.Visible = true;

                        evidencia2ImgBtn.ImageUrl = respuestaExitente.EvidenciaMarcadoPaths.ElementAt(1);

                        evidencia2ImgBtn.OnClientClick = "SegundaImgClick();";

                        ClientScript.RegisterClientScriptBlock(GetType(), "Segunda", script.Replace("@TITLE", evidencia2ImgBtn.OnClientClick.Replace(
                            ";", string.Empty)).Replace("@CONTROLID", evidencia2ImgBtn.ClientID));
                    } 

                    #endregion

                    #endregion

                    #endregion
                }
            }

            catch (Exception ex)
            {
                var msg = ex.Message;
            }

            //Disable just in case search returns empty obj
            guardarBtn.Enabled = !string.IsNullOrEmpty(urbTxtBx.Text);
        }
예제 #4
0
        protected void guardarBtn_Click(object sender, EventArgs e)
        {
            NumeroControl numeroControl = new NumeroControl()
            {
                NumControlText = numControlTxtBx.Text
            };

            try
            {
                #region Poblar respuesta

                Operador operador = (Operador)ViewState["operador"];

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

                Respuesta respuesta = new Respuesta()
                {
                    Id = operadorDDL.SelectedIndex,

                    Accion = accionesRBtnLst.SelectedIndex,

                    Calle = calleTxtBx.Text,

                    Carretera = carreteraTxtBx.Text,

                    CodigoPostal = codigoPostalTxtBx.Text,

                    Comentarios = comentarioTxtBx.Text,

                    company = new Company()
                    {
                       Nombre = companyDDL.SelectedValue
                    },

                    HM = Convert.ToInt32(hmTxtBx.Text),

                    KM = Convert.ToInt32(kmTxtBx.Text),

                    MunicipioId = municipioDDL.SelectedIndex,

                    NumeroControl = numeroControl,

                    Operador = new Operador()
                    {
                        OperadorId = operador.OperadorId
                    },

                    PersonaContactar = contactarTxtBx.Text,

                    RepresentanteAutorizado = representanteTxtBx.Text,

                    Urb = urbTxtBx.Text,

                    Zona = zonaRBtnLst.SelectedIndex == 1,

                    AccionText = accionesRBtnLst.SelectedItem.Value

                };
                #region Evidencia stuff

                string evidenciaFullDirPath = string.Format(@"{0}/{1}", Respuesta.EvidenciaInitPath, numControlTxtBx.Text);

                #region Evidencia 1

                //Save file to phys dir
                if (evidenciaFileUp.HasFile)
                    evidenciaFileUp.SaveAs(Server.MapPath(string.Format("{0}/{1}_{2}", evidenciaFullDirPath, operador.Nombre, evidenciaFileUp.PostedFile.FileName)));

                evidenciaPaths.AddLast(evidenciaFileUp.HasFile ? string.Format("{0}/{1}_{2}", evidenciaFullDirPath, operador.Nombre, evidenciaFileUp.PostedFile.FileName)
                    : string.Empty);

                #endregion

                #region Evidencia 2

                if (evidencia2FileUp.HasFile)
                    evidencia2FileUp.SaveAs(Server.MapPath(string.Format("{0}/{1}_{2}", evidenciaFullDirPath, operador.Nombre, evidencia2FileUp.PostedFile.FileName)));

                evidenciaPaths.AddLast(evidencia2FileUp.HasFile ? string.Format("{0}/{1}_{2}", evidenciaFullDirPath, operador.Nombre, evidencia2FileUp.PostedFile.FileName)
                    : string.Empty);

                #endregion

                respuesta.EvidenciaMarcadoPaths = evidenciaPaths;

                #endregion
                
                #endregion

                Respuesta respuestaExitente = new RespuestasServicio().GetRespuesta(respuesta.Operador.OperadorId, numeroControl);

                //Create
                if (respuestaExitente.Operador.OperadorId == 0)
                {      
                    //Create dir if exist
                    if (!Directory.Exists(Server.MapPath(evidenciaFullDirPath)))
                        Directory.CreateDirectory(Server.MapPath(evidenciaFullDirPath));

                    new RespuestasServicio().TryCreate(respuesta);
                }

                //Edit
                else
                {
                    #region Set up evidencias

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

                    newEvidencias.AddLast(!evidenciaFileUp.HasFile ? respuestaExitente.EvidenciaMarcadoPaths.ElementAt(0) : respuesta.EvidenciaMarcadoPaths.ElementAt(0));

                    newEvidencias.AddLast(!evidencia2FileUp.HasFile ? respuestaExitente.EvidenciaMarcadoPaths.ElementAt(1) : respuesta.EvidenciaMarcadoPaths.ElementAt(1));

                    respuesta.EvidenciaMarcadoPaths = newEvidencias; 

                    #endregion

                    new RespuestasServicio().TryUpdate(respuesta);
                }

                Response.Redirect("~/Logic/RespuestasAvisos.aspx", true);
            }

            catch (Exception ex)
            {
                var msg = ex.Message;
            }
        }
예제 #5
0
        protected void guardarBtn_Click(object sender, EventArgs e)
        {
            NumeroControl numeroControl = new NumeroControl()
            {
                NumControlText = Request.QueryString["RespuestaNumControl"]
                //NumControlText = "2015-0002" //Only for testing
            };

            try
            {
                #region Poblar respuesta

                Operador operador = (Operador)Session["operador"];

                Respuesta respuesta = new Respuesta()
                {
                    Id = operadorDDL.SelectedIndex,

                    Accion = accionesRBtnLst.SelectedIndex,

                    Calle = calleTxtBx.Text,

                    Carretera = carreteraTxtBx.Text,

                    CodigoPostal = codigoPostalTxtBx.Text,

                    Comentarios = comentarioTxtBx.Text,

                    company = new Company()
                    {
                       NombreEmpresa = companyDDL.SelectedValue
                    },

                    HM = Convert.ToInt32(hmTxtBx.Text),

                    KM = Convert.ToInt32(kmTxtBx.Text),

                    MunicipioId = municipioDDL.SelectedIndex,

                    NumeroControl = numeroControl,

                    Operador = new Operador()
                    {
                        OperadorId = operador.OperadorId
                    },

                    PersonaContactar = contactarTxtBx.Text,

                    RepresentanteAutorizado = representanteTxtBx.Text,

                    Urb = urbTxtBx.Text,

                    Zona = zonaRBtnLst.SelectedIndex == 1,

                    AccionText = accionesRBtnLst.SelectedItem.Value

                };
                #endregion

                //Respuesta respuestaExitente = new RespuestasServicio().GetRespuesta(respuesta.Id, numeroControl);

                Respuesta respuestaExitente = new RespuestasServicio().GetRespuesta(respuesta.Operador.OperadorId, numeroControl);

                //Create
                if (respuestaExitente.Operador.OperadorId == 0)
                {
                    new RespuestasServicio().TryCreate(respuesta);
                }

                //Edit
                else
                {
                    new RespuestasServicio().TryUpdate(respuesta);
                }

                Session.Remove("RespuestaNumControl");

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

            catch (Exception ex)
            {
                var msg = ex.Message;
            }
        }
예제 #6
0
        //private static Operador operador = new Operador();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["RespuestaNumControl"] != null && !IsPostBack)
            {
               Session["RespuestaNumControl"] = Request.QueryString["RespuestaNumControl"]; 
            }

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

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

            if (string.IsNullOrWhiteSpace(user.Email))
            {
                //Session["RespuestaNumControl"] = Request.QueryString["RespuestaNumControl"];

                Response.Redirect("~/Account/Ingresar.aspx");
            }

            //title.Text = "hi";

            title.InnerText = Title;

            //operadorDDL.Visible = false;

            //operadorLbl.Visible = false;

            codigoPostalTxtBx.Visible = false;

            codigoPostalLbl.Visible = false;

            if (!IsPostBack)
            {
                #region Municipios

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

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

                #endregion

                //#region Operadores

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

                //foreach (var o in operadores)
                //{
                //    operadorDDL.Items.Add(o.Nombre);
                //}

                //operadorDDL.SelectedIndex = 0;

                //#endregion

                //#region Companies

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

                //foreach (var c in companies)
                //{
                //    companyDDL.Items.Add(c.NombreEmpresa);
                //}

                //#endregion

                NumeroControl numeroControl = new NumeroControl()
                {
                    NumControlText = Request.QueryString["RespuestaNumControl"]
                    //NumControlText = "2015-0002" //only for testing
                };                

                Respuesta respuesta = new Respuesta();

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

                Operador operador = new SolicitudesInicialesServicio().GetOperador(company.NombreEmpresa);

                Session["operador"] = operador;

                //if (string.IsNullOrWhiteSpace(operador.Email))
                //{
                //    Response.Redirect("Default.aspx");
                //}

                //else
                //{

                    respuesta = new Respuesta()
                    {
                        //Id = Convert.ToInt32(Request.QueryString["OperadorID"])

                        //Id = 1 // only for testing                    

                        Operador = operador
                    };

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

                try
                {
                    // - 1 por que cuando se guarda sale de un ddl y empieza en 0. Si quiero cojer el segundo del db tiene que ser id - 1 para que sea 1
                    //Respuesta respuestaExitente = new RespuestasServicio().GetRespuesta(respuesta.Id - 1, numeroControl);

                    Respuesta respuestaExitente = new RespuestasServicio().GetRespuesta(respuesta.Operador.OperadorId, numeroControl);

                    //Create
                    if (respuestaExitente.Operador.OperadorId == 0)
                    {
                        #region Poblar Respuesta campos con info de solicitud
                        SolicitudAviso solicitud = new SolicitudesInicialesServicio().GetSolicitud(numeroControl);

                        //Operador operador = new SolicitudesInicialesServicio().GetOperador(respuesta.Id); //new SolicitudesInicialesServicio().GetOperador(respuesta.OperadorId);

                        operadorDDL.Items.Add(respuesta.Operador.Nombre);

                        numControlTxtBx.Text = solicitud.NumeroControl.NumControlText;

                        companyDDL.Items.Add(solicitud.NombreEmpresa);

                        representanteTxtBx.Text = solicitud.RepresentanteAutorizado;

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

                        else
                        {
                            zonaRBtnLst.SelectedIndex = 0;
                        }

                        urbTxtBx.Text = solicitud.BoUrb;

                        calleTxtBx.Text = solicitud.SectorCalle;

                        carreteraTxtBx.Text = solicitud.Carretera;

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

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

                        municipioDDL.SelectedIndex = solicitud.MunicipioIdTrab;

                        codigoPostalTxtBx.Text = solicitud.CodigoPostal;

                        #endregion
                    }

                    //Edit
                    else
                    {
                        #region Poblar Respuesta campos

                        numControlTxtBx.Text = respuestaExitente.NumeroControl.NumControlText;

                        companyDDL.Items.Add(respuestaExitente.company.NombreEmpresa);

                        representanteTxtBx.Text = respuestaExitente.RepresentanteAutorizado;

                        operadorDDL.Items.Add(operador.Nombre);

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

                        else
                        {
                            zonaRBtnLst.SelectedIndex = 0;
                        }

                        urbTxtBx.Text = respuestaExitente.Urb;

                        calleTxtBx.Text = respuestaExitente.Calle;

                        carreteraTxtBx.Text = respuestaExitente.Carretera;

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

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

                        municipioDDL.SelectedIndex = respuestaExitente.MunicipioId;

                        codigoPostalTxtBx.Text = respuestaExitente.CodigoPostal;

                        comentarioTxtBx.Text = respuestaExitente.Comentarios;

                        contactarTxtBx.Text = respuestaExitente.PersonaContactar;

                        accionesRBtnLst.SelectedIndex = respuestaExitente.Accion;
                        #endregion
                    }
                }

                catch (Exception ex)
                {
                    var msg = ex.Message;
                }
            }
        }
예제 #7
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");
                    }
                }
            }

        }