-
Notifications
You must be signed in to change notification settings - Fork 0
/
Mths.vb
569 lines (528 loc) · 21.7 KB
/
Mths.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
Imports System.IO
Imports System.Net
Imports System.Net.Security
Imports System.Runtime.Serialization.Json
Imports System.Security.Cryptography.X509Certificates
Imports System.Text
Imports System.Web.Script.Serialization
Imports System.Xml
Module TMP
' +----------------------------------------------------------------------------+
' | |
' | getMode |
' | ======= |
' | |
' | Inputs: VOID |
' | |
' | Returns: VOID |
' | |
' | Notes: Determine if user is expecting XML or JSON |
' +----------------------------------------------------------------------------+
Public Function getMode() As String
If Mode.Equals("XML") Then
Return "XML"
Else
Return "JSON"
End If
End Function
''' <summary>
''' SET XML or JSON
''' </summary>
Dim Mode As String = "JSON"
'+--------------------------------------------------------------------------+
'| |
'| ValidateServerCertificate |
'| ========================= |
'| |
'| Inputs: Object sender |
'| X509Certificate certificate |
'| X509Chain chain |
'| SslPolicyErrors sslPolicyErrors |
'| |
'| Returns: bool |
'| |
'| Notes: Override to allow any host certificate. |
'+--------------------------------------------------------------------------+
Public Function ValidateServerCertificate(ByVal sender As Object, ByVal certificate As X509Certificate, ByVal chain As X509Chain, ByVal sslPolicyErrors As SslPolicyErrors) As Boolean
Return True
End Function
'
' +----------------------------------------------------------------------------+
' | |
' | httpRequest |
' | =========== |
' | |
' | Inputs: string verb |
' | |
' | Returns: VOID |
' | |
' | Notes: Accept 'put', 'post', 'get', or delete from the caller and |
' | perform the appropriate HTTP communications with the SLAPI |
' | server. |
' +----------------------------------------------------------------------------+
'
Public Function httpRequest(ByVal verb As String, ByRef API_URL As String, ByRef API_ENDPOINT As String,
ByRef USERNAME As String, API_KEY As String, ByRef POST_STR As String) As String
httpRequest = ""
Try
Dim url As String = API_URL + "/" + API_ENDPOINT
Dim req As HttpWebRequest = TryCast(WebRequest.Create(New Uri(url)), HttpWebRequest)
Dim authPair As [String] = USERNAME + ":" + API_KEY
authPair = System.Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(authPair))
ServicePointManager.ServerCertificateValidationCallback = New RemoteCertificateValidationCallback(AddressOf ValidateServerCertificate)
req.Headers.Add("Authorization", "Basic " & authPair)
req.Method = verb
If getMode().Equals("XML") Then
req.ContentType = "text/json"
Else
req.ContentType = "text/xml"
End If
If (verb.Equals("post")) OrElse (verb.Equals("put")) Then
Dim content As Byte() = UTF8Encoding.UTF8.GetBytes(POST_STR.Trim())
req.ContentLength = content.Length
Using post As Stream = req.GetRequestStream()
post.Write(content, 0, content.Length)
End Using
End If
Dim result As String = Nothing
Using resp As HttpWebResponse = TryCast(req.GetResponse(), HttpWebResponse)
Dim reader As New StreamReader(resp.GetResponseStream())
result = reader.ReadToEnd()
End Using
If getMode().Equals("XML") Then
Return FormatXml(result)
Else
Return FormatJSON(result)
End If
Catch [error] As WebException
Dim extMsg As String = ""
If [error].Response IsNot Nothing Then
If [error].Response.ContentLength <> 0 Then
Using stream = [error].Response.GetResponseStream()
Using reader = New StreamReader(stream)
extMsg = reader.ReadToEnd()
End Using
End Using
End If
End If
System.Windows.Forms.MessageBox.Show([error].Message.ToString() + vbCrLf + extMsg)
End Try
End Function
'+--------------------------------------------------------------------------+
'| |
'| txtPostvars_Leave |
'| ================= |
'| |
'| Inputs: object sender (ignored) |
'| EventArgs e (ignored) |
'| |
'| Returns: VOID |
'| |
'| Notes: Default event called when text box looses focus. |
'| Whenever the user modifies the XML post vars we will see |
'| if we can't pretty it up. |
'+--------------------------------------------------------------------------+
Private Sub Textbox_Leave(ByVal sender As TextBox, ByVal e As System.EventArgs)
'Handles sender.leave
If sender.TextLength > 0 Then
Dim txt As [String] = ""
If getMode().Equals("XML") Then
txt = FormatXml(sender.Text)
Else
txt = FormatJSON(sender.Text)
End If
sender.Text = txt
End If
End Sub
'+--------------------------------------------------------------------------+
'| |
'| FormatXml |
'| ========= |
'| |
'| Inputs: string unformattedXml |
'| |
'| Returns: string formattedXml |
'| |
'| Notes: Use this method to perform some basic housekeeping on |
'| XML string before plunking them into a text box. It will |
'| make the output easier on the eyes. |
'+--------------------------------------------------------------------------+
Public Function FormatXml(ByVal unformattedXml As String) As String
Dim xd As New XmlDocument()
Try
xd.LoadXml(unformattedXml)
Catch [error] As Exception
System.Windows.Forms.MessageBox.Show([error].Message.ToString())
Return unformattedXml
End Try
Dim sb As New StringBuilder()
Dim sw As New StringWriter(sb)
Dim xtw As XmlTextWriter = Nothing
Try
xtw = New XmlTextWriter(sw)
xtw.Formatting = Formatting.Indented
xd.WriteTo(xtw)
Finally
If xtw IsNot Nothing Then
xtw.Close()
End If
End Try
Return sb.ToString()
End Function
' +---------------------------------------------------------------------------+
' | |
' | FormatJson |
' | ========= |
' | |
' | Inputs: string unformattedJson |
' | |
' | Returns: string formattedJson |
' | |
' | Notes: Use this method to perform some basic housekeeping on |
' | JSON string before plunking them into a text box. It will |
' | make the output easier on the eyes. |
' +---------------------------------------------------------------------------+
Public Function FormatJSON(ByVal unformattedJSON As String) As String
Dim sb As New StringBuilder()
Dim chars As Char() = unformattedJSON.ToCharArray()
Dim len As Integer = chars.Length
Dim indent As Integer = 0
Dim last_char As Char = " "c
Dim new_line As Boolean = True
For i As Integer = 0 To len - 1
If chars(i) = "}"c Then
new_line = True
sb.AppendLine()
ElseIf chars(i) = "{"c Then
If i > 0 Then
sb.AppendLine()
For j As Integer = 0 To indent - 1
sb.Append(" "c)
Next
End If
End If
If last_char = "}"c Then
indent -= 3
End If
If last_char = "{"c Then
new_line = True
sb.AppendLine()
indent += 3
End If
If last_char = ","c Then
sb.AppendLine()
new_line = True
End If
If new_line Then
For j As Integer = 0 To indent - 1
sb.Append(" "c)
Next
End If
sb.Append(chars(i))
new_line = False
last_char = chars(i)
Next
Return sb.ToString()
End Function
End Module
''' <summary>
''' Conversion from JSON
'''
''' ADD: DataTabFromJson
''' AddDataTab(TabDocumentBrowser, TabPages, JsonReader.JsonToDatset(LoadJson()).Tables("Json").DefaultView)
''' </summary>
Public Class JsonReader
Private JSON_TEXT As String = ""
''' <summary>
''' GET FUNCTION
''' </summary>
''' <param name="URL"></param>
''' <returns>String Response</returns>
Public Shared Function GetAPIReq(ByRef URL As String) As String
Dim Request As System.Net.HttpWebRequest = System.Net.HttpWebRequest.Create(URL)
Request.Proxy = Nothing
Request.UserAgent = "SpydazWebAI"
' request.Credentials = New NetworkCredential(Username, Password)
Dim Response As System.Net.HttpWebResponse = Request.GetResponse
Dim ResponseStream As IO.Stream = Response.GetResponseStream
Dim Streamreader As New System.IO.StreamReader(ResponseStream)
Dim Data As String = Streamreader.ReadToEnd
Streamreader.Close()
Return Data
End Function
''' <summary>
''' Get function With Credentials
''' </summary>
''' <param name="URL"></param>
''' <param name="UserName"></param>
''' <param name="Password"></param>
''' <returns>string response</returns>
Public Shared Function GetAPIReq(ByRef URL As String, ByRef UserName As String, ByRef Password As String) As String
Dim Request As System.Net.HttpWebRequest = System.Net.HttpWebRequest.Create(URL)
Request.Proxy = Nothing
Request.UserAgent = "SpydazWebAI"
Request.Credentials = New NetworkCredential(UserName, Password)
Dim Response As System.Net.HttpWebResponse = Request.GetResponse
Dim ResponseStream As IO.Stream = Response.GetResponseStream
Dim Streamreader As New System.IO.StreamReader(ResponseStream)
Dim Data As String = Streamreader.ReadToEnd
Streamreader.Close()
Return Data
End Function
''' <summary>
''' POST FUNCTION With Credentials
''' </summary>
''' <param name="URL"></param>
''' <param name="Data"></param>
''' <param name="Username"></param>
''' <param name="Password"></param>
''' <returns></returns>
Public Shared Function PostAPIReq(ByRef URL As String, ByRef Data As String, ByRef Username As String, ByRef Password As String) As String
Dim Request As System.Net.HttpWebRequest = System.Net.HttpWebRequest.Create(URL)
Dim DataReturned As String
Request.Proxy = Nothing
Request.UserAgent = "SpydazWebAI"
Request.Credentials = New NetworkCredential(Username, Password)
Request.Method = "POST"
Request.ContentType = "text/plain;charset=utf-8"
Dim encoding As New System.Text.UTF8Encoding()
Dim bytes As Byte() = encoding.GetBytes(Data)
Request.ContentLength = bytes.Length
Using requestStream As Stream = Request.GetRequestStream()
' Send the data.
requestStream.Write(bytes, 0, bytes.Length)
Dim Response As System.Net.HttpWebResponse = Request.GetResponse()
Dim ResponseStream As IO.Stream = Response.GetResponseStream
Dim Streamreader As New System.IO.StreamReader(ResponseStream)
DataReturned = Streamreader.ReadToEnd
Streamreader.Close()
End Using
'GetResponse
Return DataReturned
End Function
''' <summary>
''' Post Function
''' </summary>
''' <param name="URL"></param>
''' <param name="Data"></param>
''' <returns></returns>
Public Shared Function PostAPIReq(ByRef URL As String, ByRef Data As String) As String
Dim Request As System.Net.HttpWebRequest = System.Net.HttpWebRequest.Create(URL)
Dim DataReturned As String
Request.Proxy = Nothing
Request.UserAgent = "SpydazWebAI"
Request.Method = "POST"
Request.ContentType = "text/plain;charset=utf-8"
Dim encoding As New System.Text.UTF8Encoding()
Dim bytes As Byte() = encoding.GetBytes(Data)
Request.ContentLength = bytes.Length
Using requestStream As Stream = Request.GetRequestStream()
' Send the data.
requestStream.Write(bytes, 0, bytes.Length)
Dim Response As System.Net.HttpWebResponse = Request.GetResponse()
Dim ResponseStream As IO.Stream = Response.GetResponseStream
Dim Streamreader As New System.IO.StreamReader(ResponseStream)
DataReturned = Streamreader.ReadToEnd
Streamreader.Close()
End Using
'GetResponse
Return DataReturned
End Function
''' <summary>
'''Converts Dataset to Json string
''' </summary>
''' <param name="ds">DataSet</param>
''' <returns>Json Text</returns>
Public Shared Function DataSetToJSON(ByRef ds As DataSet) As String
Dim dict As New Dictionary(Of String, Object)
For Each dt As DataTable In ds.Tables
Dim arr(dt.Rows.Count) As Object
For i As Integer = 0 To dt.Rows.Count - 1
arr(i) = dt.Rows(i).ItemArray
Next
dict.Add(dt.TableName, arr)
Next
Dim json As New JavaScriptSerializer
Return json.Serialize(dict)
End Function
''' <summary>
''' Converts Datatable to Json String
''' </summary>
''' <param name="DT"></param>
''' <returns></returns>
Public Shared Function DataTableToJson(ByRef DT As DataTable) As String
Dim dict As New Dictionary(Of String, Object)
'Get Rows
Dim arr(DT.Rows.Count) As Object
For i As Integer = 0 To DT.Rows.Count - 1
arr(i) = DT.Rows(i).ItemArray
Next
'Add Row to Dictionary
dict.Add(DT.TableName, arr)
'Create JSON
Dim json As New JavaScriptSerializer
Return json.Serialize(dict)
End Function
''' <summary>
''' Converts data held in Datagridview to Datatable
''' </summary>
''' <param name="DGV"></param>
''' <returns></returns>
Public Shared Function DataGridToTable(ByRef DGV As DataGridView) As DataTable
'Creating DataTable.
Dim dt As New DataTable()
' Dim DGV As DataGridView = GetCurrentTabDataGridView(TabDocumentBrowser)
'Adding the Columns.
For Each column As DataGridViewColumn In DGV.Columns
dt.Columns.Add(column.HeaderText, column.ValueType)
Next
'Adding the Rows.
For Each row As DataGridViewRow In DGV.Rows
dt.Rows.Add()
For Each cell As DataGridViewCell In row.Cells
dt.Rows(dt.Rows.Count - 1)(cell.ColumnIndex) = cell.Value.ToString()
Next
Next
Return dt
End Function
''' <summary>
''' Used To Hold Json Properties
''' </summary>
Public Structure JsonColum
''' <summary>
''' FeildName
''' </summary>
Public ColumName As String
''' <summary>
''' Value Held
''' </summary>
Public Data As String
End Structure
''' <summary>
''' deserialize object from Json
''' </summary>
''' <param name="Str">json</param>
''' <returns></returns>
Public Shared Function DeSerializeJson(ByRef Str As String) As Object
Try
Dim Converter As New JavaScriptSerializer
Dim diag As Object = Converter.Deserialize(Of Object)(Str)
Return diag
Catch ex As Exception
Dim Buttons As MessageBoxButtons = MessageBoxButtons.OK
MessageBox.Show(ex.Message, "ERROR", Buttons)
End Try
Return Nothing
End Function
''' <summary>
''' Loads text file Using Open FIle DIalog
''' </summary>
''' <returns>Json string</returns>
Public Shared Function LoadJson() As String
Dim Scriptfile As String = ""
Dim Ofile As New OpenFileDialog
With Ofile
.Filter = "Json files (*.Json)|*.Json"
If (.ShowDialog() = DialogResult.OK) Then
Scriptfile = .FileName
End If
End With
Dim txt As String = ""
If Scriptfile IsNot "" Then
Try
txt = My.Computer.FileSystem.ReadAllText(Scriptfile)
Catch ex As Exception
MsgBox(ex.ToString,, "Error")
End Try
End If
Return txt
End Function
Public Shared Function CreateDataSet(ByRef JSON_TEXT As String) As List(Of JsonReader.JsonColum)
On Error Resume Next
'Deserialize
Dim JsonType As Object = JsonReader.DeSerializeJson(JSON_TEXT)
Dim JsonDataset As New List(Of JsonReader.JsonColum)
For Each item In JsonType
'New Colum (Feild)
Dim Col As New JsonReader.JsonColum
If item.value.GetType().ToString = "System.String" = True Then
'Save colum and data held
Col.ColumName = item.key.ToString
Col.Data = item.value.ToString
'Update Json DataSet
JsonDataset.Add(Col)
Else
'Dim temp As String = item.value.GetType().ToString
If item.value.GetType().ToString = "System.Object[]" Then
'Get Sub Table
'Dim Count As Integer = 1
'For Each SubItem In item.value
' Col.ColumName = item.key & " " & Count
' Col.Data = SubItem.ToString
' ' 'Update Json DataSet
' JsonDataset.Add(Col)
' Count += 1
'Next
Dim Count As Integer = 1
For Each SubItem In item.value
For Each pair In SubItem
Col.ColumName = pair.Key & " " & Count
Col.Data = pair.Value
' 'Update Json DataSet
JsonDataset.Add(Col)
Next
Count += 1
Next
Else
End If
End If
Next
Return JsonDataset
End Function
Public Shared Function JsonToDatset(ByRef JSON_TEXT As String) As DataSet
'Deserialize
Dim JsonType As Object = JsonReader.DeSerializeJson(JSON_TEXT)
'Prepare Datasets
Dim DS As New DataSet
'GET COLUMN NAMES
Dim JsonDataset As List(Of JsonReader.JsonColum) = CreateDataSet(JSON_TEXT)
''Create Table
DS.Tables.Add("Json")
'Create Feilds
For Each item In JsonDataset
'Add ColumName
DS.Tables("Json").Columns.Add(item.ColumName)
Next
'Create Datarow
Dim dsNewRow As DataRow
'Set Row For Json Table
dsNewRow = DS.Tables("Json").NewRow()
'Insert Data from JsonDataSet
For Each item In JsonDataset
'AddColumn
dsNewRow.Item(item.ColumName) = item.Data
Next
'Add Row
DS.Tables("Json").Rows.Add(dsNewRow)
Return DS
End Function
''' <summary>
''' Save Json
''' </summary>
''' <param name="Script"></param>
Public Shared Sub SaveScript(ByRef Script As String)
Try
Dim ScriptFile As String = ""
Dim S As New SaveFileDialog
With S
.Filter = "Json Script File (*.Json)|*.Json"
If (.ShowDialog() = DialogResult.OK) Then
ScriptFile = .FileName
End If
End With
My.Computer.FileSystem.WriteAllText(ScriptFile, Script, False)
Catch ex As Exception
MsgBox(ex.ToString,, "error")
End Try
End Sub
End Class