viernes, 25 de agosto de 2017

SQL - Transacciones y errores

USE [leaseoper]
GO

/****** Object:  StoredProcedure [dbo].[pa_lo_sel_bienes_pozo_solicitud_reemplazo]    Script Date: 08/25/2017 17:43:58 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[pa_lo_sel_bienes_pozo_solicitud_reemplazo]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[pa_lo_sel_bienes_pozo_solicitud_reemplazo]
GO

USE [leaseoper]
GO

/****** Object:  StoredProcedure [dbo].[pa_lo_sel_bienes_pozo_solicitud_reemplazo]    Script Date: 08/25/2017 17:43:58 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

/*
-- =============================================
 Author:        Joel Castillo
 Create date: 25-08-2017
 Description: Obtiene bienes que pueden ser reemplazados   
 Ejecución:
            --salta error
            leaseoper..pa_lo_sel_bienes_pozo_solicitud_reemplazo 17
            --trae bienes
            leaseoper..pa_lo_sel_bienes_pozo_solicitud_reemplazo 333

 Utilizado en: /Paginas/AdmContratos/ReemplazoBienPorGarantia/SolicitudReemplazoBien.aspx
-- =============================================
*/
CREATE PROCEDURE [dbo].[pa_lo_sel_bienes_pozo_solicitud_reemplazo]
@operacion NUMERIC(20,0)
AS
BEGIN

BEGIN TRANSACTION
BEGIN TRY
----------------------------------------------
--VARIABLES
----------------------------------------------
DECLARE @estado_operacion TINYINT
       ,@msg_error VARCHAR(MAX)


----------------------------------------------
--VALIDACIONES
----------------------------------------------

SELECT @estado_operacion = ISNULL(estado_operacion,99)
FROM leaseoper..t_contratos
WHERE operacion = @operacion

IF(@estado_operacion NOT IN (1,2))
BEGIN 
--CAE AL CATCH
 RAISERROR('Operación debe estar Vigente...',16,1)
END

----------------------------------------------
--SALIDA
----------------------------------------------

SELECT d.cod_material
      ,d.num_material
      ,d.descripcion
      ,d.rut_proveedor
      ,d.num_factura
      ,d.fecha_compra_mat
      ,d.valor_libro_inicial_mat
      ,d.cod_est_mat
      ,d.cod_rubro
      ,d.cod_rubro_especifico
      ,(SELECT ISNULL(r.descripcion,'')
       FROM leasecom..p_rubros_especificos r
       WHERE r.cod_rubro = d.cod_rubro AND r.cod_rubro_especifico = d.cod_rubro_especifico) AS descripcion_rubro      
FROM  leaseoper..t_bienes_detalle d
WHERE operacion = @operacion


COMMIT TRANSACTION
END TRY
BEGIN CATCH
    ROLLBACK TRANSACTION
--RESCATA ERROR Y LO MUESTRA
    SET @msg_error = (SELECT CONVERT(varchar(max), ERROR_MESSAGE()))
     RAISERROR (@msg_error,16,1)
     RETURN
END CATCH
   
END

GO



miércoles, 23 de agosto de 2017

SQL - Insertar columna en tabla.-

USE leaseoper
GO

SELECT * FROM  leaseoper..t_correccion_estado_pago


/* Para evitar posibles problemas de pérdida de datos, debe revisar este script detalladamente antes de ejecutarlo fuera del contexto del diseñador de base de datos.*/
BEGIN TRANSACTION
SET QUOTED_IDENTIFIER ON
SET ARITHABORT ON
SET NUMERIC_ROUNDABORT OFF
SET CONCAT_NULL_YIELDS_NULL ON
SET ANSI_NULLS ON
SET ANSI_PADDING ON
SET ANSI_WARNINGS ON
COMMIT
BEGIN TRANSACTION
GO
CREATE TABLE dbo.Tmp_t_correccion_estado_pago
                (
                periodo int NOT NULL,
                fecha_proceso smalldatetime NOT NULL,
                operacion numeric(20, 0) NOT NULL,
                origen_docto tinyint NULL, --CAMPO NUEVO
                id_documento int NOT NULL,
                fecha_compra smalldatetime NULL,
                factor_rev float(53) NOT NULL,
                monto_total_documento float(53) NOT NULL,
                mto_reval_ejercicio float(53) NULL,
                mto_reval_total float(53) NULL,
                fecha_ingreso datetime NULL,
                estado tinyint NULL
                )  ON [PRIMARY]
GO
ALTER TABLE dbo.Tmp_t_correccion_estado_pago SET (LOCK_ESCALATION = TABLE)
GO
GRANT DELETE ON dbo.Tmp_t_correccion_estado_pago TO Usuarios  AS dbo
GO
GRANT INSERT ON dbo.Tmp_t_correccion_estado_pago TO Usuarios  AS dbo
GO
GRANT SELECT ON dbo.Tmp_t_correccion_estado_pago TO Usuarios  AS dbo
GO
GRANT UPDATE ON dbo.Tmp_t_correccion_estado_pago TO Usuarios  AS dbo
GO
IF EXISTS(SELECT * FROM dbo.t_correccion_estado_pago)
                EXEC('INSERT INTO dbo.Tmp_t_correccion_estado_pago (periodo, fecha_proceso, operacion, id_documento, fecha_compra, factor_rev, monto_total_documento, mto_reval_ejercicio, mto_reval_total, fecha_ingreso, estado)
                               SELECT periodo, fecha_proceso, operacion, id_documento, fecha_compra, factor_rev, monto_total_documento, mto_reval_ejercicio, mto_reval_total, fecha_ingreso, estado FROM dbo.t_correccion_estado_pago WITH (HOLDLOCK TABLOCKX)')
GO
DROP TABLE dbo.t_correccion_estado_pago
GO
EXECUTE sp_rename N'dbo.Tmp_t_correccion_estado_pago', N't_correccion_estado_pago', 'OBJECT'
GO
ALTER TABLE dbo.t_correccion_estado_pago ADD CONSTRAINT
                pk_t_correccion_estado_pago PRIMARY KEY CLUSTERED
                (
                periodo,
                id_documento
                ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]

GO
COMMIT
--Compruebo el cambio
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[t_correccion_estado_pago]') AND type in (N'U'))
SELECT * FROM  leaseoper..t_correccion_estado_pago



viernes, 11 de agosto de 2017

C# - Obtener el número menor de un arreglo

private int ObtenerMenorValor(int[] arrCorrelativo)
        {
            int rest = arrCorrelativo[0]; //resultado
            for (int n = 1; n < arrCorrelativo.Length; n++)
            {
                if (arrCorrelativo[n] < rest)
                {
                    rest = arrCorrelativo[n];
                }
            }

            return rest;
        }

//Llenado y declaracion del array 
 var arrCorrelativo = new int[gv.VisibleRowCount]; //inicializa el arreglo con el numero de datos en grilla
            for (int i = 0; i < gv.VisibleRowCount; ++i)
            {
                arrCorrelativo[i] = Convert.ToInt32(gv.GetRowValues(i, "correlativo_pago"));
            }



  var correlativoMasAntiguo = ObtenerMenorValor(arrCorrelativo);

viernes, 4 de agosto de 2017

C# - Obtener el máximo número (entity)

//previamente la tabla (con su respectiva PRIMARY KEY) debe estar incluida en el MODELO.


 private int NewCodJuzgado()
        {
            var newId = 0;
            using (var context = new leaOperModel())
            {
                newId = context.p_juzgados.Select(p => p.cod_juzgado).Max() + 1;
            }
            return newId;
        }

lunes, 31 de julio de 2017

viernes, 28 de julio de 2017

SQL - Ciclo While resumido en reemplazo de un cursor

DECLARE @contador INT
    SET @contador = 1
    WHILE (@contador <= 5)
    BEGIN
    PRINT CONVERT(VARCHAR(100),@contador)
    SET @contador = @contador + 1
    END
   

miércoles, 26 de julio de 2017

C# - enabled y seteo de valores a nivel de cliente.-

 <html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server"> 

    <script type="text/javascript" language="javascript">


 function EventoCheckPago(s, e) {
            var isTrue = s.GetValue();
            if (isTrue == true) {
                dteFechaPago.SetEnabled(true); 

                chkOrigenPago.SetChecked(false);
                ddlOrigenPago.SetValue(null);
                ddlOrigenPago.SetEnabled(false);

                chkRutProveedor.SetChecked(false);
                txtRutProveedor.SetValue("");
                txtRutProveedor.SetEnabled(false);
            } else {
                dteFechaPago.SetEnabled(false);
                dteFechaPago.SetValue(null);

                chkOrigenPago.SetChecked(false);
                ddlOrigenPago.SetValue(null);
                ddlOrigenPago.SetEnabled(false);

                chkRutProveedor.SetChecked(false);
                txtRutProveedor.SetValue("");
                txtRutProveedor.SetEnabled(false);
            }
        }

  </script>

</head>
<body>

</body>

 </html>

jueves, 13 de julio de 2017

C# - Devexpress Valor de una celda editable en grilla sea obligatorio


.ASPX
<dx:ASPxGridView ID="gvParent" runat="server" AutoGenerateColumns="False" Width="100%"
                        ClientInstanceName="gvParent" CssFilePath="~/App_Themes/DevEx/{0}/styles.css"
                        CssPostfix="DevEx" DataSourceID="odsParent" KeyFieldName="ID_COMPROMISO">
                        <Settings ShowFilterRow="true" />
                        <SettingsPager PageSize="25">
                        </SettingsPager>
                        <Columns>
                            <dx:GridViewCommandColumn Width="50px" ButtonType="Image" CellStyle-Font-Size="9px"
                                VisibleIndex="0" Caption=" ">
                                <EditButton Text="Editar" Image-Url="../../images/layer_edit.png" Visible="true">
                                    <Image Url="../../images/layer_edit.png">
                                    </Image>
                                </EditButton>
                                <CancelButton Text="Cancelar" Image-Url="../../images/cancelar.png" Visible="true">
                                    <Image Url="../../images/cancelar.png">
                                    </Image>
                                </CancelButton>
                                <UpdateButton Text="Grabar" Image-Url="../../images/save.png" Visible="false">
                                    <Image Url="../../images/save.png">
                                    </Image>
                                </UpdateButton>
                                <DeleteButton Text="true" Image-Url="../../images/map_remove.png" Visible="False">
                                    <Image Url="../../images/map_remove.png">
                                    </Image>
                                </DeleteButton>
                                <ClearFilterButton Visible="True" Image-Url="../../images/broom-icon.png">
                                    <Image Url="../../images/broom-icon.png">
                                    </Image>
                                </ClearFilterButton>
                                <CellStyle Font-Size="9px">
                                </CellStyle>
                            </dx:GridViewCommandColumn>
                            <dx:GridViewDataTextColumn FieldName="ID_COMPROMISO" VisibleIndex="3" Visible="False"
                                Caption="ID_COMPROMISO">
                            </dx:GridViewDataTextColumn>
                            <dx:GridViewDataComboBoxColumn Caption="MINUTA ASOCIADA" FieldName="ID_MINUTA" ToolTip="Para Ingresar Minutas vea --> Gestion Proyectos> Minutas"
                                VisibleIndex="2">
                                <PropertiesComboBox DataSourceID="odsMinuta" ValueField="ID_MINUTA" TextField="NOMBRE_MINUTA"
                                    IncrementalFilteringMode="StartsWith" Spacing="0">
                                </PropertiesComboBox>
                            </dx:GridViewDataComboBoxColumn>
                              <dx:GridViewDataMemoColumn FieldName="DESCRIPCION_COMPROMISO" VisibleIndex="2" ReadOnly="False"
                                Caption="COMPROMISO">
                                <PropertiesMemoEdit MaxLength="1000" Height="80px">
                                </PropertiesMemoEdit>
                            </dx:GridViewDataMemoColumn>
                            <dx:GridViewDataDateColumn FieldName="FECHA_INICIO_COMPROMISO" ShowInCustomizationForm="True"
                                VisibleIndex="3" Width="100px" Caption="FECHA INICIO COMP." HeaderStyle-HorizontalAlign="Center"
                                CellStyle-HorizontalAlign="Center">
                                <EditFormSettings Visible="True" />
                                <PropertiesDateEdit DisplayFormatString="dd/MM/yyyy">
                                </PropertiesDateEdit>
                                <HeaderStyle Wrap="False" />
                                <CellStyle Wrap="False">
                                </CellStyle>
                            </dx:GridViewDataDateColumn>
                            <dx:GridViewDataDateColumn FieldName="FECHA_COMPROMETIDA_COMPROMISO" ShowInCustomizationForm="True"
                                VisibleIndex="4" Width="100px" Caption="FECHA COMPROMETIDA COMP." HeaderStyle-HorizontalAlign="Center"
                                CellStyle-HorizontalAlign="Center">
                                <EditFormSettings Visible="True" />
                                <PropertiesDateEdit DisplayFormatString="dd/MM/yyyy">
                                </PropertiesDateEdit>
                                <HeaderStyle Wrap="False" />
                                <CellStyle Wrap="False">
                                </CellStyle>
                            </dx:GridViewDataDateColumn>
                            <dx:GridViewDataDateColumn FieldName="FECHA_REAL_TERMINO_COMPROMISO" ShowInCustomizationForm="True"
                                VisibleIndex="5" Width="100px" Caption="FECHA REAL TÉRMINO COMP." HeaderStyle-HorizontalAlign="Center"
                                CellStyle-HorizontalAlign="Center">
                                <EditFormSettings Visible="True" />
                                <PropertiesDateEdit DisplayFormatString="dd/MM/yyyy">
                                </PropertiesDateEdit>
                                <HeaderStyle Wrap="False" />
                                <CellStyle Wrap="False">
                                </CellStyle>
                            </dx:GridViewDataDateColumn>
                            <dx:GridViewDataMemoColumn FieldName="TIPO_COMPROMISO" VisibleIndex="7" ReadOnly="False"
                                Caption="TIPO COMPROMISO">
                                <PropertiesMemoEdit MaxLength="50" Height="80px">
                                </PropertiesMemoEdit>
                            </dx:GridViewDataMemoColumn>
                            <dx:GridViewDataComboBoxColumn FieldName="ESTADO" VisibleIndex="8">
                                <PropertiesComboBox ValueType="System.String" IncrementalFilteringMode="StartsWith"
                                    Spacing="0">
                                    <Items>
                                        <dx:ListEditItem Text="ACTIVO" Value="1" />
                                        <dx:ListEditItem Text="INACTIVO" Value="0" />
                                    </Items>
                                </PropertiesComboBox>
                            </dx:GridViewDataComboBoxColumn>
                        </Columns>
                        <SettingsBehavior AllowFocusedRow="true" />
                        <Images SpriteCssFilePath="~/App_Themes/DevEx/{0}/sprite.css">
                            <LoadingPanelOnStatusBar Url="~/App_Themes/DevEx/GridView/StatusBarLoading.gif">
                            </LoadingPanelOnStatusBar>
                            <LoadingPanel Url="~/App_Themes/Styles/img/icons/loading.gif">
                            </LoadingPanel>
                        </Images>
                        <ImagesFilterControl>
                            <LoadingPanel Url="~/App_Themes/Styles/img/icons/loading.gif">
                            </LoadingPanel>
                        </ImagesFilterControl>
                        <Styles CssPostfix="DevEx" CssFilePath="~/App_Themes/DevEx/{0}/styles.css">
                            <Header ImageSpacing="5px" SortingImageSpacing="5px">
                            </Header>
                            <LoadingPanel ImageSpacing="5px">
                            </LoadingPanel>
                        </Styles>
                        <StylesEditors ButtonEditCellSpacing="0">
                            <ProgressBar Height="21px">
                            </ProgressBar>
                        </StylesEditors>
                    </dx:ASPxGridView>



.CS 

  protected void Page_Init(object sender, EventArgs e)
        {
            gvParent.InitNewRow += gvParent_InitNewRow;
            gvParent.CustomCallback += GvParentCustomCallback;
            gvParent.RowValidating += GvParentRowValidating;
            gvParent.RowInserting += gvParent_RowInserting;
            gvParent.RowUpdating += gvParent_RowUpdating;
            gvParent.ParseValue += gvParent_ParseValue;
            gvParent.CustomErrorText += gvParent_CustomErrorText;

            odsMinuta.Selecting += odsMinuta_Selecting;

        }







 void GvParentRowValidating(object sender, DevExpress.Web.Data.ASPxDataValidationEventArgs e)
        {
            foreach (GridViewColumn column in gvParent.Columns)
            {
                var dataColumn = column as GridViewDataColumn;
                if (dataColumn == null) continue;
                switch (dataColumn.FieldName)
                {
                    case "ID_MINUTA":
                        if (e.NewValues["ID_MINUTA"] == null)
                        {
                            e.Errors[dataColumn] = "Campo requerido";
                        }
                        break;
                    case "DESCRIPCION_COMPROMISO":
                        if (e.NewValues["DESCRIPCION_COMPROMISO"] == null)
                        {
                            e.Errors[dataColumn] = "Campo requerido";
                        }
                        break;
                    case "FECHA_INICIO_COMPROMISO":
                        if (e.NewValues["FECHA_INICIO_COMPROMISO"] == null)
                        {
                            e.Errors[dataColumn] = "Campo requerido";
                        }
                        break;
                    case "FECHA_COMPROMETIDA_COMPROMISO":
                        if (e.NewValues["FECHA_COMPROMETIDA_COMPROMISO"] == null)
                        {
                            e.Errors[dataColumn] = "Campo requerido";
                        }
                        break;
                    case "TIPO_COMPROMISO":
                        if (e.NewValues["TIPO_COMPROMISO"] == null)
                        {
                            e.Errors[dataColumn] = "Campo requerido";
                        }
                        break;
                    case "ESTADO":
                        if (e.NewValues["ESTADO"] == null)
                        {
                            e.Errors[dataColumn] = "Campo requerido";
                        }
                        break;
                }
            }
        }

miércoles, 12 de julio de 2017

C# - BRANCHES para mantener distintas versiones de un mismo proyecto.-


Team Explorer > MiProyecto > Source Control
Mi Proyecto > Branche

Selecciono el proyecto que será enlazado.-


Y eligo el target.-

Para realizar MERGE, mismo procedimiento, pero seleccionando opcion MERGE.-