-
Notifications
You must be signed in to change notification settings - Fork 0
/
Puvox__csharp_ALL.cs
6111 lines (5219 loc) · 183 KB
/
Puvox__csharp_ALL.cs
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
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/preprocessor-directives/preprocessor-if
// preprocessor directives: https://stackoverflow.com/questions/38476796/how-to-set-net-core-in-if-statement-for-compilation
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Media;
using System.Net;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Timers;
using System.Windows;
using System.Windows.Input;
using System.Windows.Forms;
using System.Xml.Linq;
using System.Xml.Serialization;
using Microsoft.CSharp.RuntimeBinder;
using Microsoft.Win32;
using System.Threading.Tasks;
/*
https://ninjatrader.com/support/helpGuides/nt8/?multi-threading.htm
https://stackoverflow.com/questions/16760689/how-many-threads-can-ran-on-a-cpu-at-a-time
using NinjaTrader.Cbi;
using NinjaTrader.Code;
using NinjaTrader.Core;
using NinjaTrader.Data;
using NinjaTrader.Gui;
using NinjaTrader.Gui.Chart;
using NinjaTrader.Gui.NinjaScript;
using NinjaTrader.Gui.Tools;
using NinjaTrader.NinjaScript;
using NinjaTrader.NinjaScript.DrawingTools;
using NinjaTrader.NinjaScript.Indicators;
using NinjaTrader.NinjaScript.Strategies;
using SharpDX;
using SharpDX.Direct2D1;
using SharpDX.DirectWrite;
*/
namespace PuvoxLibrary
{
public partial class Methods
{
#region apps
public static string mainDrive { get { return Path.GetPathRoot(Environment.SystemDirectory); } }
public static string AppNameRegex = "(XYZXYZ)";
public static string developerMachineString = "puvox_development_machine";
private Dictionary<string, string> symbols = new Dictionary<string, string>
{
{ "checkmark", "?" },
{ "checkmark2", "\ud83d\uddf9" }
};
#region Demo(Trial) period checks
// if (demoPeriodGone("demo expired", "2020-05-13")) return;
private bool demoPeriodGone_shown;
private bool demoPeriodGone_disallow;
// "yyyy-MM-dd"
public bool demoPeriodGone(string message, string dateTill)
{
if (demoPeriodGone_shown)
{
return demoPeriodGone_disallow;
}
demoPeriodGone_shown = true;
demoPeriodGone_disallow = false;
try
{
if (dateTill != "" && DateTime.Now > DateTime.ParseExact(dateTill, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture))
{
System.Windows.Forms.MessageBox.Show(message.ToString());
demoPeriodGone_disallow = true;
}
}
catch (Exception)
{
demoPeriodGone_disallow = true;
}
return demoPeriodGone_disallow;
}
public static bool initialized;
public static bool workTillDate(string program_slug, string dateTill)
{
bool result;
try
{
if (dateTill != "" && DateTime.Now > DateTime.ParseExact(dateTill, "yyyy-MM-dd", CultureInfo.InvariantCulture))
{
bool flag = initialized;
//if (mainResponse.ContainsKey("error_message") || mainResponse["error_message"] != "")
{
// m(mainResponse["error_message"]);
return false;
}
}
result = true;
}
catch (Exception)
{
result = false;
}
return result;
}
/*public static bool TimeGone(string Key, int minutes)
{
string registryValue = getRegistryValue("timegone_" + Key);
if (string.IsNullOrEmpty(registryValue) || DateTime.Now > DateTime.Parse(registryValue).AddMinutes((double)minutes))
{
setRegistryValue("timegone_" + Key, DateTime.Now.ToString());
return true;
}
return false;
}
public static bool FirstTimeAction(string regKey)
{
if (getRegistryValue("triggered_" + regKey) != "y")
{
setRegistryValue("triggered_" + regKey, "y");
return true;
}
return false;
}
*/
#endregion
#endregion
#region trading
public static string opposite(string text)
{
if (text == "") return "";
// ===== long / short
else if (text == "LONG") return "SHORT";
else if (text == "SHORT") return "LONG";
else if (text == "Long") return "Short";
else if (text == "Short") return "Long";
else if (text == "long") return "short";
else if (text == "short") return "long";
//
else if (text == "L") return "S";
else if (text == "S") return "L";
else if (text == "l") return "s";
else if (text == "s") return "l";
// ===== buy / sell
else if (text == "BUY") return "SELL";
else if (text == "SELL") return "BUY";
else if (text == "Buy") return "Sell";
else if (text == "Sell") return "Buy";
else if (text == "buy") return "sell";
else if (text == "sell") return "buy";
//
else if (text == "B") return "S";
else if (text == "S") return "B";
else if (text == "b") return "s";
else if (text == "s") return "b";
// ===== above / below
else if (text == "ABOVE") return "BELOW";
else if (text == "BELOW") return "ABOVE";
else if (text == "Above") return "Below";
else if (text == "Below") return "Above";
else if (text == "above") return "below";
else if (text == "below") return "above";
return "";
}
#endregion
public static void createDefaultValues(object obj)
{
foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(obj))
{
DefaultValueAttribute myAttribute = (DefaultValueAttribute)property.Attributes[typeof(DefaultValueAttribute)];
if (myAttribute != null)
{
//property.SetValue(this, myAttribute.Value);
}
}
}
public static int digitsInNumber(object obj)
{
return (int)Math.Ceiling(Math.Log10((double)obj)); //i.e. 12345.123 --->5
}
//https://stackoverflow.com/questions/13477689/find-number-of-decimal-places-in-decimal-value-regardless-of-culture | second variation: https://pastebin.com/KtwzB9Z6
public static int digitsAfterDot(double tickSize)
{
var precision = 0;
while (tickSize * Math.Pow(10, precision) != Math.Round(tickSize * Math.Pow(10, precision)))
precision++;
return precision;
}
public static int digitsAfterDot2(double tickSize)
{
double num = tickSize;
int num2 = 0;
while (num != Math.Round(num, 0)) { num *= 10.0; num2++; }
return num2;
}
//else if (content == 1E-05) result = 5;
//else if (content == 5E-05) result = 5;
//else if (content == 1E-06) result = 6;
//else if (content == 5E-06) result = 6;
//else if (content == 1E-07) result = 7;
//else if (content == 5E-07) result = 7;
#region GlobalVariables
public static Dictionary<string, object> GlobalVariables = new Dictionary<string, object>();
public static object getGlobalVariable(string param)
{
return (GlobalVariables.ContainsKey(param) ? GlobalVariables[param] : null);
}
public static void setGlobalVar(string param, object value)
{
Methods.GlobalVariables[param] = value;
}
#endregion
#region Dictionary
/*
public static Dictionary<string, string> CopyDictionary(Dictionary<string, string> dict)
{
return new Dictionary<string, string>(dict); // //return dict.ToDictionary(entry => entry.Key, entry => entry.Value);
}
public static Dictionary<string, int> CopyDictionary(Dictionary<string, int> dict)
{
return new Dictionary<string, int>(dict); // //return dict.ToDictionary(entry => entry.Key, entry => entry.Value);
}
public static Dictionary<string, double> CopyDictionary(Dictionary<string, double> dict)
{
return new Dictionary<string, double>(dict); // //return dict.ToDictionary(entry => entry.Key, entry => entry.Value);
}
public static Dictionary<string, bool> CopyDictionary(Dictionary<string, bool> dict)
{
return new Dictionary<string, bool>(dict); // //return dict.ToDictionary(entry => entry.Key, entry => entry.Value);
}
*/
private static string objectToXml(object output)
{
string result = "";
try
{
using (StringWriter stringWriter = new StringWriter())
{
XmlSerializer xmlSerializer = new XmlSerializer(output.GetType());
xmlSerializer.Serialize(stringWriter, output);
result = stringWriter.ToString();
}
}
catch (Exception)
{
try
{
result = output.ToString();
}
catch (Exception ex)
{
result = ex.ToString();
}
}
return result;
}
public string objectDump2(object obj)
{
string output = "";
foreach (PropertyDescriptor descriptor in System.ComponentModel.TypeDescriptor.GetProperties(obj))
{
string name = descriptor.Name;
object value = descriptor.GetValue(obj);
output += name + "=" + value;
}
return output;
}
// https://stackoverflow.com/questions/852181/c-printing-all-properties-of-an-object
public static string objectDump3(object obj) { return ObjectDumper.Dump(obj); }
public class ObjectDumper { private int _level; private readonly int _indentSize; private readonly StringBuilder _stringBuilder; private readonly List<int> _hashListOfFoundElements; private ObjectDumper(int indentSize) { _indentSize = indentSize; _stringBuilder = new StringBuilder(); _hashListOfFoundElements = new List<int>(); } public static string Dump(object element) { return Dump(element, 2); } public static string Dump(object element, int indentSize) { var instance = new ObjectDumper(indentSize); return instance.DumpElement(element); } private string DumpElement(object element) { if (element == null || element is ValueType || element is string) { Write(FormatValue(element)); } else { var objectType = element.GetType(); if (!typeof(IEnumerable).IsAssignableFrom(objectType)) { Write("{{{0}}}", objectType.FullName); _hashListOfFoundElements.Add(element.GetHashCode()); _level++; } var enumerableElement = element as IEnumerable; if (enumerableElement != null) { foreach (object item in enumerableElement) { if (item is IEnumerable && !(item is string)) { _level++; DumpElement(item); _level--; } else { if (!AlreadyTouched(item)) DumpElement(item); else Write("{{{0}}} <-- bidirectional reference found", item.GetType().FullName); } } } else { MemberInfo[] members = element.GetType().GetMembers(BindingFlags.Public | BindingFlags.Instance); foreach (var memberInfo in members) { var fieldInfo = memberInfo as FieldInfo; var propertyInfo = memberInfo as PropertyInfo; if (fieldInfo == null && propertyInfo == null) continue; var type = fieldInfo != null ? fieldInfo.FieldType : propertyInfo.PropertyType; object value = fieldInfo != null ? fieldInfo.GetValue(element) : propertyInfo.GetValue(element, null); if (type.IsValueType || type == typeof(string)) { Write("{0}: {1}", memberInfo.Name, FormatValue(value)); } else { var isEnumerable = typeof(IEnumerable).IsAssignableFrom(type); Write("{0}: {1}", memberInfo.Name, isEnumerable ? "..." : "{ }"); var alreadyTouched = !isEnumerable && AlreadyTouched(value); _level++; if (!alreadyTouched) DumpElement(value); else Write("{{{0}}} <-- bidirectional reference found", value.GetType().FullName); _level--; } } } if (!typeof(IEnumerable).IsAssignableFrom(objectType)) { _level--; } } return _stringBuilder.ToString(); } private bool AlreadyTouched(object value) { if (value == null) return false; var hash = value.GetHashCode(); for (var i = 0; i < _hashListOfFoundElements.Count; i++) { if (_hashListOfFoundElements[i] == hash) return true; } return false; } private void Write(string value, params object[] args) { var space = new string(' ', _level * _indentSize); if (args != null) value = string.Format(value, args); _stringBuilder.AppendLine(space + value); } private string FormatValue(object o) { if (o == null) return ("null"); if (o is DateTime) return (((DateTime)o).ToShortDateString()); if (o is string) return string.Format("\"{0}\"", o); if (o is char && (char)o == '\0') return string.Empty; if (o is ValueType) return (o.ToString()); if (o is IEnumerable) return ("..."); return ("{ }"); } }
public static Dictionary<string, string> objToDict(System.Windows.Forms.ComboBox.ObjectCollection objs)
{
Dictionary<string, string> dictionary = new Dictionary<string, string>();
foreach (object obj in objs)
{
KeyValuePair<string, string> keyValuePair = (KeyValuePair<string, string>)obj;
dictionary.Add(keyValuePair.Key, keyValuePair.Value);
}
return dictionary;
}
//new NameValueCollection { {"param1", "<any> kinds & of = ? strings" }, {"param2", "escaping is already handled" } }
public string urlPost(string url, NameValueCollection nv)
{
string result;
try
{
using (WebClient webClient = new WebClient())
{
byte[] bytes = webClient.UploadValues(url, "POST", nv);
// string HtmlResult = wc.UploadString(URI, myParameters);
string @string = Encoding.UTF8.GetString(bytes);
result = @string;
}
}
catch (Exception ex)
{
result = "Error:" + ex.ToString();
}
return result;
}
public static Object fileAccessLocker = new Object();
public static void FileAppend(string file, string text)
{
lock (fileAccessLocker)
{
System.IO.File.AppendAllText(file, text);
}
}
public static string sendMailCached(string username, string password, string toAddress, string subject, string message, string messageId, string cacheFileName)
{
string dir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "/c_sharp_mails/emails_sent/";
if (!System.IO.Directory.Exists(dir)) System.IO.Directory.CreateDirectory(dir);
string filePath = dir + "/" + cacheFileName + "__.txt";
string prefix = Environment.NewLine;
string message_Key = prefix + messageId;
string send = "";
if (!System.IO.File.Exists(filePath))
{
send = "_Trigger_: New file is being created.";
}
else
{
string content = System.IO.File.ReadAllText(filePath);
send = !content.Contains(message_Key) ? "_Trigger_: ID is new." : "Message with this ID was already sent";
}
if (send.Contains("_Trigger_"))
{
System.IO.File.AppendAllText(filePath, message_Key);
return sendYahooMail(username, password, toAddress, subject, message);
}
return send;
}
// RUN in TASK.NEW!!! sendYahooMail("[email protected]", "app-password", "[email protected]", "subj", "txtttt"); https://stackoverflow.com/a/54137454/2377343
public static string sendYahooMail(string username, string password, string toAddress, string subject, string text)
{
using (System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient())
{
client.Host = "smtp.mail.yahoo.com";
client.EnableSsl = true;
client.Port = 587;
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential(username, password);
using (System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage())
{
mail.Sender = new System.Net.Mail.MailAddress(username, "First Name");
mail.From = new System.Net.Mail.MailAddress(username, "Company Name");
mail.To.Add(new System.Net.Mail.MailAddress(toAddress));
mail.Subject = subject;
mail.Body = text;
mail.IsBodyHtml = true;
try
{
client.Send(mail);
return "success";
}
catch (Exception ex)
{
return (ex.Message);
}
}
}
}
public static bool sendMailCom(string username, string password, string toMail, string subject, string message)
{
try
{
using (System.Net.Mail.MailMessage mm = new System.Net.Mail.MailMessage(username, toMail))
{
mm.Subject = subject;
mm.Body = message;
mm.IsBodyHtml = false;
System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient();
smtp.Host = "smtp.mail.com";
smtp.EnableSsl = true;
System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential(username, password);
smtp.UseDefaultCredentials = false;
smtp.Credentials = NetworkCred;
smtp.Port = 587;
smtp.EnableSsl = false;
smtp.Send(mm);
}
return true;
}
catch (Exception e)
{
return false;
}
}
public static string sendNotificationCached(string message, string messageId, string cacheFileName)
{
string dir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "/c_sharp_messages/sent/";
if (!System.IO.Directory.Exists(dir)) System.IO.Directory.CreateDirectory(dir);
string filePath = dir + "/" + cacheFileName + "__.txt";
string prefix = Environment.NewLine;
string message_Key = prefix + messageId;
string send = "";
if (!System.IO.File.Exists(filePath))
{
send = "_Trigger_: New file is being created.";
}
else
{
string content = System.IO.File.ReadAllText(filePath);
send = !content.Contains(message_Key) ? "_Trigger_: ID is new." : "Message with this ID was already sent";
}
if (send.Contains("_Trigger_"))
{
FileAppend(filePath, message_Key);
}
return send;
}
// SendTelegramCached("XXXXXXXXXXXXX", "-100123123123", "Hi messageee", DateTime.Now.ToString(), "filee");
public static string SendTelegramCached(string botApiKey, string toChannel, string message, string messageId, string cacheFileName)
{
var result = sendNotificationCached(message, messageId, cacheFileName);
if (result.Contains("_Trigger_"))
{
string tgMsg = (new Regex("[<>]")).Replace(message, "");
tgMsg = Uri.EscapeDataString( tgMsg );
result = SendTelegram("chat_id=" + toChannel + "&text=" + tgMsg + "&parse_mode=html&disable_web_page_preview=true", botApiKey);
}
return result;
}
public static string SendTelegram(string query, string botApiKey)
{
return urlRead("https://api.telegram.org/bot" + botApiKey + "/sendMessage?" + query); //
}
//Action<object,RoutedEventArgs,string> x= (object sender, RoutedEventArgs e, string index )=>Print("foo") ;
//buttons[key].Click += (sender, EventArgs) => { x(sender, EventArgs, (string) key.ToString()+" Hiii"); };
// https://ninjatrader.com/support/helpGuides/nt8/en-us/?alert_and_debug_concepts.htm
//usage: ExceptionPrint(this, System.Reflection.MethodBase, e)
//Print( "["+GetType().Name+"]["+System.Reflection.MethodBase.GetCurrentMethod().Name+"]-[ERROR at " + mymethodstt.Trace(e) +"] "+ e.ToString());
public static string sanitize_filename(string dirtyString)
{
string invalid = new string(System.IO.Path.GetInvalidFileNameChars()) + new string(System.IO.Path.GetInvalidPathChars());
foreach (char c in invalid) dirtyString = dirtyString.Replace(c.ToString(), "");
return dirtyString;
}
public static string QueryStringFromDictionary(IDictionary<string, object> dict)
{
var list = new List<string>();
foreach (var item in dict)
{
list.Add(item.Key + "=" + item.Value);
}
return string.Join("&", list);
}
public static string UppercaseFirst(string str)
{
var arr = str.ToCharArray(); arr[0] = Char.ToUpperInvariant(arr[0]); return new String(arr);
}
public static List<double> ArrayGetLastItems(List<double> list, int amount)
{
return Enumerable.Reverse(list).Take(amount).Reverse().ToList();
}
public static void ListViewAsListBox(ListView listView)
{
listView.View = View.Details;
listView.HeaderStyle = ColumnHeaderStyle.None;
listView.FullRowSelect = true;
listView.Columns.Add("", -2);
}
public static int getIndexByKey(Dictionary<string, string> dict, string key)
{
List<KeyValuePair<string, string>> list = dict.ToList<KeyValuePair<string, string>>();
return list.FindIndex((KeyValuePair<string, string> x) => x.Key == key);
}
// Order by values.
//var items = from pair in dict orderby pair.Value ascending select pair;
// foreach (KeyValuePair<string, int> pair in items) { Console.WriteLine("{0}: {1}", pair.Key, pair.Value); }
//return items.ToDictionary(x => x, x => x);try
public static Dictionary<string, string> SortDict(Dictionary<string, string> dict)
{
return (Dictionary<string, string>)(from entry in dict orderby entry.Value ascending select entry);
//catch //(Exception e) { return new Dictionary<string, string> { }; }
}
public static Dictionary<string, int> SortDict(Dictionary<string, int> dict)
{
return dict.OrderBy(x => x.Value).ToDictionary(x => x.Key, x => x.Value);
}
public static bool ContainsValue(Dictionary<int, double> myd, int indx) { return myd.ContainsKey(indx) && myd[indx] != double.NaN && HasValue(myd[indx]); }
public static bool ContainsValue(Dictionary<int, bool> myd, int indx) { return myd.ContainsKey(indx); }
public static bool ContainsValue(Dictionary<string, double> myd, string indx) { return myd.ContainsKey(indx) && myd[indx] != double.NaN && HasValue(myd[indx]); }
public static bool ContainsValue(Dictionary<int, object> myd, int indx) { return myd.ContainsKey(indx) && myd[indx] != null; }
public static bool ContainsKey(NameValueCollection collection, string key)
{
return collection.Get(key) != null || collection.AllKeys.Contains(key);
}
//(int)Enum.Parse(typeof(TestAppAreana.MovieList.Movies), KeyVal);
public static bool HasValue(double value)
{
return !double.IsNaN(value) && !double.IsInfinity(value);
}
public static Dictionary<int, double> FindNearestValuesInDict(Dictionary<int, double> MyDict, double Target_value, int how_many_values_to_find)
{
Dictionary<int, double> result;
try
{
bool flag = DictIsAscendingOrDescending(MyDict);
int num = MyDict.Keys.Count<int>();
int num2 = 0;
int num3 = 0;
Dictionary<int, double> dictionary = new Dictionary<int, double>(MyDict);
for (int i = 0; i < num; i++)
{
int index = flag ? i : (num - 1 - i);
int index2 = flag ? (num - 1 - i) : i;
//remove all "grater than" occurences
if (MyDict.Keys.ElementAtOrDefault(index) != 0)
{
int num4 = MyDict.Keys.ElementAt(index);
if (ContainsValue(MyDict, num4) && MyDict[num4] > Target_value)
{
num2++;
if (num2 > how_many_values_to_find)
{
dictionary.Remove(num4);
}
}
}
//remove all "lower than" occurences
if (MyDict.Keys.ElementAtOrDefault(index2) != 0)
{
int num5 = MyDict.Keys.ElementAt(index2);
if (ContainsValue(MyDict, num5) && MyDict[num5] < Target_value)
{
num3++;
if (num3 > how_many_values_to_find)
{
dictionary.Remove(num5);
}
}
}
}
result = dictionary;
}
catch (Exception)
{
result = null;
}
return result;
}
public static bool DictIsAscendingOrDescending(Dictionary<int, double> MyDict)
{
int num = MyDict.Keys.Count<int>();
double num2 = double.NaN;
for (int i = 0; i < num; i++)
{
int num3 = MyDict.Keys.ElementAt(i);
if (ContainsValue(MyDict, num3))
{
if (!double.IsNaN(num2))
{
return MyDict[num3] > num2;
}
num2 = MyDict[num3];
}
}
return false;
}
// https://github.com/jprichardson/FridayThe13th/blob/master/FridayThe13th/JsonParser.cs
// another: https://pastebin.com/raw/hAtAwA40
/*
// referene: System.Web.Extensions.dll , #3.5+
public static string serialize2(object dict)
{
if (dict is Dictionary<string, string>) return new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(((Dictionary<string, string>)dict).ToDictionary((KeyValuePair<string, string> item) => item.Key.ToString(), (KeyValuePair<string, string> item) => item.Value.ToString()));
//else Dictionary<string, object> dict
return new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(((Dictionary<string, object>)dict).ToDictionary((KeyValuePair<string, object> item) => item.Key.ToString(), (KeyValuePair<string, object> item) => item.Value.ToString()));
}
public static class JsonHelper
{
public static string ToJson<T>(T instance)
{
var serializer = new DataContractJsonSerializer(typeof(T));
using (var tempStream = new MemoryStream())
{
serializer.WriteObject(tempStream, instance);
return System.Text.Encoding.Default.GetString(tempStream.ToArray());
}
}
public static T FromJson<T>(string json)
{
var serializer = new DataContractJsonSerializer(typeof(T));
using (var tempStream = new MemoryStream(System.Text.Encoding.Unicode.GetBytes(json)))
{
return (T)serializer.ReadObject(tempStream);
}
}
}
*/
public static string dictToString(object obj)
{
return string.Join("; ", (obj as Dictionary<object, object>).Select(x => x.Key.ToString() + "=" + x.Value.ToString()).ToArray());
}
//return ( NetFrameworkVersion() <= 3.5 ? deserializer_35(str) : deserializer(str) );
public static Dictionary<string, object> deserialize(string str)
{
return deserializer_35(str);
}
public static Dictionary<string, object> deserializer_35(string str)
{
try
{
return HelperLibraries.JsonMaker.DeserializeJson(str);
}
catch (Exception)
{
return null;
}
}
public static Dictionary<string, string> deserializer_35_stringed(string str)
{
try
{
return ConvertToStringDictionary(HelperLibraries.JsonMaker.DeserializeJson(str));
}
catch (Exception)
{
return null;
}
//Dictionary<string, string> new_dict = new Dictionary<string, string>();
//foreach (KeyValuePair<string, object> eachObj in dict)
// new_dict[eachObj.Key] = eachObj.Value.ToString();
//return new_dict;
}
public static Dictionary<string, string> ConvertToStringDictionary(Dictionary<string, object> dicti)
{
Dictionary<string, string> result;
try
{
result = dicti.ToDictionary((KeyValuePair<string, object> item) => item.Key, (KeyValuePair<string, object> item) => (string)item.Value);
}
catch (Exception)
{
result = new Dictionary<string, string>();
}
return result;
}
public static string getDictionaryKeyByValue(Dictionary<string, string> dict, string value)
{
return dict.FirstOrDefault((KeyValuePair<string, string> x) => x.Value == value).Key;
}
#endregion
// This doesn't work in all of my C# 4.0 and 4.5 projects, so making it conditional
#if Use_BLINK
public static System.Drawing.Color color_from_hex(string hex_str)
{
return (System.Drawing.Color)System.Drawing.ColorTranslator.FromHtml(hex_str);
}
//Color.FromArgb(newAlpha, mycolor); Color.FromArgb(A, color.R, color.G, color.B);
public static System.Windows.Forms.Timer BlinkTimer;
public static System.Drawing.Color initialColor;
public static void blink(bool startOrStop, System.Windows.Forms.Control ctrl, System.Drawing.Color c1, System.Drawing.Color c2, int cycleLength_MS, bool BkClr)
{
if (ctrl.InvokeRequired)
{
ctrl.Invoke(new System.Action(() => blink(startOrStop, ctrl, c1, c2, cycleLength_MS, BkClr)));
}
else
{
initialColor = BkClr ? ctrl.BackColor : ctrl.ForeColor;
if (startOrStop)
{
if (BlinkTimer == null)
{
//is called in new thread in eventhandler
var Blink_timer_Tick = new Action<object, EventArgs>((object sender, EventArgs e)=> {
{
if (BkClr)
{
var color = ctrl.BackColor != c1 ? c1 : c2;
for(var i=0; i<10; i++)
{
System.Threading.Thread.Sleep(cycleLength_MS/10);
ctrl.BackColor = System.Drawing.Color.FromArgb((255/10)*i, color.R, color.G, color.B);
}
ctrl.BackColor = color;
}
else
{
var color = ctrl.ForeColor != c1 ? c1 : c2;
ctrl.ForeColor = color;
}
}
});
BlinkTimer = new System.Windows.Forms.Timer();
BlinkTimer.Interval = cycleLength_MS;
BlinkTimer.Enabled = false;
BlinkTimer.Start();
BlinkTimer.Tick += new EventHandler(Blink_timer_Tick);
}
}
else
{
if (BkClr) ctrl.BackColor = initialColor; else ctrl.ForeColor = initialColor;
BlinkTimer.Stop();
//BlinkTimer.Tick -= Blink_timer_Tick;
BlinkTimer = null;
}
}
}
#endif
/*
public static bool blinkActive = false;
public static async void Blink_start(System.Windows.Forms.Control ctrl, Color c1, Color c2, short CycleTime_ms, bool BkClr, bool StartOrStop)
{
try
{
if(StartOrStop)
{
blinkActive = true;
var sw = new Stopwatch(); sw.Start();
short halfCycle = (short)Math.Round(CycleTime_ms * 0.5);
while (blinkActive)
{
await System.Threading.Tasks.Task.Delay(100);
var n = sw.ElapsedMilliseconds % CycleTime_ms;
var per = (double)Math.Abs(n - halfCycle) / halfCycle;
var red = (short)Math.Round((c2.R - c1.R) * per) + c1.R;
var grn = (short)Math.Round((c2.G - c1.G) * per) + c1.G;
var blw = (short)Math.Round((c2.B - c1.B) * per) + c1.B;
var clr = Color.FromArgb(red, grn, blw);
if (BkClr) ctrl.BackColor = clr; else ctrl.ForeColor = clr;
}
ctrl.BackColor = Color.Transparent;
}
else
{
blinkActive = false;
}
}
catch (Exception e)
{
m(e.Message);
return;
}
}
*/
/*
public bool propertyExists(object obj_, string propName){
PropertyInfo propInfo =
obj_.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public)
.FirstOrDefault(x => x.Name.Equals(propName, StringComparison.OrdinalIgnoreCase));
if(propInfo != null)
{
return true;
//propInfo.SetValue(table, DateTime.Now);
}
return false;
}
public static bool propertyExists_static(object obj_, string propName){
PropertyInfo propInfo =
obj_.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public)
.FirstOrDefault(x => x.Name.Equals(propName, StringComparison.OrdinalIgnoreCase));
if(propInfo != null)
{
return true;
//propInfo.SetValue(table, DateTime.Now);
}
return false;
}
public static bool fieldExists(object obj_, string fieldName){
FieldInfo fieldInfo
= obj_.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public) .FirstOrDefault(x => x.Name.Equals(fieldName, StringComparison.OrdinalIgnoreCase));
if(fieldInfo != null)
{
return true;
//propInfo.SetValue(table, DateTime.Now);
}
return false;
}
public bool objectContains(object obj_, string propName){
return objectContains_static( obj_, propName);
}
public static bool objectContains_static(object obj_, string propName){
return ( propertyExists_static( obj_, propName) || fieldExists( obj_, propName) ) ;
}
public dynamic propertyGet( object obj_, string propName, string type){
return propertyGet_static( obj_, propName, type);
}
public static dynamic propertyGet_static( object obj_, string propName){
return propertyGet_static( obj_, propName, "");
}
public static dynamic propertyGet_static( object obj_, string propName, string type){
var propInfo = obj_.GetType().GetProperty(propName);
if(propInfo != null)
{
if( type == "string" ){
return ((string) propInfo.GetValue(obj_, null));
}
else if( type == "bool"){
return ((bool) propInfo.GetValue(obj_, null));
}
else if( type == "dictionary_string_string"){
return ((Dictionary<string,string>) propInfo.GetValue(obj_, null));
}
return (dynamic) propInfo.GetValue(obj_, null) ;
}
var fieldInfo = obj_.GetType().GetField(propName);
if(fieldInfo != null)
{
if( type == "string"){
return ((string) fieldInfo.GetValue(obj_));
}
else if( type == "bool"){
return ((bool) fieldInfo.GetValue(obj_));
}
else if( type == "dictionary_string_string"){
return ((Dictionary<string,string>) fieldInfo.GetValue(obj_));
}
return ((dynamic) propInfo.GetValue(obj_) );
}
return "";
}
public static bool propertySet_static(object obj_, string propName, dynamic value){