I have found the following code
Dim p As New ProcessStartInfo With {
.FileName = "c:\Windows\System32\dsa.msc",
.Arguments = "/SAVECRED /user:DOMAIN\username"
}
' Start the process
Process.Start(p)
I want to be able to pass the following cmd that prompts for username
c:\Windows\System32\runas.exe /SAVECRED /user:DOMAIN\username "c:\Windows\System32\mmc.exe c:\Windows\System32\dsa.msc"
Which works by opening the app but does not pass the username or prompt for password, I cant figure out how to forse the different cred along with arguments.
Ideas ??
Ok figured it out - here is the code i used
Function ConvertToSecureString(ByVal str As String)
Dim password As New SecureString
For Each c As Char In str.ToCharArray
password.AppendChar(c)
Next
Return password
End Function
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim passwordString As String
passwordString = "..........."
Dim password As SecureString = ConvertToSecureString(passwordString)
' New ProcessStartInfo created
Dim p As New ProcessStartInfo
' Specify the location of the binary
p.FileName = "mmc.exe"
p.WorkingDirectory = "c:\Windows\System32\"
' Use these arguments for the process
p.Arguments = "dsa.msc"
p.Domain = "........"
p.UserName = "......."
p.Password = password
p.UseShellExecute = False
' Start the process
Process.Start(p)
End Sub
Related
Trying to learn Visual Studio, I was able to create a static log in form e.g. check if the text box and password match the hard coded data, but I just cannot get the Access query to work. I've ran through 6 different efforts (cleared them all until this point)
Imports System.Data.OleDb
Public Class Login
Dim con As New OleDbConnection
Private Sub OK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK.Click
con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\someone\source\repos\Test\Test\vs.mdb"
con.Open()
Dim logincmd As New OleDbCommand("Select * From tblLogin WHERE userName = " & tbUser.Text, con)
Dim loginrd As OleDbDataReader = logincmd.ExecuteReader
If (loginrd.Read() = True) Then
MenuPage.Show()
Me.Close()
Else
MsgBox("Sorry that's not right")
End If
End Sub
Error: System.Data.OleDb.OleDbException: 'No value given for one or more required parameters.'
On line: Dim loginrd As OleDbDataReader = logincmd.ExecuteReader
Please tell me where I'm going wrong?
EDIT: I've found some code that works, so I'm going to cross reference the two and try work out why the above code didn't work, might help me get a better understanding of things!
Database objects like Connections and Commands need to be disposed. Using...End Using blocks handle this for us. They both declare and dispose the objects. In this code both the connection and command are handled by a single Using block. Note the comma on the first line of the Using.
You can pass the connection string directly to the constructor of the connection. You can also pass the CommandText and Connection directly to the constructor of the command. A constructor will be indicated by the New keyword.
Always use parameters to help defeat sql injection. Parameters will not be treated as executable code by the database.
Don't open the connection until directly before the Execute statement and close and dispose as soon as possible with End Using.
Since we are only seeking a single piece of data (the count) we can use ExecuteScalar which returns the first column of the first row of the result set.
Private ConnStr As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\someone\source\repos\Test\Test\vs.mdb"
Private Sub OK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK.Click
'Validate input
If txtUserName.Text = "" OrElse txtPassword.Text = "" Then
MessageBox.Show("Please fill in both Name and Password.")
Exit Sub
End If
If ValidateLogin(txtUserName.Text, txtPassword.Text) Then
MenuPage.Show()
Me.Close()
Else
MessageBox.Show("Invalid Login")
End If
End Sub
Private Function ValidateLogin(uName As String, pWord As String) As Boolean
Dim IsValid As Boolean
Dim ReturnValue As Integer
Using cn As New OleDbConnection(ConnStr),
cmd As New OleDbCommand("Select Count(*) From tblLogin Where userName = #UserName AND passWord = #Password;", con)
cmd.Parameters.Add("#UserName", OleDbType.VarChar).Value = uName
cmd.Parameters.Add("#Password", OleDbType.VarChar).Value = pWord
cn.Open()
ReturnValue = CInt(cmd.ExecuteScalar)
End Using
If ReturnValue = 1 Then
IsValid = True
End If
Return IsValid
End Function
Of course, you should never store passwords as plain text. Investigate encryption and salting.
I'd suggest
Separating login code from form code
Never use string concatenation for SQL parameters, use command parameters.
Encrypting the database
If exception.Message.ToLower.Contains("not a valid password") Then in this case is for an encrypted database, ignore if not encrypting the database.
Recommend a class for login (table columns shown are different from yours but the logic will work no matter)
Login class
Permits three attempts at a login.
Imports System.Data.OleDb
Public Class ApplicationLogin
Private ReadOnly ConnectionString As String
Public Property UserName As String
Public Property UserPassword As String
Public Property Retries As Integer
Private Userid As Integer
Public ReadOnly Property UserIdentifier As Integer
Get
Return Userid
End Get
End Property
Public Sub New(pConnectionString As String)
ConnectionString = pConnectionString
End Sub
Public Function Login() As Boolean
If Not String.IsNullOrWhiteSpace(Me.UserName) AndAlso Not String.IsNullOrWhiteSpace(Me.UserPassword) Then
Using cn As New OleDbConnection With {.ConnectionString = ConnectionString}
Using cmd As New OleDbCommand With
{
.Connection = cn,
.CommandText =
"SELECT Identifer, UserName, UserPassword FROM Users " &
"WHERE UserName = #UserName AND UserPassword = #UserPassword"
}
cmd.Parameters.Add("#UserName", OleDbType.LongVarChar).Value = UserName
cmd.Parameters.Add("#UserPassword", OleDbType.LongVarChar).Value = UserPassword
Try
cn.Open()
Catch exception As Exception
If exception.Message.ToLower.Contains("not a valid password") Then
Return False
Else
Throw
End If
End Try
Dim reader = cmd.ExecuteScalar
If reader IsNot Nothing Then
Userid = CInt(reader)
Retries = 0
Return True
Else
Retries += 1
Return False
End If
End Using
End Using
Else
Return False
End If
End Function
End Class
Form code
Public Class Form1
Private Retries As Integer = 0
Private Sub LoginButton_Click(sender As Object, e As EventArgs) Handles LoginButton.Click
Dim appLogin As New ApplicationLogin("Your connection string") With
{.UserName = txtUserName.Text, .UserPassword = txtPassword.Text}
If appLogin.Login Then
' login successful
Else
Retries += 1
' too many retries
End If
End Sub
End Class
Full source (not done with .mdb but .accdb)
Front end project
Class project for login logic
Database encryption docs
I get this error:
Could not load file or assembly 'SendGrid.SmtpApi, Version=1.1.3.0, Culture=neutral, PublicKeyToken=55aa52d3c3c0d2b2' or one of its dependencies. The system cannot find the file specified.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
' Create the email object first, then add the properties.
Dim myMessage As SendGridMessage
myMessage = New SendGridMessage()
' Add the message properties.
myMessage.AddTo("example#gmail.com")
myMessage.From = New MailAddress("example#gmail.com")
myMessage.Subject = "Test Sendgrid"
' Add plain text body only:
myMessage.Text = "Body"
Dim username As String
Dim pswd As String
username = "username"
pswd = "password"
Dim credentials As NetworkCredential
credentials = New NetworkCredential(username, pswd)
' // Create an Web transport for sending email
Dim transportWeb As New Web(credentials)
transportWeb.DeliverAsync(myMessage)
End Sub
Screenshot:
https://i.imgur.com/b2iWa0L.png
Please help
Perhaps you could try:
Dim myMessage As SmtpApi.SendGridMessage
myMessage = New SmptApi.SendGridMessage()
I'm rewriting hash_hmac code I got on PHP to VB.Net.
I need same result generated both in PHP and VB.Net.
This is hash_hmac code on PHP:
$data = urlencode('2019-07-21T15:30:57.465Z');
$data = '_ts='.$data;
$signatureSecretKey = "secrete";
$hash = hash_hmac('sha256',$data,$signatureSecretKey,true);
$signature = base64_encode($hash);
echo $signature;
The result shows:
upLQYFI3pI2m9Pu5fyiobpvCRhTvRmEyxrVDrdJOYG4=
And here is my code on VB:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim _ts, data, signature, secrete, hash
secrete = "secret"
_ts = DateTime.Now.ToString("2019-07-21T15:30:57.465Z")
data = "_ts=" & HttpUtility.UrlEncode(_ts)
signature = Encrypt(data, secrete)
TextBox1.Text = signature
End Sub
Public Function Encrypt(Content As String, Secret As String) As String
Dim kode As New System.Text.ASCIIEncoding()
Dim getkode As Byte() = kode.GetBytes(Secret)
Dim cont As Byte() = kode.GetBytes(Content)
Dim hmcKu As New HMACSHA256(getkode)
Dim HashCode As Byte() = hmcKu.ComputeHash(cont)
Return Convert.ToBase64String(HashCode)
End Function
Result of my code is:
892q1ArPxIqrX48PQegliVql703V2fcipb5A08F053o=
You can see my VB code generates different result from PHP.
I have tried almost every method I got from internet but the result always different. So, what is equivalent hash_hmac of PHP on VB and what is the right way to make this same result?
Please help?
Use this:
dim hmac as HMACSHA256 = new HMACSHA256(key) ' key = Encoding.ASCII.GetBytes("<secret>")
dim hashValue as byte() = hmac.ComputeHash(Encoding.ASCII.GetBytes("<message>"))
dim result as string = BitConverter.ToString(hashValue).Replace("-", "").ToLower()
hmac.dispose()
I found solution from fb community.
This is exact solution for this cases:
Imports System.IO
Imports System.Text
Imports System.Security.Cryptography
Imports System.Text.RegularExpressions
Public Class Form1
Private Shared DES As New TripleDESCryptoServiceProvider
Private Shared MD5 As New MD5CryptoServiceProvider
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim _ts, data, signature, secrete
secrete = "secret"
_ts = DateTime.Now.ToUniversalTime.ToString("yyyy-MM-dd\THH:mm:ss.fff\Z")
data = "_ts=" & HttpUtility.UrlEncode(_ts)
Dim reg = New Regex("%[a-f0-9]{2}")
data = reg.Replace(data, Function(m) m.Value.ToUpperInvariant())
signature = Encrypt(data, secrete)
TextBox1.Text = signature
End Sub
Public Function Encrypt(Content As String, Secret As String) As String
Try
Dim kode As New System.Text.ASCIIEncoding()
Dim getkode As Byte() = kode.GetBytes(Secret)
Dim cont As Byte() = kode.GetBytes(Content)
Dim hmcKu As New HMACSHA256(getkode)
Dim HashCode As Byte() = hmcKu.ComputeHash(cont)
Return Convert.ToBase64String(HashCode)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Function
End Class
I am using vb.net 2010 to develop my software. Also have crystal reports in my projects and things are working perfectly in my PC.
My problem is that I design the crystal report in my PC with wizard and my PC is not the server, then upload it to the server so it would be accessible to users. But when try to open report a connection problem to the database pops up. I know that is due to the connection property when I designed the reports in my PC.
How can I solve this problem.
It is showing the popup for giving userid and password. I want to give the server connection programatically.
i given the following code still it showing the popup
Private Sub CrystalReportViewer1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles CrystalReportViewer1.Load
Dim cryRpt As New ReportDocument
Dim crtableLogoninfos As New TableLogOnInfos
Dim crtableLogoninfo As New TableLogOnInfo
Dim crConnectionInfo As New ConnectionInfo
Dim CrTables As Tables
Dim CrTable As Table
cryRpt.Load("E:\ColorLab1\colorlab\colorlab\rpt_bill.rpt")
With crConnectionInfo
.ServerName = "MAHESH\SQLEXPRESS"
.DatabaseName = "cc"
.UserID = "erp"
.Password = "123"
End With
CrTables = cryRpt.Database.Tables
For Each CrTable In CrTables
crtableLogoninfo = CrTable.LogOnInfo
crtableLogoninfo.ConnectionInfo = crConnectionInfo
CrTable.ApplyLogOnInfo(crtableLogoninfo)
Next
CrystalReportViewer1.RefreshReport()
End Sub
How can i solve this?
Add this code in the module(for common access)
Public Sub SetReportDb(ByVal ConnectionString As String, ByRef CrystalReportViewer As CrystalDecisions.Windows.Forms.CrystalReportViewer, ByRef reportDocument As ReportClass)
'Get SQL Server Details
Dim builder As New System.Data.Common.DbConnectionStringBuilder()
builder.ConnectionString = ConnectionString
Dim zServer As String = TryCast(builder("Data Source"), String)
Dim zDatabase As String = TryCast(builder("Initial Catalog"), String)
Dim zUsername As String = TryCast(builder("User ID"), String)
Dim zPassword As String = TryCast(builder("Password"), String)
Dim ciReportConnection As New ConnectionInfo
ciReportConnection.ServerName = zServer
ciReportConnection.DatabaseName = zDatabase
ciReportConnection.UserID = zUsername
ciReportConnection.Password = zPassword
'Assign data source details to tables
For Each table As Table In reportDocument.Database.Tables
table.LogOnInfo.ConnectionInfo = ciReportConnection
table.ApplyLogOnInfo(table.LogOnInfo)
Next
For Each subrep As ReportDocument In reportDocument.Subreports
For Each table As Table In subrep.Database.Tables
table.LogOnInfo.ConnectionInfo = ciReportConnection
table.ApplyLogOnInfo(table.LogOnInfo)
Next
Next
'Assign data source details to the report viewer
If CrystalReportViewer.LogOnInfo IsNot Nothing Then
Dim tlInfo As TableLogOnInfos = CrystalReportViewer.LogOnInfo
For Each tbloginfo As TableLogOnInfo In tlInfo
tbloginfo.ConnectionInfo = ciReportConnection
Next
End If
reportDocument.VerifyDatabase()
reportDocument.Refresh()
CrystalReportViewer.ReportSource = reportDocument
CrystalReportViewer.Refresh()
End Sub
Inside each crystal report viewer give the below code it will override the old connection with connectionstring
Private Sub CrystalReportViewer1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CrystalReportViewer1.Load
SetReportDb(My.Settings.colorlabConnectionString, CrystalReportViewer1, rpt_inwardreport1)
End Sub
So to put this into a proper answer:
Your first problem is solved by creating the same DSN on your server that you have on your PC.
Your second problem can be solved using code that looks something like this:
connection.DatabaseName = [DatabaseName]
connection.UserID = [UserID]
connection.ServerName = [ServerName]
connection.Password = [Password]
or
myCrystalReport.SetDatabaseLogon("myUsername", "myPassword","servername","dbname");
I know this post is a few years old, but after struggling with these same problems, I thought I would add a variation of Mahesh ML's routine for MS SQL 2016 server.
A three things to note:
SqlClient.SqlConnectionStringBuilder is used instead of DbConnectionStringBuilder
zSecurity (added) for Window's authentication instead of database user
reportDocument.DataSourceConnections(0).IntegratedSecurity = True is needed when Windows authentication is used
Public Sub SetReportSQL(ByVal ConnectionString As String,
ByRef CrystalReportViewer As CrystalDecisions.Windows.Forms.CrystalReportViewer,
ByRef reportDocument As ReportClass)
'Get SQL Server Details
Dim builder As New SqlClient.SqlConnectionStringBuilder
builder.ConnectionString = ConnectionString
Dim zServer As String = TryCast(builder("Data Source"), String)
Dim zDatabase As String = TryCast(builder("Initial Catalog"), String)
Dim zSecurity As Boolean = Boolean.TryParse(builder("Integrated Security"), zSecurity)
Dim zUsername As String = TryCast(builder("User ID"), String)
Dim zPassword As String = TryCast(builder("Password"), String)
Dim ciReportConnection As New ConnectionInfo
ciReportConnection.ServerName = zServer
ciReportConnection.DatabaseName = zDatabase
ciReportConnection.IntegratedSecurity = zSecurity
If zSecurity = False Then
ciReportConnection.UserID = zUsername
ciReportConnection.Password = zPassword
Else
reportDocument.DataSourceConnections(0).IntegratedSecurity = True
End If
'Assign data source details to tables
For Each table As Table In reportDocument.Database.Tables
table.LogOnInfo.ConnectionInfo = ciReportConnection
table.ApplyLogOnInfo(table.LogOnInfo)
Next
For Each subrep As ReportDocument In reportDocument.Subreports
For Each table As Table In subrep.Database.Tables
table.LogOnInfo.ConnectionInfo = ciReportConnection
table.ApplyLogOnInfo(table.LogOnInfo)
Next
Next
'Assign data source details to the report viewer
If CrystalReportViewer.LogOnInfo IsNot Nothing Then
Dim tlInfo As TableLogOnInfos = CrystalReportViewer.LogOnInfo
For Each tbloginfo As TableLogOnInfo In tlInfo
tbloginfo.ConnectionInfo = ciReportConnection
Next
End If
reportDocument.VerifyDatabase()
reportDocument.Refresh()
CrystalReportViewer.ReportSource = reportDocument
CrystalReportViewer.Refresh()
End Sub
Hi guys i got the answer
Private Sub rpt_billform_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.CrystalReportViewer1.LogOnInfo.Item(0).ConnectionInfo.ServerName = "MAHESH\SQLEXPRESS"
Me.CrystalReportViewer1.LogOnInfo.Item(0).ConnectionInfo.DatabaseName = "cc"
Me.CrystalReportViewer1.LogOnInfo.Item(0).ConnectionInfo.UserID = "erp"
Me.CrystalReportViewer1.LogOnInfo.Item(0).ConnectionInfo.Password = "123"
End Sub
I am newbie when it comes to working with the vb.net login control so bear with me...
Tp start I am using ASP.net 4.0 and vb.net.
Okay so I have a simple login control that verifies the user against a sql database. (I am hosting with hostgator so I can't use the normal windows auth). Now the biggest probelm I am having is that if the session times out and you get redirected to the login page it doesn't matter what you type in the user name/password on the login in form it just lets you right in even if the user name and password are wrong or the user doesn't exist?
How do I make sure that the login control truly authenticates the user?
Any help is greatly appreciated.
Thanks!
Public strLoginErrorMsg As String
Public type As String
Public rowcount As String
Protected Sub login_sbts_Authenticate(sender As Object, e As System.Web.UI.WebControls.AuthenticateEventArgs) Handles login_sbts.Authenticate
Dim bauthenticated As Boolean = False
bauthenticated = isValidUser(login_sbts.UserName, login_sbts.Password)
If bauthenticated Then
e.Authenticated = True
Else
e.Authenticated = False
End If
lblInfo.Text = type
FormsAuthentication.RedirectFromLoginPage(Me.login_sbts.UserName, True)
If type = "ADMIN" Then
Response.Redirect("dailynote.aspx")
Else
Response.Redirect("other.aspx")
End If
End Sub
Private Function isValidUser(ByVal username As String, ByVal pwd As String) As [Boolean]
Dim con As New SqlConnection("Data Source=localhost;Initial Catalog=sbts-scheduling;User ID=userid;Password=password;")
Dim cmd As New SqlCommand("select * from tblusers where UserName='" & username & "' and Password='" & pwd & "'")
cmd.Connection = con
Dim dt As New DataTable()
Dim da As New SqlDataAdapter(cmd)
con.Open()
da.Fill(dt)
con.Close()
If dt.Rows.Count = 0 Then
strLoginErrorMsg = "Invalid User Name/Password"
dt.Dispose()
Return False
Else
type = dt.Rows(0).Item("UserType").Trim()
Session("usertype") = type
End If
Return True
End Function
Protected Sub login_sbts_LoginError(sender As Object, e As System.EventArgs) Handles login_sbts.LoginError
login_sbts.FailureText = strLoginErrorMsg
End Sub
Actually.. the problem may lye in your call to FormsAuthentication.RedirectFromLoginPage.. I took the liberty of cleaning up your code a bit though. I also added FormsAuthentication.SetAuthCookie in your authentication method.. the name and duration of that cookie will be configured in your web.config file.. or your 'configuration settings'.
Unless you're willing to inherit, clear, and replace the ASP.NET default FormAuthenticationModule.. you're going to have to rely on, in part, the web.config configuration settings.
Public strLoginErrorMsg As String
Public type As String
Public rowcount As String
Protected Sub login_sbts_Authenticate(sender As Object, e As System.Web.UI.WebControls.AuthenticateEventArgs) Handles login_sbts.Authenticate
If isValidUser(login_sbts.UserName, login_sbts.Password) Then
e.Authenticated = True
FormsAuthentication.SetAuthCookie(login_sbts.UserName, false, "/")
lblInfo.Text = type
If type = "ADMIN" Then
Response.Redirect("dailynote.aspx")
Else
FormsAuthentication.RedirectFromLoginPage(Me.login_sbts.UserName, True)
'Response.Redirect("other.aspx")
End If
Else
e.Authenticated = false
End If
End Sub
Private Function isValidUser(ByVal username As String, ByVal pwd As String) As Boolean
isValidUser = False
Dim conn As New SqlConnection("Data Source=localhost;Initial Catalog=sbts-scheduling;User ID=userid;Password=password;")
Dim cmd As New SqlCommand("select * from tblusers where UserName='" & username & "' and Password='" & pwd & "'", conn)
Using conn
conn.open
Using reader As system.data.sqlclient.SqlDataReader = comm.ExecuteReader
If reader.Count > 0 Then
'Not Checking for multible records here.
While reader.read
If Not( IsDBNull(reader("UserType")) Then
Session("usertype") = reader("UserType").Trim()
IsValidUser = True
End If
End While
End If
End Using
If Not( conn.State = State.Close) Then
conn.Close
End If
End Using
End Function
Protected Sub login_sbts_LoginError(sender As Object, e As System.EventArgs) Handles login_sbts.LoginError
login_sbts.FailureText = strLoginErrorMsg
End Sub
I recommend you look into inheriting MembershipProvider. It makes working with the asp server tags a bit easier, as you simply specify your provider in the property of the tag. (after you reference and configure it properly in your web.config, app.config.. or through IIS (will require being placed in Global Cache Assembly and all the other loops to becoming a Trusted Provider.)