I have this VB code which is giving the above error in the code below
Try
'Job Ticket Section
StatusText = "Reading Job Ticket Data."
FileName = System.IO.Path.Combine(SoftSavePath, "cfgjt.sys")
If Not System.IO.File.Exists(FileName) Then
CopyDefaultSoftJobTicketItems(FileName, ErrorFlag)
End If
filenumber = FreeFile()
FileOpen(filenumber, FileName, OpenMode.Binary)
.ConvexJobTicketItems = GetConfigConvexJobTicketItems(filenumber)
.ConcaveJobTicketItems = GetConfigConcaveJobTicketItems(filenumber)
FileClose(filenumber)
Catch ex As Exception
ErrorFlag.NumErrors = ErrorFlag.NumErrors + 1
ReDim Preserve ErrorFlag.ErrorDef(ErrorFlag.NumErrors - 1)
With ErrorFlag.ErrorDef(ErrorFlag.NumErrors - 1)
.Number = ErrorFlag.NumErrors - 1
.Description = "Open Config job ticket File Error: " & StatusText + ex.Message
End With
FileClose(filenumber)
End Try
On debugging , I found out that when the cursor hits this statement .ConcaveJobTicketItems , it jumps to the catch block .
The function GetConfigConcaveJobTicketItems(filenumber) where I stepped into has other function calls inside it .
Public Function GetConfigConcaveJobTicketItems(ByRef InFileNumber As Short) As JobTicketConcaveDesignItemsType
With GetConfigConcaveJobTicketItems
.ComfortConic = GetConfigConcaveSphereToricJobTicket(InFileNumber, "ConfortConic")
.Multicurve = GetConfigConcaveSphereToricJobTicket(InFileNumber, "Multicurve")
End With
End Function
When the debug cursor Hits the statement .ComfortConic = GetConfigConcaveSphereToricJobTicket(InFileNumber, "ConfortConic"), I step into the function and see that everything is fine and the cursor moves to the next line.
.Multicurve = GetConfigConcaveSphereToricJobTicket(InFileNumber, "Multicurve")
The GetConfigConcaveSphereToricJobTicket() is defined as
Public Function GetConfigConcaveSphereToricJobTicket(ByRef InFileNumber As Short, ByRef InString As String) As JobTicketSphereToricConcaveItemsType
With GetConfigConcaveSphereToricJobTicket
.Sphere = GetConfigConcaveDesignJobTicket(InFileNumber, InString & "Sphere")
.Toric = GetConfigConcaveDesignJobTicket(InFileNumber, InString & "Toric")
End With
End Function
Related
I have an app (vb.net) that has worked reliably for 12 years - but has started to give error messages.
I calculate rotation values - send them to the servo - then check to see if the transmission is complete.
The issue is that readline give me a timeout error
Here is the code -
Sub SendSerialData()
CurrentPositionDisplay.BackColor = Color.White
CameraServoReadOK = 0
' Send strings to CameraServo serial port.
ServoCommdataOut = ServoCommdataOut & vbCr
CameraServoComm.DiscardOutBuffer()
CameraServoComm.ReadTimeout = 150
CameraServoComm.Write(ServoCommdataOut)
CameraServoReadOK = 0
If VerboseLogging = 2 Then
dtString = dispDt.ToString(datePatt)
outMessage = dtString & " - " & ServoCommdataOut
Call WriteToLog(outLabel, outMessage)
End If
If outLabel = "Starting Picture Sequence " Then
SkipRead = True
End If
'wait code added to accomodate 5ms turnarround time at CameraServo
Call DelayTimer(10)
' If SkipRead = False Then
If SkipRead = False Then
Try
CameraServoCommDataIn = CameraServoComm.ReadLine()
Catch ex As Exception
outMessage = "Missed Read after servo write" & ex.ToString
Call WriteToLog(outLabel, outMessage)
End Try
CameraServoReadOK = InStr(CameraServoCommDataIn, CameraServoresponseStartString, CompareMethod.Text)
If CameraServoReadOK > 0 Then
CameraServoStatusDataIn = CameraServoCommDataIn
End If
End If
End Sub
I am working on a vb.net application and I am struggling to get this function to run in parallel. This is a legacy application, I was told that it uses an event-based asynchronous pattern, but I do not exactly understand what that means for this problem.
There is a for loop that runs a function serially, but I would like to run it in parallel.
Public Function Execute() As Boolean
Dim ret As Boolean = True
' If output files are not specified, then they will be generated based on the study name
If CancelExecution Then Return CancelCleanUp()
If ValidateInputFiles() Then
If CancelExecution Then Return CancelCleanUp()
Select Case _Name
Case "Main Single"
' This is the for loop I would like to run in parallel
For Each cc As IOFile In _CCards
If ValidateOutputFiles(cc.FileName) Then
ret = RunModel(cc)
If CancelExecution Then Return CancelCleanUp()
Else
ret = False
End If
Next
' The other Cases are irrelevant
End Select
Else
ret = False
End If
Return ret
End Function
Private Function RunModel(cCard As IOFile) As Boolean
Dim uFile As String
Dim ret As Boolean = True
If CancelExecution Then Return CancelCleanUp()
' create the uconfiguration file
If _RunNumber > 0 Then
uFile = MakeUFile(cCard, _InputFiles, _OutputFiles, _RunNumber)
Else
uFile = MakeUFile(cCard, _InputFiles, _OutputFiles)
End If
' Input: was not part of the vb 6 IInputModel class, but added in this version
' Main: delete files mainmodel is about to create (even the optional files) (calls CleanUpSingleRun)
ret = KillIOFiles(_OutputFiles)
' execute the application
If File.Exists(uFile) Then
Dim arg As String = """" & uFile & """"
If _Name = "Main Single Sensitivity" Then
' 7/27/2105 add an argument for either single or production run - this is a single run module
arg = arg & " SINGLE" & " " & "NOVIZ"
End If
ret = RunApplication(arg)
Else
Return False
End If
'execute? did it terminate properly?
' kill the ufile
Try
File.Delete(uFile)
Dim cleanupFiles = Directory.GetFiles(_SensitivityFolder).Where(Function(e) e.Contains(".spw") Or Path.GetFileName(e).StartsWith("SIMU")).ToList()
For Each fileToDelete As String In cleanupFiles
File.Delete(fileToDelete)
Next
' clean up temp combined files
If CombinedFile <> "" Then System.IO.File.Delete(CombinedFile)
Catch ex As Exception
End Try
ret = VerifyOutputFiles(cCard.FileName)
Return ret
End Function
Any help is very much appreciated, thank you for taking the time to read my post.
I am trying to change categories color of a current selected mail in outlook 2013 using the explorer object to get the current selected item. Everything seems to be well except when I save it gives the error mentioned above. I have been looking for solutions and no luck any ideas? Thanks. here is my code in VB
Private Sub exp_SelectionChange() Handles exp.SelectionChange ' errrrorr
Try
waitapprovemail = Application.Session.GetItemFromID(exp.Selection.Item(1).EntryID)
if (CheckForRedCategory(waitapprovemail)) Then
If (CheckToReleaseMail(waitapprovemail)) Then
waitapprovemail.Categories = "Green Category"
waitapprovemail.Save() ''' this gives the error
End If
End If
Catch Exc As System.Runtime.InteropServices.COMException
MsgBox(Exc.Message & " " & Exc.Source)
Catch exc As System.InvalidCastException
MsgBox("Casting problem")
End Try
End Sub
Private Function CheckToReleaseMail(mail As MailItem) As Boolean ' errrrrr
' check the id with the ids in the locked mail, if found id then check the other flag if it is false or true, if found true then set the category of that waitemail to empty "" else keep it
Dim r As Boolean = True
Dim sarray As String()
' ofile2 = fso2.OpenTextFile("C:\Users\" & userName & "\Documents\Outlook Files\LockedMail.txt", 8, True) '8 for appending in arg2 0 for tristatefalse optional opens as ascii
Try
Using sr As New StreamReader("C:\Users\" & userName & "\Documents\Outlook Files\LockedMail.txt")
Dim line As String
Do
line = sr.ReadLine()
If (line.Equals("") Or line Is Nothing) Then
r = True
Continue Do
Else
sarray = line.Split(",")
If (sarray.Count > 0) Then
If (sarray(0).Equals(mail.EntryID, StringComparison.InvariantCultureIgnoreCase)) Then
r = False
sr.Close()
mail.Close(OlInspectorClose.olDiscard)
Return r
End If
End If
End If
Loop Until line Is Nothing
sr.Close()
End Using
Catch exc As System.Exception
End Try
mail.Close(OlInspectorClose.olDiscard)
Return r
End Function
Private Function CheckForRedCategory(mail As MailItem) As Boolean ' errrrrr
Dim b As Boolean = False
Try
If (mail.Categories.Equals("Red Category")) Then
b = True
mail.Close(OlInspectorClose.olDiscard)
Return b
Else
b = False
End If
Catch exc As System.NullReferenceException
b = False
mail.Close(OlInspectorClose.olDiscard)
End Try
mail.Close(OlInspectorClose.olDiscard)
Return b
End Function
I'm writing some software to import a CSV file into Active Directory (to create user accounts). At some point I know it was working perfectly importing multiple accounts. I'm not sure what I've changed as it's been a while since I last worked on it. But it now imports 2 accounts successfully and then crashes on the line below during the third loop iteration (however the third account is still created):
newUser.Save()
When it crashes I get the error "vshost32.exe has stopped working". I then enabled native code debugging and now get this error: "0xC0000374: A heap has been corrupted" and InvalidCastException (see immediate window at end of post for full error). For testing I've been deleting and recreating the same accounts. If I don't delete the first three accounts, the principal exists exception is handled and then the program crashes on the 4th iteration, and then the 5th and so on. But it never crashes on the first two. (The data I'm importing is identical except for numbers - E.g. sAMAccountNames: Test1, Test2, Test3 etc)
My Code
Private Sub bwImport_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles bwImport.DoWork
Dim _worker As BackgroundWorker = CType(sender, BackgroundWorker)
Dim beginImport As New StartImport(AddressOf progressForm.StartImport)
Me.Invoke(beginImport, New Object() {dtUsers.Rows.Count})
Dim log As New UpdateLog(AddressOf progressForm.UpdateLog)
'### TO DO: Check that all mandatory columns/attributes are in the DataTable
'### TO DO: Check for duplicate sAMAccountNames, userPrincipalNames and Cononical Names
#If Not Debug Then
Try
#End If
Dim rowNum As Integer = 0 'Keep track of how many accounts have been created
For Each row As DataRow In dtUsers.Rows
Dim newUser As UserPrincipalEx = New UserPrincipalEx(adCtx)
newUser.SamAccountName = row("sAMAccountName")
newUser.SetPassword(row("Password"))
'General Tab (of Template Exporter)
If row.Table.Columns.Contains("initials") Then
newUser.Initials = row("initials")
End If
If row.Table.Columns.Contains("givenName") Then
newUser.GivenName = row("givenName")
End If
If row.Table.Columns.Contains("sn") Then
newUser.Surname = row("sn")
End If
If row.Table.Columns.Contains("displayName") Then
newUser.DisplayName = row("displayName")
End If
If row.Table.Columns.Contains("description") Then
newUser.Description = row("description")
End If
If row.Table.Columns.Contains("physicalDeliveryOfficeName") Then
newUser.Office = row("physicalDeliveryOfficeName")
End If
If row.Table.Columns.Contains("telephoneNumber") Then
newUser.TelephoneNumber = row("telephoneNumber")
End If
If row.Table.Columns.Contains("wWWHomePage") Then
newUser.WebPage = row("wWWHomePage")
End If
'Address Tab (of Template Exporter)
If row.Table.Columns.Contains("streetAddress") Then
newUser.Street = row("streetAddress")
End If
If row.Table.Columns.Contains("postOfficeBox") Then
newUser.POBox = row("postOfficeBox")
End If
If row.Table.Columns.Contains("l") Then 'City
newUser.City = row("l")
End If
If row.Table.Columns.Contains("st") Then 'State/Province
newUser.State = row("st")
End If
If row.Table.Columns.Contains("postalCode") Then
newUser.PostCode = row("postalCode")
End If
'### TO DO: Add country fields
'Account Tab (of Template Exporter)
If row.Table.Columns.Contains("userPrincipalName") Then
newUser.UserPrincipalName = row("userPrincipalName")
End If
If row.Table.Columns.Contains("ResetPassword") Then
If row("ResetPassword").ToString.ToLower = "yes" Then
newUser.ExpirePasswordNow() 'Force the user to change their password at next logon
End If
End If
If row.Table.Columns.Contains("PreventPasswordChange") Then
If row("PreventPasswordChange").ToString.ToLower = "yes" Then
newUser.UserCannotChangePassword = True
End If
End If
If row.Table.Columns.Contains("PasswordNeverExpires") Then
If row("PasswordNeverExpires").ToString.ToLower = "yes" Then
newUser.PasswordNeverExpires = True
End If
End If
If row.Table.Columns.Contains("AccountDisabled") Then
If row("AccountDisabled").ToString.ToLower = "yes" Then
newUser.Enabled = False
Else
newUser.Enabled = True
End If
Else 'Enable the account by default if not specified
newUser.Enabled = True
End If
If row.Table.Columns.Contains("accountExpires") Then
Dim expireyDate As Date
Date.TryParse(row("accountExpires"), expireyDate) 'Try to convert the data from row("accountExpires") into a date
newUser.AccountExpirationDate = expireyDate
End If
'Profile Tab (of Template Exporter)
If row.Table.Columns.Contains("profilePath") Then
newUser.ProfilePath = row("profilePath")
End If
If row.Table.Columns.Contains("scriptPath") Then
newUser.ScriptPath = row("scriptPath")
End If
If row.Table.Columns.Contains("homeDrive") Then
newUser.HomeDrive = row("homeDrive")
End If
If row.Table.Columns.Contains("homeDirectory") Then
newUser.HomeDirectory = row("homeDirectory")
End If
'Telephones Tab (of Template Exporter)
If row.Table.Columns.Contains("homePhone") Then
newUser.HomePhone = row("homePhone")
End If
If row.Table.Columns.Contains("pager") Then
newUser.Pager = row("pager")
End If
If row.Table.Columns.Contains("mobile") Then
newUser.Mobile = row("mobile")
End If
If row.Table.Columns.Contains("facsimileTelephoneNumber") Then
newUser.Fax = row("facsimileTelephoneNumber")
End If
If row.Table.Columns.Contains("ipPhone") Then
newUser.IPPhone = row("ipPhone")
End If
'Organization Tab
If row.Table.Columns.Contains("title") Then
newUser.Title = row("title")
End If
If row.Table.Columns.Contains("department") Then
newUser.Department = row("department")
End If
If row.Table.Columns.Contains("company") Then
newUser.Company = row("company")
End If
rowNum += 1
_worker.ReportProgress(rowNum) 'Update progress dialog
Try
newUser.Save() 'Save the user to Active Directory
Me.Invoke(log, New Object() {"Successfully created " + row("sAMAccountName") + " (" + row("displayName") + ")", frmProgress.LogType.Success})
Catch ex As PrincipalExistsException
Me.Invoke(log, New Object() {"Error creating " + row("sAMAccountName") + " (" + row("displayName") + "). " + ex.Message, frmProgress.LogType.Failure})
Continue For
End Try
'Member Of Tab
If row.Table.Columns.Contains("MemberOf") Then
Dim groups() As String = row("MemberOf").ToString.Split(";")
'Add the user to any specified groups
Dim groupPrincipal As GroupPrincipal
Try 'Try adding group(s)
For Each group As String In groups
groupPrincipal = groupPrincipal.FindByIdentity(adCtx, group) 'Search for the group name, sid, sAMAccountName or display name
If groupPrincipal IsNot Nothing Then
groupPrincipal.Members.Add(newUser) 'Add the user to the group
groupPrincipal.Save()
Else
Me.Invoke(log, New Object() {"Unable to add " + row("sAMAccountName") + " to group: " + group + ". Group not found.", frmProgress.LogType.Failure})
End If
Next
Catch ex As PrincipalExistsException
'### TO DO: Try to get group name in exception
Me.Invoke(log, New Object() {"Error adding " + row("sAMAccountName") + " (" + row("displayName") + ") to " + "group(s). " + ex.Message, frmProgress.LogType.Failure})
End Try
End If
newUser.Dispose() 'Dispose of the newUser object
Next
#If Not Debug Then
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical)
End Try
#End If
End Sub
Immediate Window (When Native Debugging is enabled)
Critical error detected c0000374
First-chance exception at 0x76fbf996 in AD User Importer.exe: 0xC0000374: A heap has been corrupted.
A first chance exception of type 'System.InvalidCastException' occured in System.DirectoryServices.AccountManagement.dll
I think your issue lies in this block:
Try
newUser.Save() 'Save the user to Active Directory
Me.Invoke(log, New Object() {"Successfully created " + row("sAMAccountName") + " (" + row("displayName") + ")", frmProgress.LogType.Success})
Catch ex As PrincipalExistsException
Me.Invoke(log, New Object() {"Error creating " + row("sAMAccountName") + " (" + row("displayName") + "). " + ex.Message, frmProgress.LogType.Failure})
Continue For
End Try
This code handles exceptions but does not dispose newUser before continuing with the next loop iteration.
I recently began to receive similar heap exceptions and after a close examination I realized that I was not disposing my UserPrincipal object. Once I correctly disposed of the object the issue seems to have stopped.
You should wrap your newUser object in a Using block:
For Each row As DataRow In dtUsers.Rows
Using newUser As UserPrincipalEx = New UserPrincipalEx(adCtx)
newUser.SamAccountName = row("sAMAccountName")
newUser.SetPassword(row("Password"))
' ... the remainder of the code
' ... now wrapped in a Using block
End Using
Next
The newUser object will be automatically disposed no matter how the Using block is exited. Because the Using block disposes for you, you can remove the explicit call to newUser.Dispose().
If the Using block is not available in your version of VB.Net then you should wrap the loop in a Try...Finally block and explicitly dispose the newUser in the Finally block.
I am trying to save the text file in this path:"C:\Test\test.txt" and when the file is already opened I need to check whether the file is opened and I need to close it before writing it to the file.
Here is the code for saving the file:
Dim myfile As String = "C:\Test\test.txt"
'Check if file exists
If System.IO.File.Exists(myfile) = True Then
'Delete it!
Dim fi As New FileInfo(myfile)
fi.Delete()
End If
Using sfdlg As New Windows.Forms.SaveFileDialog
sfdlg.DefaultExt = "amk"
sfdlg.Filter = "AquaMark Project|*.amk"
If sfdlg.ShowDialog = Windows.Forms.DialogResult.OK Then
Dim SaveData As New gCanvasData
IO.Directory.CreateDirectory("C:\Test")
Dim w As New IO.StreamWriter("C:\Test\test.txt")
Dim i As Integer
For i = 0 To CheckedListBox1.Items.Count - 1
w.WriteLine(CheckedListBox1.Items.Item(i))
Next
w.Close()
With SaveData
frmDisplay.GCanvas1.UnselectCurrentAnotate()
.gAnnotates = frmDisplay.GCanvas1.gAnnotates
.Image = frmDisplay.GCanvas1.Image
End With
Using objStreamWriter As New StreamWriter(sfdlg.FileName)
Dim x As New XmlSerializer(GetType(gCanvasData))
x.Serialize(objStreamWriter, SaveData)
objStreamWriter.Close()
End Using
End If
End Using
If I am doing this way I am able to close the notepad process but I need to close the specific opened text file:
Dim Process() As Process = System.Diagnostics.Process.GetProcessesByName("notepad")
Process() = CType(Interaction.GetObject("C:\Test\test.txt"), Diagnostics.Process())
For Each p As Process In Process
p.Kill()
Next
I do not believe there is a property that will allow for you to check if the streamreader is open or not.
Best practice seems to be to .close the reader when done with it. (All in the method that it was used in.)
You could try a try block to handle the exception if you are still getting one.
May be able to find additional info and some sample code here. Good Luck.
MSDN! StreamReader
EDIT: You may be able to check using this. IO.File
Private Function CheckFile(ByVal filename As String) As Boolean
Try
System.IO.File.Open(filename, IO.FileMode.Open, IO.FileAccess.Read, IO.FileShare.None)
FileClose(1)
Return False
Catch ex As Exception
Return True
End Try
End Function
What about :
If File.Exists("File1.txt") = False Then
File.CreateText("File1.txt").Close()
Else
Exit Sub
End If
If File.Exists("File2.txt") = False Then
File.CreateText("File2.txt").Close()
Else
Exit Sub
End If
End If
Private Sub IsFileOpen(ByVal file As FileInfo)
Dim stream As FileStream = Nothing
Try
stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None)
Catch ex As IOException
If IsFileLocked(ex) Then
'do something here, either wait a few seconds, close the file if you have
'a handle, make a copy of it, read it as shared (FileAccess fileAccess = FileAccess.Read, FileShare fileShare = FileShare.ReadWrite).
'I dont recommend terminating the process - which could cause corruption and lose data
End If
Catch ex As Exception
End Try
End Sub
Private Shared Function IsFileLocked(exception As Exception) As Boolean
Dim errorCode As Integer = Marshal.GetHRForException(exception) And ((1 << 16) - 1)
Return errorCode = 32 OrElse errorCode = 33
End Function
The following function can be used to determine is a file is already open (True) or not (False). Action can then be based on the Function result.
Public Function IsFileOpen(ByVal xFileName As String, ByVal xFileChannel As Integer) As Boolean
' ************************************************************
' * Function: IsFileOpen
' * Purpose: To determine if a file is already open.
' * Can be used to determine if a file should be closed.
' * Syntax:
' * Dim bResult as Boolean
' *
' * bResult = IsFileOpen("C:\Test.txt", 1)
' *
' * OR
' *
' * If IsFileOpen("C:\Test.txt", 1) = True Then
' * Microsoft.VisualBasic.FileClose(1)
' * End If
' *
' ************************************************************
Try
Microsoft.VisualBasic.FileOpen(xFileChannel, xFileName, OpenMode.Input, OpenAccess.Read, OpenShare.Default)
Catch
' File Already Open Error Number = 55
If Trim(Err.Number.ToString) = "55" Then
Return True
Else
Return False
End If
End Try
End Function
I was having this problem with a .csv file my program attaches to an email. I added code to clear the Attachments collection in the MailMessage object then disposing the MailMessage and Attachment objects after the mail is sent. That appears to have fixed the problem.