-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBatchImporter.vb
More file actions
438 lines (355 loc) · 17.3 KB
/
BatchImporter.vb
File metadata and controls
438 lines (355 loc) · 17.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
Option Strict On
Module BatchImporter
<STAThread>
Sub Main()
Dim SEApp As SolidEdgeFramework.Application = Nothing
Dim SEDoc As SolidEdgeFramework.SolidEdgeDocument = Nothing
Dim ProgramSettings As New Dictionary(Of String, String)
Dim Filenames As List(Of String)
Dim Filename As String
Dim NewFilename As String
Dim AutoselectTemplate As Boolean
Dim TemplateFilename As String
Dim AssemblyTemplateFilename As String
Dim PartTemplateFilename As String
Dim SheetmetalTemplateFilename As String
Dim DraftTemplateFilename As String
Dim ImportFileExtensions As New List(Of String)
Dim ImportFileExtension As String
Dim ImportDirectory As String
Dim ExportDirectory As String
Dim TemplateExtension As String
Dim IOErrorsMax As Integer
Dim IOErrors As Double = 0
Dim SEWasRunning As Boolean = False
Dim DrawingExtensions As List(Of String) = {".dwg", ".dxf"}.ToList
Dim ErrorMessages As New List(Of String)
OleMessageFilter.Register()
' ###### READ PROGRAM SETTINGS ######
ProgramSettings = GetProgramSettings()
If ProgramSettings Is Nothing Then Exit Sub
AutoselectTemplate = CBool(ProgramSettings("AutoselectTemplate"))
TemplateFilename = ProgramSettings("TemplateFilename")
AssemblyTemplateFilename = ProgramSettings("AssemblyTemplateFilename")
PartTemplateFilename = ProgramSettings("PartTemplateFilename")
SheetmetalTemplateFilename = ProgramSettings("SheetmetalTemplateFilename")
DraftTemplateFilename = ProgramSettings("DraftTemplateFilename")
Dim tmpImportFileExtensions As List(Of String) = Split(ProgramSettings("ImportFileExtensions"), ",").ToList
For Each tmpExtension As String In tmpImportFileExtensions
ImportFileExtensions.Add(tmpExtension.Trim)
Next
ImportDirectory = ProgramSettings("ImportDirectory")
ExportDirectory = ProgramSettings("ExportDirectory")
IOErrorsMax = CInt(ProgramSettings("IOErrorsMax"))
' ###### CHECK INPUTS ######
Dim InputErrors As Boolean = False
If Not AutoselectTemplate Then
If Not System.IO.File.Exists(TemplateFilename) Then
InputErrors = True
Console.WriteLine(String.Format("Template not found `{0}`", TemplateFilename))
End If
Else
For Each tmpFilename As String In {AssemblyTemplateFilename, PartTemplateFilename, SheetmetalTemplateFilename, DraftTemplateFilename}
If Not System.IO.File.Exists(tmpFilename) Then
InputErrors = True
Console.WriteLine(String.Format("Template not found `{0}`", tmpFilename))
End If
Next
End If
If Not System.IO.Directory.Exists(ImportDirectory) Then
InputErrors = True
Console.WriteLine(String.Format("Import directory not found `{0}`", ImportDirectory))
End If
If Not System.IO.Directory.Exists(ExportDirectory) Then
FileIO.FileSystem.CreateDirectory(ExportDirectory)
End If
Dim AllFileExtensions As List(Of String) = {".*"}.ToList
Dim StartingFilenames As List(Of String) = GetFilenames(AllFileExtensions, ImportDirectory)
Filenames = GetFilenames(ImportFileExtensions, ImportDirectory)
If Filenames Is Nothing Then
InputErrors = True
Console.WriteLine($"No matching files found in '{ImportDirectory}'")
End If
If InputErrors Then
Console.WriteLine("")
Console.WriteLine("Press any key to continue")
Console.Read()
Exit Sub
End If
' ###### PROCESS FILES ######
Console.WriteLine("Connecting to Solid Edge")
Try
SEApp = CType(GetObject(, "SolidEdge.Application"), SolidEdgeFramework.Application)
SEWasRunning = True
Catch ex As Exception
SEApp = CType(CreateObject("SolidEdge.Application"), SolidEdgeFramework.Application)
SEWasRunning = False
End Try
SEApp.Visible = True
SEApp.DisplayAlerts = False
SEApp.WindowState = 2 'Maximizes Solid Edge
SEApp.Activate()
Dim FileCount As Integer = 0
For Each Filename In Filenames
ImportFileExtension = IO.Path.GetExtension(Filename)
FileCount += 1
If IOErrors > IOErrorsMax Then
ErrorMessages.Add(String.Format("Number of file IO errors {0} exceed maximum of {1}. Exiting...", IOErrors, IOErrorsMax))
Exit For
End If
' Discount errors for long-running jobs
IOErrors -= 0.1
If IOErrors < 0 Then IOErrors = 0
Console.WriteLine("")
Console.WriteLine(String.Format("{0}/{1} Opening {2}", FileCount, Filenames.Count, IO.Path.GetFileName(Filename)))
NewFilename = ""
TemplateExtension = ""
If Not AutoselectTemplate Then
TemplateExtension = IO.Path.GetExtension(TemplateFilename)
Try
SEDoc = DirectCast(SEApp.Documents.OpenWithTemplate(Filename, TemplateFilename), SolidEdgeFramework.SolidEdgeDocument)
SEApp.DoIdle()
SEDoc.Activate()
Catch ex As Exception
Dim s As String = $"Unable to open '{Filename}.' "
s = $"{s}The Solid Edge error message was: {ex.Message}"
ErrorMessages.Add(s)
IOErrors += 1
Continue For
End Try
Else
If ImportFileExtension.ToLower = ".igs" Or ImportFileExtension.ToLower = ".iges" Then
ErrorMessages.Add($"Cannot currently process IGES files with Autoselect '{Filename}'")
Continue For
End If
If DrawingExtensions.Contains(ImportFileExtension.ToLower) Then
TemplateExtension = ".dft"
Try
SEDoc = DirectCast(SEApp.Documents.OpenWithTemplate(Filename, DraftTemplateFilename), SolidEdgeFramework.SolidEdgeDocument)
SEApp.DoIdle()
SEDoc.Activate()
Catch ex As Exception
Dim s As String = $"Unable to open '{Filename}.' "
s = $"{s}The Solid Edge error message was: {ex.Message}"
ErrorMessages.Add(s)
IOErrors += 1
Continue For
End Try
Else
' Assume it is an assembly. If it doesn't have multiple occurrences, reopen as a single part.
TemplateExtension = ".asm"
Try
SEDoc = DirectCast(SEApp.Documents.OpenWithTemplate(Filename, AssemblyTemplateFilename), SolidEdgeFramework.SolidEdgeDocument)
SEApp.DoIdle()
SEDoc.Activate()
Catch ex As Exception
Dim s As String = $"Unable to open '{Filename}.' "
s = $"{s}The Solid Edge error message was: {ex.Message}"
ErrorMessages.Add(s)
IOErrors += 1
Continue For
End Try
Dim tmpAsmDoc As SolidEdgeAssembly.AssemblyDocument = CType(SEDoc, SolidEdgeAssembly.AssemblyDocument)
If Not tmpAsmDoc.Occurrences.Count > 1 Then
SEDoc.Close(False)
SEApp.DoIdle()
TemplateExtension = ".par"
Try
SEDoc = DirectCast(SEApp.Documents.OpenWithTemplate(Filename, PartTemplateFilename), SolidEdgeFramework.SolidEdgeDocument)
SEApp.DoIdle()
SEDoc.Activate()
Catch ex As Exception
Dim s As String = $"Unable to open '{Filename}.' "
s = $"{s}The Solid Edge error message was: {ex.Message}"
ErrorMessages.Add(s)
IOErrors += 1
Continue For
End Try
End If
End If
End If
'NewFilename = System.IO.Path.GetFileName(Filename) ' C:\project\part.stp -> part.stp
'NewFilename = String.Format("{0}\{1}", ExportDirectory, NewFilename) ' part.stp -> .\OutDir\part.stp
'NewFilename = System.IO.Path.ChangeExtension(NewFilename, TemplateExtension) ' .\OutDir\part.stp -> .\OutDir\part.psm
NewFilename = System.IO.Path.ChangeExtension(Filename, TemplateExtension)
Console.WriteLine(String.Format("Saving {0}", IO.Path.GetFileName(NewFilename)))
Try
SEDoc.SaveAs(NewFilename)
SEApp.DoIdle()
SEDoc.Close()
SEApp.DoIdle()
Catch ex As Exception
Dim s As String = $"Unable to save '{NewFilename}.' "
s = $"{s}The Solid Edge error message was: {ex.Message}"
ErrorMessages.Add(s)
IOErrors += 1
Continue For
End Try
Next
' ###### WRAP UP ######
Dim tmpAllFilenames = GetFilenames(AllFileExtensions, ImportDirectory)
Dim NewFilenames As New List(Of String)
For Each tmpFilename As String In tmpAllFilenames
If Not StartingFilenames.Contains(tmpFilename) Then
Dim Destination As String = $"{ExportDirectory}\{IO.Path.GetFileName(tmpFilename)}"
If IO.File.Exists(Destination) Then IO.File.Delete(Destination)
IO.File.Move(tmpFilename, Destination)
End If
Next
If Not SEWasRunning Then
If SEApp IsNot Nothing Then SEApp.Quit()
Else
If SEApp IsNot Nothing Then SEApp.DisplayAlerts = True
End If
If ErrorMessages.Count > 0 Then
Console.WriteLine("")
Console.WriteLine("")
Console.WriteLine("REPORTED ERRORS")
Dim Indent As String = " "
For Each s As String In ErrorMessages
Console.WriteLine($"{Indent}{s}")
Next
End If
Console.WriteLine("")
Console.WriteLine(String.Format("Finished processing {0} files", FileCount))
Console.WriteLine("")
Console.WriteLine("Press any key to continue")
Console.Read()
OleMessageFilter.Revoke()
End Sub
Private Function GetFilenames(ImportFileExtensions As List(Of String), ImportDirectory As String) As List(Of String)
Dim FoundFiles As New List(Of String)
Dim ActiveFileExtensionsList As New List(Of String)
For Each ImportFileExtension As String In ImportFileExtensions
ActiveFileExtensionsList.Add($"*{ImportFileExtension}")
Next
If FileIO.FileSystem.DirectoryExists(ImportDirectory) Then
Try
FoundFiles = FileIO.FileSystem.GetFiles(
ImportDirectory,
FileIO.SearchOption.SearchTopLevelOnly,
ActiveFileExtensionsList.ToArray).ToList
Catch ex As Exception
Dim s As String = "An error occurred searching for files."
s = String.Format("{0}{1}{2}", s, vbCrLf, ex.ToString)
Console.WriteLine(s)
FoundFiles = Nothing
End Try
Else
Console.WriteLine(String.Format("Directory '{0}' not found", ImportDirectory))
FoundFiles = Nothing
End If
If FoundFiles IsNot Nothing AndAlso FoundFiles.Count = 0 Then
'Console.WriteLine(String.Format("No '{0}' files found", ImportFileExtension))
FoundFiles = Nothing
End If
Return FoundFiles
End Function
Private Function GetProgramSettings() As Dictionary(Of String, String)
Dim ProgramSettings As New Dictionary(Of String, String)
Dim Settings As List(Of String) = Nothing
Dim Key As String
Dim Value As String
Dim ProgramSettingsFilename As String
Dim StartupPath As String = System.AppDomain.CurrentDomain.BaseDirectory
Dim tf As Boolean
Dim RequiredKeys As New List(Of String)
RequiredKeys.AddRange({"TemplateFilename", "ImportFileExtensions", "ImportDirectory", "ExportDirectory", "IOErrorsMax"})
RequiredKeys.AddRange({"AutoselectTemplate", "AssemblyTemplateFilename", "PartTemplateFilename", "SheetmetalTemplateFilename", "DraftTemplateFilename"})
ProgramSettingsFilename = String.Format("{0}program_settings.txt", StartupPath)
If Not FileIO.FileSystem.FileExists(ProgramSettingsFilename) Then
'CreateProgramSettings(ProgramSettingsFilename)
'Console.WriteLine("A new settings file was created.")
'Console.WriteLine(String.Format("The location is '{0}'", ProgramSettingsFilename))
'Console.WriteLine("You need to configure it before continuing.")
'Console.WriteLine("Instructions to do so are in the file.")
'Console.WriteLine("")
'Console.WriteLine("Press any key to continue")
'Console.Read()
Return Nothing
End If
Try
Settings = IO.File.ReadAllLines(ProgramSettingsFilename).ToList
For Each KVPair As String In Settings
Dim s As String = KVPair.Trim()
tf = s = ""
tf = tf OrElse s(0) = "'"
tf = tf OrElse Not s.Contains("=")
If tf Then Continue For
Key = s.Split("="c)(0)
Value = s.Split("="c)(1)
ProgramSettings(Key.Trim()) = Value.Trim()
Next
Catch ex As Exception
Console.WriteLine(String.Format("Problem reading {0}", ProgramSettingsFilename))
Return Nothing
End Try
Dim MissingVariables As Boolean = False
For Each s As String In RequiredKeys
If Not ProgramSettings.Keys.Contains(s) Then
MissingVariables = True
Console.WriteLine(String.Format("Missing variable in program_settings.txt '{0}'", s))
End If
Next
If MissingVariables Then
Console.WriteLine("")
Console.WriteLine("Press any key to continue")
Console.Read()
Return Nothing
Else
' Strip trailing '\' in directory names if present
For Each DirName In {"ImportDirectory", "ExportDirectory"}
Value = ProgramSettings(DirName)
If Value(Value.Count - 1) = "\" Then ProgramSettings(DirName) = Left(Value, Value.Count - 1)
Next
End If
Return ProgramSettings
End Function
'Private Sub CreateProgramSettings(ProgramSettingsFilename As String)
' Dim Outlist As New List(Of String)
' Outlist.Add("' Program settings")
' Outlist.Add("")
' Outlist.Add("' Full path names are required for directories and templates.")
' Outlist.Add("' Eg, 'c:\projects\customer_files\step_files', not '..\step_files'.")
' Outlist.Add("' Any line preceeded with a single quote character is ignored. Blank lines, too.")
' Outlist.Add("")
' Outlist.Add("")
' Outlist.Add("'###### TEMPLATE FILE ######")
' Outlist.Add("'Enter the name of the file to use as a template for import.")
' Outlist.Add("")
' Outlist.Add("TemplateFilename = C:\Program Files\Siemens\Solid Edge 2024\Template\ANSI Inch\ansi inch sheet metal.psm")
' Outlist.Add("")
' Outlist.Add("")
' Outlist.Add("'###### IMPORT FILE EXTENSION ######")
' Outlist.Add("'Enter the file extension of the files to import.")
' Outlist.Add("")
' Outlist.Add("ImportFileExtension = *.stp")
' Outlist.Add("")
' Outlist.Add("")
' Outlist.Add("'###### IMPORT DIRECTORY ######")
' Outlist.Add("'Enter the directory where to look for files to import.")
' Outlist.Add("")
' Outlist.Add("ImportDirectory = C:\data\infiles")
' Outlist.Add("")
' Outlist.Add("")
' Outlist.Add("'###### EXPORT DIRECTORY ######")
' Outlist.Add("'Enter the directory where to save imported files.")
' Outlist.Add("")
' Outlist.Add("ExportDirectory = C:\data\outfiles")
' Outlist.Add("")
' Outlist.Add("")
' Outlist.Add("'###### IO ERROR LIMIT ######")
' Outlist.Add("'Enter the number of file read/write errors to accept before stopping the program.")
' Outlist.Add("")
' Outlist.Add("IOErrorsMax = 3")
' Try
' IO.File.WriteAllLines(ProgramSettingsFilename, Outlist)
' Catch ex As Exception
' Console.WriteLine(String.Format("Could not create '{0}'", ProgramSettingsFilename))
' Console.WriteLine("It may be open elsewhere")
' Console.WriteLine("")
' Console.WriteLine("Press any key to continue")
' Console.Read()
' End Try
'End Sub
End Module