lunes, 30 de diciembre de 2019
detalle facturador
dgv(cantidad, e.RowIndex).Value = Double.Parse(dgv(cantidad, e.RowIndex).Value)
martes, 24 de diciembre de 2019
crud vista
Dim nombre_vista As String = "vista_estado_sii"
Dim query_vista_existe As String = "SELECT 1 FROM sys.views WHERE name=" & "'" & nombre_vista & "'"
Dim query_vista_crear As String = "CREATE VIEW " & nombre_vista & " AS " & My.Resources.ejemplo_vista
Dim vista_existe As Integer = get_vista_crud(conex, query_vista_existe)
If vista_existe = 1 Then ' Vista existe; eliminar y crear
Dim query_vista_eliminar As String = "DROP VIEW " & nombre_vista
Dim eliminar_vista As Integer = get_vista_crud(conex, query_vista_eliminar)
If eliminar_vista = 0 Then
Dim crear_vista As Integer = get_vista_crud(conex, query_vista_crear)
If crear_vista = 0 Then
MessageBox.Show("La vista se ha creado correctamente", "", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
End If
Else ' Vista no existe; crear
Dim crear_vista As Integer = get_vista_crud(conex, query_vista_crear)
If crear_vista = 0 Then
MessageBox.Show("La vista se ha creado correctamente", "", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
End If
'1 Preguntar si existe
'2 Si existe, borrar y crear vista
'3 Si no existe, crear vista
Public Function get_vista_crud(ByVal conex As String, ByVal query As String) As Integer
Dim return_value As Integer = 0
Dim con As New SqlConnection(conex)
con.Open()
Using cmd As New SqlCommand(query, con)
return_value = cmd.ExecuteScalar()
End Using
con.Close()
Return return_value
End Function
Dim query_vista_existe As String = "SELECT 1 FROM sys.views WHERE name=" & "'" & nombre_vista & "'"
Dim query_vista_crear As String = "CREATE VIEW " & nombre_vista & " AS " & My.Resources.ejemplo_vista
Dim vista_existe As Integer = get_vista_crud(conex, query_vista_existe)
If vista_existe = 1 Then ' Vista existe; eliminar y crear
Dim query_vista_eliminar As String = "DROP VIEW " & nombre_vista
Dim eliminar_vista As Integer = get_vista_crud(conex, query_vista_eliminar)
If eliminar_vista = 0 Then
Dim crear_vista As Integer = get_vista_crud(conex, query_vista_crear)
If crear_vista = 0 Then
MessageBox.Show("La vista se ha creado correctamente", "", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
End If
Else ' Vista no existe; crear
Dim crear_vista As Integer = get_vista_crud(conex, query_vista_crear)
If crear_vista = 0 Then
MessageBox.Show("La vista se ha creado correctamente", "", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
End If
'1 Preguntar si existe
'2 Si existe, borrar y crear vista
'3 Si no existe, crear vista
Public Function get_vista_crud(ByVal conex As String, ByVal query As String) As Integer
Dim return_value As Integer = 0
Dim con As New SqlConnection(conex)
con.Open()
Using cmd As New SqlCommand(query, con)
return_value = cmd.ExecuteScalar()
End Using
con.Close()
Return return_value
End Function
viernes, 20 de diciembre de 2019
sql recursion
WITH miCTE AS (
SELECT MIN(idcaf_activo) as n,(select max(idcaf_activo) from caf_activos) as maxid from caf_activos
UNION all
SELECT n+1,maxid from miCTE where n < maxid
)
SELECT n FROM miCTE t1 left join (select * from caf_activos)t2 on t2.idcaf_activo=t1.n
where t2.idcaf_activo is null
OPTION (MAXRECURSION 0)
fuente
fuente2
fuente3
fuente4
SELECT MIN(idcaf_activo) as n,(select max(idcaf_activo) from caf_activos) as maxid from caf_activos
UNION all
SELECT n+1,maxid from miCTE where n < maxid
)
SELECT n FROM miCTE t1 left join (select * from caf_activos)t2 on t2.idcaf_activo=t1.n
where t2.idcaf_activo is null
OPTION (MAXRECURSION 0)
fuente
fuente2
fuente3
fuente4
jueves, 19 de diciembre de 2019
listado de ultimos registros
select top 10 * from hist_DTE order by id_DTE desc
array trim y elementos no vacíos
Dim str As String = "|1|2|5|7|8|9|122 |0| 9 9|"
Dim array() As String = str.Split("|").Select(Function(w) w.Trim).Where(Function(w) w.Length > 0).ToArray
Dim array() As String = str.Split("|").Select(Function(w) w.Trim).Where(Function(w) w.Length > 0).ToArray
martes, 17 de diciembre de 2019
check boolean data
Dim c As String = " true"
If Boolean.TryParse(c, flag) Then
MessageBox.Show("True")
Else
MessageBox.Show("False")
End If
Fuente
validar formato hora
Dim time As DateTime
Dim valid As Boolean = DateTime.TryParseExact("00:05:00", "hh:mm:ss", CultureInfo.InvariantCulture, Globalization.DateTimeStyles.None, time)
fuente
Dim valid As Boolean = DateTime.TryParseExact("00:05:00", "hh:mm:ss", CultureInfo.InvariantCulture, Globalization.DateTimeStyles.None, time)
fuente
Etiquetas:
CultureInfo,
DateTime,
Globalization,
InvariantCulture,
TryParseExact
lunes, 16 de diciembre de 2019
close and open application, restart
Private Sub btn_restart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_restart.Click
Application.Restart()
Environment.Exit(0)
End Sub
fuente
Application.Restart()
Environment.Exit(0)
End Sub
fuente
Etiquetas:
Application,
close,
Environment,
open,
reiniciar,
restart
lunes, 9 de diciembre de 2019
concatenas sql
DECLARE @fecha_inicio VARCHAR(10)=CONCAT(YEAR(GETDATE()),'-01-01')
get current year, año sql
select year(getdate())
existe celda seleccionada datagridview
Dim n = DgvTareas.SelectedCells.Cast(Of DataGridViewCell).Select(Function(x) x.RowIndex).Distinct.Count
DgvTareas.SelectedCells.Count > 0
fuente
Etiquetas:
DataGridView,
Distinct,
Function,
SelectedCells
sábado, 7 de diciembre de 2019
caf vencidos
select DATEDIFF(MONTH,CAST(fecha_autorizacion as DATE), GETDATE()) from caf_activos
select DATEADD(MONTH,6,CAST(fecha_autorizacion as DATE)) from caf_activos
select DATEADD(MONTH,6,CAST(fecha_autorizacion as DATE)) from caf_activos
viernes, 6 de diciembre de 2019
socket timeout
Dim send As New Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp)
send.SendTimeout = 1000
send.ReceiveTimeout = 1000
send.Connect(remoteEP)
fuente
jueves, 5 de diciembre de 2019
timer windows service
Public Class custom_timer
Inherits Timer
Private id As String
Public Property Tag As String
Get
Return id
End Get
Set(ByVal value As String)
id = value
End Set
End Property
End Class
Dim t As New custom_timer
xt1.rut(len) = rut
t.AutoReset = False
t.Interval = TimeSpan.Parse(elem("Intervalo").InnerXml).TotalMilliseconds
t.Enabled = elem("Activar").InnerXml
t.Tag = rut & "|" & elem("Id").InnerXml & "|" & elem("Config").OuterXml
AddHandler t.Elapsed, New ElapsedEventHandler(AddressOf Timer_Elapsed1)
xt1.tareas(len) = t
Dim x As String = ""
Inherits Timer
Private id As String
Public Property Tag As String
Get
Return id
End Get
Set(ByVal value As String)
id = value
End Set
End Property
End Class
Dim t As New custom_timer
xt1.rut(len) = rut
t.AutoReset = False
t.Interval = TimeSpan.Parse(elem("Intervalo").InnerXml).TotalMilliseconds
t.Enabled = elem("Activar").InnerXml
t.Tag = rut & "|" & elem("Id").InnerXml & "|" & elem("Config").OuterXml
AddHandler t.Elapsed, New ElapsedEventHandler(AddressOf Timer_Elapsed1)
xt1.tareas(len) = t
Dim x As String = ""
cerrar procesos form al salir aplicación
System.Diagnostics.Process.GetCurrentProcess().Kill()
fuente
Etiquetas:
Form,
GetCurrentProcess,
Process
seleccionar algunas columnas al hacer clic
miércoles, 4 de diciembre de 2019
borrar todos los procesos con el mismo nombre
clean datagrid rows
Etiquetas:
Cannot clear this list,
Count,
DataGridView,
DataSource,
error
cabecera datagridview cambia de tamaño
Etiquetas:
Columns,
DataGridView,
Header
lunes, 2 de diciembre de 2019
error tab page datagrid
sábado, 30 de noviembre de 2019
sql fecha
SELECT CONVERT(char(10), GetDate(),126)
select CONVERT(VARCHAR(10), GETDATE(),120)
select CONVERT(VARCHAR(10), GETDATE(),120)
jueves, 28 de noviembre de 2019
tamaño columna datagridview
dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill
Etiquetas:
AutoSizeColumnsMode,
DataGridView,
Fill
ordenar columnas datagridview
dgv.AllowUserToOrderColumns = True
Etiquetas:
AllowUserToOrderColumns,
columnas,
DataGridView
miércoles, 27 de noviembre de 2019
arrastrar y abrir archivos
Public Class drag_files
Private Sub drag_files_DragEnter(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles MyBase.DragEnter
If e.Data.GetDataPresent(DataFormats.FileDrop, False) = True Then
e.Effect = DragDropEffects.All
End If
End Sub
Private Sub drag_files_DragDrop(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles MyBase.DragDrop
Dim drop_files() As String = e.Data.GetData(DataFormats.FileDrop)
If drop_files.Length > 0 Then
For Each elem In drop_files
MessageBox.Show(elem)
Next
End If
End Sub
End Class
' Propiedades AllowDrop = True
' https://www.youtube.com/watch?v=OyKv1Xcod6c
Private Sub drag_files_DragEnter(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles MyBase.DragEnter
If e.Data.GetDataPresent(DataFormats.FileDrop, False) = True Then
e.Effect = DragDropEffects.All
End If
End Sub
Private Sub drag_files_DragDrop(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles MyBase.DragDrop
Dim drop_files() As String = e.Data.GetData(DataFormats.FileDrop)
If drop_files.Length > 0 Then
For Each elem In drop_files
MessageBox.Show(elem)
Next
End If
End Sub
End Class
' Propiedades AllowDrop = True
' https://www.youtube.com/watch?v=OyKv1Xcod6c
lunes, 25 de noviembre de 2019
cerrar aplicación
Private Sub Form1_FormClosing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing
Application.Exit()
'Environment.Exit(1)
End Sub
fuente
aplicación ya está en ejecución
Public Function get_aplicacion_existe() As Boolean
Dim appName As String = Process.GetCurrentProcess.ProcessName
Dim sameProcessTotal As Integer = Process.GetProcessesByName(appName).Length
MessageBox.Show(sameProcessTotal)
If sameProcessTotal > 1 Then
Return 1
Else
Return 0
End If
End Function
Dim appName As String = Process.GetCurrentProcess.ProcessName
Dim sameProcessTotal As Integer = Process.GetProcessesByName(appName).Length
MessageBox.Show(sameProcessTotal)
If sameProcessTotal > 1 Then
Return 1
Else
Return 0
End If
End Function
Etiquetas:
existe,
GetProcessesByName,
Process
miércoles, 20 de noviembre de 2019
comuna ñuñoa
ñuñoa = NUNOA
MessageBox consulta
Dim result As DialogResult = MessageBox.Show("¿Crear nueva cadena de conexión?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
If result = DialogResult.Yes Then
MessageBox.Show("si")
ElseIf result = DialogResult.No Then
MessageBox.Show("no")
End If
fuente
If result = DialogResult.Yes Then
MessageBox.Show("si")
ElseIf result = DialogResult.No Then
MessageBox.Show("no")
End If
fuente
Etiquetas:
DialogReslt,
MessageBox
viernes, 15 de noviembre de 2019
conex string
Data
Source=1.1.1.1;Database=base;User
ID=123;Password=123;
jueves, 14 de noviembre de 2019
version programa
Dim nombre_programa As String = "wsconfig"
Dim version As String = "versión 0.63"
Dim anio As String = ""
Dim anio_creacion As Integer = 2019
If anio_creacion = Now.Year Then
anio = anio_creacion
Else
anio = anio_creacion & "-" & Now.Year
End If
' Fecha de compilación
Dim filepath As String = Assembly.GetExecutingAssembly().Location
Dim dt As DateTime = New FileInfo(filepath).LastWriteTime
'MessageBox.Show(dt.ToString("dddd", New CultureInfo("es-ES")) & " " & dt.ToString("dd-MM-yyyy HH:mm:ss"))
' https://docs.microsoft.com/en-us/dotnet/standard/base-types/how-to-extract-the-day-of-the-week-from-a-specific-date
My.MySettings.Default.timesrun = My.MySettings.Default.timesrun + 1
My.MySettings.Default.Save()
'My.Settings.nexe = 5
'My.Settings.Save()
MessageBox.Show(My.Settings.timesrun)
MessageBox.Show(nombre_programa & Environment.NewLine &
version & " (" & dt.ToString("dddd", New CultureInfo("es-ES")) & " " & dt.ToString("dd-MM-yyyy HH:mm:ss") & ")" & Environment.NewLine &
anio, "", MessageBoxButtons.OK, MessageBoxIcon.None)
Dim version As String = "versión 0.63"
Dim anio As String = ""
Dim anio_creacion As Integer = 2019
If anio_creacion = Now.Year Then
anio = anio_creacion
Else
anio = anio_creacion & "-" & Now.Year
End If
' Fecha de compilación
Dim filepath As String = Assembly.GetExecutingAssembly().Location
Dim dt As DateTime = New FileInfo(filepath).LastWriteTime
'MessageBox.Show(dt.ToString("dddd", New CultureInfo("es-ES")) & " " & dt.ToString("dd-MM-yyyy HH:mm:ss"))
' https://docs.microsoft.com/en-us/dotnet/standard/base-types/how-to-extract-the-day-of-the-week-from-a-specific-date
My.MySettings.Default.timesrun = My.MySettings.Default.timesrun + 1
My.MySettings.Default.Save()
'My.Settings.nexe = 5
'My.Settings.Save()
MessageBox.Show(My.Settings.timesrun)
MessageBox.Show(nombre_programa & Environment.NewLine &
version & " (" & dt.ToString("dddd", New CultureInfo("es-ES")) & " " & dt.ToString("dd-MM-yyyy HH:mm:ss") & ")" & Environment.NewLine &
anio, "", MessageBoxButtons.OK, MessageBoxIcon.None)
miércoles, 13 de noviembre de 2019
Copiar contenido TextBox
Clipboard.SetText(tb_conex.Text.Trim)
martes, 12 de noviembre de 2019
string reverse
Dim reverse As String = StrReverse("1234567")
popup firefox
popup firefox
app.update.silent = True
app.update.url = yyyhttp://
app.update.doorhanger = False
click en el botón actualizar página, para guardar cambios
fuente
fuente2
fuente3
app.update.silent = True
app.update.url = yyyhttp://
app.update.doorhanger = False
click en el botón actualizar página, para guardar cambios
fuente
fuente2
fuente3
última modificación
Dim filepath As String = Assembly.GetExecutingAssembly().Location
Dim dt As DateTime = New FileInfo(filepath).LastWriteTime
MessageBox.Show(dt.ToString("HH:mm:ss dd-MM-yyyy"))
fuente
Dim dt As DateTime = New FileInfo(filepath).LastWriteTime
MessageBox.Show(dt.ToString("HH:mm:ss dd-MM-yyyy"))
fuente
Etiquetas:
Assembly,
DateTime,
FileInfo,
LastWriteTime
lunes, 11 de noviembre de 2019
no mostrar icono windows form
comparar fecha y hora sql
if CAST('2019-11-11' as DATE) > '2019-11-10'
begin
print 'si'
end
else
begin
print 'no'
end
if CAST('05:59:00' as TIME) > '06:00:00'
begin
print 'si'
end
else
begin
print 'no'
end
SELECT CONVERT(CHAR(10),DATEADD(DAY,1,campo_tabla),121) FROM tabla WHERE id=5510
select dateadd(DAY,1,CAST(GETDATE() AS DATE))
SELECT * FROM hist_DTE
WHERE fecha_emision >='2019-11-10' AND estado_SII='Pendiente' AND --id_DTE=5510 AND
--CONVERT(CHAR(10),GETDATE(),121)>= fecha_creacion_registro AND
CONVERT(CHAR(8),GETDATE(),108)>=CONVERT(CHAR(8),DATEADD(HOUR,11,hora_creacion_registro),108)
select CAST(CONVERT(CHAR(8),DATEADD(HOUR,11,'01:21:00'),108) AS TIME)
select CAST(CONVERT(CHAR(8),GETDATE(),108) as TIME)
fuente1
fuente2
begin
print 'si'
end
else
begin
print 'no'
end
if CAST('05:59:00' as TIME) > '06:00:00'
begin
print 'si'
end
else
begin
print 'no'
end
SELECT CONVERT(CHAR(10),DATEADD(DAY,1,campo_tabla),121) FROM tabla WHERE id=5510
select dateadd(DAY,1,CAST(GETDATE() AS DATE))
SELECT * FROM hist_DTE
WHERE fecha_emision >='2019-11-10' AND estado_SII='Pendiente' AND --id_DTE=5510 AND
--CONVERT(CHAR(10),GETDATE(),121)>= fecha_creacion_registro AND
CONVERT(CHAR(8),GETDATE(),108)>=CONVERT(CHAR(8),DATEADD(HOUR,11,hora_creacion_registro),108)
select CAST(CONVERT(CHAR(8),DATEADD(HOUR,11,'01:21:00'),108) AS TIME)
select CAST(CONVERT(CHAR(8),GETDATE(),108) as TIME)
fuente1
fuente2
viernes, 8 de noviembre de 2019
split salto de línea
Dim campos() As String = Nothing
Dim arg() As String = {vbCrLf, vbLf}
Dim extras As String = xml.GetElementsByTagName("Extras")(0).OuterXml
campos = extras.Split(arg, StringSplitOptions.None)
fuente
Dim arg() As String = {vbCrLf, vbLf}
Dim extras As String = xml.GetElementsByTagName("Extras")(0).OuterXml
campos = extras.Split(arg, StringSplitOptions.None)
fuente
miércoles, 6 de noviembre de 2019
windows service forzar eliminar
martes, 5 de noviembre de 2019
insertar y obtener el id
INSERT INTO buzon_out(cuenta_destino)
SELECT cuenta_destino FROM buzon_out_tmp
WHERE tipo='PDF' AND id='5504';SELECT SCOPE_IDENTITY();
fuente
SELECT cuenta_destino FROM buzon_out_tmp
WHERE tipo='PDF' AND id='5504';SELECT SCOPE_IDENTITY();
fuente
miércoles, 30 de octubre de 2019
seleccionar ID base de datos
SELECT DB_ID('correo')
jueves, 24 de octubre de 2019
Tipo de datos sql
bigint
binary
bit
char
date
datetime
datetime2
datetimeoffset
decimal
float
image
int
money
nchar
ntext
nvarchar
real
smalldatetime
smallint
smallmoney
structured
text
time
timestamp
tinyint
udt
uniqueidentifier
varbinary
varchar
variant
xml
binary
bit
char
date
datetime
datetime2
datetimeoffset
decimal
float
image
int
money
nchar
ntext
nvarchar
real
smalldatetime
smallint
smallmoney
structured
text
time
timestamp
tinyint
udt
uniqueidentifier
varbinary
varchar
variant
xml
versión sql
SELECT CASE WHEN CONVERT(VARCHAR(128), SERVERPROPERTY ('productversion')) LIKE '8%' THEN 'SQL2000' WHEN CONVERT(VARCHAR(128), SERVERPROPERTY ('productversion')) LIKE '9%' THEN 'SQL2005' WHEN CONVERT(VARCHAR(128), SERVERPROPERTY ('productversion')) like '10.0%' THEN 'SQL2008' WHEN CONVERT(VARCHAR(128), SERVERPROPERTY ('productversion')) like '10.5%' THEN 'SQL2008R2' WHEN CONVERT(VARCHAR(128), SERVERPROPERTY ('productversion')) like '11%' THEN 'SQL2012' WHEN CONVERT(VARCHAR(128), SERVERPROPERTY ('productversion')) like '12%' THEN 'SQL2014' WHEN CONVERT(VARCHAR(128), SERVERPROPERTY ('productversion')) like '13%' THEN 'SQL2016' WHEN CONVERT(VARCHAR(128), SERVERPROPERTY ('productversion')) like '14%' THEN 'SQL2017' ELSE 'SQL????' END
hacer click botón página web
Private Sub btn_consultar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_consultar.Click
Dim elc As HtmlElementCollection = WebBrowser1.Document.GetElementsByTagName("input")
For Each el As HtmlElement In elc
If el.GetAttribute("Name").Equals("ACEPTAR") Then
el.InvokeMember("click")
Exit For
End If
Next
End Sub
Dim elc As HtmlElementCollection = WebBrowser1.Document.GetElementsByTagName("input")
For Each el As HtmlElement In elc
If el.GetAttribute("Name").Equals("ACEPTAR") Then
el.InvokeMember("click")
Exit For
End If
Next
End Sub
captcha
Private Sub btn_captcha_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_captcha.Click
Dim htmlDocument As HtmlDocument = WebBrowser1.Document
Dim htmlElementCollection As HtmlElementCollection = htmlDocument.Images
For Each htmlElement As HtmlElement In htmlElementCollection
Dim imgUrl As String = htmlElement.GetAttribute("src")
If imgUrl.StartsWith("https://zeus.sii.cl/cvc_cgi/stc/CViewCaptcha.cgi?oper=1&txtCaptcha=") Then
image_url = imgUrl
picture_box.ShowDialog()
Exit For
End If
Dim pause As String = ""
Next
End Sub
Dim htmlDocument As HtmlDocument = WebBrowser1.Document
Dim htmlElementCollection As HtmlElementCollection = htmlDocument.Images
For Each htmlElement As HtmlElement In htmlElementCollection
Dim imgUrl As String = htmlElement.GetAttribute("src")
If imgUrl.StartsWith("https://zeus.sii.cl/cvc_cgi/stc/CViewCaptcha.cgi?oper=1&txtCaptcha=") Then
image_url = imgUrl
picture_box.ShowDialog()
Exit For
End If
Dim pause As String = ""
Next
End Sub
Etiquetas:
captcha,
sii,
WebBrowser
convertir de código ascii to char
Dim char As Char = Convert.ToChar(55)
web browser
Me.WebBrowser1.Navigate("about:blank")
archivos con expresiones regulares
Dim rgx As Regex = New Regex("[^a-z]")
Dim archivosTxt() As String = Directory.GetFiles("carpeta_origen, "*.*").Where(Function(c) rgx.IsMatch(Path.GetFileName(c))).ToArray
Dim archivosTxt() As String = Directory.GetFiles("carpeta_origen, "*.*").Where(Function(c) rgx.IsMatch(Path.GetFileName(c))).ToArray
viernes, 18 de octubre de 2019
mes en palabras
dtp_fecha_ValueChanged(Me, EventArgs.Empty)
Public Function get_fecha() As String
Return dtp_fecha.Value.ToString("dd-") & New CultureInfo("es-ES", False).DateTimeFormat.GetMonthName(dtp_fecha.Value.ToString("MM")) & dtp_fecha.Value.ToString("-yyyy")
End Function
salida = 10-octubre-2019
fuente
Etiquetas:
CultureInfo,
DateTimeFormat,
GetMonthName
jueves, 17 de octubre de 2019
Estandarizar fecha para distintos lenguages y sistemas operativos
Dim ci As CultureInfo = CultureInfo.CreateSpecificCulture(CultureInfo.CurrentCulture.Name)
ci.DateTimeFormat.ShortDatePattern = "dd-MM-yyyy" System.Threading.Thread.CurrentThread.CurrentCulture = ci
fuente
ci.DateTimeFormat.ShortDatePattern = "dd-MM-yyyy" System.Threading.Thread.CurrentThread.CurrentCulture = ci
fuente
Etiquetas:
CultureInfo,
DateTimeFormat,
DateTimePicker,
Thread
suma y resta día
formato entrada fecha=20191017
Public Function suma_resta_dia(ByVal fecha As String, ByVal dias As Integer) As Integer
fecha = fecha.Insert(4, "-").Insert(7, "-")
Dim dt As DateTime = DateTime.Parse(fecha).AddDays(dias)
Return dt.ToString("yyyyMMdd")
End Function
miércoles, 16 de octubre de 2019
wsconfig
-Agregar contraseña a las tareas
-Agregar hora de inicio
-Agregar hora de inicio
martes, 15 de octubre de 2019
fecha máxima
DateTimePicker.MaxDate = DateTime.Today
Etiquetas:
DateTime,
DateTimePicker
cambiar formato fecha
fecha='20191009
Public Function get_fecha_inicio(ByVal fecha As String) As String
Dim tmp As String = ""
tmp += fecha.Substring(6, 2) & "-"
tmp += fecha.Substring(4, 2) & "-"
tmp += fecha.Substring(0, 4)
Return tmp
End Function
Etiquetas:
DateTime,
DateTimePicker
datagridview columna y fila
date time picker formato
DateTimePicker.Format = DateTimePickerFormat.Custom
DateTimePicker.CustomFormat = "HH:mm:ss"
DateTimePicker.CustomFormat = "HH:mm:ss tt" --> 23:34:54 AM/PM
fuente
DateTimePicker.CustomFormat = "HH:mm:ss"
DateTimePicker.CustomFormat = "HH:mm:ss tt" --> 23:34:54 AM/PM
fuente
Etiquetas:
DateTimePicker,
formato
lunes, 14 de octubre de 2019
windows form activo
If Application.OpenForms.OfType(Of windows_form1).Any Then
MessageBox.Show("windows form1")
ElseIf Application.OpenForms.OfType(Of windows_form2).Any Then
MessageBox.Show("windows_form2")
End If
fuente
MessageBox.Show("windows form1")
ElseIf Application.OpenForms.OfType(Of windows_form2).Any Then
MessageBox.Show("windows_form2")
End If
fuente
viernes, 11 de octubre de 2019
Bloquear tabpage
Private Sub TabControl1_Selecting(ByVal sender As System.Object, ByVal e As System.Windows.Forms.TabControlCancelEventArgs) Handles TabControl1.Selecting
If e.TabPageIndex = 1 Then
e.Cancel = True
End If
End Sub
fuente
If e.TabPageIndex = 1 Then
e.Cancel = True
End If
End Sub
fuente
miércoles, 9 de octubre de 2019
Directorio de un archivo
archivo = "D:\programa\bin\archivos\test\archivo.xml"
Dim ruta As String = New FileInfo(archivo).Directory.FullName
Dim ruta As String = Path.GetDirectoryName(archivo)
Dim ruta As String = New FileInfo(archivo).Directory.FullName
Dim ruta As String = Path.GetDirectoryName(archivo)
Etiquetas:
directorio,
Directory,
FileInfo,
GetDirectoryName
jueves, 3 de octubre de 2019
Error System.OutOfMemoryException
miércoles, 2 de octubre de 2019
Iniciar Timer después de iniciar
martes, 1 de octubre de 2019
sql producto version y nivel
select serverproperty('productversion'),serverproperty('productlevel'),serverproperty('edition')
Hora Minuto Segundo a palabras
lunes, 30 de septiembre de 2019
inicializar timer inmediatamente
martes, 24 de septiembre de 2019
Cargar combobox en datagrid
Public Sub tipo_dato()
For i As Integer = 0 To dg_variables.Rows.Count - 1 ' filas
Dim dg_cb As New DataGridViewComboBoxCell
dg_cb.Items.Add("Hola1")
dg_cb.Items.Add("Hola2")
dg_cb.Items.Add("Hola3")
dg_variables.Item(col_tipo, i) = dg_cb
Next
End Sub
For i As Integer = 0 To dg_variables.Rows.Count - 1 ' filas
Dim dg_cb As New DataGridViewComboBoxCell
dg_cb.Items.Add("Hola1")
dg_cb.Items.Add("Hola2")
dg_cb.Items.Add("Hola3")
dg_variables.Item(col_tipo, i) = dg_cb
Next
End Sub
Etiquetas:
Add,
ComboBox,
DataGridView,
Items
validar si un string es número
Dim n As Integer
Dim numero As Boolean = Integer.TryParse("123", n)
Public Function get_validar_numero(ByVal val As String) As Boolean
Dim n As Integer
Return Integer.TryParse(val, n)
End Function
Dim numero As Boolean = Integer.TryParse("123", n)
Public Function get_validar_numero(ByVal val As String) As Boolean
Dim n As Integer
Return Integer.TryParse(val, n)
End Function
jueves, 12 de septiembre de 2019
buscar dato en archivo
Private Sub btn_ok_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_ok.Click
'Dim archivo() As String = File.ReadAllLines("")
Dim archivo() As String = File.ReadAllLines("")
Dim fila As Integer = tb_fila.Text.Trim
Dim columna As Integer = tb_columna.Text.Trim
Dim largo As Integer = tb_largo.Text.Trim
Dim dato As String = ""
'If fila > archivo.Length Then
' Exit Sub
'End If
For i As Integer = 0 To archivo.Length - 1
If i = fila - 1 Then
Dim linea() As Char = archivo(i)
If linea.Length = 0 Then
MessageBox.Show("Línea vacía")
Exit Sub
Else
For j As Integer = 0 To linea.Length - 1
If j = columna - 1 Then
'MessageBox.Show(linea(j))
Dim n As Integer = j + largo - 1
If n >= linea.Length Then
MessageBox.Show("No se puede obtener el dato")
Exit Sub
Else
For k As Integer = j To n
dato += linea(k)
Next
MessageBox.Show(dato)
Return
End If
End If
Next
End If
End If
Next
Dim pause1 As String = ""
End Sub
'Dim archivo() As String = File.ReadAllLines("")
Dim archivo() As String = File.ReadAllLines("")
Dim fila As Integer = tb_fila.Text.Trim
Dim columna As Integer = tb_columna.Text.Trim
Dim largo As Integer = tb_largo.Text.Trim
Dim dato As String = ""
'If fila > archivo.Length Then
' Exit Sub
'End If
For i As Integer = 0 To archivo.Length - 1
If i = fila - 1 Then
Dim linea() As Char = archivo(i)
If linea.Length = 0 Then
MessageBox.Show("Línea vacía")
Exit Sub
Else
For j As Integer = 0 To linea.Length - 1
If j = columna - 1 Then
'MessageBox.Show(linea(j))
Dim n As Integer = j + largo - 1
If n >= linea.Length Then
MessageBox.Show("No se puede obtener el dato")
Exit Sub
Else
For k As Integer = j To n
dato += linea(k)
Next
MessageBox.Show(dato)
Return
End If
End If
Next
End If
End If
Next
Dim pause1 As String = ""
End Sub
miércoles, 11 de septiembre de 2019
inicializar formulario maximizado
WindowState = Maximized
Etiquetas:
Maximizado,
WindowState
viernes, 6 de septiembre de 2019
Eliminar fila datagridview
If dg_view.Rows.Count > 0 Then
dg_view.Rows.Remove(dg_variables.CurrentRow)
End If
dg_view.Rows.Remove(dg_variables.CurrentRow)
End If
Etiquetas:
CurrentRow,
DataGridView,
eliminar
martes, 27 de agosto de 2019
Extraer datos array
Dim dte() As String = array.Skip(2).ToArray
validar nombres de los nodos xml
Dim child As XmlElement = xml.CreateElement(XmlConvert.EncodeName(data(0)))
Etiquetas:
EncodeName,
xml,
XmlConvert
Buscar elementos repetidos en una columna
Dim query1 = (From i As DataGridViewRow In dg_captura.Rows Select i.Cells(0)).ToList()
Dim query2 = query1.GroupBy(Function(x) x.Value).Where(Function(g) g.Count > 1).Select(Function(y) y.Key).ToList()
fuente
Dim query2 = query1.GroupBy(Function(x) x.Value).Where(Function(g) g.Count > 1).Select(Function(y) y.Key).ToList()
fuente
obtener los valores de la columna datagrid
Dim query1 = (From i As DataGridViewRow In dg_captura.Rows Select i.Cells(0)).ToList()
Busca elemento repetido en una columna especifica
Dim query2 = query1.GroupBy(Function(x) x.Value).Where(Function(g) g.Count > 1).Select(Function(y) y.Key).ToList()
Busca elemento repetido en una columna especifica
Dim query2 = query1.GroupBy(Function(x) x.Value).Where(Function(g) g.Count > 1).Select(Function(y) y.Key).ToList()
Etiquetas:
DataGridView,
From,
Repetido
viernes, 23 de agosto de 2019
actualizar grid
Private Sub DataGridView1_CurrentCellDirtyStateChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DgvTareas.CurrentCellDirtyStateChanged
If DataGridView1.IsCurrentCellDirty Then
DataGridview1.CommitEdit(DataGridViewDataErrorContexts.Commit)
End If
End Sub
If DataGridView1.IsCurrentCellDirty Then
DataGridview1.CommitEdit(DataGridViewDataErrorContexts.Commit)
End If
End Sub
encriptar desencriptar
Public hash As String = "@H45H@"
Public Function encriptar(ByVal str As String) As String
Dim data As Byte() = UTF8Encoding.UTF8.GetBytes(str)
Dim transform As ICryptoTransform
Dim results As Byte()
Dim keys As Byte()
Using md5 As MD5CryptoServiceProvider = New MD5CryptoServiceProvider
keys = md5.ComputeHash(UTF8Encoding.UTF8.GetBytes(hash))
Using tripDes As TripleDESCryptoServiceProvider = New TripleDESCryptoServiceProvider
tripDes.Key = keys
tripDes.Mode = CipherMode.ECB
tripDes.Padding = PaddingMode.PKCS7
transform = tripDes.CreateEncryptor
results = transform.TransformFinalBlock(data, 0, data.Length)
Return Convert.ToBase64String(results, 0, results.Length)
End Using
End Using
End Function
' Using tripDes As TripleDESCryptoServiceProvider = New TripleDESCryptoServiceProvider With {.Key = keys, .Mode = CipherMode.ECB, .Padding = PaddingMode.PKCS7}
Public Function desencriptar(ByVal str As String) As String
Dim data As Byte() = Convert.FromBase64String(str)
Dim transform As ICryptoTransform
Dim results As Byte()
Dim keys As Byte()
Using md5 As MD5CryptoServiceProvider = New MD5CryptoServiceProvider
keys = md5.ComputeHash(UTF8Encoding.UTF8.GetBytes(hash))
Using tripDes As TripleDESCryptoServiceProvider = New TripleDESCryptoServiceProvider
tripDes.Key = keys
tripDes.Mode = CipherMode.ECB
tripDes.Padding = PaddingMode.PKCS7
transform = tripDes.CreateDecryptor
results = transform.TransformFinalBlock(data, 0, data.Length)
Return UTF8Encoding.UTF8.GetString(results)
End Using
End Using
End Function
fuente
Public Function encriptar(ByVal str As String) As String
Dim data As Byte() = UTF8Encoding.UTF8.GetBytes(str)
Dim transform As ICryptoTransform
Dim results As Byte()
Dim keys As Byte()
Using md5 As MD5CryptoServiceProvider = New MD5CryptoServiceProvider
keys = md5.ComputeHash(UTF8Encoding.UTF8.GetBytes(hash))
Using tripDes As TripleDESCryptoServiceProvider = New TripleDESCryptoServiceProvider
tripDes.Key = keys
tripDes.Mode = CipherMode.ECB
tripDes.Padding = PaddingMode.PKCS7
transform = tripDes.CreateEncryptor
results = transform.TransformFinalBlock(data, 0, data.Length)
Return Convert.ToBase64String(results, 0, results.Length)
End Using
End Using
End Function
' Using tripDes As TripleDESCryptoServiceProvider = New TripleDESCryptoServiceProvider With {.Key = keys, .Mode = CipherMode.ECB, .Padding = PaddingMode.PKCS7}
Public Function desencriptar(ByVal str As String) As String
Dim data As Byte() = Convert.FromBase64String(str)
Dim transform As ICryptoTransform
Dim results As Byte()
Dim keys As Byte()
Using md5 As MD5CryptoServiceProvider = New MD5CryptoServiceProvider
keys = md5.ComputeHash(UTF8Encoding.UTF8.GetBytes(hash))
Using tripDes As TripleDESCryptoServiceProvider = New TripleDESCryptoServiceProvider
tripDes.Key = keys
tripDes.Mode = CipherMode.ECB
tripDes.Padding = PaddingMode.PKCS7
transform = tripDes.CreateDecryptor
results = transform.TransformFinalBlock(data, 0, data.Length)
Return UTF8Encoding.UTF8.GetString(results)
End Using
End Using
End Function
fuente
Etiquetas:
encriptar,
md5,
MD5CryptoServiceProvider
martes, 13 de agosto de 2019
eliminar registros vacíos (Nothing) en un array
array = array.Where(Function(x) x IsNot Nothing).ToArray
Dim carpeta_xml() As String
carpeta_xml = carpeta_xml.Where(Function(x) Not String.IsNullOrEmpty(x)).ToArray
fuente
fuente1
fuente2
Dim carpeta_xml() As String
carpeta_xml = carpeta_xml.Where(Function(x) Not String.IsNullOrEmpty(x)).ToArray
fuente
fuente1
fuente2
TimeSpan mes,semana,día,hora,minuto,segundo
Dim total As TimeSpan = New TimeSpan((Now.AddMonths(nud_mes.Value).Date - Now.Date).TotalDays + (Now.AddDays(nud_semana.Value * 7).Date - Now.Date).TotalDays + nud_dia.Value, nud_hora.Value, nud_minuto.Value, nud_segundo.Value, 0)
Etiquetas:
AddMonths,
milisegundos,
Now,
TimeSpan,
TotalDays
consola
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Try
'Dim sr As New StreamReader("file.txt")
rtb_console.Text = File.ReadAllText("file.txt")
'rtb_console.AppendText(File.ReadAllText("file.txt"))
rtb_console.SelectionStart = rtb_console.TextLength
rtb_console.ScrollToCaret()
'rtb_console.Focus()
'rtb_console.Refresh()
Catch ex As Exception
End Try
' https://www.codeproject.com/Questions/430020/which-is-the-control-best-suited-for-displaying-th
End Sub
Try
'Dim sr As New StreamReader("file.txt")
rtb_console.Text = File.ReadAllText("file.txt")
'rtb_console.AppendText(File.ReadAllText("file.txt"))
rtb_console.SelectionStart = rtb_console.TextLength
rtb_console.ScrollToCaret()
'rtb_console.Focus()
'rtb_console.Refresh()
Catch ex As Exception
End Try
' https://www.codeproject.com/Questions/430020/which-is-the-control-best-suited-for-displaying-th
End Sub
timespan
Private Sub btn_ok_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_ok.Click
Dim totalDia As Long = (Now.AddDays(1).Date - DateTime.Now).TotalMilliseconds
'Dim t As TimeSpan = TimeSpan.FromDays(31)
Dim cantidad_dias_mes As Integer = (Now.AddMonths(12).Date - DateTime.Now).TotalDays
Dim t1 As TimeSpan = TimeSpan.FromDays(cantidad_dias_mes)
Dim cantidad_dias_semana As Integer = (Now.AddDays(2 * 7).Date - DateTime.Now).TotalDays
Dim t2 As TimeSpan = TimeSpan.FromDays(cantidad_dias_semana)
Dim cantidad_dias_dia As Integer = (Now.AddDays(1).Date - DateTime.Now).TotalDays
Dim t3 As TimeSpan = TimeSpan.FromDays(cantidad_dias_dia)
End Sub
Dim totalDia As Long = (Now.AddDays(1).Date - DateTime.Now).TotalMilliseconds
'Dim t As TimeSpan = TimeSpan.FromDays(31)
Dim cantidad_dias_mes As Integer = (Now.AddMonths(12).Date - DateTime.Now).TotalDays
Dim t1 As TimeSpan = TimeSpan.FromDays(cantidad_dias_mes)
Dim cantidad_dias_semana As Integer = (Now.AddDays(2 * 7).Date - DateTime.Now).TotalDays
Dim t2 As TimeSpan = TimeSpan.FromDays(cantidad_dias_semana)
Dim cantidad_dias_dia As Integer = (Now.AddDays(1).Date - DateTime.Now).TotalDays
Dim t3 As TimeSpan = TimeSpan.FromDays(cantidad_dias_dia)
End Sub
viernes, 9 de agosto de 2019
Split string to array con vacíos
a.Split(';').Where(s => s.Length > 0).ToArray();
bloquear combobox
Private Sub cb_tareas_MouseDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles cb_tareas.MouseDown
If e.Button = MouseButtons.Right Then
cb_tareas.DroppedDown = True
End If
End Sub
Private Sub cb_tareas_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles cb_tareas.KeyDown
e.SuppressKeyPress = True
End Sub
Private Sub cb_tareas_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles cb_tareas.KeyPress
e.Handled = True
End Sub
martes, 6 de agosto de 2019
Crear archivo xml
Dim xml As New XmlDocument
xml.AppendChild(xml.CreateXmlDeclaration("1.0", "UTF-8", Nothing))
Dim nodo As XmlNode = xml.CreateElement("DTE")
nodo.InnerXml = "<Documento>" &
"<TipoDTE></TipoDTE>" &
"<Folio></Folio>" &
"<EstadoSII></EstadoSII>" &
"<TrackID></TrackID>" &
"</Documento>"
xml.AppendChild(nodo)
xml.Save(archivo)
Fuente
xml.AppendChild(xml.CreateXmlDeclaration("1.0", "UTF-8", Nothing))
Dim nodo As XmlNode = xml.CreateElement("DTE")
nodo.InnerXml = "<Documento>" &
"<TipoDTE></TipoDTE>" &
"<Folio></Folio>" &
"<EstadoSII></EstadoSII>" &
"<TrackID></TrackID>" &
"</Documento>"
xml.AppendChild(nodo)
xml.Save(archivo)
Fuente
Etiquetas:
CreateXmlDeclaration,
xml,
XmlNode
lunes, 5 de agosto de 2019
hashset split
Dim t As New HashSet(Of String)
t.Add("33,45690;ruta xml")
t.Add("39,123;ruta txt")
Dim data As String = String.Join("@", t.Select(Function(x) x.Split(";")(0)).ToArray)
Dim path() As String = t.Select(Function(x) x.Split(";")(1)).ToArray
hashset to string separador
Dim enviar As New HashSet(Of String)
Dim str As String = ""
str = String.Join(@, enviar.ToArray)
fuente
Dim str As String = ""
str = String.Join(@, enviar.ToArray)
fuente
jueves, 1 de agosto de 2019
Tamaño de un archivo
Dim archivo As String = "xml_venta.xml"
Dim size_ As Long = New System.IO.FileInfo(archivo).Length
Dim p As String = size_.ToString("N0")
MessageBox.Show(p & " bytes")
Dim size_ As Long = New System.IO.FileInfo(archivo).Length
Dim p As String = size_.ToString("N0")
MessageBox.Show(p & " bytes")
servicio existe
Agregar referencia: System.ServiceProcess
Dim se As Boolean = ServiceExists("LanmanWorkstation")
Public Function ServiceExists(ByVal ServiceName As String)
Return ServiceController.GetServices.Any(Function(x) x.ServiceName.Equals(ServiceName))
End Function
Dim status As String = ServiceIsRunning("LanmanWorkstation")
Public Function ServiceIsRunning(ByVal ServiceName As String) As String
Dim sc As ServiceController = New ServiceController(ServiceName)
Select Case sc.Status
Case ServiceControllerStatus.Running ' Iniciado
Return "Running"
Case ServiceControllerStatus.Stopped ' Detenido
Return "Stopped"
Case ServiceControllerStatus.Paused ' Pausado
Return "Paused"
Case ServiceControllerStatus.StopPending ' Deteniendose
Return "Stopping"
Case ServiceControllerStatus.StartPending ' Iniciando
Return "Starting"
Case Else
Return "Status Changing" ' Desconocido
End Select
End Function
fuente
buscar string regex
Dim rx As Regex = New Regex("[a-z]")
If rx.IsMatch("string") Then
Return True
End If
If rx.IsMatch("string") Then
Return True
End If
Crear archivo
File.Create("nombre_archivo").Dispose
martes, 30 de julio de 2019
servicio timer elapsed
SystemTimers.Timer
Timer1_Elapsed(Me, Nothing)
Etiquetas:
servicio,
Timer,
windows service
jueves, 25 de julio de 2019
ordenar elementos combobox
ComboBox1.Sorted = True
Buscar todos los archivos en todos los directorios
Dim array() As String = Directory.GetFiles(ruta_carpeta, "*", SearchOption.AllDirectories)
buscar texto en string con regex
Dim rgx As String = ".PDF"
Dim rx As Regex = New(rgx)
If rx.IsMatch("c:\archivo.PDF") Then
End If
Dim rx As Regex = New(rgx)
If rx.IsMatch("c:\archivo.PDF") Then
End If
carpetas directorios
Public Function get_fecha(ByVal f As String) As String
Dim t As FileInfo = New FileInfo(f)
Return t.Directory.Parent.Parent.ToString & t.Directory.Parent.ToString & t.Directory.Name
End Function
Dim t As FileInfo = New FileInfo(f)
Return t.Directory.Parent.Parent.ToString & t.Directory.Parent.ToString & t.Directory.Name
End Function
Etiquetas:
carpetas,
directorios,
FileInfo
martes, 23 de julio de 2019
boleta declaración de cumplimiento
https://www4.sii.cl/certBolElectDteInternet
lunes, 22 de julio de 2019
tabla en html
tr: table row (fila de tabla)
td: table data (celda de una tabla)
<table border="5" bordercolor="#ff0000">
<tr>
<td>Cell A</td>
<td>Cell B</td>
<td>Cell C</td>
</tr>
</table>
td: table data (celda de una tabla)
<table border="5" bordercolor="#ff0000">
<tr>
<td>Cell A</td>
<td>Cell B</td>
<td>Cell C</td>
</tr>
</table>
jueves, 18 de julio de 2019
lista de procesos
Imports System.IO
Public Class Form1
Public t As Timer
Private mtimers() As Timer
Private sc1 As New Object
Private sc2 As New Object
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim max As Integer = 2
ReDim mtimers(max)
For i As Integer = 0 To max
t = New Timer
If i = 0 Then
t.Interval = 100 * 1
ElseIf i = 1 Then
t.Interval = 1000 * 1
ElseIf i = 2 Then
t.Interval = 1000 * 30
End If
t.Enabled = True
t.Tag = i + 1
AddHandler t.Tick, AddressOf Timer_Tick
mtimers(i) = t
Next
End Sub
Private Sub Timer_Tick(ByVal sender As Object, ByVal e As EventArgs)
Dim timer As Timer = DirectCast(sender, Timer)
Select Case timer.Tag
Case "1"
Dim th1 As Threading.Thread
'th1 = New Threading.Thread(AddressOf function1)
th1 = New Threading.Thread(Sub() Me.function1(7))
th1.Start()
'Dim sw As New StreamWriter("test1.txt", True)
'sw.WriteLine(Now.ToString("HH:mm:ss"))
'sw.Close()
'While True
'End While
'timer.Stop()
Case "2"
'MessageBox.Show("TAG 2")
Dim th2 As Threading.Thread
th2 = New Threading.Thread(AddressOf function2)
th2.Start()
'Dim sw As New StreamWriter("test2.txt", True)
'sw.WriteLine(Now.ToString("HH:mm:ss"))
'sw.Close()
Case 3
Dim th3 As Threading.Thread
th3 = New Threading.Thread(AddressOf function3)
th3.Start()
End Select
End Sub
Private Sub function1(ByVal id As Integer)
SyncLock sc1
'If id = 1 Then
' Exit Sub
'End If
'While True
' Threading.Thread.Sleep(1000)
'End While
Dim sw As New StreamWriter("test1.txt", True)
sw.WriteLine(Now.ToString("HH:mm:ss"))
sw.Close()
End SyncLock
End Sub
Private Sub function2()
SyncLock sc1
Dim sw As New StreamWriter("test1.txt", True)
'sw.WriteLine(Now.ToString("HH:mm:ss"))
sw.WriteLine("hola!")
sw.Close()
End SyncLock
End Sub
Private Sub function3()
Dim sw As New StreamWriter("test3.txt", True)
sw.WriteLine(Now.ToString("HH:mm:ss"))
sw.Close()
End Sub
Private Sub btn_cancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_cancel.Click
For Each t As Timer In mtimers
t.Stop()
Next
End Sub
End Class
' https://www.dreamincode.net/forums/topic/140657-how-to-use-the-timer-as-array/
' http://vbcity.com/forums/t/36812.aspx
' https://social.msdn.microsoft.com/Forums/vstudio/en-US/ce7214c3-2116-4cfa-bb70-58ba2997cea7/stop-all-timers-at-once?forum=vbgeneral
Public Class Form1
Public t As Timer
Private mtimers() As Timer
Private sc1 As New Object
Private sc2 As New Object
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim max As Integer = 2
ReDim mtimers(max)
For i As Integer = 0 To max
t = New Timer
If i = 0 Then
t.Interval = 100 * 1
ElseIf i = 1 Then
t.Interval = 1000 * 1
ElseIf i = 2 Then
t.Interval = 1000 * 30
End If
t.Enabled = True
t.Tag = i + 1
AddHandler t.Tick, AddressOf Timer_Tick
mtimers(i) = t
Next
End Sub
Private Sub Timer_Tick(ByVal sender As Object, ByVal e As EventArgs)
Dim timer As Timer = DirectCast(sender, Timer)
Select Case timer.Tag
Case "1"
Dim th1 As Threading.Thread
'th1 = New Threading.Thread(AddressOf function1)
th1 = New Threading.Thread(Sub() Me.function1(7))
th1.Start()
'Dim sw As New StreamWriter("test1.txt", True)
'sw.WriteLine(Now.ToString("HH:mm:ss"))
'sw.Close()
'While True
'End While
'timer.Stop()
Case "2"
'MessageBox.Show("TAG 2")
Dim th2 As Threading.Thread
th2 = New Threading.Thread(AddressOf function2)
th2.Start()
'Dim sw As New StreamWriter("test2.txt", True)
'sw.WriteLine(Now.ToString("HH:mm:ss"))
'sw.Close()
Case 3
Dim th3 As Threading.Thread
th3 = New Threading.Thread(AddressOf function3)
th3.Start()
End Select
End Sub
Private Sub function1(ByVal id As Integer)
SyncLock sc1
'If id = 1 Then
' Exit Sub
'End If
'While True
' Threading.Thread.Sleep(1000)
'End While
Dim sw As New StreamWriter("test1.txt", True)
sw.WriteLine(Now.ToString("HH:mm:ss"))
sw.Close()
End SyncLock
End Sub
Private Sub function2()
SyncLock sc1
Dim sw As New StreamWriter("test1.txt", True)
'sw.WriteLine(Now.ToString("HH:mm:ss"))
sw.WriteLine("hola!")
sw.Close()
End SyncLock
End Sub
Private Sub function3()
Dim sw As New StreamWriter("test3.txt", True)
sw.WriteLine(Now.ToString("HH:mm:ss"))
sw.Close()
End Sub
Private Sub btn_cancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_cancel.Click
For Each t As Timer In mtimers
t.Stop()
Next
End Sub
End Class
' https://www.dreamincode.net/forums/topic/140657-how-to-use-the-timer-as-array/
' http://vbcity.com/forums/t/36812.aspx
' https://social.msdn.microsoft.com/Forums/vstudio/en-US/ce7214c3-2116-4cfa-bb70-58ba2997cea7/stop-all-timers-at-once?forum=vbgeneral
threads con parámetros
Dim th1 As Threading.Thread
th1 = New Threading.Thread(Sub() Me.function(1))
th1.Start()
Private Sub function1(ByVal id As Integer)
End Sub
fuente
th1 = New Threading.Thread(Sub() Me.function(1))
th1.Start()
Private Sub function1(ByVal id As Integer)
End Sub
fuente
lista de funciones con timer
Imports System.IO
Public Class Form1
Public t As Timer
Private mtimers() As Timer
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
ReDim mtimers(1)
For i As Integer = 0 To 1
t = New Timer
t.Interval = 1000 * (i + 1)
t.Enabled = True
t.Tag = i + 1
AddHandler t.Tick, AddressOf Timer_Tick
mtimers(i) = t
Next
End Sub
Private Sub Timer_Tick(ByVal sender As Object, ByVal e As EventArgs)
Dim timer As Timer = DirectCast(sender, Timer)
Select Case timer.Tag
Case "1"
Dim sw As New StreamWriter("test1.txt", True)
sw.WriteLine(Now.ToString("HH:mm:ss"))
sw.Close()
'timer.Stop()
Case "2"
'MessageBox.Show("TAG 2")
Dim sw As New StreamWriter("test2.txt", True)
sw.WriteLine(Now.ToString("HH:mm:ss"))
sw.Close()
End Select
End Sub
Private Sub btn_cancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_cancel.Click
For Each t As Timer In mtimers
t.Stop()
Next
End Sub
End Class
fuente1
fuente2
fuente3
Public Class Form1
Public t As Timer
Private mtimers() As Timer
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
ReDim mtimers(1)
For i As Integer = 0 To 1
t = New Timer
t.Interval = 1000 * (i + 1)
t.Enabled = True
t.Tag = i + 1
AddHandler t.Tick, AddressOf Timer_Tick
mtimers(i) = t
Next
End Sub
Private Sub Timer_Tick(ByVal sender As Object, ByVal e As EventArgs)
Dim timer As Timer = DirectCast(sender, Timer)
Select Case timer.Tag
Case "1"
Dim sw As New StreamWriter("test1.txt", True)
sw.WriteLine(Now.ToString("HH:mm:ss"))
sw.Close()
'timer.Stop()
Case "2"
'MessageBox.Show("TAG 2")
Dim sw As New StreamWriter("test2.txt", True)
sw.WriteLine(Now.ToString("HH:mm:ss"))
sw.Close()
End Select
End Sub
Private Sub btn_cancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_cancel.Click
For Each t As Timer In mtimers
t.Stop()
Next
End Sub
End Class
fuente1
fuente2
fuente3
log
Public Sub log(ByVal msj As String)
Dim lista As New List(Of String)
Try
lista = File.ReadAllLines(archivo).ToList
lista.Insert(0, msj)
'Dim formatter As IFormatter
'Using st As Stream = New MemoryStream
' formatter = New BinaryFormatter
' formatter.Serialize(st, lista)
' MessageBox.Show(st.Length \ 1024)
'End Using
File.WriteAllText(archivo, String.Empty)
File.WriteAllLines(archivo, lista.ToArray, System.Text.Encoding.UTF8)
lista.Clear()
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
End Sub
Dim lista As New List(Of String)
Try
lista = File.ReadAllLines(archivo).ToList
lista.Insert(0, msj)
'Dim formatter As IFormatter
'Using st As Stream = New MemoryStream
' formatter = New BinaryFormatter
' formatter.Serialize(st, lista)
' MessageBox.Show(st.Length \ 1024)
'End Using
File.WriteAllText(archivo, String.Empty)
File.WriteAllLines(archivo, lista.ToArray, System.Text.Encoding.UTF8)
lista.Clear()
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
End Sub
miércoles, 17 de julio de 2019
crear log aplicación / servicio tamaño archivo
Public Sub log(ByVal mensaje As String)
Dim filename As String = Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location) & "\" & "log.txt"
If File.Exists(filename) Then
Dim archivo_size As Long = New FileInfo(filename).Length / 1024
If archivo_size >= 500 Then
Try
Kill(filename)
Catch ex As Exception
End Try
End If
End If
Dim tempfile As String = Path.GetTempFileName()
If Not File.Exists(filename) Then
File.Create(filename).Close()
End If
Using writer = New StreamWriter(tempfile)
Using reader = New StreamReader(filename)
writer.WriteLine("[" & Now.ToString("dd-MM-yyyy_HH:mm:ss") & "]-->" & mensaje)
While Not reader.EndOfStream
writer.WriteLine(reader.ReadLine())
End While
End Using
End Using
File.Copy(tempfile, filename, True)
File.Delete(tempfile)
End Sub
fuente1
Dim filename As String = Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location) & "\" & "log.txt"
If File.Exists(filename) Then
Dim archivo_size As Long = New FileInfo(filename).Length / 1024
If archivo_size >= 500 Then
Try
Kill(filename)
Catch ex As Exception
End Try
End If
End If
Dim tempfile As String = Path.GetTempFileName()
If Not File.Exists(filename) Then
File.Create(filename).Close()
End If
Using writer = New StreamWriter(tempfile)
Using reader = New StreamReader(filename)
writer.WriteLine("[" & Now.ToString("dd-MM-yyyy_HH:mm:ss") & "]-->" & mensaje)
While Not reader.EndOfStream
writer.WriteLine(reader.ReadLine())
End While
End Using
End Using
File.Copy(tempfile, filename, True)
File.Delete(tempfile)
End Sub
fuente1
jueves, 11 de julio de 2019
transformar de byte a string ItemArray DataRow
Dim str As String = Encoding.Default.GetString(dr.ItemArray(5), 0, dr.ItemArray(5).Length)
Agregar columna a un ItemArray Datarow
ds.Tables(0).Columns.Add("CAF", Type.GetType("System.Byte[]"))
If ds.Tables(0).Rows.Count > 0 Then
For Each dr As DataRow In ds.Tables(0).Rows
tipos de dato para la columna
If ds.Tables(0).Rows.Count > 0 Then
For Each dr As DataRow In ds.Tables(0).Rows
tipos de dato para la columna
miércoles, 10 de julio de 2019
tcp socket windows service
Etiquetas:
socket,
windows service
número de elementos de una estructura
Public Structure empresa
Dim rut As String
Dim rsa As String
End Structure
Dim i As Integer = GetType(empresa).GetFields((BindingFlags.NonPublic Or (BindingFlags.Public Or BindingFlags.Instance))).Length
fuente
Dim rut As String
Dim rsa As String
End Structure
Dim i As Integer = GetType(empresa).GetFields((BindingFlags.NonPublic Or (BindingFlags.Public Or BindingFlags.Instance))).Length
fuente
Etiquetas:
estructura,
Lenght,
Structure
martes, 9 de julio de 2019
cambiar fondo textbox
TextBox1.BackColor = System.Drawing.SystemColors.Info
crear archivo xml
Public Sub crear_archivo_cfg(ByVal archivo As String)
Dim sw As New StreamWriter(archivo, False, Encoding.UTF8)
sw.WriteLine("<?xml version=""1.0"" encoding=""UTF-8""?>")
sw.WriteLine("<DATA>")
sw.Write("</DATA>")
sw.Close()
End Sub
Dim sw As New StreamWriter(archivo, False, Encoding.UTF8)
sw.WriteLine("<?xml version=""1.0"" encoding=""UTF-8""?>")
sw.WriteLine("<DATA>")
sw.Write("</DATA>")
sw.Close()
End Sub
Etiquetas:
crear archivo xml,
utf,
utf8,
xml
eliminar nodo archivo xml
Public Sub eliminar_empresa(ByVal archivo As String, ByVal rut As String)
Dim doc As New XmlDocument
doc.Load(archivo)
Dim nodos As XmlNodeList = doc.GetElementsByTagName("empresa")
For Each nodo As XmlNode In nodos
Dim x = nodo("rut").InnerXml
If nodo("rut").InnerXml = rut Then
nodo.ParentNode.RemoveChild(nodo)
Exit For
End If
Next
doc.Save(archivo)
End Sub
Dim doc As New XmlDocument
doc.Load(archivo)
Dim nodos As XmlNodeList = doc.GetElementsByTagName("empresa")
For Each nodo As XmlNode In nodos
Dim x = nodo("rut").InnerXml
If nodo("rut").InnerXml = rut Then
nodo.ParentNode.RemoveChild(nodo)
Exit For
End If
Next
doc.Save(archivo)
End Sub
Etiquetas:
ParentNode,
RemoveChild,
xml
viernes, 5 de julio de 2019
dataset a lista
Dim ds As New DataSet
Dim list As List(Of Long) = ds.Tables(0).AsEnumerable.Select(Function(x) x.Field(Of Long)(0)).ToList
fuente
Dim list As List(Of Long) = ds.Tables(0).AsEnumerable.Select(Function(x) x.Field(Of Long)(0)).ToList
fuente
jueves, 4 de julio de 2019
descargar archivo
Imports System.Net
Imports System.Text
Public Class Form1
Private Sub btn_ok_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_ok.Click
Dim wc As New WebClient
Dim result() As Byte = Nothing
Dim str As String
Try
result = wc.DownloadData("")
str = Encoding.UTF8.GetString(result)
Dim pause As String = ""
Catch ex As Exception
End Try
End Sub
Private Sub btn_async_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_async.Click
Dim url As String = ""
Dim wc As New WebClient
AddHandler wc.DownloadDataCompleted, AddressOf DownloadDataCompleted
wc.DownloadDataAsync(New Uri(url))
End Sub
Private Shared Sub DownloadDataCompleted(ByVal sender As Object, ByVal e As DownloadDataCompletedEventArgs)
Dim str As String
Dim raw() As Byte = e.Result
str = Encoding.UTF8.GetString(raw)
Dim pause As String = ""
End Sub
End Class
' https://stackoverflow.com/questions/2375896/vb-net-downloaddataasync
' https://stackoverflow.com/questions/1585985/how-to-use-the-webclient-downloaddataasync-method-in-this-context
' https://stackoverflow.com/questions/35056500/download-file-from-google-drive-using-c-sharp-without-google-api
' https://stackoverflow.com/questions/19686599/download-file-directly-to-memory
Imports System.Text
Public Class Form1
Private Sub btn_ok_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_ok.Click
Dim wc As New WebClient
Dim result() As Byte = Nothing
Dim str As String
Try
result = wc.DownloadData("")
str = Encoding.UTF8.GetString(result)
Dim pause As String = ""
Catch ex As Exception
End Try
End Sub
Private Sub btn_async_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_async.Click
Dim url As String = ""
Dim wc As New WebClient
AddHandler wc.DownloadDataCompleted, AddressOf DownloadDataCompleted
wc.DownloadDataAsync(New Uri(url))
End Sub
Private Shared Sub DownloadDataCompleted(ByVal sender As Object, ByVal e As DownloadDataCompletedEventArgs)
Dim str As String
Dim raw() As Byte = e.Result
str = Encoding.UTF8.GetString(raw)
Dim pause As String = ""
End Sub
End Class
' https://stackoverflow.com/questions/2375896/vb-net-downloaddataasync
' https://stackoverflow.com/questions/1585985/how-to-use-the-webclient-downloaddataasync-method-in-this-context
' https://stackoverflow.com/questions/35056500/download-file-from-google-drive-using-c-sharp-without-google-api
' https://stackoverflow.com/questions/19686599/download-file-directly-to-memory
Etiquetas:
AddressOf,
DownloadDataAsync,
WebClient
viernes, 28 de junio de 2019
warning windows service
The target version of the .NET Framework in the project does not match the .NET Framework launch condition version '.NET Framework 4'. Update the version of the .NET Framework launch condition to match the target version of the .NET Framework in the Advanced Compile Options Dialog Box (VB) or the Application Page (C#, F#).
1. Setup
2. Click mouse right button and select View options Launch Conditions
3. Select Launch conditions properties and change version framework prerequisites, example: .NET Framework 3.5
fuente
1. Setup
2. Click mouse right button and select View options Launch Conditions
3. Select Launch conditions properties and change version framework prerequisites, example: .NET Framework 3.5
fuente
Etiquetas:
Framework,
windows service
miércoles, 26 de junio de 2019
Obtener el primer directorio después del directorio raíz
Dim dir As System.IO.FileInfo = New System.IO.FileInfo(nombre_archivo)
dir.Directory.Parent.FullName
dir.Directory.Parent.FullName
Etiquetas:
directorio,
Directory,
FileInfo
martes, 25 de junio de 2019
obtener el nombre del directorio de un archivo
ejemplo:
c:\tareas\archivo.xml --->tareas
return Path.GetFileName(Path.GetDirectoryName(c:\tareas\archivo.xml))
fuente
c:\tareas\archivo.xml --->tareas
return Path.GetFileName(Path.GetDirectoryName(c:\tareas\archivo.xml))
fuente
Etiquetas:
GetDirectoryName,
GetFileName,
Path
The underlying connection was closed
The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.
solución:
ServicePointManager.ServerCertificateValidationCallback = AddressOf ValidateRemoteCertificate
'Public Shared Function ValidateRemoteCertificate(ByVal sender As Object, ByVal certificate As X509Certificate, ByVal chain As X509Chain, ByVal sslPolicyErrors As Net.Security.SslPolicyErrors) As Boolean
' Return True
'End Function
fuente
solución:
ServicePointManager.ServerCertificateValidationCallback = AddressOf ValidateRemoteCertificate
'Public Shared Function ValidateRemoteCertificate(ByVal sender As Object, ByVal certificate As X509Certificate, ByVal chain As X509Chain, ByVal sslPolicyErrors As Net.Security.SslPolicyErrors) As Boolean
' Return True
'End Function
fuente
viernes, 21 de junio de 2019
archivo bloqueado
Dim ok As Boolean = file_is_lock(New FileInfo(archivo))
Public Function file_is_lock(ByVal f As FileInfo) As Boolean
Dim stream As FileStream = Nothing
Try
stream = f.Open(FileMode.Open, FileAccess.Read, FileShare.None)
Catch ex As Exception
Return True
Finally
If Not stream Is Nothing Then
stream.Close()
End If
End Try
Return False
End Function
martes, 18 de junio de 2019
Certificación
IDK= 100
IDK= 300
lunes, 17 de junio de 2019
guardar xml con caracteres especiales < > / &
Public Sub guardar_query_cv(ByVal nodo As String, ByVal query_sql As String)
Dim doc As New XmlDocument
doc.Load(Directory.GetCurrentDirectory & "\" & Form1.archivoConfiguracion)
Dim xnode As XmlNode = doc.GetElementsByTagName(nodo)(0)
xnode.InnerXml = System.Security.SecurityElement.Escape(query_sql)
doc.Save(Directory.GetCurrentDirectory & "\" & Form1.archivoConfiguracion)
End Sub
fuente
fuente1
fuente2
jueves, 13 de junio de 2019
obtener el número de línea achivo xml
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim xdoc As XDocument = XDocument.Load("archivo.xml", LoadOptions.SetLineInfo)
Dim categories As IEnumerable(Of XElement) = xdoc.Descendants("TipoDespacho")
For Each category As XElement In categories
Dim lineNumber As Integer = CType(category, IXmlLineInfo).LinePosition
Next
End Sub
Dim xdoc As XDocument = XDocument.Load("archivo.xml", LoadOptions.SetLineInfo)
Dim categories As IEnumerable(Of XElement) = xdoc.Descendants("TipoDespacho")
For Each category As XElement In categories
Dim lineNumber As Integer = CType(category, IXmlLineInfo).LinePosition
Next
End Sub
TabControl TabPage agregar/remover
string a archivo
File.WriteAllText(Directory.GetCurrentDirectory & "\" & "blob.xml", caf_string)
File.WriteAllText(ruta_destino_archivo,dim_string)
Etiquetas:
File,
String,
WriteAllText
Insertar nodo xml antes o después de un elemento
Private Sub bt_insert_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bt_insert.Click
' Insertar el nodo asdf, después del nodo TipoDTE
'doc.PreserveWhitespace = True
doc.Load("DTE33.xml")
Dim elem As XmlNode = doc.CreateElement("asdf")
elem.InnerXml = "456"
Dim node As XmlNode = doc.GetElementsByTagName("IdDoc")(0)
Dim x As XmlElement = doc.GetElementsByTagName("IdDoc")(0).Item("TipoDTE") 'node("TipoDTE")
node.InsertAfter(elem, x)
doc.Save("DTE33.xml")
End Sub
fuente
' Insertar el nodo asdf, después del nodo TipoDTE
'doc.PreserveWhitespace = True
doc.Load("DTE33.xml")
Dim elem As XmlNode = doc.CreateElement("asdf")
elem.InnerXml = "456"
Dim node As XmlNode = doc.GetElementsByTagName("IdDoc")(0)
Dim x As XmlElement = doc.GetElementsByTagName("IdDoc")(0).Item("TipoDTE") 'node("TipoDTE")
node.InsertAfter(elem, x)
doc.Save("DTE33.xml")
End Sub
fuente
Etiquetas:
InsertAfter,
InsertBefore,
xml
miércoles, 12 de junio de 2019
For each array
For Each c As String In New String() {"1", "2", "3", "4"}
MessageBox.Show(c)
Next
MessageBox.Show(c)
Next
martes, 11 de junio de 2019
borrar múltiples filas datagridview
Dim selectedCellCount As Integer = dgv_nodos_sii.SelectedRows.Count
Dim j As DataGridViewSelectedRowCollection = dgv_nodos_sii.SelectedRows
Seleccionar filas de mayor a menor
For Each row As DataGridViewRow In dgv_nodos_sii.SelectedRows
MessageBox.Show(row.Index)
Next
Seleccionar filas de menor a mayor
For Each row As DataGridViewRow In dgv_nodos_sii.SelectedRows.Cast(Of DataGridViewRow).OrderBy(Function(dgvr) dgvr.Index)
MessageBox.Show(row.Index)
Next
fuente
viernes, 7 de junio de 2019
seleccionar item automaticamente
ToolTip listbox
Private Sub lb_dte_MouseMove(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles lb_dte.MouseMove
Dim i As Integer = lb_dte.IndexFromPoint(e.Location)
If i > -1 Then
Dim tip As String = lb_dte.Items(i).ToString
'Dim tipw As ToolTip = Nothing
If tip = 33 Then
tip = "Factura electrónica"
ElseIf tip = 34 Then
tip = "Factura exenta"
ElseIf tip = 39 Then
tip = "Boleta electrónica"
ElseIf tip = 41 Then
tip = "Boleta exenta"
ElseIf tip = 43 Then
ElseIf tip = 46 Then
End If
If (ToolTip1.GetToolTip(lb_dte) IsNot tip) Then
ToolTip1.SetToolTip(lb_dte, tip)
End If
End If
End Sub
Dim i As Integer = lb_dte.IndexFromPoint(e.Location)
If i > -1 Then
Dim tip As String = lb_dte.Items(i).ToString
'Dim tipw As ToolTip = Nothing
If tip = 33 Then
tip = "Factura electrónica"
ElseIf tip = 34 Then
tip = "Factura exenta"
ElseIf tip = 39 Then
tip = "Boleta electrónica"
ElseIf tip = 41 Then
tip = "Boleta exenta"
ElseIf tip = 43 Then
ElseIf tip = 46 Then
End If
If (ToolTip1.GetToolTip(lb_dte) IsNot tip) Then
ToolTip1.SetToolTip(lb_dte, tip)
End If
End If
End Sub
jueves, 6 de junio de 2019
ordenar listbox
Dim arr() As Integer = New Integer(lb_dte_activo.Items.Count - 1) {}
Dim i As Integer = 0
For Each elem In lb_dte_activo.Items
arr(i) = elem
i += 1
Next
Array.Sort(arr)
'lb_dte_activo.Sorted = False
lb_dte_activo.Items.Clear()
lb_dte_activo.Items.AddRange(arr.Cast(Of Object).ToArray())
fuente
Dim i As Integer = 0
For Each elem In lb_dte_activo.Items
arr(i) = elem
i += 1
Next
Array.Sort(arr)
'lb_dte_activo.Sorted = False
lb_dte_activo.Items.Clear()
lb_dte_activo.Items.AddRange(arr.Cast(Of Object).ToArray())
fuente
contar elementos de un nodo
Dim i As Integer = doc.GetElementsByTagName(nodo)(0).ChildNodes.Count
miércoles, 5 de junio de 2019
crear setgesys
Private Sub btn_envio_xml_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_envio_xml.Click
Dim lineas As New ArrayList
Dim txt() As String = File.ReadAllLines("D:\z\brown\tasks\tasks\bin\Debug\DTEOK\DTE33F10331.xml", Encoding.GetEncoding("ISO-8859-1"))
lineas.AddRange(txt)
lineas.Insert(1, "<SetGESYS xmlns=""http://www.sii.cl/SiiDte"">")
lineas.Insert(2, " <Extras>")
lineas.Insert(3, " </Extras>")
lineas.Add("</SetGESYS>")
'txt(1) = " <EnvioDTE xmlns=""http://www.sii.cl/SiiDte"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xsi:schemaLocation=""http://www.sii.cl/SiiDte EnvioDTE_v10.xsd"" version=""1.0"">"
'txt(1) = "<SetGESYS xmlns=""http://www.sii.cl/SiiDte"">"
'File.WriteAllText("D:\z\brown\tasks\tasks\bin\Debug\DTEOK" & "\" & "gesys.xml2", , System.Text.Encoding.GetEncoding("ISO-8859-1")) ' sólo prueba
File.WriteAllLines("D:\z\brown\tasks\tasks\bin\Debug\DTEOK" & "\" & "archivo.xml", lineas.Cast(Of String).ToArray, System.Text.Encoding.GetEncoding("ISO-8859-1"))
End Sub
Dim lineas As New ArrayList
Dim txt() As String = File.ReadAllLines("D:\z\brown\tasks\tasks\bin\Debug\DTEOK\DTE33F10331.xml", Encoding.GetEncoding("ISO-8859-1"))
lineas.AddRange(txt)
lineas.Insert(1, "<SetGESYS xmlns=""http://www.sii.cl/SiiDte"">")
lineas.Insert(2, " <Extras>")
lineas.Insert(3, " </Extras>")
lineas.Add("</SetGESYS>")
'txt(1) = " <EnvioDTE xmlns=""http://www.sii.cl/SiiDte"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xsi:schemaLocation=""http://www.sii.cl/SiiDte EnvioDTE_v10.xsd"" version=""1.0"">"
'txt(1) = "<SetGESYS xmlns=""http://www.sii.cl/SiiDte"">"
'File.WriteAllText("D:\z\brown\tasks\tasks\bin\Debug\DTEOK" & "\" & "gesys.xml2", , System.Text.Encoding.GetEncoding("ISO-8859-1")) ' sólo prueba
File.WriteAllLines("D:\z\brown\tasks\tasks\bin\Debug\DTEOK" & "\" & "archivo.xml", lineas.Cast(Of String).ToArray, System.Text.Encoding.GetEncoding("ISO-8859-1"))
End Sub
Suscribirse a:
Entradas (Atom)