jueves, 21 de enero de 2016

SQL - Tabla Type

*Para enviar un DataTable desde el APP a SQL y tratarlo directamente.

/****************************CREA TABLA TYPE******************************/

USE miBD

CREATE TYPE [dbo].CargaMITABLAValidaType AS TABLE(
    [periodo] [int]  NULL,
[tipo_registro] [int]  NULL,
[fecha_proceso] [smalldatetime] NOT NULL
)

/**************************FIN CREA TABLA TYPE******************************/


/*************************SP QUE USA TABLA TYPE*************************/


/****** Object:  StoredProcedure [dbo].[pa_lo_valida_edicion_c13]    Script Date: 01/20/2016 18:39:43 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/* =============================================
-- Author: JC
-- Create date: 20-01-2016
-- Description: Valida que los campos ingresados en informe

declare @cod_error INT
declare @desc_error varchar(500)
declare @miTabla CargaMITABLAValidaType
insert into @miTabla VALUES (201601,2,'20150102')
--select * FROM @miTabla
exec pa_lo_valida_edicion @miTabla , @cod_error OUTPUT, @desc_error OUTPUT
--select @cod_error, @desc_error


-- =============================================
*/
CREATE PROCEDURE [dbo].[pa_lo_valida_edicion]
@miTabla AS CargaMITABLAValidaType  READONLY ,
@cod_error INT OUTPUT ,
@desc_error VARCHAR(500) OUTPUT
AS
BEGIN
--variables de recorido
DECLARE @periodo [int] ,
@tipo_registro [int] ,
@fecha_proceso [smalldatetime]


--tabla de validaciones
CREATE TABLE #validaciones
(
 [periodo] [int] NOT NULL ,
 [tipo_registro] [int] NOT NULL ,
 [fecha_proceso] [smalldatetime] NOT NULL ,

)
--cursor de recorrido - VALIDACIONES
DECLARE c_valida CURSOR LOCAL
FOR
SELECT periodo ,
tipo_registro ,
fecha_proceso ,
FROM @miTabla

OPEN c_valida
FETCH c_valida INTO @periodo, @tipo_registro,@fecha_proceso
--
WHILE ( @@FETCH_STATUS = 0 )
BEGIN -- Inicio Ciclo

-- Seteo varaiables con valores OK
SELECT @cod_error = 0 ,
@desc_error = 'OK'
--Validaciones
IF ( @periodo <> '2016'
  )
BEGIN
SELECT @cod_error = 1 ,
@desc_error = 'Mensaje de Error Aquí'
END



-- fin ciclo
INSERT INTO #validaciones
VALUES ( @periodo, @tipo_registro, @fecha_proceso,
@cod_error,
 @desc_error )


FETCH c_valida INTO @periodo, @tipo_registro,
@fecha_proceso
END
CLOSE c_valida
DEALLOCATE c_valida


SELECT error,desc_error FROM #validaciones

END

GO





/*************************FIN SP QUE USA TABLA TYPE*************************/


/*************************DAC llamada desde .NET C#*************************/

public DataTable ValidaEdicionC13(DataTable dt)
        {
            Database db = DatabaseFactory.CreateDatabase("LeaseOper"); //enterprise library 5.0
            var ds = new DataSet();
            var retorno = false;
            var dataTable = new DataTable();
            try
            {
                using (var cnxx = new SqlConnection(db.ConnectionString))
                {
                    SqlCommand cmd = new SqlCommand("pa_lo_valida_edicion", cnxx);
                    cmd.CommandType = CommandType.StoredProcedure;

                    SqlParameter tvparam = cmd.Parameters.AddWithValue("@miTabla", dt);

                    tvparam.SqlDbType = SqlDbType.Structured;
               
                    db.AddOutParameter(cmd, "@cod_error", DbType.Int32, int.MaxValue);
                    db.AddOutParameter(cmd, "@desc_error", DbType.String, int.MaxValue);

                    cmd.Connection.Open();
                    SqlDataAdapter theDataAdapter = new SqlDataAdapter(cmd);

                    //los rescato pero no los estoy usando
                    var codError = db.GetParameterValue(cmd, "@cod_error");
                    var desError = db.GetParameterValue(cmd, "@desc_error");

                    theDataAdapter.Fill(ds);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            if (ds.Tables[0].Rows.Count > 0)
                return ds.Tables[0];
            return dataTable;
        }

/*************************.CS llamada desde .NET C# con JQUERY*************************/
 [WebMethod]
        public static string GeneraCuponera(object rows, string idDoc)
        {
            try
            {
                DataTable dt = new DataTable();
                dt.Columns.Add("operacion", typeof(decimal));
                dt.Columns.Add("cod_material", typeof(int));

                string json = new JavaScriptSerializer().Serialize(rows);
                dynamic selectedRows = JsonConvert.DeserializeObject(json);

                foreach (dynamic rowGrid in selectedRows)
                {
                    DataRow rowDt = dt.NewRow();
                    rowDt["operacion"] = Convert.ToDecimal(rowGrid.operacion);
                    rowDt["cod_material"] = Convert.ToDecimal(rowGrid.cod_material);

                    dt.Rows.Add(rowDt);

                }
                var retorno = new BcCuponeras().GeneraCuponera(dt);
                return JsonConvert.SerializeObject(retorno);
            }
            catch (Exception ex)
            {
                var err = JsonConvert.SerializeObject(ex.Message);
                return err;
            }

        }


miércoles, 20 de enero de 2016

C# - retorno de DataSet desde consulta al Entity Framework / Convertir lista a DataTable

  public DataSet SelectbyPeriodoExcel(int periodo, ref string msj)
        {
            var ds = new DataSet();
            DataTable dt = new DataTable();
            try
            {
                using (var context = new leaOperModel())
                {
                    var dtContex = context.t_c13.Where(p => p.periodo == periodo).ToList();
                    // obj.AddRange(dtContex.Select(C13Be.DbToBe));
                    dt = ConvertToDataTable(dtContex);
                    ds.Tables.Add(dt);
                }
            }
            catch (Exception ex)
            {
                msj = ex.Message;
            }
            return ds;
            //return obj.ToList();
        }



 public DataTable ConvertToDataTable<T>(IList<T> data)
        {
            PropertyDescriptorCollection properties =
               TypeDescriptor.GetProperties(typeof(T));
            DataTable table = new DataTable();
            foreach (PropertyDescriptor prop in properties)
                table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
            foreach (T item in data)
            {
                DataRow row = table.NewRow();
                foreach (PropertyDescriptor prop in properties)
                    row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
                table.Rows.Add(row);
            }
            return table;

        }

C# - Remover columnas de un DataTable

 DataTable dt = ds.Tables[0];

                     if (dt.Columns.Contains("periodo"))
                    dt.Columns.Remove("periodo");

                     if (dt.Columns.Contains("EntityState"))
                    dt.Columns.Remove("EntityState");

                     if (dt.Columns.Contains("EntityKey"))
                    dt.Columns.Remove("EntityKey");

lunes, 11 de enero de 2016

C# - Solo letras con control textbox asp y javascript


1. Método solo letras.


//Solo número
 function SoloLetras(e) {
                key = e.keyCode || e.which;
                tecla = String.fromCharCode(key).toLowerCase();
                letras = " áéíóúabcdefghijklmnñopqrstuvwxyz";
              //  letras = " áéíóúabcdefghijklmnñopqrstuvwxyz0123456798-"; pueden ser letras o cualquier caracter
                especiales = "8-37-39-46";

                tecla_especial = false;
                for (var i in especiales) {
                    if (key == especiales[i]) {
                        tecla_especial = true;
                        break;
                    }
                }

                if (letras.indexOf(tecla) == -1 && !tecla_especial) {
                    return false;
                }
            }

2. Agregar la function como atributo en el control requerido en evento Page_Init() o Page_Load() de la página, como en el ejemplo de la Imagen. (poner SoloLetras(event))



 protected void Page_Init(object sender, EventArgs e)
    {
        this.txtRut.Attributes.Add("OnKeyPress", "return SoloLetras(event)");
    }



jueves, 7 de enero de 2016

JQuery - Tag

El tag:

 <!--#include file="~/Scripts/jquery.includes.htm"-->

siempre debe estar incluido dentro de la página .asxp para poder hacer referencia a las bibliotecas Jquery.



miércoles, 30 de diciembre de 2015

C# - Insert/Update/Select/SP con Enterprise Library

/********************************INSERT/UPDATE***************************/
public bool GrabaNominaPagoProveedorEnc(BeNominaPagoProveedorEncabezado obj)
        {
            try
            {
                //BeNominaPagoProveedorEncabezado
                var result = false;
                var upd = 0;
                var ins = 0;
                Database db = DatabaseFactory.CreateDatabase("LeaseOper");

                //intento actualizar, de no haber filas afectadas inserto.
                DbCommand command = db.GetSqlStringCommand("UPDATE dbo.t_nomina_pago_proveedor_enc SET numero_nomina = @numero_nomina ,fecha_nomina = @fecha_nomina ,total_nomina = @total_nomina ,envio_contab = @envio_contab ,cod_usuario = @envio_contab,fecha_ingreso_reg = @fecha_ingreso_reg,estado = @estado WHERE numero_nomina = @numero_nomina");
                db.AddInParameter(command, "@numero_nomina", DbType.Int32, obj.NumeroNomina);
                db.AddInParameter(command, "@fecha_nomina", DbType.DateTime, obj.FechaNomina);
                db.AddInParameter(command, "@total_nomina", DbType.Single, obj.TotalNomina);
                db.AddInParameter(command, "@envio_contab", DbType.Int32, obj.EnvioContab);
                db.AddInParameter(command, "@cod_usuario", DbType.Int32, obj.CodUsuario);
                db.AddInParameter(command, "@fecha_ingreso_reg", DbType.DateTime, obj.FechaIngreso);
                db.AddInParameter(command, "@estado", DbType.Int16, obj.Estado);

                upd = db.ExecuteNonQuery(command);

                if (upd == 0)
                {
                    command =
                        db.GetSqlStringCommand(
                            "INSERT INTO dbo.t_nomina_pago_proveedor_enc ( numero_nomina ,fecha_nomina ,total_nomina ,envio_contab ,cod_usuario ,fecha_ingreso_reg ,estado) VALUES ( @numero_nomina ,@fecha_nomina ,@total_nomina ,@envio_contab ,@cod_usuario ,@fecha_ingreso_reg ,@estado)");
                    db.AddInParameter(command, "@numero_nomina", DbType.Int32, obj.NumeroNomina);
                    db.AddInParameter(command, "@fecha_nomina", DbType.DateTime, obj.FechaNomina);
                    db.AddInParameter(command, "@total_nomina", DbType.Single, obj.TotalNomina);
                    db.AddInParameter(command, "@envio_contab", DbType.Int32, obj.EnvioContab);
                    db.AddInParameter(command, "@cod_usuario", DbType.Int32, obj.CodUsuario);
                    db.AddInParameter(command, "@fecha_ingreso_reg", DbType.DateTime, obj.FechaIngreso);
                    db.AddInParameter(command, "@estado", DbType.Int16, obj.Estado);

                    ins = db.ExecuteNonQuery(command);
                }
                //compruebo si hubo actualización o inserción
                if (upd > 0 || ins > 0)
                    result = true;

                //cierro las conexiones
                command.Connection.Close();
                command.Connection.Dispose();
                //devuelvo el resultado
                return result;
            }
            catch (Exception ex)
            {

                return false;
            }
        }

/********************************SELECT***************************/
   public DataTable SelectReqPagoDetalle(int numeroReq)
        {
            DataSet ds = new DataSet();
            var dt = new DataTable();
            try
            {
                var result = false;
                var upd = 0;
                var ins = 0;
                Database db = DatabaseFactory.CreateDatabase("LeaseOper");

                //intento actualizar, de no haber filas afectadas inserto.
                DbCommand command =
                    db.GetSqlStringCommand(
                        "SELECT corrrelativo ,num_req ,monto ,rut_beneficiario ,digito ,nombre_beneficiario ,modo_pago ,cod_inst_financ ,cta_cte ,cod_sucursal ,cuenta_contable ,observacion ,envio_contab ,envio_banco ,fecha_envio_banco ,usuario_envio_banco ,fecha_ingreso_reg ,estado FROM  leaseoper..t_req_pago_detalle WHERE num_req = @num_req");
                db.AddInParameter(command, "@num_req", DbType.Int32, numeroReq);

                ds = db.ExecuteDataSet(command);

                command.Connection.Close();
                command.Connection.Dispose();
            }
            catch (Exception ex)
            {
                throw ex;
            }
         
            if (ds != null && ds.Tables.Count > 0)
            {
                dt = ds.Tables[0];
            }
            return dt;
        }

/********************************SP*************************************/

 public DataTable ValidayCargaExcelDetalleAnticipo(int idAnticipo, Int16 tipoProceso, DataTable dt)
        {
            Database db = DatabaseFactory.CreateDatabase("LeaseOper");
            var ds = new DataSet();
            var retorno = false;
            var dataTable = new DataTable();
            try
            {
                using (var cnxx = new SqlConnection(db.ConnectionString))
                {
                    SqlCommand cmd = new SqlCommand("pa_lo_valida_y_carga_det_insc_trans", cnxx);
                    cmd.CommandType = CommandType.StoredProcedure;                
               

                    db.AddInParameter(cmd, "@id_anticipo", DbType.Int32, idAnticipo);
                    db.AddInParameter(cmd, "@tipo_proceso", DbType.Int16, tipoProceso);
                    db.AddOutParameter(cmd, "@cod_error", DbType.Int32, int.MaxValue);
                    db.AddOutParameter(cmd, "@desc_error", DbType.String, int.MaxValue);

                    cmd.Connection.Open();
                    SqlDataAdapter theDataAdapter = new SqlDataAdapter(cmd);

                    //var mensaje = db.GetParameterValue(cmd, "@cod_error");
                    //var codigoRespuesta = db.GetParameterValue(cmd, "@desc_error");

                    theDataAdapter.Fill(ds);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            if (ds.Tables[0].Rows.Count > 0)
                return ds.Tables[0];
            return dataTable;
        }

miércoles, 9 de diciembre de 2015

C# - Gif cargando al presionar botón

//previo al update panel de la pagina.
<div class="centrar">
        <asp:UpdatePanel ID="udpanel" runat="server">
            <ContentTemplate>
                <dx:ASPxButton ID="btnLoad" runat="server" ClientInstanceName="btnLoad" Text="" ClientVisible="false"
                    AutoPostBack="true" OnClick="btnLoad_Click">
                </dx:ASPxButton>
                <asp:UpdateProgress ID="UpdateProgress1" runat="server">
                    <ProgressTemplate>
                        <table width="100%" border="0" cellpadding="0" cellspacing="0" class="bonder">
                            <tr>
                                <td colspan="3">&nbsp;
                                 
                                </td>
                            </tr>
                            <tr>
                                <td width="30">&nbsp;
                                 
                                </td>
                                <td align="center">
                                    <table width="100%" border="0" cellpadding="0" cellspacing="0" class="td-colum">
                                        <tr>
                                            <td align="center" style="color: white; font-weight: bold">
                                                Cargando
                                            </td>
                                        </tr>
                                        <tr>
                                            <td align="center">
                                                <dx:ASPxImage ID="ASPxImage1" runat="server" ImageUrl="~/Images/carga.gif" Width="160px"
                                                    Height="24">
                                                </dx:ASPxImage>
                                            </td>
                                        </tr>
                                    </table>
                                </td>
                                <td width="30">&nbsp;
                                 
                                </td>
                            </tr>
                            <tr>
                                <td colspan="3">&nbsp;
                                 
                                </td>
                            </tr>
                        </table>
                    </ProgressTemplate>
                </asp:UpdateProgress>
            </ContentTemplate>
        </asp:UpdatePanel>
    </div>
  <asp:UpdatePanel ID="UpdatePanel1" runat="server">
//contenido, eventos y botones de la página
 </asp:UpdatePanel>

miércoles, 2 de diciembre de 2015

C# - DEVEXPRESS Evitar que una grilla se llene por primera vez

//PAGE INIT , la grilla tiene un evento selecting, con este evento se puede cancelar la carga la primera vez.

 protected void Page_Init(object sender, EventArgs e)
        {
            ObjDataDocumentos.Selecting += ObjDataSourceDocumentos_Selecting;      
         
        }


//dentro de este evento cancelo la carga si es la primera vez que entro a la pantalla
  void ObjDataSourceDocumentos_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
        {
            if (IsPostBack)
            {
                e.InputParameters["todos"] = Convert.ToByte(chkTodos.Checked == true ? 1 : 0);            
            }
            else
            {
                e.Cancel = true;
            }
        }

martes, 1 de diciembre de 2015

SQL - Tablas con registros en la Base de Datos

--USE BASE_DE_DATOS
SET NOCOUNT ON DBCC UPDATEUSAGE(0) -- DB size.
--EXEC sp_spaceused-- Table row counts and sizes.
CREATE TABLE #t (     [name] NVARCHAR(128),  
 [rows] CHAR(11),  
 reserved VARCHAR(18),    
 data VARCHAR(18),    
 index_size VARCHAR(18),  
 unused VARCHAR(18))
INSERT #t EXEC sp_msForEachTable 'EXEC sp_spaceused ''?'''
SELECT 'TABLAS CON MAS DE UN REGISTRO',* FROM   #t WHERE rows > 0   -- # of rows.
SELECT COUNT(*) AS tablas_con_datos FROM   #t WHERE rows > 0
DROP TABLE #t