'espero y sea lo que buscas, es lo que utilizo
'Imports System.Globalization
Imports System.Data.SqlClient
Imports System.Security.Principal
Imports System.Net.Mail
Public Class Servidor
#Region "Variables Compartidas"
'Public Shared NombreServidor As String = "" ' "192.168etc" '"ERP86"
'Public Shared NomBaseDatos As String = "Checador"
'Public Shared IDUsuario As String = "root"
'Public Shared ElPassword As String = "Twinc3pt."
Public Shared NombreServidor As String = "192.168etc" '"ERP86"
' Public Shared NomBaseDatos_SQL As String = "PRUEBA"
Public Shared NomBaseDatos As String = "BASEDEDATOS"
Public Shared IDUsuario As String = "sa_casi_siempre_default_es_sa"
Public Shared ElPassword As String = "Contraseña"
Public Shared Conexion As String = "server=" + NombreServidor + ";initial catalog=" + NomBaseDatos + ";User ID=" + IDUsuario + ";password=" + ElPassword + ";"
' Public Shared Conexion_SQL As String = "data source=" + NombreServidor_SQL + ";initial catalog=" + NomBaseDatos_SQL + ";integrated security=false;persist security info=False;User ID=" + IDUsuario_SQL + "; pwd=" + ElPassword_SQL + "; packet size=4096;"
' Public Shared SqlConexion As New MySqlConnection(Conexion)
Public Shared SqlConexion As SqlClient.SqlConnection = New SqlClient.SqlConnection(Conexion)
' Public Shared SqlConexion As SqlClient.SqlConnection = New SqlClient.SqlConnection(Conexion_SQL)
Public Shared SysAdmin As Boolean = False
Public Shared Usuario As String
Public Shared EMP_EmployeeID As String
Public Shared EMP_FirstName As String
Public Shared EMP_LastName As String
Public Shared EMP_RecordID As String
Public Shared EMP_EMailAddress As String
Public Shared EMP_Puesto As String
Public Shared EMP_Planta As String
Public Shared IP As String
Public Shared EMP_encKey As String = "CEGP_Twinc3pt"
Public Shared Ruta_Fotos As String = "\\192.168etc\Recursos Humanos\f"
#End Region
#Region "Variables Solicitud Cheques"
Public Shared tipo_cheque As String
Public Shared Planta As String
Public Shared Caja_chica As String
Public Shared solCheq_empresa As String
Public Shared solCheq_proveedor As String
Public Shared solCheq_nombre_proveedor As String
Public Shared solCheq_por_la_cantidad As Decimal
Public Shared solCheq_moneda As String
Public Shared solCheq_cuenta_bancaria1 As String
Public Shared solCheq_cuenta_bancaria2 As String
Public Shared solCheq_condiciones_pago As String
#Region "Variables Solicitud Cheques Grid Especial"
Public Shared Campo1 As String
Public Shared Campo2 As String
Public Shared Campo3 As String
Public Shared Campo4 As String
Public Shared Campo5 As String
Public Shared Campo6 As String
Public Shared Campo1_1(100) As String
Public Shared Campo2_2(100) As String
Public Shared Campo3_3(100) As String
Public Shared Campo4_4(100) As String
Public Shared Campo5_5(100) As String
Public Shared Campo6_6(100) As String
Public Shared Grupo_grid As String
Public Shared Campo_encabezado As String
Public Shared Campo_encabezado_1(100) As String
#End Region
#End Region
#Region "Variables Impersonation"
Public Shared LOGON32_LOGON_INTERACTIVE As Integer = 2
Public Shared LOGON32_PROVIDER_DEFAULT As Integer = 0
Public Shared impersonationContext As WindowsImpersonationContext
'Public Shared Admin_Usuario As String = "administrador"
'Public Shared Admin_Contraseña As String = "contraseña"
Public Shared Admin_Usuario As String = "usuario"
Public Shared Admin_Contraseña As String = "contraseña"
' Public Shared Folder_Temp As String = "C:\Checador\"
Public Shared Folder_Temp As String = "C:\Integracion\"
Declare Function LogonUserA Lib "advapi32.dll" (ByVal lpszUsername As String, ByVal lpszDomain As String, ByVal lpszPassword As String, ByVal dwLogonType As Integer, ByVal dwLogonProvider As Integer, ByRef phToken As IntPtr) As Integer
Declare Auto Function DuplicateToken Lib "advapi32.dll" (ByVal ExistingTokenHandle As IntPtr, ByVal ImpersonationLevel As Integer, ByRef DuplicateTokenHandle As IntPtr) As Integer
Declare Auto Function RevertToSelf Lib "advapi32.dll" () As Long
Declare Auto Function CloseHandle Lib "kernel32.dll" (ByVal handle As IntPtr) As Long
#End Region
Public Function AbrirConexion_status_sqlconn_trans(ByVal servidor As String,
ByVal BD As String,
ByVal Usuario As String,
ByVal passwd As String) As Object
Dim Conexion As String
Dim SqlConexion As SqlClient.SqlConnection
Dim status As Boolean = False
Dim objetos(3) As Object
Dim transaction As SqlClient.SqlTransaction
Try
Conexion = "data source=" & servidor &
";initial catalog=" & BD &
";integrated security=false;persist security info=False;User ID=" & Usuario &
"; pwd=" & passwd &
"; packet size=4096;"
SqlConexion = New SqlClient.SqlConnection(Conexion)
SqlConexion.Open()
transaction = SqlConexion.BeginTransaction()
status = True
objetos(1) = SqlConexion
objetos(2) = transaction
Catch ex As Exception
objetos(3) = ex.Message
End Try
objetos(0) = status
Return objetos
End Function
Public Function CerrarConexion(ByVal SqlConexion As SqlClient.SqlConnection) As Boolean
Dim band As Boolean = False
Try
SqlConexion.Close()
band = True
Catch ex As Exception
MsgBox("No se puede cerrar la conexion." & vbNewLine & ex.Message, MsgBoxStyle.Critical)
End Try
Return band
End Function
''SQL
Public Shared Function ValidaExisteRegistro(ByVal Notas As String, ByVal campoClave As String, ByVal Tabla As String, ByVal conexion As SqlClient.SqlConnection) As Boolean
'Esta Funcion valida que existen registros referentes a lo buscado, para no mostrar un reporte en blanco
If Not Notas.Equals("") Then
If conexion.State = ConnectionState.Closed Then
conexion.Open()
End If
Dim MiComando As New SqlClient.SqlCommand("Select " + campoClave + " From " + Tabla + " where " + campoClave + " ='" + Notas + "'", conexion)
Dim Midatareader As SqlClient.SqlDataReader = MiComando.ExecuteReader()
Try
If Midatareader.Read Then
Return True
Else
Return False
End If
Catch e As Exception
Return False
Finally
conexion.Close()
Midatareader.Close()
MiComando.Dispose()
End Try
Else
Return False
End If
End Function
Public Shared Function EjecutarTransaccion(ByVal ListaSentencias As ArrayList, ByVal SqlConexionFun As SqlClient.SqlConnection) As Boolean
Dim band As Boolean = False
If SqlConexionFun.State = ConnectionState.Closed Then
SqlConexionFun.Open()
End If
Dim command As SqlCommand = SqlConexionFun.CreateCommand()
Dim transaction As SqlTransaction
Dim strSentencia As Object
Dim sentencia As String = ""
transaction = SqlConexionFun.BeginTransaction()
command.Connection = SqlConexionFun
command.Transaction = transaction
Try
For Each strSentencia In ListaSentencias
sentencia = strSentencia.ToString()
command.CommandText = sentencia.ToString()
command.ExecuteNonQuery()
Next
transaction.Commit()
band = True
Catch ex As Exception
'MsgBox("No se puede terminar la transaccion.", MsgBoxStyle.Critical)
MsgBox(ex.Message, MsgBoxStyle.Critical)
Try
transaction.Rollback()
Catch ex2 As Exception
MsgBox("No se puede revertir la transaccion.", MsgBoxStyle.Critical)
'MsgBox(ex2.Message, MsgBoxStyle.Critical)
End Try
Finally
SqlConexionFun.Close()
End Try
Return band
End Function
Public Shared Function RegresaRegistros(ByVal sQuery As String, ByVal SqlConexionFun As SqlClient.SqlConnection) As DataTable
Dim miDataAdapter As New SqlDataAdapter
Dim miDataTable As New DataTable
Dim miResultado As New DataTable
If Not sQuery.Equals("") Then
Try
If SqlConexionFun.State = ConnectionState.Closed Then
SqlConexionFun.Open()
End If
miDataAdapter.SelectCommand = New SqlCommand(sQuery, SqlConexionFun)
miDataAdapter.SelectCommand.CommandTimeout = 90000
miDataAdapter.Fill(miDataTable)
miResultado = miDataTable
Catch ex As Exception
Try
Catch ex2 As Exception
'Error controlado
MsgBox(ex2.Message)
End Try
Finally
SqlConexionFun.Close()
miDataAdapter.Dispose()
miDataTable.Dispose()
End Try
End If
Return miResultado
End Function
'Public Shared Function ValidaAlmacen(ByVal almacen As String, ByVal usuario As String, ByVal conexion As SqlClient.SqlConnection) As Boolean
' 'Esta Funcion valida que existen registros referentes a lo buscado, para no mostrar un reporte en blanco
' If Not almacen.Equals("") Then
' If conexion.State = ConnectionState.Closed Then
' conexion.Open()
' End If
' Dim MiComando As New SqlClient.SqlCommand("Select almacen From Temp_Inventario_Movil where Almacen ='" + almacen + "'and usuario ='" + usuario + "' ", conexion)
' Dim Midatareader As SqlClient.SqlDataReader = MiComando.ExecuteReader()
' Try
' If Midatareader.Read Then
' Return True
' Else
' Return False
' End If
' Catch e As Exception
' Return False
' Finally
' conexion.Close()
' Midatareader.Close()
' MiComando.Dispose()
' End Try
' Else
' Return False
' End If
'End Function
Public Shared Function impersonateValidUser(ByVal userName As String, ByVal domain As String, ByVal password As String) As Boolean
Dim tempWindowsIdentity As WindowsIdentity
Dim token As IntPtr = IntPtr.Zero
Dim tokenDuplicate As IntPtr = IntPtr.Zero
impersonateValidUser = False
If RevertToSelf() Then
If LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, token) <> 0 Then
If DuplicateToken(token, 2, tokenDuplicate) <> 0 Then
tempWindowsIdentity = New WindowsIdentity(tokenDuplicate)
impersonationContext = tempWindowsIdentity.Impersonate()
If Not impersonationContext Is Nothing Then
impersonateValidUser = True
End If
End If
End If
End If
If Not tokenDuplicate.Equals(IntPtr.Zero) Then
CloseHandle(tokenDuplicate)
End If
If Not token.Equals(IntPtr.Zero) Then
CloseHandle(token)
End If
End Function
Public Sub undoImpersonation()
impersonationContext.Undo()
End Sub
Friend Class email
#Region "variables"
Dim correoHost = "smtp.gmail.com"
'Dim correoHost = "smtp.office365.com"
'Dim correoPuerto = "25"
'Dim correoUsuario As String = "correoelectronico@gmail.com"
'Dim correoPassword As String = "contraseña"
Dim correoPuerto = "587"
Public Shared correoUsuario As String = ""
Public Shared correoPassword As String = ""
Dim EnableSsl = True
Dim Correo As New MailMessage
Dim Cliente As New SmtpClient()
Dim Subject As String
Dim Body As String
Dim Reenvio As New ArrayList
Dim esHtml As Boolean = True
Dim Priority As New MailPriority
#End Region
#Region "Métodos"
Sub New()
Priority = MailPriority.Normal
esHtml = True
End Sub
Public Sub setSubject(ByVal Subject As String)
Me.Subject = Subject
End Sub
Public Sub setBody(ByVal Body As String)
Me.Body = Body
End Sub
Public Sub setReenvio(ByVal Reenvio As ArrayList)
Me.Reenvio = Reenvio
End Sub
Public Sub setesHTML(ByVal esHTML As Boolean)
Me.esHtml = esHTML
End Sub
'Public Sub setAdjunto(ByVal rutaArchivo As String)
' Try
' Dim att As New System.Net.Mail.Attachment(rutaArchivo)
' Correo.Attachments.Add(att)
' Catch ex As Exception
' MessageBox.Show("Error al intentar adjuntar el archivo" & vbNewLine & "ErrorMag: " & ex.Message, "GpoPolesa", MessageBoxButtons.OK, MessageBoxIcon.Error)
' End Try
'End Sub
#End Region
#Region "Funciones"
Public Function getSubject() As String
Return Subject
End Function
Public Function getBody() As String
Return Body
End Function
Public Function getReenvio() As ArrayList
Return Reenvio
End Function
Public Function getCorreo() As MailMessage
Return Correo
End Function
#End Region
Public Function EnviarCorreo()
Dim enviado = False
Cliente.EnableSsl = True
Cliente.Host = correoHost
Cliente.Port = correoPuerto
Cliente.UseDefaultCredentials = False
Cliente.Credentials = New System.Net.NetworkCredential(correoUsuario, correoPassword)
' Correo.From = New System.Net.Mail.MailAddress(correoUsuario, "blabla" + _Alias + "")
Correo.From = New System.Net.Mail.MailAddress(correoUsuario)
If Correo.Subject Is Nothing Then
Try
Correo.Subject = Subject
Catch ex As Exception
MessageBox.Show(ex.Message.ToString, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End If
If Correo.Body Is Nothing Then
Try
Correo.Body = Body
Catch ex As Exception
MessageBox.Show(ex.Message.ToString, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End If
For Each element In Reenvio
Try
Correo.ReplyToList.Add(New MailAddress(element))
Catch ex As Exception
MessageBox.Show(ex.Message.ToString, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
Next
Correo.IsBodyHtml = esHtml
Application.DoEvents()
Cliente.Send(Correo)
Correo.Dispose()
enviado = True
' Catch ex As Exception
'MessageBox.Show("Error al intentar enviar el correo." & vbNewLine & "ErrorMsg: " & ex.Message, "Dynámica", MessageBoxButtons.OK, MessageBoxIcon.Error)
' End Try
Return enviado
End Function
End Class
End Class