-
Notifications
You must be signed in to change notification settings - Fork 1
/
ErrorWindow.vb
634 lines (602 loc) · 29.9 KB
/
ErrorWindow.vb
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
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
Imports System.Drawing
Imports System.Environment
Imports System.IO
Imports System.Reflection
Imports System.Runtime.InteropServices
Imports System.Security.Permissions
Imports System.Text.RegularExpressions
Imports System.Windows.Forms
Imports System.Windows.Forms.LinkLabel
Imports System.Xml
Imports HarmonyLib
Imports Newtonsoft.Json
Imports TaleWorlds.Core
Imports TaleWorlds.Library
Imports TaleWorlds.Localization
Imports TaleWorlds.SaveSystem
<PermissionSet(SecurityAction.Demand, Name:="FullTrust")>
<ComVisibleAttribute(True)>
Public Class ErrorWindow
Public Shared exceptionData As Exception
Shared errorCount = 0
Dim problematicModules = New SortedSet(Of String)
Dim html = File.ReadAllText(BewBasePath() & "\errorui.htm")
Dim bAttachedFileNotSavedYet = False
Private Sub ErrorWindow_Load(sender As Object, e As EventArgs) Handles MyBase.Load
html = LocaliseTheHtmlPage(html)
Me.TopMost = True
Dim menu As New Windows.Forms.ContextMenu()
menu.MenuItems.Add("none")
widget.ContextMenu = menu
widget.ObjectForScripting = Me
Dim additionalInfo = ""
If errorCount > 0 Then
additionalInfo = "The game has crashed " & errorCount & IIf(errorCount = 1, " time.", " times.")
additionalInfo = additionalInfo & "<br />"
End If
errorCount = errorCount + 1
additionalInfo = additionalInfo & GetAdviseOnAttemptContinue()
If CheckIsAssemblyLoaded("Bannerlord.ButterLib.dll") Then
html = html.Replace("{butterlibMessage}",
New TextObject("{=BewShowButterlib}<a href='#' onclick='window.external.ShowButterlibException()'>Click here</a> to show Butterlib exception.<br /><br />").ToString())
Else
html = html.Replace("{butterlibMessage}", "")
End If
html = html.Replace("{additionalMessage}", additionalInfo)
html = html.Replace("{errorString}", exceptionData.Message)
html = html.Replace("{faultingSource}", exceptionData.Source)
html = html.Replace("{fullStackString}", exceptionData.StackTrace)
Dim installedMods = ""
Dim listOfInstalledMods = GetAssembliesList(False)
For Each x In listOfInstalledMods
installedMods = installedMods + x
Next
html = html.Replace("{installedMods}", installedMods)
If exceptionData.InnerException IsNot Nothing Then
html = html.Replace("{innerException}", exceptionData.InnerException.Message)
html = html.Replace("{innerFaultingSource}", exceptionData.InnerException.Source)
html = html.Replace("{innerExceptionCallStack}", exceptionData.InnerException.StackTrace)
Else
Dim noInnerExceptionString = New TextObject("{=BewNoInnterException}No inner exception was thrown").ToString()
html = html.Replace("{innerException}", noInnerExceptionString)
html = html.Replace("{innerFaultingSource}", "No module")
html = html.Replace("{innerExceptionCallStack}", noInnerExceptionString)
End If
html = html.Replace("{jsonData}", AnalyseModules())
'wait a bit to gather game log
Sleep(5 * 1000)
html = html.Replace("{gameLogs}", GetGameLog())
html = html.Replace("(logtime)", GetGameLogDateTime())
html = html.Replace("{jsonHarmony}", GetHarmonyPatches())
html = html.Replace("{version}", Version)
html = html.Replace("{commit}", Commit)
widget.DocumentText = html
AddHandler widget.Document.ContextMenuShowing, AddressOf WebContextMenuShowing
AddHandler widget.PreviewKeyDown, AddressOf WebShorcut
widget.WebBrowserShortcutsEnabled = False
widget.ScriptErrorsSuppressed = True
'widget.Document.InvokeScript("AnalyseModule", Nothing)
PrintExceptionToDebug()
End Sub
Private Function LocaliseTheHtmlPage(html As String) As String
Dim xml = File.ReadAllText(BewBasePath() & "\ModuleData\Languages\str_EN.xml")
Dim doc As New XmlDocument()
doc.LoadXml(xml)
Dim nodeList As XmlNodeList = doc.SelectNodes("//string[starts-with(@id, 'htmlXX')]")
For Each node As XmlNode In nodeList
Dim localisedId = node.Attributes("id").Value
Dim localisedString = node.Attributes("text").Value
Dim curlyBracket = "{" & localisedId & "}"
Dim localisedText = New TextObject("{=" & localisedId & "}" & localisedString)
html = html.Replace(curlyBracket, localisedText.ToString())
Next
nodeList = doc.SelectNodes("//string[starts-with(@id, 'javascriptXX')]")
For Each node As XmlNode In nodeList
Dim localisedId = node.Attributes("id").Value
Dim localisedString = node.Attributes("text").Value
Dim curlyBracket = "{" & localisedId & "}"
Dim localisedText = New TextObject("{=" & localisedId & "}" & localisedString)
html = html.Replace(curlyBracket, localisedText.ToString())
Next
Return html
End Function
Public Function GetAdviseOnAttemptContinue()
If Not File.Exists(BewBasePath() & "\solutions.json") Then
Print("Error loading solutions.json to explain the current crash")
Return ""
End If
Try
Dim text = File.ReadAllText(BewBasePath() & "\solutions.json")
Dim jsonData = JsonConvert.DeserializeObject(text)
For Each x In jsonData
If IsNothing(x("Keywords")) Then Continue For
If IsNothing(x("Reason")) Then Continue For
Dim foundReasonOnOuterException = True
With exceptionData.InnerException.StackTrace
For Each y In x("Keywords")
foundReasonOnOuterException = foundReasonOnOuterException And .Contains(y)
Next
End With
Dim foundReasonOnInnerException = True
With exceptionData.StackTrace
For Each y In x("Keywords")
foundReasonOnInnerException = foundReasonOnInnerException And .Contains(y)
Next
End With
If foundReasonOnOuterException Or foundReasonOnInnerException Then
Return x("Reason")
End If
Next
Catch ex As Exception
Print("Error parsing solution.json (ignore this error)")
End Try
Return ""
End Function
Public Sub ShowButterlibException()
'HtmlBuilder.BuildAndShow(new CrashReport(__exception))
Me.TopMost = False
Dim butterlibAsm = GetAssemblyByDll("Bannerlord.ButterLib.dll")
If IsNothing(butterlibAsm) Then Exit Sub
Dim BannerlordButterLibExceptionHandler = GetTypeFromAssembly(butterlibAsm, "Bannerlord.ButterLib.ExceptionHandler.ExceptionReporter")
If IsNothing(BannerlordButterLibExceptionHandler) Then Exit Sub
Dim Show = BannerlordButterLibExceptionHandler.GetMethod("Show", BindingFlags.Static Or BindingFlags.Public)
If IsNothing(Show) Then Exit Sub
Show.Invoke(Nothing, New Object() {exceptionData})
End Sub
Private Sub PrintExceptionToDebug()
Debug.Print("Better exception window unhandled exception: " & exceptionData.Message)
Debug.Print(exceptionData.StackTrace)
If Not IsNothing(exceptionData.InnerException) Then
Debug.Print("Inner exception: " & exceptionData.InnerException.Message)
Debug.Print(exceptionData.InnerException.StackTrace)
End If
End Sub
Private Sub WebContextMenuShowing(ByVal sender As Object, ByVal e As HtmlElementEventArgs)
'disables context menu
widgetMenu.Show(widget, e.MousePosition)
'Me.widget.ContextMenuStrip.Show(Cursor.Position)
e.ReturnValue = False
End Sub
Private Sub WebShorcut(ByVal sender As Object, ByVal e As PreviewKeyDownEventArgs)
If e.Modifiers = Keys.Control And e.KeyCode = Keys.C Then
widget.Document.ExecCommand("Copy", False, Nothing)
End If
If e.Modifiers = Keys.Control And e.KeyCode = Keys.P Then
widget.Document.InvokeScript("window.print", Nothing)
End If
If e.Modifiers = Keys.Control And e.KeyCode = Keys.A Then
widget.Document.ExecCommand("SelectAll", False, Nothing)
End If
End Sub
Public Function Screenshot()
TakeScreenshot("temporary")
Dim b64image = FileToBase64String(BewTemp & "\temporary.compressed.jpg")
html = html.Replace("{screenshotBase64}", b64image)
bAttachedFileNotSavedYet = True
Return "file://" & BewTemp & "/temporary.compressed.jpg"
End Function
Public Function AttachSavegame()
Dim savegamePath = GetFolderPath(SpecialFolder.MyDocuments) & "\Mount and Blade II Bannerlord\Game Saves\"
If Not Directory.Exists(savegamePath) Then Return False
Dim savegameFile = New DirectoryInfo(savegamePath).EnumerateFiles() _
.Where(Function(x)
Dim reg = New Regex(".*\.sav")
Return reg.Match(x.Name).Success
End Function) _
.OrderByDescending(Function(x)
Return x.LastWriteTimeUtc
End Function) _
.FirstOrDefault()
If Not IsNothing(savegameFile) Then
Dim base64savegame = FileToBase64String(savegameFile.FullName)
html = html.Replace("{saveGameBase64}", base64savegame)
html = html.Replace("{saveGameFileName}", savegameFile.Name)
End If
bAttachedFileNotSavedYet = True
Return savegameFile.Name
End Function
Public Function Save()
'Dim filename = Str(DateTime.Now.ToFileTimeUtc()) + ".htm"
Dim fileDialog As New SaveFileDialog()
fileDialog.Filter = "HTML (*.htm)|*.htm|All files (*.*)|*.*"
If fileDialog.ShowDialog() = DialogResult.OK AndAlso fileDialog.FileName <> "" Then
Dim filename = fileDialog.FileName
File.WriteAllText(filename, html)
bAttachedFileNotSavedYet = False
Return filename
End If
Return Nothing
End Function
Public Sub AttemptToContinue()
Me.DialogResult = DialogResult.Retry
ShowToastMessage("Better Exception Window WARNING: User attempted to continue program execution despite unhandled exception! This may (or may not) trigger unwanted side effect.")
Close()
End Sub
Public Function DumpMemory(fullMemory As Boolean) As Integer
Dim fileDialog As New SaveFileDialog()
fileDialog.Filter = "Memory Dump (*.dmp)|*.dmp|All files (*.*)|*.*"
If fileDialog.ShowDialog() = DialogResult.OK AndAlso fileDialog.FileName <> "" Then
Dim filename = fileDialog.FileName
If DumpFile(filename, fullMemory) Then
Return 0
Else
Return 1
End If
End If
Return 2
End Function
Public Function IsPageModified() As Boolean
Return bAttachedFileNotSavedYet
End Function
Public Sub CloseProgram()
KillGame()
End Sub
Public Sub OpenConfig()
Try
Dim p = Path.GetFullPath(BewBasePath() & "\config.json")
Process.Start(p)
Catch ex As Exception
End Try
End Sub
Public Function IsRunningBannerlord()
Return True
End Function
Public Sub OpenFile(s As String)
Process.Start(s)
End Sub
Public Sub OpenPath(s As String)
Dim p = Path.GetDirectoryName(s)
Process.Start(p)
End Sub
Private Function GetGameLog()
Dim dataPath = GetBanenrlordProgramDataPath() + "\logs\"
Dim temptFile = New DirectoryInfo(dataPath).EnumerateFiles() _
.Where(Function(x)
Dim reg = New Regex("rgl_log_([0-9])*\.txt")
Return reg.Match(x.Name).Success
End Function) _
.FirstOrDefault()
If temptFile IsNot Nothing Then
Dim filestrm As New FileStream(temptFile.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
Dim txtreader As New StreamReader(filestrm)
Return txtreader.ReadToEnd()
End If
Return ""
End Function
Private Class HarmonyPatchInformation
Public Finalisers As List(Of Patch)
Public Prefixes As List(Of Patch)
Public Postfixes As List(Of Patch)
Public Transpilers As List(Of Patch)
End Class
Private Function GetHarmonyPatches()
Dim patches = Harmony.GetAllPatchedMethods()
Dim listOfPatches As New Dictionary(Of String, HarmonyPatchInformation)
For Each p In patches
Dim patch = Harmony.GetPatchInfo(p)
Dim patchInfo As New HarmonyPatchInformation
With patchInfo
.Finalisers = patch.Finalizers.ToList()
.Postfixes = patch.Postfixes.ToList()
.Prefixes = patch.Prefixes.ToList()
.Transpilers = patch.Transpilers.ToList()
End With
listOfPatches(p.FullDescription()) = patchInfo
Next
Return JsonConvert.SerializeObject(listOfPatches)
End Function
Private Function GetGameLogDateTime()
Dim dataPath = GetBanenrlordProgramDataPath() + "\logs\"
Dim biggestFile = New DirectoryInfo(dataPath).EnumerateFiles() _
.Where(Function(x) x.Name.StartsWith("rgl_log_")) _
.OrderByDescending(Function(x) x.LastWriteTimeUtc) _
.FirstOrDefault()
If biggestFile IsNot Nothing Then
Return biggestFile.LastWriteTime.ToString("yyyy-MM-dd HH:mm : ss 'GMT'z")
End If
Return ""
End Function
Private Function GetModulePathFromAssembly(dll As Assembly) As String
Dim location = dll.Location
location = Path.GetDirectoryName(location)
Dim realLocation = Path.GetFullPath(location + "\..\..\")
Return realLocation
End Function
Private Function ReadXmlAsJson(path As String) As Object
Dim data = File.ReadAllText(path)
Dim xmldata As New XmlDocument()
xmldata.LoadXml(data)
Return JsonConvert.DeserializeObject(JsonConvert.SerializeXmlNode(xmldata))
End Function
Private Sub AddXMLDiagResult(filename As String, filepath As String, Optional errorStr As String = "")
If errorStr <> "" Then
widget.Document.InvokeScript("addXMLDiagResult", New String() {filename, filepath, errorStr})
Else
widget.Document.InvokeScript("addXMLDiagResult", New String() {filename, filepath})
End If
End Sub
Private Function GetAssembliesList(searchAlsoInGameBins As Boolean) As List(Of String)
Dim dlls = Process.GetCurrentProcess().Modules
Dim out As New List(Of String)
For Each dll As ProcessModule In dlls
Try
Dim asm = AssemblyName.GetAssemblyName(dll.FileName)
Dim version = asm.Version
Dim name = asm.Name
Dim location = dll.FileName
Dim link = location.Replace("\", "\\")
Dim li = $"Managed Assembly {name}, version: {version}. Location: <a href='#' onclick='window.external.OpenPath(""{link}"")'>{location}</a>"
Dim output = ""
output = $"<li class='taleworlds_ul'>{li}</li>" & vbNewLine
out.Add(output)
Catch ex As BadImageFormatException
Dim name = Path.GetFileNameWithoutExtension(dll.ModuleName)
Dim location = dll.FileName
Dim link = location.Replace("\", "\\")
Dim li = $"Native Code {name}. Location: <a href='#' onclick='window.external.OpenPath(""{link}"")'>{location}</a>"
Dim output = ""
output = $"<li class='taleworlds_ul'>{li}</li>" & vbNewLine
out.Add(output)
End Try
Next
Dim appdomainDlls = AppDomain.CurrentDomain.GetAssemblies()
For Each dll In appdomainDlls
Try
Dim name = dll.GetName().Name
Dim assmeblyVer = dll.GetName().Version
Dim location = dll.Location
Dim link = dll.Location.Replace("\", "\\")
Dim version = assmeblyVer
Dim li = $"Assembly {name}, version: {version}. Location: <a href='#' onclick='window.external.OpenPath(""{link}"")'>{location}</a>"
Dim output = ""
If name.StartsWith("TaleWorlds") Or
name.StartsWith("SandBox") Or
name.StartsWith("StoryMode") Or
name.StartsWith("Steamworks") Then
output = $"<li class='taleworlds_ul'>{li}</li>" & vbNewLine
Else
output = $"<li>{li}</li>" & vbNewLine
End If
out.Add(output)
Catch ex As Exception
End Try
Next
Return out
End Function
Public Sub DisableProblematicModules()
Dim myDocument = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
Dim xmlPath = myDocument + "\Mount and Blade II Bannerlord\Configs\LauncherData.xml"
Dim loadedModuleJSON = ReadXmlAsJson(xmlPath)
Debug.Print(JsonConvert.SerializeObject(loadedModuleJSON))
Dim nativeModules = {"Native", "SandBoxCore", "CustomBattle", "StoryMode"}
Dim modulesString = ""
For Each x In problematicModules
modulesString = modulesString + x + ","
Next
If problematicModules.Count() = 0 Then
MsgBox("Unable to fix this. We can't determine faulting modules.", MsgBoxStyle.Critical)
Exit Sub
End If
modulesString = modulesString.Substring(0, modulesString.Length() - 1)
Dim prompt = MsgBox("Are you sure to disable these modules: " + vbNewLine +
modulesString,
MsgBoxStyle.Exclamation Or MsgBoxStyle.YesNo,
"Disable mods"
)
If prompt = MsgBoxResult.Yes Then
Dim userModData = loadedModuleJSON("UserData")("SingleplayerData")("ModDatas")("UserModData")
For Each x In userModData
Dim moduleId = x("Id").ToString()
For Each y In problematicModules
If moduleId = y AndAlso Not nativeModules.Contains(y) Then
x("IsSelected") = "false"
Exit For
End If
Next
Next
Dim jsonString = JsonConvert.SerializeObject(loadedModuleJSON)
Debug.Print(jsonString)
Dim xmlData As XmlDocument = JsonConvert.DeserializeXmlNode(jsonString)
Dim stringXml = New IO.StringWriter()
Dim xmlWriter = New XmlTextWriter(stringXml)
xmlData.WriteTo(xmlWriter)
Debug.Print(stringXml.ToString())
File.WriteAllText(xmlPath, stringXml.ToString())
MsgBox("mods have been disabled")
End If
End Sub
Public Function AnalyseModules()
'Dim modulePath = Path.GetFullPath(BewDir & "\..\..\Modules\")
Dim modulePath = Path.GetFullPath(BaseDir & "\..\..\Modules\")
Dim myDocument = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
Dim loadedModuleJSON = ReadXmlAsJson(myDocument + "\Mount and Blade II Bannerlord\Configs\LauncherData.xml")
Dim loadedModule = loadedModuleJSON("UserData")("SingleplayerData")("ModDatas")("UserModData")
Dim loadedModuleList As New List(Of String)
Dim analysedModuleJSON As New List(Of Object)
For Each x In loadedModule
If x("IsSelected") Then
loadedModuleList.Add(x("Id"))
End If
Next
Dim modulesInGameDirectories = Directory.GetDirectories(modulePath)
Dim directories = New List(Of String)
Dim isSteamWorkshopFolderExists = Directory.Exists(Path.GetFullPath(BaseDir & "/../../../../workshop/content/261550"))
If IsRunningSteam And isSteamWorkshopFolderExists Then
Dim modulesInSteamWorkshopDirectory = Directory.GetDirectories(Path.GetFullPath(BaseDir & "/../../../../workshop/content/261550"))
directories.AddRange(modulesInSteamWorkshopDirectory)
End If
directories.AddRange(modulesInGameDirectories)
'2875090166\\SubModule.xml
For Each x In directories
Dim jsondata
Try
jsondata = ReadXmlAsJson(x + "\SubModule.xml")
Catch ex As Exception
Continue For
End Try
jsondata("isModLoaded") = loadedModuleList.Any(Function(f) f.Contains(jsondata("Module")("Id")("@value")))
jsondata("isPDBIncluded") = False
jsondata("location") = Path.GetFullPath(x)
jsondata("manifest") = (Path.GetFullPath(x) + "\SubModule.xml").Replace("\", "\\")
'MAYBE NOT AN ARRAY BUT PLAIN OBJECT INSTEAD
Dim maybeArray = True
Try
Dim subModuleClassType As String = jsondata("Module")("SubModules")("SubModule")("Name")("@value")
'Dim subModuleClassType As String = jsondata("Module")("SubModules")("SubModule")("SubModuleClassType")("@value")
'subModuleClassType = subModuleClassType.Substring(0, subModuleClassType.IndexOf("."))
Dim modId = jsondata("Module")("Id")("@value")
jsondata("isFaultingMod") = exceptionData.StackTrace.Contains(subModuleClassType) Or exceptionData.StackTrace.Contains(modId) And jsondata("isModLoaded")
If exceptionData.InnerException IsNot Nothing Then
jsondata("isFaultingMod") = jsondata("isFaultingMod") Or exceptionData.InnerException.StackTrace.Contains(subModuleClassType)
End If
If (jsondata("isFaultingMod")) Then
problematicModules.Add(modId)
End If
maybeArray = False
Catch ex As Exception
End Try
Try
Dim reg = New Regex(".*workshop\\content\\261550\\([0-9]*)")
Dim matches = reg.Match(Path.GetFullPath(x))
If matches.Success Then
jsondata("WorkshopUrl") = "https://steamcommunity.com/sharedfiles/filedetails/?id=" & matches.Groups()(1).Value
End If
For Each dll In jsondata("Module")("SubModules")("SubModule")
Dim name As String = dll("Name")("@value")
Dim modId = jsondata("Module")("Id")("@value")
'subModuleClassType = subModuleClassType.Substring(0, subModuleClassType.IndexOf("."))
jsondata("isFaultingMod") = exceptionData.StackTrace.Contains(name) Or exceptionData.StackTrace.Contains(modId) And jsondata("isModLoaded")
Dim result = CheckIsAssemblyLoaded(dll("DLLName")("@value"))
If result Then
dll("isLoadedInMemory") = True
Else
dll("isLoadedInMemory") = False
End If
If (jsondata("isFaultingMod")) Then
problematicModules.Add(modId)
End If
Next
Catch ex As Exception
End Try
'widget.Document.InvokeScript("DisplayModulesReport", New String() {JsonConvert.SerializeObject(jsondata)})
analysedModuleJSON.Add(jsondata)
Next
Return JsonConvert.SerializeObject(analysedModuleJSON)
End Function
Public Sub ScanAndLintXmls()
Dim errorDetected = False
Dim modulePath = Path.GetFullPath(BaseDir & "\..\..\Modules\")
Dim files = Directory.GetFiles(modulePath, "*.xml", SearchOption.AllDirectories).ToList()
If IsRunningSteam Then
Dim modulePath2 = Path.GetFullPath(modulePath & "../../../workshop/content/261550")
files.AddRange(Directory.GetFiles(modulePath2, "*.xml", SearchOption.AllDirectories))
End If
For Each x In files
Dim filename = Path.GetFileName(x)
Try
Dim doc As New XmlDocument()
doc.Load(New StreamReader(x))
Debug.Print(x)
widget.Document.InvokeScript("addXMLDiagResult", New String() {filename, x})
Catch ex As XmlException
widget.Document.InvokeScript("addXMLDiagResult", New String() {filename, x, ex.Message})
errorDetected = True
End Try
Application.DoEvents() 'bad, but i dont care, TASK.RUN CompleteWith DOESN'T WORK FOR SOME REASONS
Next
If errorDetected Then widget.Document.InvokeScript("finishSearch", New Object() {errorDetected})
End Sub
Public Function IsCampaignRunning()
Return TaleWorlds.CampaignSystem.Campaign.Current IsNot Nothing
End Function
Public Function ForceSave(filename As String)
'TaleWorlds.Core.MBSaveLoad.SaveAsCurrentGame()
Try
If TaleWorlds.Core.Game.Current Is Nothing OrElse
TaleWorlds.Core.Game.Current.GameType Is Nothing Then
MsgBox("Unable to save as this is not a campaign!", MsgBoxStyle.Critical)
Return False
Else
'https://stackoverflow.com/questions/135443/how-do-i-use-reflection-to-invoke-a-private-method
Dim CampaignSaveMetaData = TaleWorlds.CampaignSystem.Campaign.Current.SaveHandler.GetSaveMetaData()
Dim dynamicMethodGetSaveMetaData = GetType(MBSaveLoad).GetMethod("GetSaveMetaData", BindingFlags.NonPublic Or BindingFlags.Static)
Dim SaveMetaData As MetaData = dynamicMethodGetSaveMetaData.Invoke(Nothing, {CampaignSaveMetaData})
'https://docs.microsoft.com/en-us/dotnet/api/system.reflection.fieldinfo.getvalue?view=net-6.0
'find the save driver
Dim dynamicSaveDriver = GetType(MBSaveLoad).GetField("_saveDriver", BindingFlags.NonPublic Or BindingFlags.Static)
Dim saveDriver As ISaveDriver = CType(dynamicSaveDriver.GetValue(Nothing), ISaveDriver)
Return SaveManager.Save(Game.Current, SaveMetaData, filename, saveDriver).Successful = True
End If
Catch ex As Exception
MsgBox("error while saving! " + vbCrLf + ex.Message, MsgBoxStyle.Critical)
Return False
End Try
End Function
Private Sub widget_Navigating(sender As Object, e As WebBrowserNavigatingEventArgs) Handles widget.Navigating
If e.Url.ToString() = "about:dummy" Then
e.Cancel = True
Exit Sub
End If
Dim isUri = Uri.IsWellFormedUriString(e.Url.ToString(), UriKind.RelativeOrAbsolute)
If (isUri AndAlso (e.Url.ToString().StartsWith("http://") Or e.Url.ToString().StartsWith("https://"))) Then
e.Cancel = True
Try
Process.Start(e.Url.ToString())
Catch ex As Exception
End Try
Exit Sub
Try
Process.Start("firefox.exe", e.Url.ToString())
Catch ex As Exception
End Try
Exit Sub
Try
Process.Start("chrome.exe", e.Url.ToString())
Catch ex As Exception
End Try
End If
End Sub
Dim dnspyInstall As New DnspyInstaller
Public Sub InstallDnspy()
dnspyInstall.Download(
Sub() widget.Invoke(
Sub()
widget.Document.InvokeScript("Callback_InstallDnspyComplete",
New String() {1, Nothing})
End Sub),
Sub(prog As DnspyInstaller.Progress) widget.Invoke(
Sub()
widget.Document.InvokeScript("Callback_InstallDnspyProgress",
New String() {
prog.PercentageDownload,
prog.TotalDownloadedInByte,
prog.SizeInByte})
End Sub),
Sub(ex As Exception) widget.Invoke(
Sub()
widget.Document.InvokeScript("Callback_InstallDnspyComplete",
New String() {0, ex.Message})
End Sub))
End Sub
Public Sub StartDnspyDebugger()
RestartAndAttachDnspy()
End Sub
Public Function IsUnderdebugger()
Return Debugger.IsAttached
End Function
Public Function IsdnSpyAvailable()
Return Util.IsDnspyAvailable()
End Function
Private Sub widget_DocumentCompleted(sender As Object, e As WebBrowserDocumentCompletedEventArgs) Handles widget.DocumentCompleted
'AnalyseModules()
End Sub
Private Sub CopyToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles CopyToolStripMenuItem.Click
widget.Document.ExecCommand("Copy", False, Nothing)
End Sub
Private Sub SelectAllToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles SelectAllToolStripMenuItem.Click
widget.Document.ExecCommand("SelectAll", False, Nothing)
End Sub
Private Sub SaveToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles SaveToolStripMenuItem.Click
widget.Document.InvokeScript("window.print", Nothing)
End Sub
End Class