miércoles, 27 de diciembre de 2017

update left join

Update t 
SET 
       t.Column1=100
FROM 
       myTableA t 
LEFT JOIN 
       myTableB t2 
ON 
       t2.ID=t.ID
fuente: https://stackoverflow.com/questions/6335388/update-and-left-outer-join-statements

martes, 26 de diciembre de 2017

Validar números TextBox

If String.IsNullOrEmpty(tbnumber.Text.Trim("0")) Then
            tbnumber.Clear()
            MessageBox.Show("Ingrese un valor mayor que cero")

            Exit Sub
        Else
            Dim number As Long = 0
            Dim result As Boolean = Int64.TryParse(tbnumber.Text.Trim, number)

            If Not result Then
                MessageBox.Show("Número no válido")
            Else
                tbnumber.Text = tbnumber.Text.TrimStart("0")
            End If

            MessageBox.Show(result)
        End If

Deshabilitar copiar-pegar en un TextBox

Propiedades
ShortcutsEnabled = False

martes, 19 de diciembre de 2017

viernes, 15 de diciembre de 2017

Servicio modo debug

Service1.Designer.vb

#If DEBUG Then
        Dim x As New Service1
        x.Ondebug()
#Else
#End If




' The main entry point for the process
    <MTAThread()> _
    <System.Diagnostics.DebuggerNonUserCode()> _
    Shared Sub Main()

#If DEBUG Then
        Dim debug_service As New Service1
        debug_service.Ondebug()
#Else


        Dim ServicesToRun() As System.ServiceProcess.ServiceBase

        ' More than one NT Service may run within the same process. To add
        ' another service to this process, change the following line to
        ' create a second service object. For example,
        '
        '   ServicesToRun = New System.ServiceProcess.ServiceBase () {New Service1, New MySecondUserService}
        '
        ServicesToRun = New System.ServiceProcess.ServiceBase() {New Service1}

        System.ServiceProcess.ServiceBase.Run(ServicesToRun)
#End If
    End Sub

miércoles, 13 de diciembre de 2017

Crear directorio

Try
            Directory.CreateDirectory("nombreDirectorio")
        Catch ex As Exception
            MessageBox.Show(ex.ToString())
        End Try

jueves, 30 de noviembre de 2017

Acerca de...

Imports System.Windows.Forms
Imports System.Runtime.InteropServices

Public Class Form1

    Private Const WM_SYSCOMMAND As Integer = 274
    Private Const MF_STRING As Integer = 0
    Private Const MF_SEPARATOR As Integer = 2048

    <DllImport("user32.dll", CharSet:=CharSet.Auto, SetLastError:=True)>
    Private Shared Function GetSystemMenu(ByVal hWnd As IntPtr, ByVal bRevert As Boolean) As IntPtr
    End Function
    <DllImport("user32.dll", CharSet:=CharSet.Auto, SetLastError:=True)>
    Private Shared Function AppendMenu(ByVal hMenu As IntPtr, ByVal uFlags As Integer, ByVal uIDNewItem As Integer, ByVal lpNewItem As String) As Boolean
    End Function
    <DllImport("user32.dll", CharSet:=CharSet.Auto, SetLastError:=True)>
    Private Shared Function InsertMenu(ByVal hMenu As IntPtr, ByVal uPosition As Integer, ByVal uFlags As Integer, ByVal uIDNewItem As Integer, ByVal lpNewItem As String) As Boolean
    End Function

    Private SYSMENU_ABOUT_ID As Integer = 1

    Public Sub CustomForm()
    End Sub

    Protected Overrides Sub OnHandleCreated(ByVal e As EventArgs)
        MyBase.OnHandleCreated(e)
        Dim hSysMenu As IntPtr = GetSystemMenu(Me.Handle, False)
        AppendMenu(hSysMenu, MF_SEPARATOR, 0, String.Empty)
        AppendMenu(hSysMenu, MF_STRING, SYSMENU_ABOUT_ID, "&About…")
    End Sub

    Protected Overrides Sub WndProc(ByRef m As Message)
        MyBase.WndProc(m)
        If (m.Msg = WM_SYSCOMMAND) AndAlso (CInt(m.WParam) = SYSMENU_ABOUT_ID) Then
            MessageBox.Show("Custom About Dialog")
        End If
    End Sub
End Class



fuente: https://stackoverflow.com/questions/4615940/how-can-i-customize-the-system-menu-of-a-windows-form

miércoles, 29 de noviembre de 2017

Limpiar un arreglo (array)

Dim readtext() As String = File.ReadAllLines("archivo.txt")
Array.Clear(readtext, 0, readtext.Length)

fuente: https://stackoverflow.com/questions/713867/what-is-the-best-way-to-clear-an-array-of-strings

ReDim readtext(0)

ReDim Preserve

Erase array fuente

martes, 28 de noviembre de 2017

Factura de exportación electrónica

RLV - DTE Aceptado con Reparos Leves
(HED-1-835) Export.: desde el 01-12-2017 sera obligatorio informar en la seccion <OtraMoneda> el <TpoMoneda> con valor "PESO CL"

Ejemplo:
<Totales>
  <TpoMoneda>DOLAR USA</TpoMoneda>
  <MntExe>52974</MntExe>
  <MntTotal>52974</MntTotal>
</Totales>
<OtraMoneda>
  <TpoMoneda>PESO CL</TpoMoneda>
  <TpoCambio>630.41</TpoCambio>
  <MntExeOtrMnda>33395339.34</MntExeOtrMnda>
  <MntTotOtrMnda>33395339.34</MntTotOtrMnda>
</OtraMoneda>

lunes, 20 de noviembre de 2017

jueves, 16 de noviembre de 2017

Quitar los caracteres de un string función Replace

'fecha = data(j + 23)
 'fecha = fecha.Replace(".", String.Empty)



Formato fecha y hora para sql 2005 y sql 2008

declare @dateserver varchar(20)
set @dateserver = CONVERT(varchar(10), GETDATE(), 121)
print @dateserver

2017-11-16

DECLARE @horacreacion VARCHAR(8)
SET @horacreacion = CONVERT(VARCHAR(8), GETDATE(), 108)
print @horacreacion

16:17:12


Sólo consulta
SELECT CONVERT(VARCHAR(10), GETDATE(),120)
SELECT GETDATE()

declare @dateserver varchar(20)
set @dateserver = dateadd(day,45,CAST(GETDATE() AS DATE))
print @dateserver  --imprime yyyy-MM-dd

fuente



Estilos de fecha:
https://docs.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql




Cambiar nombre a proyecto en visual net

https://www.youtube.com/watch?v=SjGCfj04WoM

Volver al icono por defecto en WindowsForm

Properties
Icon
click botón derecho mouse
seleccionar Reset

TreeView para opciones

Public Class Form1


    Private f As Form
 
    Private Sub TreeView1_AfterSelect(ByVal sender As System.Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles TreeView1.AfterSelect

        Dim node As TreeNode = TreeView1.SelectedNode

        Select Case node.Text

            Case "General"
                'general.TextBox1.Enabled = False
                f.Dispose()
                f = New general()
                f.TopLevel = False
                Me.Panel1.Controls.Add(f)
                f.Dock = DockStyle.Fill
                f.Show()



            Case "Factura electrónica"
                f.Dispose()
                f = New fa()
                f.TopLevel = False
                Me.Panel1.Controls.Add(f)
                f.Dock = DockStyle.Fill
                f.Show()
            Case "Nota de credito"
                f.Dispose()
                f = New nc()
                f.TopLevel = False
                Me.Panel1.Controls.Add(f)
                f.Dock = DockStyle.Fill
                f.Show()


        End Select

    End Sub

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load



        'TreeView1.HideSelection = True
        TreeView1.TabIndex = 0

        f = New general()
        f.TopLevel = False
        Me.Panel1.Controls.Add(f)
        f.Dock = DockStyle.Fill
        f.Show()
    End Sub
End Class

no copiar,pegar,seleccionar en TextBox

ShortcutsEnabled = False

Bloquear cursor TextBox

Imports System.Runtime.InteropServices

Public Class general

    <DllImport("user32")> _
    Private Shared Function HideCaret(ByVal hWnd As IntPtr) As Integer
    End Function

    Private Sub TextBox1_GotFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.GotFocus
        HideCaret(TextBox1.Handle)
    End Sub

    Private Sub general_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        TextBox1.Cursor = Cursors.Arrow
    End Sub
End Class

miércoles, 15 de noviembre de 2017

Cantidad de decimales


 Dim n As Double = 56.7865
  n = n.ToString("N3")
  n = Math.Round(n, 3)


fuente: https://stackoverflow.com/questions/16209509/what-is-tostringn0-format

Limpiar un TextBox

TextBox1.Clear()

viernes, 10 de noviembre de 2017

Eliminar índice de una tabla

DROP INDEX nombre_indice on dbo.DTE_recibos

Consultar si existe un índice en una tabla

IF EXISTS (select * from sys.indexes where object_id = (select object_id from sys.objects where name = 'DTE_recibos') and name ='fecha_emision')
print 'ok'
else
print 'bad'


IF EXISTS (SELECT * FROM sys.indexes WHERE
object_id = (SELECT object_id FROM sys.objects WHERE name = 'DTE_recibos') AND name ='fecha_emision')
BEGIN
DROP INDEX fecha_emision on dbo.DTE_recibos
END
ELSE
BEGIN
print '435345'
END

jueves, 9 de noviembre de 2017

Fórmula modulo

x % y = x - (10 * (x/10))  <-- fórmula para el modulo

z = x - (10 * (x/10))
if z = 0  then montoNeto
if z <= 5 then montoNeto - z
if z >= 6 then montoNeto + (10-z)

miércoles, 8 de noviembre de 2017

Borrar procedimiento almacenado pasando el nombre por variable

declare @sp varchar(1000)
set @sp ='DROP PROCEDURE ' + 'SP_name'
print @sp
exec(@sp)

obtener el nombre de la base de datos y guardar en una variable

declare @p varchar(10) = db_name()
print @p

Ingresar a certificación servicio de impuestos internos


  1. Ingresar a la página del servicio de impuestos internos
  2. Servicios online
  3. Factura electrónica
  4. Sistema de facturación de mercado
  5. Menú postulantes
  6. Ambiente de certificación y prueba

lunes, 6 de noviembre de 2017

Extraer string con expresiones regulares

Dim rgx As New Regex("GO")
Dim j As Long = rgx.Match(sp).Index ' donde inicia
Dim fin As Long = string.Length
Dim match As Match = rgx.Match(string)
If match.Success Then
Dim i As Integer = match.Index
Dim st As String = string.Substring(i, fin - i)
End If

martes, 31 de octubre de 2017

Cambiar el valor en un ComboBox y asignarlo a la barra de título

Private Sub cbdte_SelectedValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cbdte.SelectedValueChanged
        Me.Text = cbdte.SelectedItem
    End Sub

Borrar elementos de un ComboBox

ComboBox.Items.Clear()

Escribir en un archivo txt

Dim wr As New StreamWriter("clientes.txt", True, System.Text.Encoding.UTF8)
wr.Close()

True ---> adjuntar-agrega líneas
False--->crea un archivo nuevo y agrega una línea

Remover fila DataGridView


If DataGridView.Rows.Count > 0 Then
     DataGridView.Rows.Remove(DataGridView.CurrentRow)
End If

Escribir en un archivo txt

Dim dataconfig() As String = File.ReadAllLines("config.txt", Encoding.UTF8)
System.IO.File.WriteAllLines("config.txt", dataconfig, Encoding.UTF8)

Posicionarse en una celda

DataGridView.CurrentCell = DataGridView(e.ColumnIndex + 1, e.RowIndex)


dgv1.CurrentCell = dgv1(columna, fila)

Leer archivo de texto

Dim readtext() As String = File.ReadAllLines("archivo.txt", Encoding.UTF8)

lunes, 30 de octubre de 2017

Detectar tecla Enter en un TextBox

private void input_KeyDown(object sender, KeyEventArgs e)
{                       
    if(e.KeyData == Keys.Enter) 
    { 
        MessageBox.Show("Pressed enter."); 
    }           
}

Sumar días a un DateTimePicker

Dim x As String = DateTimePicker1.Value.AddDays(1).ToString("yyyy-MM-dd")

miércoles, 25 de octubre de 2017

Llamar al evento DataGridView_CellClick desde un botón

e = New DataGridViewCellEventArgs(col, row)
                    dgvtotales_CellClick(Nothing, e)

private void kryptonbtnEdit_Click(object sender, EventArgs e)
{
    //set parameters of your event args
    var eventArgs = new DataGridViewCellEventArgs(yourColumnIndex, yourRowIndex);

    // or setting the selected cells manually before executing the function
    kryptonDataGridView1.Rows[yourRowIndex].Cells[yourColumnIndex].Selected = true;

    kryptonDataGridView1_CellDoubleClick(sender, eventArgs);
}
fuente: https://stackoverflow.com/questions/27838861/how-to-call-a-datagridview-event-with-a-click-of-a-button

jueves, 19 de octubre de 2017

Obtener el nombre de la base de datos

Public Function returndb(ByVal conex As String) As String
        Dim data() As String = conex.Split(";")
        Dim db As String = ""
        For Each rd As String In data
            If rd.Contains("atalog") Then
                db = rd.Split("=")(1)
                Exit For
            End If
        Next
        Return db
    End Function

martes, 17 de octubre de 2017

Obtener la fila y columna seleccionada

Dim var As Integer =  dgv1.CurrentCell.RowIndex
Dim var As Integer =  dgv1.CurrentCell.ColumnIndex

Dim i As Integer = DataGridView1.CurrentRow.Index



viernes, 13 de octubre de 2017

DataGridView opciones


Cambiar el colo azul de seleccion que viene por defecto:
dgv.DefaultCellStyle.SelectionBackColor = Color.Yellow



AllowUserToResizeRow = False
SelectionMode = FullRowSelect
RowHeadersVisible = False

Cambiar el color de la cabecera:
dgv.ColumnHeadersDefaultCellStyle.BackColor = Color.LightSkyBlue

Properties:
EnableHeaderVisualStyles: False


Centrar el nombre de todas columnas:
 'Dim dgvColumnHeaderStyle As New DataGridViewCellStyle()
 'dgvColumnHeaderStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
 'dgv.ColumnHeadersDefaultCellStyle = dgvColumnHeaderStyle


Centrar el nombre de una columna:
dgv.Columns("Column1").HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter


fuente:
https://stackoverflow.com/questions/4550836/how-can-i-center-the-heading-in-a-column-on-a-datagridview

miércoles, 11 de octubre de 2017

Verificar si existe un procedimiento almacenado

IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'SP_ver_rcv')
BEGIN
DROP PROCEDURE SP_ver_rcv
END
GO
CREATE PROCEDURE SP_ver_rcv
AS
BEGIN...
.
.
.

fuente: https://msdn.microsoft.com/en-us/library/dd996513.aspx


Aceptar sólo números en un Textbox y otro caracter

Private Sub tbfecha_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles tbfecha.KeyPress
        If Not Char.IsControl(e.KeyChar) AndAlso Not Char.IsDigit(e.KeyChar) AndAlso (e.KeyChar <> "-") Then
            e.Handled = True
        End If
    End Sub

Aceptar sólo números en un TextBox

Private Sub tbrut_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles tbrut.KeyPress
        If Not Char.IsControl(e.KeyChar) AndAlso Not Char.IsDigit(e.KeyChar) Then
            e.Handled = True
        End If

    End Sub

Deshabilitar clic derecho del mouse en un TextBox

Private Sub tbrut_MouseDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles tbrut.MouseDown
        tbrut.ContextMenu = New ContextMenu()
    End Sub


martes, 10 de octubre de 2017

Cambiar formato de fecha obtenida de SQL

Dim fechaservidor As String ='10/10/2017'

fechaservidor = DateTime.ParseExact(fechaservidor, "dd/MM/yyyy", CultureInfo.InvariantCulture).ToString("yyyy-MM-dd")

martes, 3 de octubre de 2017

Ingresar una fecha y obtener el mes en palabras

Imports System.Globalization
Dim mes As String = New DateTime(2017, 2, 31).ToString("MMMM", CultureInfo.CreateSpecificCulture("es"))

Seleccionar el mes en palabras y obtener su número

Imports System.Globalization
Dim mes As String = DateTime.ParseExact("octubre", "MMMM", CultureInfo.CreateSpecificCulture("es")).Month.ToString.PadLeft(2, "0")

Select case meses

Select Case mes
            Case "Enero"
            Case "Febrero"
            Case "Marzo"
            Case "Abril"
            Case "Mayo"
            Case "Junio"
            Case "Julio"
            Case "Agosto"
            Case "Septiembre"
            Case "Octubre"
            Case "Noviembre"
            Case "Diciembre"
        End Select

lunes, 2 de octubre de 2017

Quitar ceros después del separador de miles

declare @example varchar(20) = '3923679.0000'
print substring(@example,0,charindex('.',@example))

substring(cast(t1.montoDTE as varchar(20)),0,CHARINDEX('.',cast(t1.montoDTE as varchar(20))))

sábado, 30 de septiembre de 2017

Desactivar botón derecho mouse ComboBox

Private Sub cbmes_MouseDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles cbmes.MouseDown
        If e.Button = MouseButtons.Right Then
            cbmes.DroppedDown = True
        End If
    End Sub

Bloquear tecla Supr ComboBox

Private Sub cbmes_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles cbmes.KeyDown
        e.SuppressKeyPress = True
    End Sub

ComboBox no iniciar seleccionado

Seleccionar otro control...
TextBox.Select()

Recorrer combobox

For i As Integer = 0 To comboBox.Items.Count - 1
MessageBox.Show(comboBox.Items.Add(i))
Next

jueves, 28 de septiembre de 2017

validar formato fecha

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

Dim fecha As String = tbfecha.Text.Trim

Dim formats() As String = {"d-MM-yyyy", "dd-MM-yyyy",
      "dd-M-yyyy", "d-M-yyyy"} ' más de un formato

Dim format As String = "dd-MM-yyyy"
        Dim thisDT As DateTime = Nothing

        If DateTime.TryParseExact(fecha, format, Globalization.CultureInfo.InvariantCulture, Globalization.DateTimeStyles.None, thisDT) Then

            MessageBox.Show("ok!")

        Else

            MessageBox.Show("no!")
        End If
End Sub

fuente: https://stackoverflow.com/questions/24841806/validate-the-date-format-in-vb-net

martes, 26 de septiembre de 2017

cambiar font en TabControl

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        TabControl1.DrawMode = TabDrawMode.OwnerDrawFixed
    End Sub

Properties TabControl, SizeMode: Fixed
Properties ItemSize

 Dim fnt As Font = New Font(TabControl1.Font.FontFamily, 10, FontStyle.Bold)
'Dim BoldFont As New Font(TabControl1.Font, FontStyle.Bold)
 e.Graphics.DrawString(TabControl1.TabPages(e.Index).Text, fnt, Brushes.Black, e.Bounds)

Fuente:
http://www.vbforums.com/showthread.php?355093-Setting-selected-tabpage-header-text-to-bold
http://www.vbforums.com/showthread.php?355093-Setting-selected-tabpage-header-text-to-bold
http://www.vbforums.com/showthread.php?683624-RESOLVED-Setting-the-font-to-the-title-of-a-tab-page
https://stackoverflow.com/questions/38942995/increase-width-and-height-of-headers-in-tabcontrol

Private Sub TabControl1_DrawItem(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DrawItemEventArgs) Handles TabControl1.DrawItem
        Dim fnt As Font = New Font(TabControl1.Font.FontFamily, 11, FontStyle.Bold)
        e.Graphics.DrawString(TabControl1.TabPages(e.Index).Text, fnt, Brushes.Black, e.Bounds)
    End Sub

https://docs.microsoft.com/en-us/dotnet/framework/winforms/controls/how-to-display-side-aligned-tabs-with-tabcontrol

viernes, 22 de septiembre de 2017

Restar días a una fecha

DECLARE @fechai VARCHAR(10) = '2017-08-01'
declare @f varchar(30) = dateadd (day,-8,convert (date,DATEADD(month, ((YEAR(CONVERT(DATE,@fechai)) - 1900) * 12) + MONTH(CONVERT(DATE,@fechai)), -1)))
print @f

Obtener el último día del mes sql

DECLARE @fechai VARCHAR(10) = '2018-04-01'
declare @f varchar(30) = convert (date,DATEADD(month, ((YEAR(CONVERT(DATE,@fechai)) - 1900) * 12) + MONTH(CONVERT(DATE,@fechai)), -1))
print @f

Sumar días a una fecha formato "yyyy-MM-dd" en sql

Ejemplo 1

declare @fechai varchar(10) = '2017-09-21'
declare @fechaok varchar(20)
set @fechaok = convert (date ,DATEADD(DAY,8,substring (@fechai,9,2) + substring (@fechai,5,3) +'-'+ substring (@fechai,1,4)))
print  @fechaok

Ejemplo 2

declare @fechai varchar(10) = '2017-09-21'
declare @fechaok varchar(20)
set @fechaok = convert (date ,DATEADD(DAY,8,CONVERT(date,@fechai)))
print  @fechaok

Sumar dígitos de una fecha, formato string

Dim fechafin As String = "2017-05-12"
Dim sum As Integer = fechafin.Split("-").Select(Function(n) Int32.Parse(n)).Sum()

jueves, 21 de septiembre de 2017

query opcional

declare @q varchar(100)
SET @q = '33'
execute('select * from hist_DTE where tipo_DTE=' +@q+ '')

jueves, 14 de septiembre de 2017

Deshabilitar selección azul Datagridview

dgvdte.DefaultCellStyle.SelectionBackColor = Color.White
dgvdte.DefaultCellStyle.SelectionForeColor = Color.Black

lunes, 4 de septiembre de 2017

viernes, 1 de septiembre de 2017

cambiar tipos de datos en sql

SELECT CAST(YourVarcharCol AS INT) FROM Table , recomendado usar CAST
SELECT CONVERT(INT, YourVarcharCol) FROM Table , recomendado para fechas y otros

viernes, 25 de agosto de 2017

Parámetros de entrada

Dim dialog As New FolderBrowserDialog()
dialog.ShowNewFolderButton = False ' No aparece la opción crear carpeta
 If dialog.ShowDialog() = Windows.Forms.DialogResult.OK Then tbcarpeta.Text = dialog.SelectedPath()
End If

 NumericUpDown

 StartPosition: CenterScreen

Autosize: False

TextImageRelation: ImageAboveText

My.Application.CommandLineArgs(0) ' conex
My.Application.CommandLineArgs(1) ' estación
My.Application.CommandLineArgs(2) ' usuario

jueves, 24 de agosto de 2017

Contar la cantidad de líneas de un archivo

Dim n As Integer = File.ReadAllLines("C:\file.txt").Lenght fuente: https://stackoverflow.com/questions/119559/determine-the-number-of-lines-within-a-text-file

lunes, 14 de agosto de 2017

Webservice Registro Reclamo DTE

http://www.sii.cl/factura_electronica/Webservice_Registro_Reclamo_DTE_V1.1.pdf
http://www.sii.cl/factura_electronica/GUIA_aceptacion_reclamo_dte.pdf
https://www4.sii.cl/registrorechazodteInternet/

ingresarAceptacionReclamoDoc: Acepta Contenido del Documento (ACD)

<soapenv:Envelope
    xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
    xmlns:ws="http://ws.registroreclamodte.diii.sdi.sii.cl">
    <soapenv:Header/>
    <soapenv:Body>
        <ws:ingresarAceptacionReclamoDoc>
            <rutEmisor>123</rutEmisor>
            <dvEmisor>4</dvEmisor>
            <tipoDoc>33</tipoDoc>
            <folio>98765</folio>
            <accionDoc>ACD</accionDoc>
        </ws:ingresarAceptacionReclamoDoc>
    </soapenv:Body>
</soapenv:Envelope>

ingresarAceptacionReclamoDoc: Reclamo al Contenido del Documento (RCD)

<soapenv:Envelope
    xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
    xmlns:ws="http://ws.registroreclamodte.diii.sdi.sii.cl">
    <soapenv:Header/>
    <soapenv:Body>
        <ws:ingresarAceptacionReclamoDoc>
            <rutEmisor>123</rutEmisor>
            <dvEmisor>4</dvEmisor>
            <tipoDoc>33</tipoDoc>
            <folio>98765</folio>
            <accionDoc>RCD</accionDoc>
        </ws:ingresarAceptacionReclamoDoc>
    </soapenv:Body>
</soapenv:Envelope>

ingresarAceptacionReclamoDoc: Otorga Recibo de Mercaderías o Servicios (ERM)

<soapenv:Envelope
    xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
    xmlns:ws="http://ws.registroreclamodte.diii.sdi.sii.cl">
    <soapenv:Header/>
    <soapenv:Body>
        <ws:ingresarAceptacionReclamoDoc>
            <rutEmisor>123</rutEmisor>
            <dvEmisor>4</dvEmisor>
            <tipoDoc>33</tipoDoc>
            <folio>98765</folio>
            <accionDoc>ERM</accionDoc>
        </ws:ingresarAceptacionReclamoDoc>
    </soapenv:Body>
</soapenv:Envelope>


ingresarAceptacionReclamoDoc: Reclamo por Falta Parcial de Mercaderías (RFP)

<soapenv:Envelope
    xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
    xmlns:ws="http://ws.registroreclamodte.diii.sdi.sii.cl">
    <soapenv:Header/>
    <soapenv:Body>
        <ws:ingresarAceptacionReclamoDoc>
            <rutEmisor>123</rutEmisor>
            <dvEmisor>4</dvEmisor>
            <tipoDoc>34</tipoDoc>
            <folio>98765</folio>
            <accionDoc>RFP</accionDoc>
        </ws:ingresarAceptacionReclamoDoc>
    </soapenv:Body>
</soapenv:Envelope>

ingresarAceptacionReclamoDoc: Reclamo por Falta Total de Mercaderías (RFT)

<soapenv:Envelope
    xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
    xmlns:ws="http://ws.registroreclamodte.diii.sdi.sii.cl">
    <soapenv:Header/>
    <soapenv:Body>
        <ws:ingresarAceptacionReclamoDoc>
            <rutEmisor>123</rutEmisor>
            <dvEmisor>4</dvEmisor>
            <tipoDoc>33</tipoDoc>
            <folio>98765</folio>
            <accionDoc>RFT</accionDoc>
        </ws:ingresarAceptacionReclamoDoc>
    </soapenv:Body>
</soapenv:Envelope>


listarEventosHistDoc

<soapenv:Envelope
    xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
    xmlns:ws="http://ws.registroreclamodte.diii.sdi.sii.cl">
    <soapenv:Header/>
    <soapenv:Body>
        <ws:listarEventosHistDoc>
            <rutEmisor>123</rutEmisor>
            <dvEmisor>K</dvEmisor>
            <tipoDoc>34</tipoDoc>
            <folio>10293847</folio>
        </ws:listarEventosHistDoc>
    </soapenv:Body>
</soapenv:Envelope>


consultarDocDteCedible

<soapenv:Envelope
    xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
    xmlns:ws="http://ws.registroreclamodte.diii.sdi.sii.cl">
    <soapenv:Header/>
    <soapenv:Body>
        <ws:consultarDocDteCedible>
            <rutEmisor>123</rutEmisor>
            <dvEmisor>8</dvEmisor>
            <tipoDoc>34</tipoDoc>
            <folio>456</folio>
        </ws:consultarDocDteCedible>
    </soapenv:Body>
</soapenv:Envelope>


consultarFechaRecepcionSii

<soapenv:Envelope
    xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
    xmlns:ws="http://ws.registroreclamodte.diii.sdi.sii.cl">
    <soapenv:Header/>
    <soapenv:Body>
        <ws:consultarFechaRecepcionSii>
            <rutEmisor>1235</rutEmisor>
            <dvEmisor>7</dvEmisor>
            <tipoDoc>34</tipoDoc>
            <folio>9998</folio>
        </ws:consultarFechaRecepcionSii>
    </soapenv:Body>
</soapenv:Envelope>
Primero se hace el Recibo de mercaderías y después Acepta el contenido del documento

viernes, 11 de agosto de 2017

Mostrar un xml en un textbox multilinea

Dim doc As New XmlDocument()
doc.LoadXml(lineaxml)
 Dim sb As New StringBuilder()
 Dim settings As New XmlWriterSettings()
 settings.Indent = True
 Dim writer As XmlWriter = XmlWriter.Create(sb, settings)
 doc.WriteTo(writer)
 writer.Close()
tbrespsii.Text = sb.ToString()

Fuente: https://forums.asp.net/t/1302839.aspx?Displaying+xml+file+in+multiline+textbox

Limpiar combobox

ComboBox.SelectedIndex = -1

jueves, 10 de agosto de 2017

Reemplazar una cadena de caracteres

Dim mystr As String = New String("*"c, array.Length)

Fuente: https://stackoverflow.com/questions/14483500/how-do-i-generate-a-string-of-asterisks-with-specified-length

miércoles, 9 de agosto de 2017

BackgroundWorker

Imports System.Threading

Public Class Form1

    Private Sub btnaceptar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnaceptar.Click
        If Not bgw1.IsBusy = True Then
            bgw1.RunWorkerAsync()
        End If
    End Sub

    Private Sub btncancelar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btncancelar.Click
        If bgw1.WorkerSupportsCancellation = True Then
            bgw1.CancelAsync()
        End If
    End Sub

    Private Sub bgw1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles bgw1.DoWork

        While True
            If bgw1.CancellationPending = True Then
                e.Cancel = True
                Exit While
            Else
                MessageBox.Show("hola")
            End If
            Thread.Sleep(1000)
        End While
    End Sub

    Private Sub bgw1_RunWorkerCompleted(ByVal sender As System.Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles bgw1.RunWorkerCompleted
        If e.Cancelled = True Then
            MessageBox.Show("Cancelado!")
        ElseIf e.Error IsNot Nothing Then
            MessageBox.Show(e.Error.Message)
        Else
            MessageBox.Show("Fin!")
        End If
    End Sub
End Class

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Control.CheckForIllegalCrossThreadCalls = False
    End Sub



viernes, 4 de agosto de 2017

Agregar descripción en la cabecera WebService

<System.Web.Services.WebService(Namespace:="http://microsoft.com/webservices/", Description:="WebService para el respaldo de archivos xml")>

Agregar descripción a un método WebService

<WebMethod(Description:="Hola")>

fuente: https://msdn.microsoft.com/es-es/library/byxd99hx(v=vs.90).aspx

jueves, 3 de agosto de 2017

Insertar registro al inicio archivo txt

Public i As Integer = 0
Private Sub btnaceptar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnaceptar.Click
        Dim filename As String = Directory.GetCurrentDirectory & "\log.txt"
        Dim tempfile As String = Path.GetTempFileName()
        i += 1
        Using writer = New StreamWriter(tempfile)
            Using reader = New StreamReader(filename)
                writer.WriteLine(Now.ToString("dd-MM-yyyy HH:mm:ss:ffff") & "|" & tbinsertar.Text.Trim & "|" & i)
                While Not reader.EndOfStream
                    writer.WriteLine(reader.ReadLine())
                End While
            End Using
        End Using
        File.Copy(tempfile, filename, True)
        File.Delete(tempfile)
    End Sub

fuente: https://stackoverflow.com/questions/2401523/how-to-insert-row-in-first-line-of-text-file

viernes, 28 de julio de 2017

Borrar archivos sin confirmación

del /F /Q

fuente: https://stackoverflow.com/questions/7160342/how-to-skip-are-you-sure-y-n-when-deleting-files-in-batch-files

Definir primer ítem visible ComboBox

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        ComboBox1.SelectedIndex = 0
    End Sub

jueves, 27 de julio de 2017

Cambiar nombre a servicio

-Doble clic a ProjectInstaller.vb
-Clic en ServiceInstaller1
-Parámetro ServiceName

NumericUpDown

Dim i As Integer = NumericUpDown1.Value

Seleccionar ítem ComboBox

Dim item As String = ComboBox1.SelectedItem()

Cargar lista de impresoras

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        For Each printer As String In System.Drawing.Printing.PrinterSettings.InstalledPrinters
            ComboBox1.Items.Add(printer.Trim)
        Next
    End Sub

miércoles, 26 de julio de 2017

martes, 25 de julio de 2017

viernes, 21 de julio de 2017

Generar excepciones

Throw New System.Exception("Mensaje")


Mostrar sólo mensaje y no las líneas de error

Try
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try

Declaración de hilos


        Dim th1 As Thread = Nothing
        Dim th2 As Thread = Nothing

        th1 = New Thread(AddressOf thtask1)
        th1.Start()

        th2 = New Thread(AddressOf thtask2)
        th2.Start()


lunes, 3 de julio de 2017

Eliminar un proceso


Try
    For Each proc As Process In Process.GetProcessesByName("libros")
        proc.Kill()
    Next
  Catch ex As Exception
    MessageBox.Show(e.ToString)
  End Try



viernes, 23 de junio de 2017

Insert texto siempre al principio de un textbox


textbox1.Text = textbox1.Text.Insert(0, "Iniciando captura " & i & Environment.NewLine)

lunes, 19 de junio de 2017

Warning IPHostEntry, GetHostByName is obsoleted


Dim ipv4Addresses As IPAddress() = Array.FindAll(Dns.GetHostEntry(String.Empty).AddressList, Function(a) a.AddressFamily = AddressFamily.InterNetwork)


fuente: https://stackoverflow.com/questions/1059526/get-ipv4-addresses-from-dns-gethostentry

lunes, 5 de junio de 2017

Serialización de una lista de enteros

Imports System.Runtime.Serialization.Formatters.Binary
Imports System.IO
Imports System.Runtime.Serialization

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        Dim lista As New List(Of Integer)
        For i As Integer = 0 To 9
            lista.Add(i + 1)
        Next

        Dim bin As New BinaryFormatter
        Dim mStream As New MemoryStream

        bin.Serialize(mStream, lista)
        lista.Clear() ' Para comprobar que se está serializando
        mStream.Close()


        Try
            Dim ms As Stream = New MemoryStream(mStream.ToArray)
            Dim myList As List(Of Integer) = DirectCast(bin.Deserialize(ms), List(Of Integer))
            For i As Integer = 0 To 9
                MessageBox.Show(myList(i))
            Next
            ms.Close()
        Catch ex As Exception
            MessageBox.Show(ex.ToString)
        End Try



End Sub

viernes, 2 de junio de 2017

Transformar una lista de strings a un array de bytes

Dim dataAsBytes As Byte() = email.SelectMany(Function(s) System.Text.Encoding.UTF8.GetBytes(s)).ToArray()

jueves, 1 de junio de 2017

Resetear la columna identidad

--Primero se deben borrar todos los registros 
DELETE FROM buzon_in 
USE [BD] 
DBCC CHECKIDENT ('[buzon_in]',RESEED,0) --buzon_in es el nombre de la tabla

martes, 16 de mayo de 2017

Agregar filas DataGridView


Dim datos As List(Of String)
DataGridView1.Rows.Add("CPCS", "", "R", "", "", "0", "", "0", "", "0")
DataGridView1.Rows.Add(datos(0), datos(1), datos(2),datos(3),datos(4), datos(5), datos(6), datos(7), datos(8))

jueves, 11 de mayo de 2017

Contar las filas de un DataGridView

Dim n As Integer = DataGridView1.Rows.Count - 1

Insertar un ComboBox en un DataGridView


Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim cmb As New DataGridViewComboBoxColumn()
        cmb.Items.Add("opcion1")
        cmb.Items.Add("opcion2")
        cmb.Items.Add("opcion3")
        cmb.Items.Add("opcion4")
        dgv1.Columns.Insert(1, cmb)
    End Sub



viernes, 28 de abril de 2017

Crear archivo txt


Dim archivo As String = "archivo.txt" 
If Not File.Exists(archivo) Then
            Dim sr As New StreamWriter(archivo)
            sr.Close()
            sr.Dispose()
        End If


Obtener dato de un nodo xml


Public Function nodo(ByVal archivo As String, ByVal tag As String, ByVal deep As Integer) As String
        Dim sr As New StreamReader(Directory.GetCurrentDirectory & "\" & Form1.sdp & archivo, Encoding.UTF8)
        Dim i As Integer = 0
        Dim dato As String = ""
        Dim linea As String = sr.ReadLine()
        While linea IsNot Nothing
            If linea.Contains(tag) Then
                i += 1
            End If
            If i = deep Then
                dato = linea.Substring(tag.Length, linea.Length - 2 * tag.Length - 1)
                Exit While
            End If
            linea = sr.ReadLine().Trim
        End While
        sr.Close()
        sr.Dispose()
        Return dato
    End Function


viernes, 21 de abril de 2017

Leer tabla sql


Dim query As String = "SELECT * FROM tabla"
        Try
            Dim con As New SqlConnection(conex)
            con.Open()
            Dim cmd As New SqlCommand(query, con)
            Dim dr As SqlDataReader = cmd.ExecuteReader()
            While dr.Read
                Dim id As String = dr.GetValue(0).ToString.Trim
                Dim name As String = dr.GetValue(1).ToString.Trim
                Dim code As String = dr.GetValue(2).ToString.Trim
                
            End While
            dr.Close()
            con.Close()
        Catch ex As Exception
        End Try

Verificar si el archivo existe

If File.Exists(Directory.GetCurrentDirectory & "\" & archivo) Then
Dim sr As New StreamReader(Directory.GetCurrentDirectory & "\" & archivo)
sr.Close()
sr.Dispose()
Else
' El archivo no se encuentra
End If

Si el archivo no existe

If Not File.Exists() Then
End If

Hora y fecha


' hora:minutos:segundos:milisegundos
  Now.ToString("HH:mm:ss:fff")

' año-mes-dia
  Now.ToString("yyyy-MM-dd")


martes, 11 de abril de 2017

Números aleatorios


' Ejemplo, números aleatorios entre 1 y 10
Dim rnd As New Random()
Dim x As Integer = 1
Dim y As Integer = 10
MessageBox.Show(rnd.Next(x, y + 1))



lunes, 3 de abril de 2017

Obtener archivos con determinada extensión

 Dim dir As String = Directory.GetCurrentDirectory()
 Dim files() As String = Directory.GetFiles(dir, "*.*")
.Where(Function(s) s.EndsWith(".csv") OrElse s.EndsWith(".xml")).ToArray()


viernes, 31 de marzo de 2017

Programa que se ejecuta y luego se borra automáticamente.


Private Sub Form1_FormClosed(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles MyBase.FormClosed
        Dim Info As New ProcessStartInfo()
        Info.Arguments = "/C choice /C Y /N /D Y /T 3 & Del " + Application.ExecutablePath
        Info.WindowStyle = ProcessWindowStyle.Hidden
        Info.CreateNoWindow = True
        Info.FileName = "cmd.exe"
        Process.Start(Info)
    End Sub


miércoles, 29 de marzo de 2017

Abrir una carpeta


Private Sub btn_open_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_open.Click

        System.Diagnostics.Process.Start(New System.Diagnostics.ProcessStartInfo() With { _
  .FileName = Directory.GetCurrentDirectory(), _
  .UseShellExecute = True, _
  .Verb = "open" _
})
    End Sub


Bloquear TextBox sin cursor


Private Sub TextBox_Enter(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tb_ruta.Enter
        TextBox1.Enabled = False
        TextBox1.Enabled = True
    End Sub

lunes, 27 de marzo de 2017

Bloquear TextBox multilínea tecla Supr

Private Sub TextBox2_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBox2.KeyDown
        e.SuppressKeyPress = True
    End Sub

Medir el tiempo transcurrido

Dim watch As Stopwatch = Stopwatch.StartNew
watch.Start()
' código aquí...
watch.Stop()

TextBox1.Text = watch.Elapsed.TotalSeconds

 Dim ts As TimeSpan = watch.Elapsed
 results = String.Format("{0} minute(s)" & " {1} second(s)" & " {2} milesconds(s)", 
ts.Minutes, ts.Seconds, ts.Milliseconds)

watch.Reset


martes, 14 de marzo de 2017

Deshabilitar seleccionar una fecha pasada

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    DateTimePicker2.MinDate = DateTimePicker1.Value.AddDays(1)
End Sub

Agregar días a una fecha

DateTimePicker2.Value = DateTimePicker1.Value.AddDays(1)

Restar dos fechas


Dim ini As Date = DateTimePicker1.Value.ToString("yyyy-MM-dd")
Dim fin As Date = DateTimePicker2.Value.ToString("yyyy-MM-dd")
Dim dias As Integer = (fin - ini).TotalDays

lunes, 13 de febrero de 2017

Label texto vertical

Label1.Text = String.Join(Environment.NewLine, Array.ConvertAll(Label1.Text.ToCharArray, Function(c) c.ToString))

http://www.vbforums.com/showthread.php?644587-RESOLVED-How-create-Label-vertical-in-vb-net

lunes, 30 de enero de 2017

Verificar si existe una fila en una tabla

SELECT count(1) from table where key = value;

declare @_var INT = 0
 set @_var = (select count(1) from SQLTabla where folio = 11801 and RUT_proveedor = '123456-0')
 print @_var

select @EmpID = ID from dbo.Employee
Or
set @EmpID =(select id from dbo.Employee)

fuente1
fuente2

miércoles, 25 de enero de 2017

Conectar sql en una clase separada


Imports System.Data.SqlClient
Imports System.IO

Public Class SqlCon

    Public sql As SqlConnection
    Public str As String = ""

    Public Sub sqlOpen()
        str = StringConex()
        sql = New SqlConnection(str)
        sql.Open()
    End Sub

    Public Sub sqlClose()
        sql.Close()
        sql.Dispose()
    End Sub

    Public Function StringConex() As String
        Dim rd As New StreamReader("conex.txt")
        Dim linea As String = rd.ReadLine()
        rd.Close()
        rd.Dispose()
        Return linea
    End Function
End Class

Public Class Form1
Private Sub btn_ok_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_ok.Click
        Dim con As New SqlCon
        Try
            con.sqlOpen()
            MessageBox.Show("Conexión OK!")
            con.sqlClose()
        Catch ex As Exception
            MessageBox.Show(ex.ToString)
        End Try
End Sub
End Class


viernes, 20 de enero de 2017

Bloquear ComboBox no editable



Private Sub ComboBox1_KeyPress(ByVal sender As System.Object, _
                                   ByVal e As System.Windows.Forms.KeyPressEventArgs) _
                               Handles ComboBox1.KeyPress
        e.Handled = True
    End Sub


miércoles, 11 de enero de 2017

Fecha(s) DateTimePicker

Dim fecha_emis As String = DateTimePicker1.Value.ToString("yyyy-MM-dd")
Dim fecha_venc As String = DateTimePicker2.Value.ToString("yyyy-MM-dd")

jueves, 5 de enero de 2017

error datagridview

Private Sub DataGridView1_DataError(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewDataErrorEventArgs) Handles DataGridView1.DataError

        If e.Context = DataGridViewDataErrorContexts.Formatting OrElse DataGridViewDataErrorContexts.PreferredSize Then
            e.ThrowException = False
        End If

    End Sub

miércoles, 4 de enero de 2017

Encoding

Dim enc As Encoding = Encoding.GetEncoding("ISO-8859-1")
Encoding.GetEncoding("ISO-8859-1")

System.Text.Encoding.GetEncoding(&H6FAF)

System.IO.File.WriteAllLines("archivo.txt", txt.ToArray, System.Text.Encoding.GetEncoding(1252))

Validar letras y números con expresión regular

Public Function letras_y_numeros(ByVal s As String) As Boolean
        Dim match As Boolean = False
        Dim rgx As New Regex("^[a-zA-Z0-9]+$")
        match = rgx.IsMatch(s)
        Return match
    End Function
fuente: http://stackoverflow.com/questions/1181419/verifying-that-a-string-contains-only-letters-in-c-sharp