public void TryCreate(SolicitudAviso solicitud)
        {
            Exception ex = repository.Create(solicitud);

            if (ex != null)
            {
                throw new Exception(ex.Message);
            }
        }
        public void TryUpdate(SolicitudAviso solicitud)
        {
            var ex = repository.Update(solicitud);

            if (ex != null)
            {
                throw new Exception(ex.Message);
            }
        }
        public SolicitudAviso BuildSolicitud(SqlCommand command)
        {
            SolicitudAviso solicitud = new SolicitudAviso();

            SqlDataReader reader = command.ExecuteReader();

            #region Read query

            while (reader.Read())
            {
                int col = 0;

                solicitud = new SolicitudAviso()
                {
                    NumeroControl = new NumeroControl
                    {
                        NumControl = 0,

                        Year = DateTime.MinValue.Year,

                        NumControlText = reader[col++].ToString()
                    },

                    TipoAviso = reader[col++].ToString(),

                    EstatusId = reader[col++].ToString(),

                    Emergencia = reader.GetBoolean(col++),

                    NombreContacto = reader[col++].ToString(),

                    CelularContacto = reader[col++].ToString(),

                    DireccionPostalContacto = reader[col++].ToString(),

                    NombreEmpresa = reader[col++].ToString(),

                    AreaDept = reader[col++].ToString(),

                    RepresentanteAutorizado = reader[col++].ToString(),

                    TelOficina = reader[col++].ToString(),

                    TelCampoTrabajo = reader[col++].ToString(),

                    TelCelular = reader[col++].ToString(),

                    CorreoElectronico = reader[col++].ToString(),

                    DireccionPostal = reader[col++].ToString(),

                    MunicipioId = reader.GetInt32(col++),

                    CodigoPostal = reader[col++].ToString(),

                    Subcontratista = reader[col++].ToString(),

                    AreaDeptSub = reader[col++].ToString(),

                    RepresentanteAutorizadoSub = reader[col++].ToString(),

                    DireccionPostalSub = reader[col++].ToString(),

                    MunicipioIdSub = reader.GetInt32(col++),

                    CodigoPostalSub = reader[col++].ToString(),

                    TelOficinaSub = reader[col++].ToString(),

                    TelCampoTrabajoSub = reader[col++].ToString(),

                    TelCelularSub = reader[col++].ToString(),

                    CorreoElectronicoSub = reader[col++].ToString(),

                    Zona = reader.GetBoolean(col++),

                    BoUrb = reader[col++].ToString(),

                    SectorCalle = reader[col++].ToString(),

                    Carretera = reader[col++].ToString(),

                    KM = reader.GetInt32(col++),

                    HM = reader.GetInt32(col++),

                    MunicipioIdTrab = reader.GetInt32(col++),

                    Referencias = reader[col++].ToString(),

                    FechaPropuesta = reader.GetDateTime(col++),

                    FechaComienzo = reader.GetDateTime(col++),

                    FechaExpiracion = reader.GetDateTime(col++),

                    TiempoDuracion = reader[col++].ToString(),

                    Horario = reader[col++].ToString(),

                    Maquinaria = reader.GetBoolean(col++),

                    TipoMaquinaria = reader[col++].ToString(),

                    Explosivos = reader.GetBoolean(col++),

                    LicenciaExplosivo = reader[col++].ToString(),

                    FechaExpiracionExplosivo = reader.GetDateTime(col++),

                    AreaMarcada = reader.GetBoolean(col++),

                    TipoExcavacion = reader.GetBoolean(col++),

                    RazonTrabajos = reader[col++].ToString(),

                    ProfundidadPies = reader.GetInt32(col++),

                    ProfundidadPulgadas = reader.GetInt32(col++),

                    LongitudPies = reader.GetInt32(col++),

                    LongitudPulgadas = Convert.ToInt32(reader[col++]),

                    CoordenadaX = decimal.Parse(reader[col++].ToString()),

                    CoordenadaY = decimal.Parse(reader[col++].ToString()),

                    EnCasoEmergencia = reader[col++].ToString(),

                    TramitadoPor = reader[col++].ToString(),

                    FechaTramite = reader.GetDateTime(col++),

                    FechaDocsIncompletos = reader.GetDateTime(col++),

                    Coordinador = new Coordinador()
                    {
                        Nombre = reader[col++].ToString()
                    },

                    Inspector = new Inspector()
                    {
                        Nombre = reader[col++].ToString()
                    },

                    Usuario = new User()
                    {
                        Email = reader.GetString(col++)
                    },

                    ExtensionID = reader.GetInt32(col++),

                    SolicitudStatusID = reader.GetInt32(col++),

                    Observaciones = reader.GetString(col++)
                };
            }
            #endregion

            return solicitud;
        }
        public SolicitudAviso GetSegundaExtension(NumeroControl numeroControl)
        {
            SolicitudAviso solicitud = new SolicitudAviso();

            //using (SqlConnection conn = sql.GetConnection())
            using (SqlConnection conn = new SQL().GetLocalConnection())
            {
                SqlCommand cmd = new SqlCommand(@"SELECT * FROM Extension2 WHERE NumeroControl = @NumeroControl", conn);

                cmd.Parameters.AddWithValue("NumeroControl", numeroControl.NumControlText);

                conn.Open();

                cmd.ExecuteNonQuery();

                solicitud = BuildSolicitud(cmd);
            }

            return solicitud;

            //return new SolicitudAvisoExcavacionDemolicion();
        }
        public Exception Update(SolicitudAviso solicitud)
        {
            //using (SqlConnection conn = sql.GetConnection())
            using (SqlConnection conn = new SQL().GetLocalConnection())
            {
                #region Sql command

                SqlCommand cmd = new SqlCommand(@"UPDATE Extension2 SET TipoAviso = @TipoAviso,
                                                                    EstatusID = @EstatusID,
                                                                    NombreContacto = @NombreContacto,
                                                                    CelularContacto = @CelularContacto,
                                                                    DireccionPostalContacto = @DireccionPostalContacto,
                                                                    NombreEmpresa = @NombreEmpresa,
                                                                    AreaDepartamento = @AreaDepartamento,
                                                                    RepresentanteAutorizado = @RepresentanteAutorizado,
                                                                    TelOficina = @TelOficina,
                                                                    TelCampoTrabajo = @TelCampoTrabajo,
                                                                    TelCelular = @TelCelular,
                                                                    CorreoElectronico = @CorreoElectronico,
                                                                    DireccionPostal = @DireccionPostal,
                                                                    MunicipioIDPostal = @MunicipioIDPostal,
                                                                    CodigoPostal = @CodigoPostal,
                                                                    Subcontratista = @Subcontratista,
                                                                    AreaDepartamentoSub = @AreaDepartamentoSub,
                                                                    RepresentanteAutorizadoSub = @RepresentanteAutorizadoSub,
                                                                    DireccionPostalSub = @DireccionPostalSub,
                                                                    MunicipioIDPostalSub = @MunicipioIDPostalSub,
                                                                    CodigoPostalSub = @CodigoPostalSub,
                                                                    TelOficinaSub = @TelOficinaSub,
                                                                    TelCampoTrabajoSub = @TelCampoTrabajoSub,
                                                                    TelCelularSub = @TelCelularSub,
                                                                    CorreoElectronicoSub = @CorreoElectronicoSub,
                                                                    Zona = @Zona,
                                                                    BoUrb = @BoUrb,
                                                                    SectorCalle = @SectorCalle,
                                                                    Carretera = @Carretera,
                                                                    KM = @KM,
                                                                    HM = @HM,
                                                                    MunicipioIDTrab = @MunicipioIDTrab,
                                                                    Referencias = @Referencias,
                                                                    FechaComienzo = @FechaComienzo,
                                                                    FechaExpiracion = @FechaExpiracion,
                                                                    Duracion = @Duracion,
                                                                    Horario = @Horario,
                                                                    Maquinaria = @Maquinaria,
                                                                    TipoMaquinaria = @TipoMaquinaria,
                                                                    Explosivos = @Explosivos,
                                                                    LicenciaExplosivos = @LicenciaExplosivos,
                                                                    FechaExpiracionLicExp = @FechaExpiracionLicExp,
                                                                    AreaMarcada = @AreaMarcada,
                                                                    TipoExcavacion = @TipoExcavacion,
                                                                    RazonTrabajos = @RazonTrabajos,
                                                                    ProfundidadPies = @ProfundidadPies,
                                                                    ProfundidadPulgadas = @ProfundidadPulgadas,
                                                                    LongitudPies = @LongitudPies,
                                                                    LongitudPulgadas = @LongitudPulgadas,
                                                                    CoordenadaX = @CoordenadaX,
                                                                    CoordenadaY = @CoordenadaY,
                                                                    EnCasoEmergencia = @EnCasoEmergencia,
                                                                    TramitadoPor = @TramitadoPor,
                                                                    FechaTramite = @FechaTramite,
                                                                    FechaDocsIncompletos = @FechaDocsIncompletos,
                                                                    UsuarioID = @UsuarioID,
                                                                    Emergencia = @Emergencia,
                                                                    PlacaInspector = @PlacaInspector,
                                                                    CoordinadorID = @CoordinadorID,
                                                                    ExtensionID = @ExtensionID,
                                                                    SolicitudStatusID = @SolicitudStatusID,
                                                                    Observaciones = @Observaciones
                                                                    WHERE NumeroControl = @NumeroControl", conn);

                #endregion

                #region Command Parameteres

                cmd.Parameters.AddWithValue("Observaciones", solicitud.Observaciones);

                cmd.Parameters.AddWithValue("SolicitudStatusID", solicitud.SolicitudStatusID);

                cmd.Parameters.AddWithValue("NumeroControl", solicitud.NumeroControl.NumControlText);

                cmd.Parameters.AddWithValue("ExtensionID", solicitud.ExtensionID);

                cmd.Parameters.AddWithValue("PlacaInspector", solicitud.Inspector.Nombre);

                cmd.Parameters.AddWithValue("CoordinadorID", solicitud.Coordinador.Nombre);

                cmd.Parameters.AddWithValue("Emergencia", solicitud.Emergencia);

                cmd.Parameters.AddWithValue("TipoAviso", solicitud.TipoAviso);

                cmd.Parameters.AddWithValue("EstatusID", solicitud.EstatusId);

                cmd.Parameters.AddWithValue("NombreContacto", solicitud.NombreContacto);

                cmd.Parameters.AddWithValue("CelularContacto", solicitud.CelularContacto);

                cmd.Parameters.AddWithValue("DireccionPostalContacto", solicitud.DireccionPostalContacto);

                cmd.Parameters.AddWithValue("NombreEmpresa", solicitud.NombreEmpresa);

                cmd.Parameters.AddWithValue("AreaDepartamento", solicitud.AreaDept);

                cmd.Parameters.AddWithValue("RepresentanteAutorizado", solicitud.RepresentanteAutorizado);

                cmd.Parameters.AddWithValue("TelOficina", solicitud.TelOficina);

                cmd.Parameters.AddWithValue("TelCampoTrabajo", solicitud.TelCampoTrabajo);

                cmd.Parameters.AddWithValue("TelCelular", solicitud.TelCelular);

                cmd.Parameters.AddWithValue("CorreoElectronico", solicitud.CorreoElectronico);

                cmd.Parameters.AddWithValue("DireccionPostal", solicitud.DireccionPostal);

                cmd.Parameters.AddWithValue("MunicipioIDPostal", solicitud.MunicipioId);

                cmd.Parameters.AddWithValue("CodigoPostal", solicitud.CodigoPostal);

                cmd.Parameters.AddWithValue("Subcontratista", solicitud.Subcontratista);

                cmd.Parameters.AddWithValue("AreaDepartamentoSub", solicitud.AreaDeptSub);

                cmd.Parameters.AddWithValue("RepresentanteAutorizadoSub", solicitud.RepresentanteAutorizadoSub);

                cmd.Parameters.AddWithValue("DireccionPostalSub", solicitud.DireccionPostalSub);

                cmd.Parameters.AddWithValue("MunicipioIDPostalSub", solicitud.MunicipioIdSub);

                cmd.Parameters.AddWithValue("CodigoPostalSub", solicitud.CodigoPostalSub);

                cmd.Parameters.AddWithValue("TelOficinaSub", solicitud.TelOficinaSub);

                cmd.Parameters.AddWithValue("TelCampoTrabajoSub", solicitud.TelCampoTrabajoSub);

                cmd.Parameters.AddWithValue("TelCelularSub", solicitud.TelCelularSub);

                cmd.Parameters.AddWithValue("CorreoElectronicoSub", solicitud.CorreoElectronicoSub);

                cmd.Parameters.AddWithValue("Zona", solicitud.Zona);

                cmd.Parameters.AddWithValue("BoUrb", solicitud.BoUrb);

                cmd.Parameters.AddWithValue("SectorCalle", solicitud.SectorCalle);

                cmd.Parameters.AddWithValue("Carretera", solicitud.SectorCalle);

                cmd.Parameters.AddWithValue("KM", solicitud.KM);

                cmd.Parameters.AddWithValue("HM", solicitud.HM);

                cmd.Parameters.AddWithValue("MunicipioIDTrab", solicitud.MunicipioIdTrab);

                cmd.Parameters.AddWithValue("Referencias", solicitud.Referencias);

                cmd.Parameters.AddWithValue("FechaComienzo", solicitud.FechaComienzo);

                cmd.Parameters.AddWithValue("FechaExpiracion", solicitud.FechaExpiracion);

                cmd.Parameters.AddWithValue("Duracion", solicitud.TiempoDuracion);

                cmd.Parameters.AddWithValue("Horario", solicitud.Horario);

                cmd.Parameters.AddWithValue("Maquinaria", solicitud.Maquinaria);

                cmd.Parameters.AddWithValue("TipoMaquinaria", solicitud.TipoMaquinaria);

                cmd.Parameters.AddWithValue("Explosivos", solicitud.Explosivos);

                cmd.Parameters.AddWithValue("LicenciaExplosivos", solicitud.LicenciaExplosivo);

                cmd.Parameters.AddWithValue("FechaExpiracionLicExp", solicitud.FechaExpiracionExplosivo);

                cmd.Parameters.AddWithValue("AreaMarcada", solicitud.AreaMarcada);

                cmd.Parameters.AddWithValue("TipoExcavacion", solicitud.TipoExcavacion);

                cmd.Parameters.AddWithValue("RazonTrabajos", solicitud.RazonTrabajos);

                cmd.Parameters.AddWithValue("ProfundidadPies", solicitud.ProfundidadPies);

                cmd.Parameters.AddWithValue("ProfundidadPulgadas", solicitud.ProfundidadPulgadas);

                cmd.Parameters.AddWithValue("LongitudPies", solicitud.LongitudPies);

                cmd.Parameters.AddWithValue("LongitudPulgadas", solicitud.LongitudPulgadas);

                cmd.Parameters.AddWithValue("CoordenadaX", float.Parse(solicitud.CoordenadaX.ToString()));

                cmd.Parameters.AddWithValue("CoordenadaY", float.Parse(solicitud.CoordenadaY.ToString()));

                cmd.Parameters.AddWithValue("EnCasoEmergencia", solicitud.EnCasoEmergencia);

                cmd.Parameters.AddWithValue("TramitadoPor", solicitud.TramitadoPor);

                cmd.Parameters.AddWithValue("FechaTramite", solicitud.FechaTramite);

                cmd.Parameters.AddWithValue("FechaDocsIncompletos", solicitud.FechaDocsIncompletos);

                cmd.Parameters.AddWithValue("UsuarioID", solicitud.Usuario.Email);

                #endregion

                conn.Open();

                using (SqlTransaction transaction = conn.BeginTransaction())
                {
                    cmd.Transaction = transaction;

                    try
                    {
                        cmd.ExecuteNonQuery();

                        transaction.Commit();

                        return null;
                    }

                    catch (Exception ex)
                    {
                        transaction.Rollback();

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

                        //File.WriteAllText("SolicitudInicLog.txt", errorLog);

                        return ex;
                    }
                }
            }
        }
Example #6
0
        /// <summary>
        /// Llena campos en la area de documentos
        /// </summary>
        /// <param name="ctrls">Todos los controles en la area de documentos req</param>
        /// <param name="documentosRequeridos">Objetos documentoRequerido</param>
        /// <param name="estatusId">Estatus de solicitud</param>
        private void SetDocsRequeridos(Dictionary<TextBox, DropDownList> ctrls, LinkedList<DocumentoRequerido> documentosRequeridos, SolicitudAviso solici)
        {
            for (int i = 0; i < documentosRequeridos.Count; i++)
            {
                ctrls.Keys.ElementAt(i).Text = documentosRequeridos.ElementAt(i).Path;

                ctrls.Values.ElementAt(i).SelectedIndex = documentosRequeridos.ElementAt(i).Status;

                if (!solici.EstatusId.Equals(((int)SolicitudAviso.Estatus.PendienteRevisarCoordinador).ToString()))
                {
                    ctrls.Values.ElementAt(i).Enabled = false;
                }
            }


            //ddls = new LinkedList<DropDownList>();

            //txtBxs = new LinkedList<TextBox>();
        }
Example #7
0
        protected void GuardarBtnClick(object sender, EventArgs e)
        {
            User user = Session["UserObj"] == null ? new User() : (User)Session["UserObj"];

            string exceptionMsg = string.Empty;

            guardarBtn.Enabled = false;

            NumeroControl exceptionNumControl = new NumeroControl();

            try
            {
                #region Validate controls server side

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

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

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

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

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

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

                //#region Docs

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

                //#endregion

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

                #endregion

                #region Genera numero Control

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

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

                #endregion

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

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

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

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

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


                //}

                #endregion

                #region Poblar docs

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

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

                docControls = GetDocCtrls();

                //#region Docs

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

                //        NumeroControl = numeroControl,

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

                //        Tipo = tipoAvisoRBtnLst.SelectedIndex,

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

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

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

                //#endregion

                #endregion

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

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

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

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

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

                #region Poblar solicitud

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

                            NumeroControl = numeroControl,

                            Emergencia = emergenciaChkBx.Checked,

                            TipoAviso = tipoAvisoRBtnLst.SelectedIndex.ToString(),

                            //EstatusId = statusHF.Value,

                            NombreContacto = nombreContactoTxtBx.Text.ToUpper(),

                            CelularContacto = celularContactoTxtBx.Text.ToUpper(),

                            DireccionPostalContacto = direccionPostalContactoTxtBx.Text.ToUpper(),

                            #endregion

                            #region Contratista

                            NombreEmpresa = companyDDL.SelectedValue,

                            AreaDept = areaDepartamentoTxtBx.Text.ToUpper(),

                            RepresentanteAutorizado = representanteTxtBx.Text.ToUpper(),

                            TelOficina = telOficinaTxtBx.Text.ToUpper(),

                            TelCampoTrabajo = telTrabajoTxtBx.Text.ToUpper(),

                            TelCelular = celularTxtBx.Text.ToUpper(),

                            CorreoElectronico = emailTxtBx.Text.ToUpper(),

                            DireccionPostal = direccionTxtBx.Text,

                            MunicipioId = municipioDDL.SelectedIndex,

                            CodigoPostal = codigoPostalTxtBx.Text.ToUpper(),

                            #endregion

                            #region Sub

                            Subcontratista = companySubTxtBx.Text,

                            AreaDeptSub = areaDepartamentoSubTxtBx.Text.ToUpper(),

                            RepresentanteAutorizadoSub = representanteSubTxtBx.Text.ToUpper(),

                            TelOficinaSub = telOficinaSubTxtBx.Text.ToUpper(),

                            TelCampoTrabajoSub = telTrabajoSubTxtBx.Text.ToUpper(),

                            TelCelularSub = celularSubTxtBx.Text.ToUpper(),

                            CorreoElectronicoSub = emailSubTxtBx.Text,

                            DireccionPostalSub = direccionSubTxtBx.Text.ToUpper(),

                            MunicipioIdSub = municipioSubDDL.SelectedIndex,

                            CodigoPostalSub = codigoPostalSubTxtBx.Text.ToUpper(),

                            #endregion

                            #region Info trabajo

                            Zona = zona,

                            BoUrb = boUrbTxtBx.Text.ToUpper(),

                            SectorCalle = sectorCalleTxtBx.Text.ToUpper(),

                            Carretera = carreteraTxtBx.Text.ToUpper(),

                            MunicipioIdTrab = municipioTrabajoDDL.SelectedIndex,

                            KM = Convert.ToInt32(kmTxtBx.Text),

                            HM = Convert.ToInt32(hmTxtBx.Text),

                            Referencias = referenciasTxtBx.Text.ToUpper(),

                            RazonTrabajos = razonTxtBx.Text.ToUpper(),

                            FechaPropuesta = Convert.ToDateTime(fechaComienzoPropuestoTxtBx.Text),

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

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

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

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

                            Maquinaria = maquinariaChkBx.Checked,

                            TipoMaquinaria = tipoMaquinariaTxtBx.Text.ToUpper(),

                            Explosivos = explosivoChkBx.Checked,

                            LicenciaExplosivo = licExplosivoTxtBx.Text.ToUpper(),

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

                            AreaMarcada = areaMarcadaChkBx.Checked,

                            TipoExcavacion = tipoExcavacion,

                            ProfundidadPies = Convert.ToInt32(profundidadPiesTxtBx.Text),

                            ProfundidadPulgadas = profundidadPulgadasDLL.SelectedIndex,

                            LongitudPies = Convert.ToInt32(longitudPiesTxtBx.Text),

                            LongitudPulgadas = longitudPulgadasDDL.SelectedIndex,

                            CoordenadaX = decimal.Parse(coordenadasXTxtBx.Text),

                            CoordenadaY = decimal.Parse(coordenadasYTxtBx.Text),

                            EnCasoEmergencia = enCasoEmergenciaTxtBx.Text.ToUpper(),

                            //TramitadoPor = currentUser.NombreCompleto,

                            //FechaTramite = DateTime.Now,

                            #endregion

                            Documentos = documentos,

                            ExtensionID = (int)SolicitudAviso.TiposExtensiones.Primera                         

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

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

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

                #endregion

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

                #region Create / Edit

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

                    #region validate docs

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

                    var files = Request.Files;

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

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

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

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

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

                    #endregion

                    #region Docs

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

                            NumeroControl = numeroControl,

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

                            Tipo = tipoAvisoRBtnLst.SelectedIndex,

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

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

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

                        documentos.AddLast(docReq);

                        #region Create aviso dir

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

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

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

                    #endregion

                    exceptionNumControl = solicitud.NumeroControl;

                    averias = SetAveriasNumControl(averias, numeroControl);

                    documentos = SetDocumentsNumControl(documentos, numeroControl);

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

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

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

                    solicitud.TramitadoPor = solicitud.Usuario.NombreCompleto;

                    solicitud.FechaTramite = DateTime.Now;

                    new DocumentosRequeridosServicio().TryCreate(documentos);

                    new AveriasServicio().TryCreate(averias);

                    new PrimerasExtensionesServicio().TryCreate(solicitud);

                    SaveDocs(_docRequeridosFileUpload, documentos);

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

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

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

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

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

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

                    //Uncomment when intergrating

                    //to.AddLast(currentUser.Email);

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

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

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

                    catch (Exception ex)
                    { } 
                    #endregion

                    #endregion
                }

                else
                {
                    #region Edit

                    exceptionNumControl = solicitud.NumeroControl;

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

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

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

                    to.AddLast(user.Email);

                    #region Actualiza status solicitud

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

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

                        documentos = docsExistentes;

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

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

                            solicitud.FechaComienzo = ValidarFecha(solicitudIncial.FechaComienzo);

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

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

                            #region Poblar hoja inspeccion

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

                                TipoInspeccionID = "1",

                                NumeroInspeccion = solicitud.NumeroControl.NumControlText,

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

                                NumeroPlacaID = "000",

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

                                    Year = solicitud.NumeroControl.Year,

                                    NumControlText = solicitud.NumeroControl.NumControlText
                                },

                                NombreEmpresa = solicitud.NombreEmpresa,

                                RepresentateAutorizado = solicitud.RepresentanteAutorizado,

                                CorreoElectronico = solicitud.CorreoElectronico,

                                DireccionPostal = solicitud.DireccionPostal,

                                DireccionFisica = company.DireccionFisica,

                                TelOficina = solicitud.TelOficina,

                                TelTrabajo = solicitud.TelCampoTrabajo,

                                Celular = solicitud.TelCelular,

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

                                TipoTrabajo = solicitud.TipoAviso,

                                FechaComienzo = solicitud.FechaComienzo,

                                FechaExpiracion = solicitud.FechaExpiracion,

                                LongitudPies = solicitud.LongitudPies,

                                LongitudPulgadas = solicitud.LongitudPulgadas,

                                ProfundidadPies = solicitud.ProfundidadPies,

                                ProfundidadPulgadas = solicitud.ProfundidadPulgadas,

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

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

                                RazonTrabajos = solicitud.RazonTrabajos,

                                Zona = solicitud.Zona,

                                BoUrbT = solicitud.BoUrb,

                                SectorCalleT = solicitud.SectorCalle,

                                CarreteraT = solicitud.Carretera,

                                KM = solicitud.KM,

                                HM = solicitud.HM,

                                MunicipioT = municipioTrabajoDDL.SelectedValue,
                            };

                            #endregion

                            new InspeccionesServicio().TryCrear(inspeccion);

                            ViewState["justCreatedInspeccion"] = true;

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

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

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

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

                            //to.AddLast(currentUser.Email);

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

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

                            #region pdf stuff

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

                            String Fecha = DateTime.Now.ToString();

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

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

                                doc.Open();

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

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

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

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

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

                                doc.Add(table);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                                doc.Add(table);
                                #endregion

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

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

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

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

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

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

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

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

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

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

                                doc.Add(table);

                                #endregion

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

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

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

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

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

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

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

                                doc.Add(table);
                                #endregion

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

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

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

                                table.AddCell(cell);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                                doc.Add(table);
                                #endregion


                                #region Footer
                                table = new PdfPTable(6);

                                //cell = signatureImgCell;

                                //cell.Colspan = 2;

                                //cell.Border = 0;

                                //cell.PaddingTop = 20f;

                                //table.AddCell(cell);

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

                                //p.Alignment = Element.ALIGN_TOP;

                                //p = new Paragraph();

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

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

                                //p.Alignment = Element.ALIGN_LEFT;

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


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

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

                                firmaImg.ScalePercent(50f);

                                firmaImg.SpacingBefore = 100f;

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

                                //p.Add(phr);

                                //firmaImg.Alignment = Element.ALIGN_BOTTOM;

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

                                cell.AddElement(firmaImg);

                                //cell.AddElement(phr);


                                //cell.AddElement(p);

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

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

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

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


                                doc.Add(table);
                                #endregion

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

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



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

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

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

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

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

                            #endregion

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

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

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

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

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

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

                            catch (Exception ex)
                            { }
                            #endregion

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

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

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

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

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

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

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

                            #endregion
                        }

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

                            solicitud.FechaDocsIncompletos = DateTime.Now;

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

                            catch (Exception ex)
                            { }

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

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

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

                        #region Validate docs requeridos

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

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

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

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

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

                        #endregion

                        #region Docs

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

                                NumeroControl = numeroControl,

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

                                Tipo = tipoAvisoRBtnLst.SelectedIndex,

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

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


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


                            documentos.AddLast(docReq);
                        }

                        #endregion

                        //documentos = SetDocumentsNumControl(documentos, numeroControl);

                        #region Set docs id

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

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

                        #endregion

                        SaveDocs(_docRequeridosFileUpload, documentos);

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

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

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

                        catch (Exception ex)
                        { }
                    }

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

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

                    #endregion

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

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

                    solicitud.FechaTramite = primeraExtExistente.FechaTramite;

                    solicitud.TramitadoPor = primeraExtExistente.TramitadoPor;

                    solicitud.Usuario = primeraExtExistente.Usuario;

                    //documentos = SetDocumentsNumControl(documentos, numeroControl);

                    averias = SetAveriasNumControl(averias, numeroControl);

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

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

                    new DocumentosRequeridosServicio().TryUpdate(documentos);

                    new AveriasServicio().TryCreate(averias);

                    new PrimerasExtensionesServicio().TryUpdate(solicitud);

                    #endregion
                }

                #endregion

                guardarBtn.Enabled = true;

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

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

                    errorLbl2.InnerText = ex.Message;
                }

                else
                {
                    guardarBtn.Enabled = true;

                    errorLbl2.InnerHtml = exceptionMsg;
                }

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

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

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

                Page.DataBind();

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

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

            guardarBtn.Enabled = false;

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

            NumeroControl exceptionNumControl = new NumeroControl();

            #region Set comentario txtBx if empty

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

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

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

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

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

                    #region Validate controls server side

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

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

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

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

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

                    #endregion

                    #region Genera numero Control

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

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

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

                    #endregion

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

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

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

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

                    #endregion

                    #region Poblar docs

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

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

                    docControls = GetDocCtrls();



                    #endregion

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

                    #region Poblar solicitud

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

                        NumeroControl = numeroControl,

                        Emergencia = emergenciaChkBx.Checked,

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

                        NombreContacto = nombreContactoTxtBx.Text.ToUpper(),

                        CelularContacto = celularContactoTxtBx.Text.ToUpper(),

                        DireccionPostalContacto = direccionPostalContactoTxtBx.Text.ToUpper(),

                        #endregion

                        #region Contratista

                        NombreEmpresa = companyDDL.SelectedValue,

                        AreaDept = areaDepartamentoTxtBx.Text.ToUpper(),

                        RepresentanteAutorizado = representanteTxtBx.Text.ToUpper(),

                        TelOficina = telOficinaTxtBx.Text.ToUpper(),

                        TelCampoTrabajo = telTrabajoTxtBx.Text.ToUpper(),

                        TelCelular = celularTxtBx.Text.ToUpper(),

                        CorreoElectronico = emailTxtBx.Text,

                        DireccionPostal = direccionTxtBx.Text.ToUpper(),

                        MunicipioId = municipioDDL.SelectedIndex,

                        CodigoPostal = codigoPostalTxtBx.Text.ToUpper(),

                        #endregion

                        #region Sub

                        Subcontratista = companySubTxtBx.Text,

                        AreaDeptSub = areaDepartamentoSubTxtBx.Text.ToUpper(),

                        RepresentanteAutorizadoSub = representanteSubTxtBx.Text.ToUpper(),

                        TelOficinaSub = telOficinaSubTxtBx.Text.ToUpper(),

                        TelCampoTrabajoSub = telTrabajoSubTxtBx.Text.ToUpper(),

                        TelCelularSub = celularSubTxtBx.Text.ToUpper(),

                        CorreoElectronicoSub = emailSubTxtBx.Text,

                        DireccionPostalSub = direccionSubTxtBx.Text.ToUpper(),

                        MunicipioIdSub = municipioSubDDL.SelectedIndex,

                        CodigoPostalSub = codigoPostalSubTxtBx.Text.ToUpper(),

                        #endregion

                        #region Info trabajo

                        Zona = zona,

                        BoUrb = boUrbTxtBx.Text.ToUpper(),

                        SectorCalle = sectorCalleTxtBx.Text.ToUpper(),

                        Carretera = carreteraTxtBx.Text.ToUpper(),

                        MunicipioIdTrab = municipioTrabajoDDL.SelectedIndex,

                        KM = Convert.ToInt32(kmTxtBx.Text),

                        HM = Convert.ToInt32(hmTxtBx.Text),

                        Referencias = referenciasTxtBx.Text.ToUpper(),

                        RazonTrabajos = razonTxtBx.Text.ToUpper(),

                        FechaPropuesta = Convert.ToDateTime(fechaComienzoPropuestoTxtBx.Text),

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

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

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

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

                        Maquinaria = maquinariaChkBx.Checked,

                        TipoMaquinaria = tipoMaquinariaTxtBx.Text.ToUpper(),

                        Explosivos = explosivoChkBx.Checked,

                        LicenciaExplosivo = licExplosivoTxtBx.Text.ToUpper(),

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

                        AreaMarcada = areaMarcadaChkBx.Checked,

                        TipoExcavacion = tipoExcavacion,

                        ProfundidadPies = Convert.ToInt32(profundidadPiesTxtBx.Text),

                        ProfundidadPulgadas = profundidadPulgadasDLL.SelectedIndex,

                        LongitudPies = Convert.ToInt32(longitudPiesTxtBx.Text),

                        LongitudPulgadas = longitudPulgadasDDL.SelectedIndex,

                        CoordenadaX = decimal.Parse(coordenadasXTxtBx.Text),

                        CoordenadaY = decimal.Parse(coordenadasYTxtBx.Text),

                        EnCasoEmergencia = enCasoEmergenciaTxtBx.Text.ToUpper(),

                        #endregion

                        Documentos = documentos,

                        //Averias = averias,

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

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

                    #endregion

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

                    #region Create / Edit

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

                        #region validate docs

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

                        var files = Request.Files;

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

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

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

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

                        #endregion

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

                        string numTxt = numeroControl.NumControl.ToString();

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

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

                        exceptionNumControl = numeroControl;
                        #endregion

                        #region Docs

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

                                NumeroControl = numeroControl,

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

                                Tipo = tipoAvisoRBtnLst.SelectedIndex
                            };

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

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

                            documentos.AddLast(docReq);
                        }

                        #endregion

                        documentos = SetDocumentsNumControl(documentos, numeroControl);

                        solicitud.NumeroControl = numeroControl;

                        numControlPopupLbl.Text = numeroControl.NumControlText;

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

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

                        solicitud.TramitadoPor = solicitud.Usuario.NombreCompleto;

                        solicitud.FechaTramite = DateTime.Now;

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

                        new NumerosControlServicio().Create(numeroControl);

                        new DocumentosRequeridosServicio().TryCreate(documentos);

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

                        new SolicitudesInicialesServicio().TryCreate(solicitud);

                        SaveDocs(_docRequeridosFileUpload, documentos);

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

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

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

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

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

                        numControlPopupTriggerBtn_Click(numControlPopupTriggerBtn, EventArgs.Empty);

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

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

                            }
                        }
                        #endregion

                        Page.DataBind();

                        #endregion
                    }

                    else
                    {
                        #region Edit

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

                        exceptionNumControl = numeroControl;

                        solicitud.FechaTramite = solicitudExistente.FechaTramite;

                        solicitud.TramitadoPor = solicitudExistente.TramitadoPor;

                        solicitud.Usuario = solicitudExistente.Usuario;

                        solicitud.SolicitudStatusID = solicitudStatusDDL.SelectedIndex;

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

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

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

                        #region Actualiza status solicitud

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

                        to.AddLast(user.Email);

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

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

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

                            documentos = docsExistentes;

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

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

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

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

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

                                #region Poblar hoja inspeccion

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

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

                                    DireccionFisica = company.DireccionFisica,

                                    EstatusInspeccionID = "1",

                                    TipoInspeccionID = "1",

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

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

                                        Year = solicitud.NumeroControl.Year,

                                        NumControlText = solicitud.NumeroControl.NumControlText
                                    },

                                    NombreEmpresa = solicitud.NombreEmpresa,

                                    RepresentateAutorizado = solicitud.RepresentanteAutorizado,

                                    CorreoElectronico = solicitud.CorreoElectronico,

                                    TelOficina = solicitud.TelOficina,

                                    TelTrabajo = solicitud.TelCampoTrabajo,

                                    Celular = solicitud.TelCelular,

                                    TipoAviso = solicitud.ExtensionID.ToString(),

                                    FechaComienzo = solicitud.FechaComienzo,

                                    FechaExpiracion = solicitud.FechaExpiracion,

                                    LongitudPies = solicitud.LongitudPies,

                                    LongitudPulgadas = solicitud.LongitudPulgadas,

                                    ProfundidadPies = solicitud.ProfundidadPies,

                                    ProfundidadPulgadas = solicitud.ProfundidadPulgadas,

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

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

                                    RazonTrabajos = solicitud.RazonTrabajos,

                                    Zona = solicitud.Zona,

                                    BoUrbT = solicitud.BoUrb,

                                    SectorCalleT = solicitud.SectorCalle,

                                    CarreteraT = solicitud.Carretera,

                                    KM = solicitud.KM,

                                    HM = solicitud.HM,

                                    MunicipioT = municipioTrabajoDDL.SelectedValue,
                                };

                                #endregion

                                new InspeccionesServicio().TryCrear(inspeccion);

                                ViewState["justCreatedInspeccion"] = true;

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

                                #region Enviar email excavador

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

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

                                to = new LinkedList<string>();

                                //Uncomment when intergrating

                                to.AddLast(solicitud.Usuario.Email);

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

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

                                #region pdf stuff

                                #region Init

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

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

                                string Fecha = solicitud.FechaTramite.ToString();

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

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

                                    Phrase phrase = null;

                                    PdfPCell cell = null;

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

                                    PdfPTable table = null;

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

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

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

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

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

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

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

                                    doc.Open();

                                #endregion

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

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

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

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

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

                                    doc.Add(table);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                                    doc.Add(table);
                                    #endregion

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

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

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

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

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

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

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

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


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

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

                                    doc.Add(table);

                                    #endregion

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

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

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

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

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

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

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

                                    doc.Add(table);
                                    #endregion

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

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

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

                                    table.AddCell(cell);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                                    doc.Add(table);
                                    #endregion

                                    #region Footer
                                    table = new PdfPTable(6);

                                    //cell = signatureImgCell;

                                    //cell.Colspan = 2;

                                    //cell.Border = 0;

                                    //cell.PaddingTop = 20f;

                                    //table.AddCell(cell);

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

                                    //p.Alignment = Element.ALIGN_TOP;

                                    //p = new Paragraph();

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

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

                                    //p.Alignment = Element.ALIGN_LEFT;

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


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

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

                                    firmaImg.ScalePercent(50f);

                                    firmaImg.SpacingBefore = 100f;

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

                                    //p.Add(phr);

                                    //firmaImg.Alignment = Element.ALIGN_BOTTOM;

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

                                    cell.AddElement(firmaImg);

                                    //cell.AddElement(phr);


                                    //cell.AddElement(p);

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

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

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

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


                                    doc.Add(table);
                                    #endregion

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

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



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

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

                                #endregion

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

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

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

                                    }
                                }
                                #endregion


                                #region Enviar email a operadores

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

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

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

                                to = new LinkedList<string>();

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

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

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

                                #region Add croquis to email

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

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

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

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

                                //            break;
                                //        }
                                //    }

                                #endregion

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

                                }

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

                                    }
                                }
                                #endregion
                                #endregion
                            }

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

                                to.AddLast(solicitud.Usuario.Email);

                                solicitud.FechaDocsIncompletos = DateTime.Now;

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

                                        string razonesMsg = string.Empty;

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

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

                                        #endregion

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

                                catch (Exception)
                                {
                                }
                                #endregion
                            }
                        }

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

                            #region Validate docs requeridos

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

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

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

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

                            #endregion

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

                                    NumeroControl = numeroControl,

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

                                    Tipo = tipoAvisoRBtnLst.SelectedIndex
                                };

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

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

                                documentos.AddLast(docReq);
                            }

                            #endregion

                            #region Update documentos con data de documentosExistentes

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

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

                            #endregion

                            SaveDocs(_docRequeridosFileUpload, documentos);

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

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

                            #region Email coordinadores

                            to = new LinkedList<string>();

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

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

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

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

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

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

                                }
                            }

                            #endregion

                            #endregion

                        }

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

                            solicitud.EstatusId = solicitudExistente.EstatusId;

                            solicitud.FechaRespuestaSolicitadas = solicitudExistente.FechaRespuestaSolicitadas;
                        }

                        #endregion

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

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

                        //documentos = SetDocumentsNumControl(documentos, numeroControl);

                        //averias = SetAveriasNumControl(averias, numeroControl);

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

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

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

                        new DocumentosRequeridosServicio().TryUpdate(documentos);

                        new SolicitudesInicialesServicio().TryUpdate(solicitud);

                        Session.Remove("Respuesta");

                        Session.Remove("RespuestaVisibility");

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

                        #endregion
                    }

                    #endregion

                }
            }

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

                else
                {
                    errorLbl2.InnerHtml = exceptionMsg;
                }

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

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

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

                //transaction.Rollback();

                Page.DataBind();

                errorPopup.Show();
            }

            

            guardarBtn.Enabled = true;
        }
Example #9
0
        protected void Guardar_Click(object sender, EventArgs e)
        {
            TipoInspeccionID = (ddlTipoInspeccion.SelectedIndex).ToString();

            #region Estatus inspeccion
            if (RB1.Checked) // Pendiente
                EstatusInspeccionID = "1";
            else
                if (RB2.Checked) // Completada
                    EstatusInspeccionID = "2";
                else
                    if (RB3.Checked) // Cancelada
                        EstatusInspeccionID = "3";
                    else
                        EstatusInspeccionID = "";
            #endregion

            #region Tipo trabajo

            if (RB4.Checked)
                TipoTrabajo = "1";
            else
                if (RB5.Checked)
                    TipoTrabajo = "2";
                else
                    if (RB6.Checked)
                        TipoTrabajo = "3";
                    else
                        TipoTrabajo = "";
            #endregion

            #region Tipo aviso
            if (RB7.Checked)
                TipoAviso = "0";
            else
                if (RB8.Checked)
                    TipoAviso = "1";
                else
                    if (RB9.Checked)
                        TipoAviso = "2";
                    else
                        TipoAviso = "";
            #endregion

            if (RB10.Checked)
                Zona = true;
            else
                if (RB11.Checked)
                    Zona = false;

            #region Some validations
            int[] err = new int[36];

            if (NumeroInspeccion.Text.Equals("")) { err[1] = 1; err[0] = 1; }
            if (FechaVisita.Text.Equals("")) { err[2] = 1; err[0] = 1; }
            if (TipoInspeccionID.Equals("")) { err[3] = 1; err[0] = 1; }
            if (EstatusInspeccionID.Equals("")) { err[4] = 1; err[0] = 1; }
            if (PlacaInspector.Text.Equals("")) { err[5] = 1; err[0] = 1; }
            if (NombreEmpresa.Text.Equals("")) { err[6] = 1; err[0] = 1; }
            if (RepresentanteAutorizado.Text.Equals("")) { err[7] = 1; err[0] = 1; }
            if (CorreoElectronico.Text.Equals("")) { err[8] = 1; err[0] = 1; }
            if (DireccionPostal.Text.Equals("")) { err[9] = 1; err[0] = 1; }
            if (TelOficina.Text.Equals("")) { err[10] = 1; err[0] = 1; }
            //if (TelTrabajo.Text.Equals("")) { err[11] = 1; err[0] = 1; }
            if (Celular.Text.Equals("")) { err[12] = 1; err[0] = 1; }

            if (DireccionFisica.Text.Equals("")) { err[13] = 1; err[0] = 1; }
            if (NumeroControl.Text.Equals("")) { err[14] = 1; err[0] = 1; }
            //if (ExisteAviso.Text.Equals("")) { err[15] = 1; err[0] = 1; }
            if (!RB4.Checked && !RB5.Checked && !RB6.Checked) { err[16] = 1; err[0] = 1; }
            if (TipoAviso.Equals("")) { err[17] = 1; err[0] = 1; }
            if (FechaComienzo.Equals("")) { err[18] = 1; err[0] = 1; }
            if (FechaExpiracion.Text.Equals("")) { err[19] = 1; err[0] = 1; }
            if (LongitudPies.Text.Equals("")) { err[20] = 1; err[0] = 1; }
            if (ddlLongitudPulgadas.SelectedValue.Equals("")) { err[21] = 1; err[0] = 1; }
            if (ProfundidadPies.Text.Equals("")) { err[22] = 1; err[0] = 1; }
            if (ddlProfundidadPulgadas.SelectedValue.Equals("")) { err[23] = 1; err[0] = 1; }
            if (CoordenadaX.Text.Equals("")) { err[24] = 1; err[0] = 1; }
            if (CoordenadaY.Text.Equals("")) { err[25] = 1; err[0] = 1; }
            if (RazonTrabajos.Text.Equals("")) { err[26] = 1; err[0] = 1; }
            if (Zona.Equals("")) { err[27] = 1; err[0] = 1; }
            if (BoUrbT.Text.Equals("")) { err[28] = 1; err[0] = 1; }

            if (SectorCalleT.Text.Equals("")) { err[29] = 1; err[0] = 1; }
            if (CarreteraT.Text.Equals("")) { err[30] = 1; err[0] = 1; }
            if (KM.Text.Equals("")) { err[31] = 1; err[0] = 1; }
            if (HM.Text.Equals("")) { err[32] = 1; err[0] = 1; }
            if (ddlMunicipioT.SelectedIndex.Equals(0)) { err[33] = 1; err[0] = 1; }
            if (CodigoPostalT.Text.Equals("")) { err[34] = 1; err[0] = 1; }
            if (Observaciones.Text.Equals("")) { err[35] = 1; err[0] = 1; }
            #endregion

            err[0] = 0; ////////////////////////////////// EAF /////////////////////////////////////////

            if (err[0] == 1)
            {
                ScriptManager.RegisterStartupScript(NumeroControl, this.GetType(), "Pop", "faltanrequeridos()", true);
            }
            else
            {
                string cs = ConfigurationManager.ConnectionStrings["EXC"].ConnectionString;
                using (SqlConnection conn = new SqlConnection(cs))
                {
                    using (SqlCommand cmd = new SqlCommand())
                    {
                        cmd.Connection = conn;
                        cmd.CommandType = CommandType.Text;

                        try
                        {
                            conn.Open();
                        }

                        catch (Exception)
                        {
                        }                        

                        cmd.Connection = conn;
                        cmd.CommandType = CommandType.Text;

                        cmd.CommandText = @"DELETE FROM Inspecciones WHERE NumeroInspeccion = @NumeroInspeccion AND TipoAviso = @TipoAviso;";

                        cmd.CommandText += "INSERT INTO Inspecciones VALUES (" +
                            "@NumeroInspeccion, @FechaVisita, @TipoInspeccionID, @EstatusInspeccionID, @PlacaInspector," +
                            " @NombreEmpresa, @RepresentanteAutorizado, @CorreoElectronico, @DireccionPostal, @TelOficina, " +
                            "@TelTrabajo, @Celular, @DireccionFisica, @NumeroControl, @ExisteAviso, @TipoTrabajo, @TipoAviso, " +
                            "@FechaComienzo, @FechaExpiracion, @LongitudPies, @LongitudPulgadas, @ProfundidadPies, @ProfundidadPulgadas, " +
                            "@CoordenadaX, @CoordenadaY, @RazonTrabajos, @Zona, @BoUrbT, @SectorCalleT, @CarreteraT, @KM, @HM, " +
                            "@MunicipioT, @CodigoPostalT, @Observaciones, @NombreInspector, @ImagePath, @NumInspeccionAplica, @ImagePath2, @ImagePath3, @ImagePath4)";

                        #region SQL params

                        #region Set imgpath params

                        Inspector inspector = new SolicitudesInicialesServicio().GetInspector(PlacaInspector.Text);

                        string filename = string.Empty,
                            filename2 = string.Empty,
                            filename3 = string.Empty,
                            filename4 = string.Empty;

                        #region img1

                        if (FileUpload1.HasFile)
                        {
                            filename = GenerateInpeccionImgName(FileUpload1);

                            //filename = System.IO.Path.GetFileName(FileUpload1.FileName);
                            ////FileUpload1.SaveAs(Server.MapPath("~/Uploads/") + filename);

                            //if (RB7.Checked)
                            //{
                            //    filename = "Inicial_" + NumeroInspeccion.Text + "_" + filename;
                            //}

                            //else if (RB8.Checked)
                            //{
                            //    filename = "EXT1_" + NumeroInspeccion.Text + "_" + filename;
                            //}

                            //else
                            //{
                            //    filename = "EXT2_" + NumeroInspeccion.Text + "_" + filename;
                            //}

                            FileUpload1.SaveAs(Server.MapPath(string.Format("{0}/{1}/{2}",
                                new DocumentoRequerido().DocumentosInspeccionesSavePath, inspector.CorreoElectronico, filename)));

                            cmd.Parameters.AddWithValue("@ImagePath", string.Format("{0}/{1}/{2}",
                                new DocumentoRequerido().DocumentosInspeccionesSavePath, inspector.CorreoElectronico, filename));

                            //cmd.Parameters.AddWithValue("@ImagePath", );
                        }

                        else
                        {
                            if (string.IsNullOrEmpty(imgViewFile.ImageUrl))
                            {
                                cmd.Parameters.AddWithValue("@ImagePath", filename);

                                //filename = GenerateInpeccionImgName(FileUpload1);
                            }

                            else
                            {
                                cmd.Parameters.AddWithValue("@ImagePath", imgViewFile.ImageUrl);
                            }
                        }  

                        #endregion

                        #region img2

                        if (fUp2.HasFile)
                        {
                            filename2 = GenerateInpeccionImgName(fUp2);

                            //filename = System.IO.Path.GetFileName(FileUpload1.FileName);
                            ////FileUpload1.SaveAs(Server.MapPath("~/Uploads/") + filename);

                            //if (RB7.Checked)
                            //{
                            //    filename = "Inicial_" + NumeroInspeccion.Text + "_" + filename;
                            //}

                            //else if (RB8.Checked)
                            //{
                            //    filename = "EXT1_" + NumeroInspeccion.Text + "_" + filename;
                            //}

                            //else
                            //{
                            //    filename = "EXT2_" + NumeroInspeccion.Text + "_" + filename;
                            //}

                            fUp2.SaveAs(Server.MapPath(string.Format("{0}/{1}/{2}",
                                new DocumentoRequerido().DocumentosInspeccionesSavePath, inspector.CorreoElectronico, filename2)));

                            cmd.Parameters.AddWithValue("@ImagePath2", string.Format("{0}/{1}/{2}",
                                new DocumentoRequerido().DocumentosInspeccionesSavePath, inspector.CorreoElectronico, filename2));

                            //cmd.Parameters.AddWithValue("@ImagePath", );
                        }

                        else
                        {
                            if (string.IsNullOrEmpty(img2.ImageUrl))
                            {
                                cmd.Parameters.AddWithValue("@ImagePath2", filename2);

                                //filename = GenerateInpeccionImgName(FileUpload1);
                            }

                            else
                            {
                                cmd.Parameters.AddWithValue("@ImagePath2", img2.ImageUrl);
                            }
                        }

                        #endregion

                        #region img3

                        if (fUp3.HasFile)
                        {
                            filename3 = GenerateInpeccionImgName(fUp3);

                            //filename = System.IO.Path.GetFileName(FileUpload1.FileName);
                            ////FileUpload1.SaveAs(Server.MapPath("~/Uploads/") + filename);

                            //if (RB7.Checked)
                            //{
                            //    filename = "Inicial_" + NumeroInspeccion.Text + "_" + filename;
                            //}

                            //else if (RB8.Checked)
                            //{
                            //    filename = "EXT1_" + NumeroInspeccion.Text + "_" + filename;
                            //}

                            //else
                            //{
                            //    filename = "EXT2_" + NumeroInspeccion.Text + "_" + filename;
                            //}

                            fUp3.SaveAs(Server.MapPath(string.Format("{0}/{1}/{2}",
                                new DocumentoRequerido().DocumentosInspeccionesSavePath, inspector.CorreoElectronico, filename3)));

                            cmd.Parameters.AddWithValue("@ImagePath3",string.Format("{0}/{1}/{2}",
                                new DocumentoRequerido().DocumentosInspeccionesSavePath, inspector.CorreoElectronico, filename3));

                            //cmd.Parameters.AddWithValue("@ImagePath", );
                        }

                        else
                        {
                            if (string.IsNullOrEmpty(img3.ImageUrl))
                            {
                                cmd.Parameters.AddWithValue("@ImagePath3", filename3);

                                //filename = GenerateInpeccionImgName(FileUpload1);
                            }

                            else
                            {
                                cmd.Parameters.AddWithValue("@ImagePath3", img3.ImageUrl);
                            }
                        }

                        #endregion

                        #region img4

                        if (fUp4.HasFile)
                        {
                            filename4 = GenerateInpeccionImgName(fUp4);

                            //filename = System.IO.Path.GetFileName(FileUpload1.FileName);
                            ////FileUpload1.SaveAs(Server.MapPath("~/Uploads/") + filename);

                            //if (RB7.Checked)
                            //{
                            //    filename = "Inicial_" + NumeroInspeccion.Text + "_" + filename;
                            //}

                            //else if (RB8.Checked)
                            //{
                            //    filename = "EXT1_" + NumeroInspeccion.Text + "_" + filename;
                            //}

                            //else
                            //{
                            //    filename = "EXT2_" + NumeroInspeccion.Text + "_" + filename;
                            //}

                            fUp4.SaveAs(Server.MapPath(string.Format("{0}/{1}/{2}",
                                new DocumentoRequerido().DocumentosInspeccionesSavePath, inspector.CorreoElectronico, filename4)));

                            cmd.Parameters.AddWithValue("@ImagePath4",string.Format("{0}/{1}/{2}",
                                new DocumentoRequerido().DocumentosInspeccionesSavePath, inspector.CorreoElectronico, filename4));

                            //cmd.Parameters.AddWithValue("@ImagePath", );
                        }

                        else
                        {
                            if (string.IsNullOrEmpty(img4.ImageUrl))
                            {
                                cmd.Parameters.AddWithValue("@ImagePath4", filename4);

                                //filename = GenerateInpeccionImgName(FileUpload1);
                            }

                            else
                            {
                                cmd.Parameters.AddWithValue("@ImagePath4", img4.ImageUrl);
                            }
                        }

                        #endregion

                        #endregion

                        //cmd.Parameters.AddWithValue("@ImagePath", imgViewFile.ImageUrl);

                        cmd.Parameters.AddWithValue("@NumInspeccionAplica", chkExisteAviso.Checked);

                        cmd.Parameters.AddWithValue("@NumeroInspeccion", NumeroInspeccion.Text);
                        cmd.Parameters.AddWithValue("@FechaVisita", FechaVisita.Text);
                        cmd.Parameters.AddWithValue("@TipoInspeccionID", TipoInspeccionID);
                        cmd.Parameters.AddWithValue("@EstatusInspeccionID", EstatusInspeccionID);
                        cmd.Parameters.AddWithValue("@PlacaInspector", string.Format("{0}", PlacaInspector.Text));

                        //Sometimes ddl was picking default val. Maybe due to disabled status. But, in some cases, values was correct even if it was disabled
                        cmd.Parameters.AddWithValue("@NombreInspector", ddlInspector.SelectedIndex < 1 ? (string)ViewState["Inspector"]
                            : ddlInspector.SelectedValue);

                        cmd.Parameters.AddWithValue("@NombreEmpresa", NombreEmpresa.Text.ToUpper());
                        cmd.Parameters.AddWithValue("@RepresentanteAutorizado", RepresentanteAutorizado.Text.ToUpper());
                        cmd.Parameters.AddWithValue("@CorreoElectronico", CorreoElectronico.Text);
                        cmd.Parameters.AddWithValue("@DireccionPostal", DireccionPostal.Text.ToUpper());
                        cmd.Parameters.AddWithValue("@TelOficina", TelOficina.Text);
                        cmd.Parameters.AddWithValue("@TelTrabajo", TelTrabajo.Text);
                        cmd.Parameters.AddWithValue("@Celular", Celular.Text);

                        cmd.Parameters.AddWithValue("@DireccionFisica", DireccionFisica.Text.ToUpper());
                        cmd.Parameters.AddWithValue("@NumeroControl", NumeroControl.Text);
                        cmd.Parameters.AddWithValue("@ExisteAviso", ExisteAviso);
                        cmd.Parameters.AddWithValue("@TipoTrabajo", TipoTrabajo);
                        cmd.Parameters.AddWithValue("@TipoAviso", TipoAviso);
                        cmd.Parameters.AddWithValue("@FechaComienzo", FechaComienzo.Text);
                        cmd.Parameters.AddWithValue("@FechaExpiracion", FechaExpiracion.Text);
                        cmd.Parameters.AddWithValue("@LongitudPies", LongitudPies.Text);
                        cmd.Parameters.AddWithValue("@LongitudPulgadas", Int32.Parse(ddlLongitudPulgadas.SelectedValue));
                        cmd.Parameters.AddWithValue("@ProfundidadPies", ProfundidadPies.Text);
                        cmd.Parameters.AddWithValue("@ProfundidadPulgadas", Int32.Parse(ddlProfundidadPulgadas.SelectedValue));
                        cmd.Parameters.AddWithValue("@CoordenadaX", CoordenadaX.Text);
                        cmd.Parameters.AddWithValue("@CoordenadaY", CoordenadaX.Text);
                        cmd.Parameters.AddWithValue("@RazonTrabajos", RazonTrabajos.Text.ToUpper());
                        cmd.Parameters.AddWithValue("@Zona", Zona);
                        cmd.Parameters.AddWithValue("@BoUrbT", BoUrbT.Text.ToUpper());

                        cmd.Parameters.AddWithValue("@SectorCalleT", SectorCalleT.Text.ToUpper());
                        cmd.Parameters.AddWithValue("@CarreteraT", CarreteraT.Text.ToUpper());
                        cmd.Parameters.AddWithValue("@KM", KM.Text);
                        cmd.Parameters.AddWithValue("@HM", HM.Text);
                        cmd.Parameters.AddWithValue("@MunicipioT", ddlMunicipioT.SelectedValue.ToString());
                        cmd.Parameters.AddWithValue("@CodigoPostalT", CodigoPostalT.Text);
                        cmd.Parameters.AddWithValue("@Observaciones", Observaciones.Text.ToUpper());
                        #endregion

                        try
                        {
                            int recordsAffected = cmd.ExecuteNonQuery();

                            #region Refresh inspecciones addicionales

                            inspeccionesAdicionalesLbl.Visible = false;

                            string numControlFormat = NumeroInspeccion.Text.Contains('#') ? "{0}#{1}" : "{0}-{1}";

                            FillInspecionesAdicionalesDDL(InspeccionesServicio.GetInspeccionesNumControlsByNumControl(string.Format(numControlFormat,
                                NumeroInspeccion.Text.Split('-', '#')[0], NumeroInspeccion.Text.Split('-', '#')[1]))); 

                            #endregion

                            //Inspector inspector = new SolicitudesInicialesServicio().GetInspector(PlacaInspector.Text);

                            var to = new LinkedList<string>();

                            to.AddLast(inspector.CorreoElectronico);

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

                            //Update status solicitud
                            if (!string.IsNullOrWhiteSpace(inspector.NumeroPlacaID))
                            {
                                NumeroControl numControl = new Entidad.NumeroControl()
                                {
                                    NumControlText = NumeroInspeccion.Text
                                };

                                SolicitudAviso aviso = new SolicitudAviso();

                                if (TipoAviso.Equals(((int)SolicitudAviso.TiposExtensiones.Inicial).ToString()))
                                {
                                    #region update aviso inicial
                                    aviso = new SolicitudesInicialesServicio().GetSolicitud(numControl);

                                    aviso.EstatusId = aviso.EstatusId.Replace(new SolicitudAviso().LetraStatus, string.Empty);

                                    if (!aviso.EstatusId.Equals(((int)SolicitudAviso.Estatus.EnProcesoInspeccion).ToString())
                                        && !RB2.Checked)
                                    {
                                        aviso.EstatusId = new SolicitudAviso().LetraStatus + ((int)SolicitudAviso.Estatus.EnProcesoInspeccion).ToString();

                                        aviso.Inspector.Nombre = ddlInspector.SelectedIndex < 1 ? (string)ViewState["Inspector"]
                            : ddlInspector.SelectedValue;

                                        new SolicitudesInicialesServicio().TryUpdate(aviso);
                                        try
                                        {
                                            if (CheckForInternetConnection())
                                                SendEmail(to, "*****@*****.**",
                                                mails.ElementAt((int)Mail.Notifications.InspectorNuevoAviso).Subject,
                                                mails.ElementAt((int)Mail.Notifications.InspectorNuevoAviso).Body.Replace(
                                                "@NumControl", NumeroInspeccion.Text).Replace("@NombreEmpresa",
                                                NombreEmpresa.Text), new LinkedList<string>()); // only test
                                        }

                                        catch (Exception ex)
                                        { }
                                    }

                                    else if (aviso.EstatusId.Equals(((int)SolicitudAviso.Estatus.EnProcesoInspeccion).ToString())
                                        && RB2.Checked)
                                    {
                                        aviso.EstatusId = new SolicitudAviso().LetraStatus + ((int)SolicitudAviso.Estatus.InspeccionCompletada).ToString();
                                        
                                        new SolicitudesInicialesServicio().TryUpdate(aviso);
                                    }
                                    #endregion
                                }

                                else if (TipoAviso.Equals(((int)SolicitudAviso.TiposExtensiones.Primera).ToString()))
                                {
                                    #region Update 1st ext
                                    aviso = new PrimerasExtensionesServicio().GetPrimeraExtension(numControl);

                                    aviso.EstatusId = aviso.EstatusId.Replace(new SolicitudAviso().LetraStatus, string.Empty);

                                    if (!aviso.EstatusId.Equals(((int)SolicitudAviso.Estatus.EnProcesoInspeccion).ToString())
                                        && !RB2.Checked)
                                    {
                                        aviso.EstatusId = new SolicitudAviso().LetraStatus + ((int)SolicitudAviso.Estatus.EnProcesoInspeccion).ToString();

                                        aviso.Inspector.Nombre = ddlInspector.SelectedIndex < 1 ? (string)ViewState["Inspector"]
                            : ddlInspector.SelectedValue;

                                        new PrimerasExtensionesServicio().TryUpdate(aviso);
                                        try
                                        {
                                            if (CheckForInternetConnection())
                                                SendEmail(to, "*****@*****.**",
                                                mails.ElementAt((int)Mail.Notifications.InspectorNuevoAviso).Subject,
                                                mails.ElementAt((int)Mail.Notifications.InspectorNuevoAviso).Body.Replace(
                                                "@NumControl", NumeroInspeccion.Text).Replace("@NombreEmpresa", NombreEmpresa.Text), new LinkedList<string>()); // only test
                                        }

                                        catch (Exception)
                                        { }
                                    }

                                    else if (aviso.EstatusId.Equals(((int)SolicitudAviso.Estatus.EnProcesoInspeccion).ToString())
                                           && RB2.Checked)
                                    {
                                        aviso.EstatusId = new SolicitudAviso().LetraStatus + ((int)SolicitudAviso.Estatus.InspeccionCompletada).ToString();

                                        new PrimerasExtensionesServicio().TryUpdate(aviso);
                                    }
                                    #endregion
                                }

                                else
                                {
                                    #region Update 2nd ext
                                    aviso = new SegundasExtensionesServicio().GetSegundaExtension(numControl);

                                    aviso.EstatusId = aviso.EstatusId.Replace(new SolicitudAviso().LetraStatus, string.Empty);

                                    if (!aviso.EstatusId.Equals(((int)SolicitudAviso.Estatus.EnProcesoInspeccion).ToString())
                                        && !RB2.Checked)
                                    {
                                        aviso.EstatusId = new SolicitudAviso().LetraStatus + ((int)SolicitudAviso.Estatus.EnProcesoInspeccion).ToString();

                                        aviso.Inspector.Nombre = ddlInspector.SelectedIndex < 1 ? (string)ViewState["Inspector"]
                            : ddlInspector.SelectedValue;

                                        new SegundasExtensionesServicio().TryUpdate(aviso);

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

                                        catch (Exception)
                                        { }
                                    }

                                    else if (aviso.EstatusId.Equals(((int)SolicitudAviso.Estatus.EnProcesoInspeccion).ToString())
                                           && RB2.Checked)
                                    {
                                        aviso.EstatusId = new SolicitudAviso().LetraStatus + ((int)SolicitudAviso.Estatus.InspeccionCompletada).ToString();

                                        new SegundasExtensionesServicio().TryUpdate(aviso);
                                    }
                                    #endregion
                                }                               

                                Cancelar_Click(sender, e);
                            }
                        }
                        catch (Exception)
                        {
                            ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "sqlerr()", true);
                        }
                        finally
                        {
                            conn.Close();
                        }
                    }
                }
            }

            Cancelar_Click(sender, e);
        }
Example #10
0
        protected void Guardar_Click(object sender, EventArgs e)
        {
            TipoInspeccionID = (ddlTipoInspeccion.SelectedIndex).ToString();

            #region Estatus inspeccion
            if (RB1.Checked)
                EstatusInspeccionID = "1";
            else
                if (RB2.Checked)
                    EstatusInspeccionID = "2";
                else
                    if (RB3.Checked)
                        EstatusInspeccionID = "3";
                    else
                        EstatusInspeccionID = "";
            #endregion

            #region Tipo trabajo

            if (RB4.Checked)
                TipoTrabajo = "1";
            else
                if (RB5.Checked)
                    TipoTrabajo = "2";
                else
                    if (RB6.Checked)
                        TipoTrabajo = "3";
                    else
                        TipoTrabajo = "";
            #endregion

            #region Tipo aviso
            if (RB7.Checked)
                TipoAviso = "0";
            else
                if (RB8.Checked)
                    TipoAviso = "1";
                else
                    if (RB9.Checked)
                        TipoAviso = "2";
                    else
                        TipoAviso = "";
            #endregion

            //if (chkExisteAviso.Checked)
            //    ExisteAviso = true;
            //else
            //    ExisteAviso = false;

            if (RB10.Checked)
                Zona = true;
            else
                if (RB11.Checked)
                    Zona = false;

            #region Some validation
            int[] err = new int[36];

            if (NumeroInspeccion.Text.Equals("")) { err[1] = 1; err[0] = 1; }
            if (FechaVisita.Text.Equals("")) { err[2] = 1; err[0] = 1; }
            if (TipoInspeccionID.Equals("")) { err[3] = 1; err[0] = 1; }
            if (EstatusInspeccionID.Equals("")) { err[4] = 1; err[0] = 1; }
            if (PlacaInspector.Text.Equals("")) { err[5] = 1; err[0] = 1; }
            if (NombreEmpresa.Text.Equals("")) { err[6] = 1; err[0] = 1; }
            if (RepresentanteAutorizado.Text.Equals("")) { err[7] = 1; err[0] = 1; }
            if (CorreoElectronico.Text.Equals("")) { err[8] = 1; err[0] = 1; }
            if (DireccionPostal.Text.Equals("")) { err[9] = 1; err[0] = 1; }
            if (TelOficina.Text.Equals("")) { err[10] = 1; err[0] = 1; }
            //if (TelTrabajo.Text.Equals("")) { err[11] = 1; err[0] = 1; }
            if (Celular.Text.Equals("")) { err[12] = 1; err[0] = 1; }

            if (DireccionFisica.Text.Equals("")) { err[13] = 1; err[0] = 1; }
            if (NumeroControl.Text.Equals("")) { err[14] = 1; err[0] = 1; }
            //if (ExisteAviso.Text.Equals("")) { err[15] = 1; err[0] = 1; }
            if (!RB4.Checked && !RB5.Checked && !RB6.Checked) { err[16] = 1; err[0] = 1; }
            if (TipoAviso.Equals("")) { err[17] = 1; err[0] = 1; }
            if (FechaComienzo.Equals("")) { err[18] = 1; err[0] = 1; }
            if (FechaExpiracion.Text.Equals("")) { err[19] = 1; err[0] = 1; }
            if (LongitudPies.Text.Equals("")) { err[20] = 1; err[0] = 1; }
            if (ddlLongitudPulgadas.SelectedValue.Equals("")) { err[21] = 1; err[0] = 1; }
            if (ProfundidadPies.Text.Equals("")) { err[22] = 1; err[0] = 1; }
            if (ddlProfundidadPulgadas.SelectedValue.Equals("")) { err[23] = 1; err[0] = 1; }
            if (CoordenadaX.Text.Equals("")) { err[24] = 1; err[0] = 1; }
            if (CoordenadaY.Text.Equals("")) { err[25] = 1; err[0] = 1; }
            if (RazonTrabajos.Text.Equals("")) { err[26] = 1; err[0] = 1; }
            if (Zona.Equals("")) { err[27] = 1; err[0] = 1; }
            if (BoUrbT.Text.Equals("")) { err[28] = 1; err[0] = 1; }

            if (SectorCalleT.Text.Equals("")) { err[29] = 1; err[0] = 1; }
            if (CarreteraT.Text.Equals("")) { err[30] = 1; err[0] = 1; }
            if (KM.Text.Equals("")) { err[31] = 1; err[0] = 1; }
            if (HM.Text.Equals("")) { err[32] = 1; err[0] = 1; }
            if (ddlMunicipioT.SelectedIndex.Equals(0)) { err[33] = 1; err[0] = 1; }
            if (CodigoPostalT.Text.Equals("")) { err[34] = 1; err[0] = 1; }
            if (Observaciones.Text.Equals("")) { err[35] = 1; err[0] = 1; }
            #endregion

            err[0] = 0; ////////////////////////////////// EAF /////////////////////////////////////////

            if (err[0] == 1)
            {
                ScriptManager.RegisterStartupScript(NumeroControl, this.GetType(), "Pop", "faltanrequeridos()", true);
            }
            else
            {
                string cs = ConfigurationManager.ConnectionStrings["EXC"].ConnectionString;
                using (SqlConnection conn = new SqlConnection(cs))
                {
                    using (SqlCommand cmd = new SqlCommand())
                    {
                        cmd.Connection = conn;
                        cmd.CommandType = CommandType.Text;

                        try
                        {
                            conn.Open();
                        }

                        catch (Exception ex)
                        {
                        }

                        #region Genera numero inspeccion si esta vacio
                        if (string.IsNullOrWhiteSpace(NumeroInspeccion.Text))
                        {
                            cmd.CommandText = @"SELECT TOP 1 NumeroInspeccion FROM Inspecciones ORDER BY NumeroInspeccion DESC";

                            using (SqlDataReader reader = cmd.ExecuteReader())
                            {
                                int col = 0;

                                while (reader.Read())
                                {
                                    NumeroInspeccion.Text = reader.GetString(col);
                                }

                                string[] numInspeccionSplit = NumeroInspeccion.Text.Split('-');

                                int numInpeccionCounter = Convert.ToInt32(numInspeccionSplit[1]);

                                NumeroInspeccion.Text = string.Format("2015-{0}", numInpeccionCounter + 1);
                            }
                        }
                        #endregion

                        cmd.Connection = conn;
                        cmd.CommandType = CommandType.Text;

                        cmd.CommandText = @"DELETE FROM Inspecciones WHERE NumeroInspeccion = @NumeroInspeccion AND TipoAviso = @TipoAviso;";

                        cmd.CommandText += "INSERT INTO Inspecciones VALUES (" +
                            "@NumeroInspeccion, @FechaVisita, @TipoInspeccionID, @EstatusInspeccionID, @PlacaInspector," +
                            " @NombreEmpresa, @RepresentanteAutorizado, @CorreoElectronico, @DireccionPostal, @TelOficina, " +
                            "@TelTrabajo, @Celular, @DireccionFisica, @NumeroControl, @ExisteAviso, @TipoTrabajo, @TipoAviso, " +
                            "@FechaComienzo, @FechaExpiracion, @LongitudPies, @LongitudPulgadas, @ProfundidadPies, @ProfundidadPulgadas, " +
                            "@CoordenadaX, @CoordenadaY, @RazonTrabajos, @Zona, @BoUrbT, @SectorCalleT, @CarreteraT, @KM, @HM, " +
                            "@MunicipioT, @CodigoPostalT, @Observaciones, @NombreInspector, @ImagePath)";

                        #region SQL params
                        cmd.Parameters.AddWithValue("@ImagePath", imgViewFile.ImageUrl);

                        cmd.Parameters.AddWithValue("@NumeroInspeccion", NumeroInspeccion.Text);
                        cmd.Parameters.AddWithValue("@FechaVisita", FechaVisita.Text);
                        cmd.Parameters.AddWithValue("@TipoInspeccionID", TipoInspeccionID);
                        cmd.Parameters.AddWithValue("@EstatusInspeccionID", EstatusInspeccionID);
                        cmd.Parameters.AddWithValue("@PlacaInspector", string.Format("{0}", PlacaInspector.Text));

                        cmd.Parameters.AddWithValue("@NombreInspector", string.Format("{0}", ddlInspector.SelectedValue));

                        cmd.Parameters.AddWithValue("@NombreEmpresa", NombreEmpresa.Text.ToUpper());
                        cmd.Parameters.AddWithValue("@RepresentanteAutorizado", RepresentanteAutorizado.Text.ToUpper());
                        cmd.Parameters.AddWithValue("@CorreoElectronico", CorreoElectronico.Text);
                        cmd.Parameters.AddWithValue("@DireccionPostal", DireccionPostal.Text.ToUpper());
                        cmd.Parameters.AddWithValue("@TelOficina", TelOficina.Text);
                        cmd.Parameters.AddWithValue("@TelTrabajo", TelTrabajo.Text);
                        cmd.Parameters.AddWithValue("@Celular", Celular.Text);

                        cmd.Parameters.AddWithValue("@DireccionFisica", DireccionFisica.Text.ToUpper());
                        cmd.Parameters.AddWithValue("@NumeroControl", NumeroControl.Text);
                        cmd.Parameters.AddWithValue("@ExisteAviso", ExisteAviso);
                        cmd.Parameters.AddWithValue("@TipoTrabajo", TipoTrabajo);
                        cmd.Parameters.AddWithValue("@TipoAviso", TipoAviso);
                        cmd.Parameters.AddWithValue("@FechaComienzo", FechaComienzo.Text);
                        cmd.Parameters.AddWithValue("@FechaExpiracion", FechaExpiracion.Text);
                        cmd.Parameters.AddWithValue("@LongitudPies", LongitudPies.Text);
                        cmd.Parameters.AddWithValue("@LongitudPulgadas", Int32.Parse(ddlLongitudPulgadas.SelectedValue));
                        cmd.Parameters.AddWithValue("@ProfundidadPies", ProfundidadPies.Text);
                        cmd.Parameters.AddWithValue("@ProfundidadPulgadas", Int32.Parse(ddlProfundidadPulgadas.SelectedValue));
                        cmd.Parameters.AddWithValue("@CoordenadaX", CoordenadaX.Text);
                        cmd.Parameters.AddWithValue("@CoordenadaY", CoordenadaX.Text);
                        cmd.Parameters.AddWithValue("@RazonTrabajos", RazonTrabajos.Text.ToUpper());
                        cmd.Parameters.AddWithValue("@Zona", Zona);
                        cmd.Parameters.AddWithValue("@BoUrbT", BoUrbT.Text.ToUpper());

                        cmd.Parameters.AddWithValue("@SectorCalleT", SectorCalleT.Text.ToUpper());
                        cmd.Parameters.AddWithValue("@CarreteraT", CarreteraT.Text.ToUpper());
                        cmd.Parameters.AddWithValue("@KM", KM.Text);
                        cmd.Parameters.AddWithValue("@HM", HM.Text);
                        cmd.Parameters.AddWithValue("@MunicipioT", ddlMunicipioT.SelectedValue.ToString());
                        cmd.Parameters.AddWithValue("@CodigoPostalT", CodigoPostalT.Text);
                        cmd.Parameters.AddWithValue("@Observaciones", Observaciones.Text.ToUpper());
                        #endregion

                        try
                        {
                            //conn.Open();
                            int recordsAffected = cmd.ExecuteNonQuery();
                            //if (recordsAffected == 1)
                            //{
                            Inspector inspector = new SolicitudesInicialesServicio().GetInspector(PlacaInspector.Text);

                            var to = new LinkedList<string>();

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

                            to.AddLast(inspector.CorreoElectronico);

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

                            //Update status solicitud
                            if (!string.IsNullOrWhiteSpace(inspector.NumeroPlacaID))
                            {
                                NumeroControl numControl = new Entidad.NumeroControl()
                                {
                                    NumControlText = NumeroInspeccion.Text
                                };

                                SolicitudAviso aviso = new SolicitudAviso();

                                if (TipoAviso.Equals(((int)SolicitudAviso.TiposExtensiones.Inicial).ToString()))
                                {
                                    #region update aviso inicial
                                    aviso = new SolicitudesInicialesServicio().GetSolicitud(numControl);

                                    aviso.EstatusId = aviso.EstatusId.Replace(new SolicitudAviso().LetraStatus, string.Empty);

                                    if (!aviso.EstatusId.Equals(((int)SolicitudAviso.Estatus.EnProcesoInspeccion).ToString())
                                        && !RB2.Checked)
                                    {
                                        aviso.EstatusId = new SolicitudAviso().LetraStatus + ((int)SolicitudAviso.Estatus.EnProcesoInspeccion).ToString();

                                        aviso.Inspector.Nombre = ddlInspector.SelectedValue;

                                        new SolicitudesInicialesServicio().TryUpdate(aviso);
                                        try
                                        {
                                            if (CheckForInternetConnection())
                                                SendEmail(to, "*****@*****.**",
                                                mails.ElementAt((int)Mail.Notifications.InspectorNuevoAviso).Subject,
                                                mails.ElementAt((int)Mail.Notifications.InspectorNuevoAviso).Body.Replace(
                                                "@NumControl", NumeroInspeccion.Text).Replace("@NombreEmpresa",
                                                NombreEmpresa.Text), new LinkedList<string>()); // only test
                                        }

                                        catch (Exception ex)
                                        { }
                                    }

                                    else if (aviso.EstatusId.Equals(((int)SolicitudAviso.Estatus.EnProcesoInspeccion).ToString())
                                        && RB2.Checked)
                                    {
                                        aviso.EstatusId = new SolicitudAviso().LetraStatus + ((int)SolicitudAviso.Estatus.InspeccionCompletada).ToString();

                                        //aviso.Inspector.Nombre = ddlInspector.SelectedValue;

                                        new SolicitudesInicialesServicio().TryUpdate(aviso);
                                    }
                                    #endregion
                                }

                                else if (TipoAviso.Equals(((int)SolicitudAviso.TiposExtensiones.Primera).ToString()))
                                {
                                    #region Update 1st ext
                                    aviso = new PrimerasExtensionesServicio().GetPrimeraExtension(numControl);

                                    aviso.EstatusId = aviso.EstatusId.Replace(new SolicitudAviso().LetraStatus, string.Empty);

                                    if (!aviso.EstatusId.Equals(((int)SolicitudAviso.Estatus.EnProcesoInspeccion).ToString())
                                        && !RB2.Checked)
                                    {
                                        aviso.EstatusId = new SolicitudAviso().LetraStatus + ((int)SolicitudAviso.Estatus.EnProcesoInspeccion).ToString();

                                        aviso.Inspector.Nombre = ddlInspector.SelectedValue;

                                        new PrimerasExtensionesServicio().TryUpdate(aviso);
                                        try
                                        {
                                            if (CheckForInternetConnection())
                                                SendEmail(to, "*****@*****.**",
                                                mails.ElementAt((int)Mail.Notifications.InspectorNuevoAviso).Subject,
                                                mails.ElementAt((int)Mail.Notifications.InspectorNuevoAviso).Body.Replace(
                                                "@NumControl", NumeroInspeccion.Text).Replace("@NombreEmpresa", NombreEmpresa.Text), new LinkedList<string>()); // only test
                                        }

                                        catch (Exception ex)
                                        { }
                                    }

                                    else if (aviso.EstatusId.Equals(((int)SolicitudAviso.Estatus.EnProcesoInspeccion).ToString())
                                           && RB2.Checked)
                                    {
                                        aviso.EstatusId = new SolicitudAviso().LetraStatus + ((int)SolicitudAviso.Estatus.InspeccionCompletada).ToString();

                                        new PrimerasExtensionesServicio().TryUpdate(aviso);
                                    }
                                    #endregion
                                }

                                else
                                {
                                    #region Update 2nd ext
                                    aviso = new SegundasExtensionesServicio().GetSegundaExtension(numControl);

                                    aviso.EstatusId = aviso.EstatusId.Replace(new SolicitudAviso().LetraStatus, string.Empty);

                                    if (!aviso.EstatusId.Equals(((int)SolicitudAviso.Estatus.EnProcesoInspeccion).ToString())
                                        && !RB2.Checked)
                                    {
                                        aviso.EstatusId = new SolicitudAviso().LetraStatus + ((int)SolicitudAviso.Estatus.EnProcesoInspeccion).ToString();

                                        aviso.Inspector.Nombre = ddlInspector.SelectedValue;

                                        new SegundasExtensionesServicio().TryUpdate(aviso);

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

                                        catch (Exception ex)
                                        { }
                                    }

                                    else if (aviso.EstatusId.Equals(((int)SolicitudAviso.Estatus.EnProcesoInspeccion).ToString())
                                           && RB2.Checked)
                                    {
                                        aviso.EstatusId = new SolicitudAviso().LetraStatus + ((int)SolicitudAviso.Estatus.InspeccionCompletada).ToString();

                                        new SegundasExtensionesServicio().TryUpdate(aviso);
                                    }
                                    #endregion
                                }
                                //}                                

                                Cancelar_Click(sender, e);
                            }
                        }
                        catch (SqlException)
                        {
                            ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "sqlerr()", true);
                        }
                        finally
                        {
                            conn.Close();
                        }
                    }
                }
            }

            Cancelar_Click(sender, e);
        }