'imports' statement must precede any declarations - vb.net

module module1
imports System.Collections.Generic
imports System.Io
sub main()
dim subject as string
dim topic(5) as string
dim question(5) as string
dim foundfile as List
dim directory as string
console.writeline("enter the subject your revising")
subject=console.readline()
directory="C:\Users\Zak\Documents\revisionhog\subjects\physics\imaging"
For each file as String In IO.directory.Getfiles(directory, "*.pdf", IO.SearchOption.AllDirectories)
foundfile.add(file)
Next
for x = 0 to 5
console.writeline(foundFile)
next
end sub
end module
tyring to add file that i have found after a search to a list of strings.
i thought that i had placed import before declarations???
help???

imports System.Collections.Generic
imports System.Io
module module1
sub main()
dim subject as string
dim topic(5) as string
dim question(5) as string
dim foundfile as List
dim directory as string
console.writeline("enter the subject your revising")
subject=console.readline()
directory="C:\Users\Zak\Documents\revisionhog\subjects\physics\imaging"
For each file as String In IO.directory.Getfiles(directory, "*.pdf", IO.SearchOption.AllDirectories)
foundfile.add(file)
Next
for x = 0 to 5
console.writeline(foundFile)
next
end sub
end module
The imports come first, like you mentioned. This fixes the problem with the import statements, but your question is a bit unclear. If you have other issues, please state those clearly.

Related

VB.NET Tool To List And Change Users Groups On Active Directory

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 & "))"

£ symbol not beind Read from TXT file in Visual Basic 2010

When i run my program to open a txt file, it doesnt display the £ symbol. Is there a way to display it? Heres my code
Imports System
Imports System.IO
Imports System.Text
Public Class Test
Public Shared Sub Main()
Dim path As String = ("H:\16.1\Stock.txt")
' Open the file to read from.
Dim readText() As String = File.ReadAllLines(path, Encoding.UTF8)
Dim Z As String
For Each Z In readText
Console.WriteLine(Z)
Next
Console.ReadLine()
End Sub
End Class

referencing a dll in a windows service

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

Testing in Visual Basic with structures

I have a VS2012 Visual Basic.NET application and am wanting to create some unit tests for this application.
In my application, I have a module that contains the following structure:
<Serializable()> Public Structure MediaItem
Dim longMediaID As Long
Dim MediaObject As WMPLib.IWMPMedia
Dim FileInfoObject As FileInfo
Dim stringGenre As String
Dim stringMediaDuration As String
Dim doubleMediaLength As Double
End Structure
How do I 'Import' the above MediaItem structure so that I can do some Unit Testing using this structure? Currently, the TestClass cannot 'see' this structure.
UPDATE
This structure is custom made by myself. It is not actually in a class, it is in a module.
UPDATE 2
Here is the module code:
Imports System.IO
Namespace modCanMediaStructures
Module modCanMediaStructures
<Serializable()> Public Structure MediaItem
Dim longMediaID As Long
Dim MediaObject As WMPLib.IWMPMedia
Dim FileInfoObject As FileInfo
Dim stringGenre As String
Dim stringMediaDuration As String
Dim doubleMediaLength As Double
End Structure
<Serializable()> Public Structure MediaPlayList
Dim stringMediaPlayListName As String
Dim stringMediaPlayListDescription As String
Dim stringMediaPlayListComments As String
Dim mediaItemList As List(Of MediaItem)
Dim stringPlayListDuration As String
Dim doublePlayListDuration As Double
Dim booleanShuffle As Boolean
Dim booleanLoop As Boolean
End Structure
Public Structure genreItem
Dim stringGenreName As String
Dim longGenreCount As Long
Dim doubleGenreDuration As Double
End Structure
<Serializable()> Public Structure ScheduleItem
Dim stringItemName As String
Dim stringItemPlaylist As String
Dim stringItemDuration As String
Dim stringItemComments As String
Dim doubleItemDuration As Double
Dim booleanStartDateIsDerivedFromEndOfOtherScheduleItem As Boolean
Dim stringScheduleItemThatStartDateIsDerivedFrom As String
Dim dateItemStartDateTime As Date
Dim dateItemEndDateTime As Date
Dim booleanEndDateIsDerivedFromPlayListDuration As Boolean
End Structure
End Module
End Namespace
In my main form, I declare a variable as follows:
Dim testMediaItem As modCanMediaStructures.MediaItem
After importing the following statement:
Imports modCanMediaStructures
This works. However, when I do the same statement in the UnitTest test, the following error occurs:
Type 'modCanMediaStructures.MediaItem' is not defined
Here is my code:
Imports System.Text
Imports Microsoft.VisualStudio.TestTools.UnitTesting
Imports CanMediaPlayer
Imports modCanMediaStructures
<TestClass()> Public Class MediaListTests
<TestMethod()> Public Sub TestaddMediaItemToList()
Dim myStructure As New modCanMediaStructures.MediaItem
End Sub
End Class
I believe that this is happeneing because the UnitTest Project cannot actually 'see' the code in the other solution files.
May I please have some help to get this working?

SSIS script task component to write Input0Buffer to a text file

I'm trying to dump all input0Buffer to a txt file, to end my struggle with making the flat destination re-usable as i've over 100 package and each structure and columns are different.
I'm redirecting the error rows to a flat file, so it's a nightmare to set that manually in every package, so I wanna write the whole input without specifieng Row.Name, all of them into text file.
I'm up to the point that i'm getting only one column!! it's driving me crazy!!
Imports System
Imports System.Data
Imports System.Math
Imports Microsoft.SqlServer.Dts.Pipeline.Wrapper
Imports Microsoft.SqlServer.Dts.Runtime.Wrapper
Imports System.IO
Imports System.Reflection
Imports System.Xml
Imports Microsoft.SqlServer.Dts.Pipeline
<Microsoft.SqlServer.Dts.Pipeline.SSISScriptComponentEntryPointAttribute()> _
<CLSCompliant(False)> _
Public Class ScriptMain
Inherits UserComponent
Dim textWriter As StreamWriter
Private inputBuffer As PipelineBuffer
Public Overrides Sub ProcessInput(ByVal InputID As Integer, ByVal Buffer As Microsoft.SqlServer.Dts.Pipeline.PipelineBuffer)
inputBuffer = Buffer
MyBase.ProcessInput(InputID, Buffer)
End Sub
Public Overrides Sub PreExecute()
MyBase.PreExecute()
textWriter = New StreamWriter( "c:\Test4.txt", True)
End Sub
Public Overrides Sub PostExecute()
MyBase.PostExecute()
textWriter.Close()
''
End Sub
Public Overrides Sub Input0_ProcessInputRow(ByVal Row As Input0Buffer)
Dim delim As String = ", "
Dim RowCount As Integer = 0
For RowCount = 0 To inputBuffer.ColumnCount = -1
If inputBuffer.Item(RowCount).ToString() = "" Then
inputBuffer.Item(RowCount) = String.Empty
End If
Next
textWriter.WriteLine(inputBuffer.Item(RowCount).ToString() & delim)
End Sub
End Class
can anyone help me please?
The issue is where your write is at. You are writing outside of your For loop. You loop through each row and set the value of the entry to String.Empty but you aren't doing any writing to the textWriter here. Adjust the code as follows:
Dim myBuilder As New StringBuilder
For RowCount = 0 To inputBuffer.ColumnCount = -1
If inputBuffer.Item(RowCount).ToString() = "" Then
inputBuffer.Item(RowCount) = String.Empty
End If
myBuilder.Append(inputBuffer.Item(RowCount).ToString() & delim)
Next
textWriter.WriteLine(myBuilder.ToString)
That will ensure that each column gets written. The only issue will be that your last column will have a delimiter after it. You might want to trim that off before you write it. Also, you will need to add an Imports System.Text to your code as well.
One note I wanted to add since it can cause some confusion: your loop counter is called RowCount when it is performing the act of counting columns (ColumnCount-1 shows us that). That might cause some confusion down the road and assumptions could be made that might cause coding mistakes.