I'm getting this error when trying to debug my VB code in Visual Studio to interact with a specific WebService .
Im not very familiar with Visual Basic.
The error is on the line Dim ticket_handle As String = " CR 1001 " ws.closeTicket ( Sid , " closed ticket " ticket_handle )
The complete code:
Imports System.IO Imports System.Xml
Imports System.Xml.Serialization
Imports WebReference
Partial Class _Default
Inherits System.Web.UI.Page
Dim ws As New USD_WebService
Dim sid As String
Dim userhandle, username, password As String
Dim attrVal(5), attr(0), prop(0) As String
Dim requestHandle, requestNumber As String
Dim persistent_id As String
Dim catAttrib(5) As String
Sub Main()
Dim ws As New USD_WebService
ws.Url = "http://hummer:8080/axis/services/USD_R11_WebService?wsdl"
Dim username, password
Dim sid
username = "servicedesk"
password = "password"
sid = ws.login(username, password)
Dim userhandle
userhandle = ws.getHandleForUserid(sid, username)
Dim USD As New WebReference.USD_WebService
sid = USD.login(username, password)
Dim ticket_handle As String = “cr:1001” ws.closeTicket(Sid,“ticket fechado”, ticket_handle)
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
ws.Url = "http://hummer:8080/axis/services/USD_R11_WebService?wsdl"
End Sub
End Class
Can anyone help me plis?!?!
In VB.NET, only one statement may be executed per line. Other languages, like Java or C# use a ';' to denote the end of a statement, however in VB.NET it is the end of a line. The compiler is trying to tell you that you have two statements on a single line and it expects there to only be one.
Dim ticket_handle As String = “cr:1001” ws.closeTicket(Sid,“ticket fechado”, ticket_handle)
Should be
Dim ticket_handle As String = “cr:1001”
ws.closeTicket(Sid,“ticket fechado”, ticket_handle)
Related
I'm trying to make a tool to list and change users group on active directory based on groups that manager has control. I'm stuck on listing function, and it keep getting me this error:
System.DirectoryServices.DirectoryServicesCOMException
Hresult=0x80072032 Message=Invalid distinguished name (DN) syntax specified
Line: Dim searchResults As Search...
Public Class Form1
Private Sub btnSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnsearch.Click
Dim managerID As String
managerID = mngID.Text
Dim employeeID As String
employeeID = empID.Text
Dim emptybox
emptybox = mngID.Text.Length
If emptybox < 8 Then
MsgBox("ManagerID Inválido")
End If
Dim emptybox2
emptybox2 = empID.Text.Length
If emptybox2 < 8 Then
MsgBox("EmployeeID Inválido")
End If
If emptybox = 8 Then
Dim domain = New PrincipalContext(ContextType.Domain)
Dim user = UserPrincipal.FindByIdentity(domain, managerID)
Dim userDN
userDN = user.DistinguishedName
Dim ADEntry As New DirectoryEntry
ADEntry.Path = "LDAP://domain/CN:Users;DC:domain"
Dim Groups As New Collection
Dim mySearcher As DirectorySearcher = New DirectorySearcher(ADEntry)
Dim arrList As New ArrayList()
mySearcher.Filter = "(&(ObjectClass=user)(DistinguisedName=" & userDN & "))"
mySearcher.PropertiesToLoad.Add("MemberOf")
Dim searchResults As SearchResultCollection = mySearcher.FindAll()
If searchResults.Count = 0 Then
MsgBox("ManagerID inválido2")
End If
If searchResults.Count > 0 Then
Dim group As New DirectoryEntry(searchResults(0).Path)
For Each member As Object In group.Properties("MemberOf")
groupbox.Items.Add(member)
Next
End If
End If
End Sub
Your Error
Error 0x80072032 - ERROR_DS_INVALID_DN_SYNTAX
An invalid 'dn' syntax has been specified
Here's something to get you going.
Example VB Script To Connect to Active Directory
Imports System
Imports System.Data
Imports System.Linq
Imports System.IO
Imports System.DirectoryServices
Imports System.DirectoryServices.AccountManagement
Imports System.DirectoryServices.ActiveDirectory
Imports System.Security
Imports System.Security.Permissions
Imports System.Text
Imports System.Collections
Imports System.ComponentModel
Imports System.Drawing
Imports System.Web
Imports System.Web.SessionState
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.HtmlControls
Public Function EnumerateDomains() As ArrayList
Dim alDomains As New ArrayList()
Dim currentForrest As Forest = Forest.GetCurrentForest()
Dim myDomains As DomainCollection = currentForrest.Domains
For Each objDomain As Domain In myDomains
alDomains.Add(objDomain.Name)
Next
Return alDomains
End Function
Public Function EumerateDomainUsers() As ArrayList
Dim domainUsers As New ArrayList()
Dim usr As String
'Dim fqdns As String = DropDownList1.SelectedItem.ToString()
Dim fqdns As String = DropDownList1.SelectedItem.Text
Dim adStrng As String = "LDAP://" & fqdns
Dim adEntry As DirectoryEntry = GetObject(adStrng)
Dim searcher As DirectorySearcher = New DirectorySearcher(adEntry)
searcher.Sort.PropertyName = "cn"
Dim results As SearchResultCollection
Dim result As SearchResult
searcher.PropertiesToLoad.Add("cn")
results = searcher.FindAll
For Each result In results
usr = result.GetDirectoryEntry().Properties("cn").Value
domainUsers.Add(usr)
Next
Return domainUsers
End Function
There is a spelling mistake and should be "DistinguishedName" instead of "DistinguisedName":
mySearcher.Filter = "(&(ObjectClass=user)(DistinguishedName=" & userDN & "))"
I've got an application. I haven't had to use command line arguments before but my research suggests my method isn't wrong. In VS2015, in my project properties->debug I've added /boxID=123 but when I debug, I get nothing in my inputVal variable. Where am I going wrong?
Imports Word = Microsoft.Office.Interop.Word 'needed for COM object interaction with MS Word
Imports System.Data.SqlClient 'needed for DB interactions
Imports System.IO 'needed for BLOB
Public Class Window
'set form level declarations
Dim appPath As String
Dim objWordApp As New Word.Application
Dim objDoc As Word.Document
Function boxIDfromCommandLine() As Integer
Dim inputArg As String = "/boxID="
Dim inputVal As String = ""
For Each s As String In My.Application.CommandLineArgs
If s.ToLower.StartsWith(inputArg) Then
inputVal = s.Remove(0, inputArg.Length)
End If
Next
If inputVal = "" Then
inputVal = "0"
End If
boxIDfromCommandLine = Convert.ToInt32(inputVal)
End Function
'form load subroutine
Private Sub Window_Load(ByVal sender As System.Object, e As System.EventArgs) Handles MyBase.Load
'Establish application path, replace appPath on deployment
Dim appPath As String = Application.StartupPath()
'Run application in foreground or background.
'If in background (false), be sure to add objDoc.close() and objWordApp.Quit()
objWordApp.Visible = False
'Declarations
Dim localDateTimeString As String = DateTime.Now.ToString
Dim localDateTimeFileName As String = DateTime.Now.ToString("yyyyMMddhhmm")
Dim soNumber As String = "No_SO_Selected"
Dim boxID As Integer = boxIDfromCommandLine()
Dim saveString As String 'file name format
Dim savePath As String = "C:\ITO_PackingLists" 'set folder location
Dim connection As SqlConnection = New SqlConnection() 'set SQL server connection string
...
...
...
I wrote an OPC client using interop.opcautomation.dll. I wrote it as a windows form in vb 2010 express. everything is currently working well. I wanted to make it a windows service though. The problem I am having is that it will not connect to the opc server when I run the service. I get the following exception "Object reference not set to an instance of an object.- OPC Connect Error" I get the exception at the end of the code where I am trying to connect. Below is the code. Thanks for any input, it is appreciated.
Imports System.ServiceProcess
Imports System.Threading
Imports System.Text
Imports System.Windows.Forms
Imports System
Imports System.IO
Imports System.IO.File
Imports System.Net
Imports OPCAutomation
Public Class Service1
Inherits System.ServiceProcess.ServiceBase
Dim WithEvents OPCServer As OPCAutomation.OPCServer
Dim WithEvents ConnectedGroup As OPCAutomation.OPCGroup
Dim Batch As String
Dim Group As String
Dim Press As String
Dim Line As String
Dim sWidth As String
Dim sHeight As String
Dim sBifold As String
Dim sCore As String
Dim StartUp As Integer
Dim iHandle As Integer
Dim sError As String
Dim ItemIds(60) As String
Dim ServerHandles As Array
Dim ClientHandles(60) As Integer
Dim ServerErrors As Array
Dim SnapServerURL As String = "snapserver"
Private trd As Thread
Private Stopping As Boolean = False
Private StoppedEvent As New ManualResetEvent(False)
Protected Overrides Sub OnStart(ByVal args() As String)
EventLog.WriteEntry("PressControlService in OnStart.")
trd = New Thread(AddressOf ServiceMain)
trd.IsBackground = True
trd.Start()
End Sub
Protected Overrides Sub OnStop()
EventLog.WriteEntry("PressControlService in OnStop.")
Me.Stopping = True
Me.StoppedEvent.WaitOne()
End Sub
Private Sub ServiceMain()
Dim strOPCServerName As String
Dim strOPCServerNode As String
Dim strOPCGroupName As String
Dim i As Integer
StartUp = 0
strOPCServerName = "Kepware.KEPServerEX.V5"
strOPCServerNode = ""
strOPCGroupName = "MyGroup"
Try
Dim OPCServer As New OPCAutomation.OPCServer
Catch ex As Exception
EventLog.WriteEntry(ex.Message & " - New OPC Server")
End Try
Try
OPCServer.Connect(strOPCServerName, strOPCServerNode)
Catch ex As Exception
EventLog.WriteEntry(ex.Message & "- OPC Connect Error")
End Try
End Sub
End Class
I am new for programming and trying to learn VB.net through youtube tutorials.
I created a windows form app for users to create new account.
I am also trying to apply the hash and salt technique to store the password for security reason.
The main issue I have is maintaining successful connection between a two class I called "DatabaseManager" and "DataHandling", codes in "btnRegister" and the database called "Test".
The program runs fine. When I click btnRegister after filling the "txtUsername.Text" and "txtPassword.Text", it gives me error that says "ColumnUser_IDdoes not allow nulls.".
So this is where I keep getting issues. I tried to make it work a lot and I have no idea why it is not recording the new data. Here are my codes. I use V Studio 2012. Please help.
Just to be clear I copied some of the codes from internet and tried to make them work with the class
Imports System
Imports System.IO
Imports System.Text
Imports System.Data.OleDb
Imports System.Data
Imports System.Windows.Forms
Imports System.Data.SqlClient
Imports System.Security.Cryptography
Public Class DatabaseManager
Private Const CONNECTION_STRING As String = "Data Source=(localdb)\Projects;Initial Catalog=Test;Integrated Security=True"
Private connection As SqlConnection = Nothing
Private usersdataadapter As SqlDataAdapter = Nothing
Sub New()
connection = New SqlConnection(CONNECTION_STRING)
usersdataadapter = New SqlDataAdapter("select * from Test", connection)
End Sub
Public Sub Register(ByVal Username As String, ByVal Password As String)
connection.Open()
Dim usersDataset As New DataSet()
usersdataadapter.FillSchema(usersDataset, SchemaType.Source, "Test")
Dim table As DataTable = usersDataset.Tables("Test")
Dim newRecord As DataRow = table.NewRow()
newRecord("Username") = Username
newRecord("Password") = Password
table.Rows.Add(newRecord)
Dim command As New SqlCommandBuilder(usersdataadapter)
usersdataadapter.Update(usersDataset, "Test")
usersDataset.Dispose()
connection.Close()
End Sub
Public Function UsernameAvailable(ByVal username As String) As Boolean
Dim usersDataset As New DataSet()
usersdataadapter.FillSchema(usersDataset, SchemaType.Source, "Test")
usersdataadapter.Fill(usersDataset, "Test")
Dim table As DataTable = usersDataset.Tables("Test")
For i As Integer = 0 To table.Rows.Count - 1
Dim currnetUser As String = table.Rows(i)("Username").ToString().Trim()
If (currnetUser = username) Then
usersDataset.Dispose()
connection.Close()
Return False
End If
Next
Return True
usersDataset.Dispose()
connection.Close()
End Function
Public Function Login(ByVal username As String, ByVal password As String) As Boolean
Dim usersDataset As New DataSet()
usersdataadapter.FillSchema(usersDataset, SchemaType.Source, "Test")
usersdataadapter.Fill(usersDataset, "Test")
Dim table As DataTable = usersDataset.Tables("Test")
For i As Integer = 0 To table.Rows.Count - 1
Dim currnetUser As String = table.Rows(i)("Username").ToString().Trim()
Dim currnetPassword As String = table.Rows(i)("Password").ToString().Trim()
If (currnetUser = username AndAlso currnetPassword = password) Then
usersDataset.Dispose()
connection.Close()
Return True
End If
Next
usersDataset.Dispose()
connection.Close()
Return False
End Function
End Class
Imports System
Imports System.Text
Imports System.Data.OleDb
Imports System.Data
Imports System.Data.SqlClient
Imports System.Windows.Forms
Imports System.Security.Cryptography
Public Class DataHandling
Inherits Form1
Public Shared Function GenerateRandomString() As String
Dim i_key As Integer
Dim Random1 As Single
Dim arrIndex As Int16
Dim sb As New StringBuilder
Dim RandomLetter As String
Dim KeyLetters As String = "abcdefghijklmnopqrstuvwxyz"
Dim KeyNumbers As String = "0123456789"
Dim KeyLength As Integer = 12
Dim LettersArray = KeyLetters.ToCharArray
Dim NumbersArray = KeyNumbers.ToCharArray
For i_key = 1 To KeyLength
Randomize()
Random1 = Rnd()
arrIndex = -1
If (CType(Random1 * 111, Integer)) Mod 2 = 0 Then
Do While arrIndex < 0
arrIndex = _
Convert.ToInt16(LettersArray.GetUpperBound(0) _
* Random1)
Loop
RandomLetter = LettersArray(arrIndex)
If (CType(arrIndex * Random1 * 99, Integer)) Mod 2 <> 0 Then
RandomLetter = LettersArray(arrIndex).ToString
RandomLetter = RandomLetter.ToUpper
End If
sb.Append(RandomLetter)
Else
Do While arrIndex < 0
arrIndex = _
Convert.ToInt16(NumbersArray.GetUpperBound(0) _
* Random1)
Loop
sb.Append(NumbersArray(arrIndex))
End If
Next
Return sb.ToString
End Function
Public Shared Function CheckPassword(ByVal plainText As String, ByVal passwordHash As Byte(), ByVal salt As Byte()) As Boolean
Dim encoding As New System.Text.UTF8Encoding
'Retrieve Salt String from byte array
Dim saltStr As String = encoding.GetString(salt)
Dim hashable As String = Trim(plainText) & Trim(saltStr)
' Convert into hash strings
Dim testhash As String = EncryptStringAsHash(hashable)
Dim realHash As String = encoding.GetString(passwordHash)
' Compare and return result
Return testhash = realHash
End Function
Public Shared Function EncryptStringAsHash(ByVal value As String) As String
Dim encoding As New System.Text.UTF8Encoding
Dim stringBytes As Byte() = encoding.GetBytes(value)
Dim SHhash As SHA512Managed = New SHA512Managed
Dim hash As String = Convert.ToBase64String(SHhash.ComputeHash(stringBytes))
Return hash
End Function
Public Shared Function ConvertStringToByteArray(ByVal value As String) As Byte()
Dim encoding As New System.Text.UTF8Encoding
Return encoding.GetBytes(value)
End Function
End Class
Imports System.IO
Imports System.Text
Imports System.Security.Cryptography
Imports System.Data.OleDb
Imports System.Windows.Forms
Imports System.Data.OleDb.OleDbConnection
Imports System.Data.SqlClient
Public Class Form1
Dim maxrows As Integer
Dim incdec As Integer
Dim con As New OleDb.OleDbConnection
Dim dbprovider As String
Dim dbsource As String
Dim ds As New DataSet
Dim da As OleDb.OleDbDataAdapter
Dim sql As String
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim con As New OleDbConnection
Dim dbprovider As String
Dim dbsource As String
dbprovider = "PROVIDER = Microsoft.ACE.OLEDB.12.0;"
dbsource = "Data Source=(localdb)\Projects;Initial Catalog=Test;Integrated Security=True"
con.ConnectionString = dbprovider & dbsource
End Sub
Private Sub btnRegister_Click(sender As Object, e As EventArgs) Handles btnRegister.Click
Dim dbmanager As New DatabaseManager
Dim Data As New DataHandling
'Generate Hash and Salt for password
Dim salt As String = DataHandling.GenerateRandomString
Dim hashable As String = Trim(txtPassword.Text) & Trim(salt) 'txtPassword.Text used to be password
Dim hash As String = DataHandling.EncryptStringAsHash(hashable)
Dim confirmationId As String = System.Guid.NewGuid.ToString
Dim reg As user
reg.Username = txtUsername.Text 'txtUsername.Text used to be username
reg.Password = DataHandling.ConvertStringToByteArray(hash)
reg.Salt = DataHandling.ConvertStringToByteArray(salt)
If dbmanager.UsernameAvailable(txtUsername.Text) Then
dbmanager.Register(txtUsername.Text, txtPassword.Text)
Dim password As String
If txtPassword.Text = String.Empty Then
password = "217tABCDEF42#$tolq"
Else
password = txtPassword.Text
End If
Dim salt As String = GenerateRandomString(12)
Dim hashable As String = Trim(password) & Trim(salt)
MsgBox("Hashable = " & hashable)
Dim hash As String = EncryptStringAsHash(hashable)
CheckPassword(password, ConvertStringToByteArray(hash), ConvertStringToByteArray(salt))
frmAccessGranted.Show()
Me.Hide()
Else
MessageBox.Show("Cannot Register, Username Already Taken!")
End If
End Sub
Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
txtUsername.Clear()
txtPassword.Clear()
End Sub
End Class
I think your User table User_id value is just missing Identity Specification option. It makes the User_id field to be generated automatically and increased by 1 (by default) for each User you add into
If you have SQL Server management studio you can put this option on:
Right click User table -> Select "Desing" -> Select "User_id" field -> in "Column Propetries" window put "Indentity Specification" option to "Yes" and save
Example SQL Command to create table could be something like this:
CREATE TABLE User (User_id BIGINT IDENTITY NOT NULL, Username NVARCHAR(100) NOT NULL, Password NVARCHAR(100) NOT NULL)
The problem in your code is not in the VB side, it is in the database.
You have set primary key to UserId but you are not passing any values to the userId, you are just passing values to the user name and password.
So there are two ways to solve this issues
you can send userid also from the VB code
you can just make the column UserId as autoincrement field by the following code
CREATE TABLE [dbo].[Test1](
[id] [int] IDENTITY(1,1) NOT NULL,
YourColumnname1 datatype,
YourColumnname2 datatype
)
This works only in the later versions of sqlserver 2008
alter table tablename
alter column columnname
add Identity(100,1)
To know more Click here
I’m still stumbling with this page over and over again. Just couldn’t get the user’s Username (using email as the username) to display on mysupport.aspx page after she’s successfully logged in. The result should look like this with the email showing but it is not retrieving anything:
Email: barb#hotmail.com
Being an amateur, I know I’m missing a big piece of the puzzle but I don’t know what. Am I using the mailLBL.Text = User.Identity.Name.ToString() wrongly? Below are the code-behind:
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Data.SqlClient
Partial Class mysupport
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
Dim sConnection As New SqlConnection(ConfigurationManager.ConnectionStrings("TrackTicketsConnectionString2").ConnectionString)
sConnection.Open()
Dim cmdS As String = "Select Email from Users Where Deleted='N'"
Dim cmdCheckmail As New SqlCommand(cmdS, sConnection)
If Session("Ticket") IsNot Nothing Then
mailLBL.Text = User.Identity.Name.ToString()
Else
Response.Redirect("SignIn.aspx")
End If
End Sub
Protected Sub signinBTN_Click(ByVal sender As Object, ByVal e As EventArgs)
Session("Ticket") = Nothing
Response.Redirect("SignIn.aspx")
End Sub
End Class
Any help and guidance is truly appreciated!
What you could do first is study these links:
How to: Implement Simple Forms Authentication
How to use Sessions
There are several things wrong with this code.
Old Code:
Dim cmdS As String = "Select Email from Users Where Deleted='N'"
Dim cmdCheckmail As New SqlCommand(cmdS, sConnection)
If Session("Ticket") IsNot Nothing Then
mailLBL.Text = User.Identity.Name.ToString()
Else
Response.Redirect("SignIn.aspx")
End If
Corrected Code:
If Session("Ticket") Is Nothing Then
Response.Redirect("SignIn.aspx")
Else
Dim cmdS As String = "Select Email from Users Where Deleted='N' AND Username=#Username"
Dim cmdCheckEmail as new SqlCommand(cmdS, sConnection)
cmd.AddParameters(new SqlParameter("#UserName", SqlDbType.VarChar).Value = Session("Ticket")
Dim obj as Object = cmd.ExecuteScalar()
If obj isNot Nothing
mailLBL.Text = Convert.ToString(obj)
End If
End
I hope that helps.