How can I search for a string inside another one and then select all the characters till end of line ?
For example, given this string:
PrinterName: PDFCreator
PortName: PDFCreator:
Status: Unknown
DriverName: PDFCreator
PrinterName: Lexmark E360dn XL
PortName: someport
Status: Unknown
DriverName: Lexmark E360dn XL
HostAddress: somehostaddress
I'd like to search the string: "PrinterName" once it finds it, add it into a combobox, in order to get only the PrinterName.
So far i wrote this:
Dim TextSearched As String = tmp.Text
Dim Paragraph As String = "PrinterName:"
Dim location As Integer = 0
Dim occurances As Integer = 0
Do
location = TextSearched.IndexOf(Paragraph, location)
If location <> -1 Then
occurances += 1
If TextSearched.EndsWith(vbCrLf) Then
Debug.Print(TextSearched.Substring(location, TextSearched.IndexOf(vbCrLf)))
End If
location += Paragraph.Length
End If
Loop Until location = -1
where tmp.Text is a long string like the example above.
When i run it I get something like this:
PrinterName: PDFCreator
PrinterName: Lexmark E3
I don't get the "360dn XL"
Have you given any thought to using Regex? You can use a pattern like:
"PrinterName: (.*?)\r\n"
Which should find the line in your long string and capture the data into group 1. You would access the result like this:
Imports System.Text.RegularExpressions
Module Module1
Sub Main()
Dim TextSearch As String = _
"PrinterName : PDFCreator()" + vbCrLf + _
"PortName: PDFCreator()" + vbCrLf + _
"Status: Unknown()" + vbCrLf + _
"DriverName: PDFCreator()" + vbCrLf + _
"PrinterName: Lexmark E360dn XL" + vbCrLf + _
"PortName: someport()" + vbCrLf + _
"Status: Unknown()" + vbCrLf + _
"DriverName: Lexmark E360dn XL" + vbCrLf + _
"HostAddress: somehostaddress()"
Dim Matcher = Regex.Match(TextSearch, "PrinterName: (.*?)\r\n")
If Matcher.Success Then
Console.WriteLine(Matcher.Groups(1))
End If
End Sub
End Module
Results:
Lexmark E360dn XL
You would add Matcher.Groups(1) to your combobox.
This involves some simple parsing using the IndexOf and SubString Extension Methods. Here is an example that puts all of the PrinterName values into a List(of String).:
Dim lstLines As List(Of String) = IO.File.ReadAllLines("C:\Your\Location\tmp.txt").ToList()
Dim lstPrinters As New List(Of String)
lstLines.ForEach(Sub(strLine As String)
If strLine.IndexOf("PrinterName:") > -1 Then
lstPrinters.Add(strLine.Substring(strLine.IndexOf("PrinterName:") + 13))
End If
End Sub)
Another one...
Dim TextSearch As String =
"PrinterName : PDFCreator()" + vbCrLf +
"PortName: PDFCreator()" + vbCrLf +
"Status: Unknown()" + vbCrLf +
"DriverName: PDFCreator()" + vbCrLf +
"PrinterName: Lexmark E360dn XL" + vbCrLf +
"PortName: someport()" + vbCrLf +
"Status: Unknown()" + vbCrLf +
"DriverName: Lexmark E360dn XL" + vbCrLf +
"HostAddress: somehostaddress()"
Dim printers As List(Of String) = TextSearch.Split(vbCrLf.ToCharArray, StringSplitOptions.RemoveEmptyEntries).Where(Function(x) x.ToLower.StartsWith("printername")).Select(Function(x) x.Split(":").Last).ToList
For Each printer As String In printers
Debug.Print(printer)
Next
This could also be written as:
Dim TextSearch As String =
"PrinterName : PDFCreator()" + vbCrLf +
"PortName: PDFCreator()" + vbCrLf +
"Status: Unknown()" + vbCrLf +
"DriverName: PDFCreator()" + vbCrLf +
"PrinterName: Lexmark E360dn XL" + vbCrLf +
"PortName: someport()" + vbCrLf +
"Status: Unknown()" + vbCrLf +
"DriverName: Lexmark E360dn XL" + vbCrLf +
"HostAddress: somehostaddress()"
Dim printers = From printer In TextSearch.Split(vbCrLf.ToCharArray)
Where printer.ToLower.StartsWith("printername")
Select printer.Split(":").Last
For Each printer As String In printers
Debug.Print(printer)
Next
Related
I want to be able to add together the individual digits of a 4 digit number, but it does not seem to work.
I am doing this purely in VBA code. The result is output to a worksheet.
I have extracted part of my code and put it into a separate macro to test it and still get the same result. It concatenates the digits together.
I have added in lots of msgbox lines to see what it is doing, but cannot work out why, in this case, the value of main is not added up into the intm variable.
The variables intd1 to intd4 get the values correctly, but when I try to add them together into intm, it just concatenates them together.
Sub AddDigits()
'
' Add individual digits of number together
'
Dim intd1, intd2, intd3, intd4, main, intm As Integer
main = 1234
intd1 = Left(main, 1)
MsgBox (intd1)
intd2 = Mid(main, 2, 1)
MsgBox (intd2)
intd3 = Mid(main, 3, 1)
MsgBox (intd3)
intd4 = Right(main, 1)
MsgBox (intd4)
intm = intd1 + intd2 + intd3 + intd4
MsgBox ("intm = " & intm & Chr(13) & _
"intd1 = " & intd1 & Chr(13) & _
"intd2 = " & intd2 & Chr(13) & _
"intd3 = " & intd3 & Chr(13) & _
"intd4 = " & intd4 & Chr(13))
End Sub
When you declare the variables the way you did, the first bit are all "variants", and VBA your use of Mid, Left, and Right are all string functions, so VBA coverts the variant to Strings:
If you dim your variables properly, you get the expected result:
Sub AddDigits()
'
' Add individual digits of number together
'
Dim intd1 As Integer, _
intd2 As Integer, _
intd3 As Integer, _
intd4 As Integer, _
main As Integer, _
intm As Integer
main = 1234
intd1 = Left(main, 1)
MsgBox (intd1)
intd2 = Mid(main, 2, 1)
MsgBox (intd2)
intd3 = Mid(main, 3, 1)
MsgBox (intd3)
intd4 = Right(main, 1)
MsgBox (intd4)
intm = intd1 + intd2 + intd3 + intd4
MsgBox ("intm = " & intm & Chr(13) & _
"intd1 = " & intd1 & Chr(13) & _
"intd2 = " & intd2 & Chr(13) & _
"intd3 = " & intd3 & Chr(13) & _
"intd4 = " & intd4 & Chr(13))
End Sub
In addition to the above answer, you can also convert the data type anywhere later in the code. To convert anything to int use Cint. Similarly for other type conversion you check the link
intm = CInt(intd1) + CInt(intd2) + CInt(intd3) + CInt(intd4)
i am using visual studio 2005 and i want to print Arabic on POS thermal printer. when i try to print it shows ????? in print
here is my code:
Public Sub GiftReceipt()
Try
Dim displayString As String
Dim ESC As String = Chr(&H1B) + "a" + Chr(0)
Dim ESC2 As String = Chr(&H1B) + "#"
Dim ESC1 As String = Chr(&H1B) + "a" + Chr(1)
Dim ESC4 As String = Chr(&H1B) + "a" + Chr(2)
Dim ESC5 As String = Chr(&H1B) + "!" + Chr(17)
Dim ESC6 As String = Chr(&H1B) + "!" + Chr(1)
Dim ESC7 As String = Chr(&H1B) + "t%"
Dim ESC8 As String = Chr(&H1B) + "?0"
Dim ESC9 As String = Chr(&H1B) + "R" + Chr(17)
displayString = vbNewLine
displayString += ESC7 + "معطار" + ESC8 + vbNewLine
displayString += vbNewLine
Dim pd As New PrintDialog()
pd.PrinterSettings = New PrinterSettings()
pd.UseEXDialog = True
Call DefaultPrinterName()
RawPrinterHelper.SendStringToPrinter(DefaultPrinterName, displayString)
Catch ex As Exception
MsgBox(ex.ToString())
End Try
End Sub
i have alredy tried to convert it to windows-1256, and also tried using many esc pos commands
I have a form_load thats selecting a string in a RTB and it works perfectly, makes the line I specify highlighted yellow and all other lines untouched. when I click a button and load another form and use it then close it, the original form now has the entirety of its contents highlighted yellow. I tried adding rtb.DeselectAll() after the lines of code that select, but nothing seems to work.
I appreciate any and all suggestions. thanks in advance
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
ReminderList.SelectionStart = ReminderList.GetFirstCharIndexFromLine(0)
ReminderList.SelectionLength = ReminderList.Lines(Globalvar.ReminderCount 1).Length
ReminderList.SelectionBackColor = Color.Yellow
Call FillOutCal()
End Sub
UPDATE: What Jim has said I am already aware of, the problem is that when I use another form and revisit the original form, the yellow selected portion has changed to encompass the whole rich text box. Here is the code for a Save button that brings back the main form with the selection bug:
Private Sub SaveButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveButton.Click
FormDesktop.ReminderList.DeselectAll()
If ItemName.Text = Nothing Then
Dim newerror As DialogResult = MessageBox.Show("Missing some information to complete the entry, make sure everything is filled out.", _
"Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Exit Sub
ElseIf ReminderRadio.Checked = False And TaskRadio.Checked = False And IdeaRadio.Checked = False Then
Dim newerror As DialogResult = MessageBox.Show("Missing some information to complete the entry, make sure everything is filled out.", _
"Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Exit Sub
End If
Dim TypeOfIdea As Integer
If ReminderRadio.Checked = True Then
FormDesktop.ReminderList.Text += vbCrLf
TypeOfIdea = 1
Globalvar.ReminderCount += 1
ElseIf TaskRadio.Checked = True Then
FormDesktop.TaskList.Text += vbCrLf
TypeOfIdea = 2
Globalvar.TaskCount += 1
Else
FormDesktop.IdeaList.Text += vbCrLf
TypeOfIdea = 3
Globalvar.IdeaCount += 1
End If
Dim NameOfItem As String = ItemName.Text
Dim DueMonth As Integer = DateTimePick.Value.Month
Dim DueDay As Integer = DateTimePick.Value.Day
Dim DueYear As Integer = DateTimePick.Value.Year
Dim SubMonth As Integer = DateTime.Now.Month
Dim SubDay As Integer = DateTime.Now.Day
Dim SubYear As Integer = DateTime.Now.Year
Dim DueHour As Integer = Hour.Value
Dim DueMinute As Integer = Minute.Value
If TypeOfIdea = 1 Then
If Globalvar.ReminderCount = 1 Then
FormDesktop.ReminderList.Text += "#" + Globalvar.ReminderCount.ToString + " " + NameOfItem + vbCrLf
Else
FormDesktop.ReminderList.Text += vbCrLf + "#" + Globalvar.ReminderCount.ToString + " " + NameOfItem + vbCrLf
End If
If CheckBox1.Checked = True Then
FormDesktop.ReminderList.Text += "Due: " + DueMonth.ToString + "/" + DueDay.ToString + "/" + DueYear.ToString + ", " + _
DueHour.ToString + ":" + DueMinute.ToString + vbCrLf
Else
FormDesktop.ReminderList.Text += "Due: " + "N/A" + vbCrLf
End If
FormDesktop.ReminderList.Text += "Added: " + SubMonth.ToString + "/" + SubDay.ToString + "/" + SubYear.ToString + _
", " + DateTime.Now.Hour.ToString + ":" + DateTime.Now.Minute.ToString
ElseIf TypeOfIdea = 2 Then
If Globalvar.TaskCount = 1 Then
FormDesktop.TaskList.Text += "#" + Globalvar.TaskCount.ToString + " " + NameOfItem + vbCrLf
Else
FormDesktop.TaskList.Text += vbCrLf + "#" + Globalvar.TaskCount.ToString + " " + NameOfItem + vbCrLf
End If
If CheckBox1.Checked = True Then
FormDesktop.TaskList.Text += "Due: " + DueMonth.ToString + "/" + DueDay.ToString + "/" + DueYear.ToString + ", " + _
DueHour.ToString + ":" + DueMinute.ToString + vbCrLf
Else
FormDesktop.TaskList.Text += "Due: " + "N/A"
End If
FormDesktop.TaskList.Text += "Added: " + SubMonth.ToString + "/" + SubDay.ToString + "/" + SubYear.ToString + ", " + _
DateTime.Now.Hour.ToString + ":" + DateTime.Now.Minute.ToString
Else
If Globalvar.IdeaCount = 1 Then
FormDesktop.IdeaList.Text += "#" + Globalvar.IdeaCount.ToString + " " + NameOfItem + vbCrLf
Else
FormDesktop.IdeaList.Text += vbCrLf + "#" + Globalvar.IdeaCount.ToString + " " + NameOfItem + vbCrLf
End If
FormDesktop.IdeaList.Text += "Due: " + "N/A" + vbCrLf
FormDesktop.IdeaList.Text += "Added: " + SubMonth.ToString + "/" + SubDay.ToString + "/" + SubYear.ToString + ", " + _
DateTime.Now.Hour.ToString + ":" + DateTime.Now.Minute.ToString
End If
Me.Hide()
FormDesktop.BringToFront()
End Sub
I routine searches for images and moves the files that are images.
The code works inconsistently.
Sometime, it gives error 75.
Sometimes it works just fine.
The problem is in the following line:
Name MoveFrom as MoveTo
Where MoveFrom is the source file name.
MoveTo is the target file name (in a different folder--subfolder \Exceptions\Images, relateve to the MoveFrom Folder).
Any ideas of how to move this file consistently without this blasted error...
To assist, I have marked the problem line with comments as follows in the code:
'--------------------------------------------------------------------
' ------------PROBLEM HERE
'--------------------------------------------------------------------
...THE CODE:
Public Sub MoveImages()
' ShellCommand = ActiveWorkbook_UNC_Path + "\cpdf.exe -list-fonts " + Chr(34) + ActiveWorkbook_UNC_Path + "\" + t + Chr(34) + " > " + Chr(34) + ActiveWorkbook_UNC_Path + "\" + "fontlist.txt" + Chr(34)
' ShellCommand = ActiveWorkbook_UNC_Path + "\cpdf.exe -missing-fonts " + Chr(34) + ActiveWorkbook_UNC_Path + "\" + t + Chr(34) + " > " + Chr(34) + ActiveWorkbook_UNC_Path + "\" + "fontlist.txt" + Chr(34)
'On Error GoTo 0
Dim FileList As Variant
FileList = GetFileList(ActiveWorkbook_UNC_Path + "\*.pdf")
RunMoveImagesCount = RunMoveImagesCount + 1
Dim t As String
Dim Ndx As Integer
Dim ShellCommand
Dim ReturnCode As Long
Dim WshShell As Variant
Set WshShell = CreateObject("WScript.Shell")
Dim MoveFrom As String
Dim MoveTo As String
If IsArray(FileList) Then
For Ndx = LBound(FileList) To UBound(FileList)
t = FileList(Ndx)
ShellCommand = "cpdf.exe -list-fonts " + Chr(34) + t + Chr(34) + " > fontlist.txt"
ShellCommand = "cmd.exe /c " + ShellCommand
ReturnCode = WshShell.Run(ShellCommand, 0, True)
If FileLen(ActiveWorkbook_UNC_Path + "\" + "fontlist.txt") > 0 Then
If RunMoveImagesCount > 1 Then
'not an image
ActiveCell.Value = "Warning! Detected PDF, not converted to CSV "
ActiveCell.Font.ColorIndex = 5
ActiveCell.Offset(1, 0).Select
End If
Else
'possibly not an image
ShellCommand = "cpdf.exe -missing-fonts " + Chr(34) + t + Chr(34) + " > fontlist.txt"
ShellCommand = "cmd.exe /c " + ShellCommand
ReturnCode = WshShell.Run(ShellCommand, 0, True)
If FileLen(ActiveWorkbook_UNC_Path + "\" + "fontlist.txt") > 0 Then
If RunMoveImagesCount > 1 Then
'not an image
ActiveCell.Value = "Warning! Detected PDF(s), not converted to CSV "
ActiveCell.Font.ColorIndex = 5
ActiveCell.Offset(1, 0).Select
End If
Else
'an image.... move it....
MoveFrom = ActiveWorkbook_UNC_Path + "\" + t
MoveTo = ActiveWorkbook_UNC_Path + "\Exceptions\Images\" + t
MoveFrom = ReplaceUNC(MoveFrom)
MoveTo = ReplaceUNC(MoveTo)
If FileThere(MoveTo) Then
'Kill MoveFrom
'shouldn't happen, but if it does, lets leave it there and investigate....
Else
'--------------------------------------------------------------------
' ------------PROBLEM HERE
'--------------------------------------------------------------------
Name MoveFrom As MoveTo
ImageCount = ImageCount + 1
End If
MoveFrom = ReplaceLastOccurance(MoveFrom, ".pdf", ".csv")
If FileThere(MoveFrom) Then
MoveTo = ReplaceLastOccurance(MoveTo, ".pdf", ".csv")
If FileThere(MoveTo) Then
'Kill MoveFrom
'shouldn't happen, but if it does, lets leave it there and investigate....
Else
Name MoveFrom As MoveTo
End If
End If
End If
End If
Next
Else
'no files; you're done.
End If
End Sub
I am using this asmx.VB code to authenticate a user in AD. I need to also bring back what groups they are members of. Any help would be appreciated.
<WebMethod(Description:="Checks User against Active Directory.", EnableSession:=False)> _
Public Function CHECK_AD(ByVal userid As String, ByVal Password As String) As Integer
Dim iErrorNumber As Integer
Dim isPass As Boolean = False
Try
Dim pc As New PrincipalContext(ContextType.Domain, "SomeDomain")
isPass = pc.ValidateCredentials(userid, Password, ContextOptions.Negotiate)
If isPass = True Then
iErrorNumber = 1
Else
iErrorNumber = 0
End If
Catch ex As Exception
iErrorNumber = -1
End Try
Return iErrorNumber
End Function
I Have this code to get properties of user in active directory, maybe can help you, just add a button and if you want uncomment the first three comment lines and comment the first three lines of code after declarations.
(sorry the code is in spanish).
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim objetoUsuario, gruposSeguridad
Dim ultimoInicioSesion As String
Dim dominio As String
Dim nombreUsuario As String
Dim estadoCuenta As String
Dim gruposSeguridadUsuario As String = ""
'dominio = InputBox("Nombre del dominio Windows Server", "")
dominio = Environment.UserDomainName
'nombreUsuario = InputBox("Nombre de usuario del dominio", "")
nombreUsuario = Environment.UserName
' On Error GoTo cError
On Error Resume Next
objetoUsuario = GetObject("WinNT://" + dominio + "/" + nombreUsuario + ",user")
If Err.Number = 0 Then
If objetoUsuario.AccountDisabled = True Then
estadoCuenta = "Deshabilitado"
ultimoInicioSesion = "No existe"
Else
estadoCuenta = "Habilitado"
ultimoInicioSesion = objetoUsuario.Get("Lastlogin")
End If
gruposSeguridad = ""
For Each gruposSeguridad In objetoUsuario.Groups
If gruposSeguridadUsuario = "" Then
gruposSeguridadUsuario = gruposSeguridad.Name
Else
gruposSeguridadUsuario = gruposSeguridadUsuario + ", " + gruposSeguridad.Name
End If
Next
'Mostramos los datos del usuario
MsgBox("Nombre completo: " & objetoUsuario.Get("Fullname") & vbCrLf & _
"Descripción: " & objetoUsuario.Get("Description") & vbCrLf & _
"Nombre: " & objetoUsuario.Get("Name") & vbCrLf & _
"Carpeta de inicio: " & objetoUsuario.Get("HomeDirectory") & vbCrLf & _
"Script de inicio: " & objetoUsuario.Get("LoginScript") & vbCrLf & _
"Último inicio de sesión: " & ultimoInicioSesion & vbCrLf & _
"Perfil: " & objetoUsuario.Get("Profile") & vbCrLf & _
"Estado de la cuenta: " & estadoCuenta & vbCrLf & _
"Grupos seguridad: " & gruposSeguridadUsuario, vbInformation + vbOKOnly)
objetoUsuario = Nothing
Else
MsgBox("No existe el usuario " + nombreUsuario + " o el dominio " + dominio, vbExclamation + vbOKOnly)
End If
'cSalir:
' Exit Sub
'
'cError:
' MsgBox "Error " + CStr(Err.Number) + " " + Err.Description
' GoTo cSalir
End Sub