-
Notifications
You must be signed in to change notification settings - Fork 0
/
Utils.cs
637 lines (574 loc) · 20.1 KB
/
Utils.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
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Windows.Forms;
using System.Xml.Serialization;
namespace LTC
{
public static class Utils
{
public class TEventArgs<T> : EventArgs
{
public T Arg { get; set; }
public TEventArgs(T arg)
{
Arg = arg;
}
}
public static string GetMyFolder()
{
return GetFolder(Application.ExecutablePath);
//return GetFolder(System.Reflection.Assembly.GetExecutingAssembly().Location);
}
public static string GetMyFolderX()
{
string s1 = GetMyFolder().ToLower();
string s2 = s1.ToLower();
string[] ss = new[] { "\\bin\\debug", "\\bin\\release" };
foreach (string s in ss)
{
if (s2.EndsWith(s))
{
return s1.Substring(0, s1.Length - s.Length);
}
}
return s1;
}
//returns path without "\"
public static string GetFolder(string filename)
{
if (string.IsNullOrEmpty(filename)) return null;
int k = filename.LastIndexOfAny("\\/".ToArray());
if (k > -1) return filename.Substring(0, k);
return filename;
}
public static string GetFileNameFromURL(string url)
{
if (string.IsNullOrEmpty(url)) return null;
int k = url.LastIndexOfAny("\\/".ToArray());
if (k > -1) return url.Substring(k + 1);
return url;
}
public static string RemoveExt(string filename)
{
int i, k = filename.Length - 1;
char c;
for (i = k; i >= 0; i--)
{
c = filename[i];
if (c == '.') return filename.Substring(0, i);
if (c == '\\' || c == '/') return filename;
}
return filename;
}
public static string GetExt(string filename)
{
int i, k = filename.Length - 1;
char c;
for (i = k; i >= 0; i--)
{
c = filename[i];
if (c == '.') return filename.Substring(i + 1, k - i);
if (c == '\\' || c == '/') return "";
}
return "";
}
public static string GetNextFile(string folder, string prefix, string ext)
{
string fnm = folder + "\\" + prefix;
ext = "." + ext;
int i = 1;
string s;
do
{
s = fnm + i + ext;
i++;
}
while (File.Exists(s)) ;
return s;
}
public static long GetFileSize(string filename)
{
try
{
FileInfo fileinfo = new FileInfo(filename);
return fileinfo.Length;
}
catch (Exception)
{
return -1;
}
}
public static bool IN(int val, params int[] list)
{
if (list == null || list.Length == 0) return false;
foreach(int v in list)
if (v == val) return true;
return false;
}
public static bool StringToDate(string value, out DateTime date)
{
return DateTime.TryParseExact(value, "d.M.yyyy", CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out date);
}
public static DateTime? StringToDate(string value)
{
DateTime dt;
if (DateTime.TryParseExact(value, "d.M.yyyy", CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out dt))
{
return dt;
}
return null;
}
public static string DateToString(DateTime date)
{
return date.ToString("dd.MM.yyyy", CultureInfo.InvariantCulture);
}
public static string ReformatDateString(string date)
{
DateTime dt;
if (!StringToDate(date, out dt)) return date;
return DateToString(dt);
}
public static string[] MonthNames = new string[]
{
"janvāris", "februāris", "marts", "aprīlis", "maijs", "jūnijs",
"jūlijs", "augusts", "septembris", "oktobris", "novembris", "decembris"
};
public static string[] MonthNamesAcc = new string[]
{
"janvāri", "februāri", "martu", "aprīli", "maiju", "jūniju",
"jūliju", "augustu", "septembri", "oktobri", "novembri", "decembri"
};
public static int DaysInMonth(this DateTime dt)
{
var dt1 = new DateTime(dt.Year, dt.Month, 1);
return (dt1.AddMonths(1) - dt1).Days;
}
public static DateTime FirstDayOfMonth(this DateTime dt)
{
return new DateTime(dt.Year, dt.Month, 1);
}
public static DateTime LastDayOfMonth(this DateTime dt)
{
return new DateTime(dt.Year, dt.Month, 1).AddMonths(1).AddDays(-1);
}
public static bool IsBetween(this DateTime dt, DateTime dt1, DateTime dt2)
{
return dt >= dt1 && dt <= dt2;
}
public static void AddMonths(ref int yr, ref int mt, int addmt)
{
yr += (addmt - 1) / 12;
mt += (addmt - 1) % 12 + 1;
if (mt < 1)
{
yr--;
mt = 12 - mt;
}
if (mt > 12)
{
yr++;
mt = mt - 12;
}
}
public static bool StringEndsWith(string s, string end)
{
if (string.IsNullOrEmpty(s) || string.IsNullOrEmpty(end)) return false;
int ls = s.Length, lend = end.Length;
if (ls < lend) return false;
return s.Substring(ls - lend) == end;
}
public static string Nz(this string s)
{
return s == null ? "" : s;
}
public static string Zn(this string s)
{
return string.IsNullOrEmpty(s) ? null : s;
}
public static string LeftMax(this string s, int count)
{
if (s == null) return null;
if (s.Length < count) return s;
return s.Substring(0, count);
}
public static int FontSizeX(this Font font)
{
return (int) Math.Round(font.SizeInPoints, 0);
}
public static bool IsTheSameArray(this int[] arr1, int[] arr2)
{
if (arr1 == null || arr2 == null || arr1.Length != arr2.Length) return false;
for (int i = 0; i < arr1.Length; i++)
{
if (arr1[i] != arr2[i]) return false;
}
return true;
}
public static int IndexOf(this string[] arr, string value)
{
if (arr == null || arr.Length == 0) return -1;
for (int i = 0; i < arr.Length; i++)
{
if (arr[i] == value) return i;
}
return -1;
}
public static int IndexOf(this object[] arr, object value)
{
if (arr == null || arr.Length == 0) return -1;
for (int i = 0; i < arr.Length; i++)
{
if (object.ReferenceEquals(arr[i], value)) return i;
}
return -1;
}
public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
{
if (source == null) throw new ArgumentNullException("source");
if (action == null) throw new ArgumentNullException("action");
foreach (T item in source)
action(item);
}
public static IEnumerable<TSource> DistinctByForOrdered<TSource, TKey>(this IEnumerable<TSource> source,
Func<TSource, TSource, bool> fequals)
{
if (source == null) throw new ArgumentNullException("source");
if (fequals == null) throw new ArgumentNullException("fequals");
bool firsrfound = false;
TSource prevobj = default(TSource);
foreach (var element in source)
{
if (!firsrfound)
{
firsrfound = true;
prevobj = element;
yield return element;
continue;
}
if (fequals(element, prevobj)) continue;
yield return element;
}
}
public static IEnumerable<TSource> DistinctByForOrdered<TSource, TKey>(this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector)
{
if (source == null) throw new ArgumentNullException("source");
if (keySelector == null) throw new ArgumentNullException("keySelector");
bool firsrfound = false;
TSource prevobj = default(TSource);
foreach (var element in source)
{
if (!firsrfound)
{
firsrfound = true;
prevobj = element;
yield return element;
continue;
}
if (object.Equals(keySelector(element), keySelector(prevobj))) continue;
yield return element;
}
}
public static IEnumerable<TSource> DistinctForOrdered<TSource>(this IEnumerable<TSource> source)
{
if (source == null) throw new ArgumentNullException("source");
bool firsrfound = false;
TSource prevobj = default(TSource);
foreach (var element in source)
{
if (!firsrfound)
{
firsrfound = true;
prevobj = element;
yield return element;
continue;
}
if (object.Equals(element, prevobj)) continue;
yield return element;
}
}
public static TSource WithMaxOrDefault<TSource>(this IEnumerable<TSource> source,
Func<TSource, IComparable> fgetcomparable, TSource defaultvalue = default(TSource))
{
if (source == null) throw new ArgumentNullException("source");
if (fgetcomparable == null) throw new ArgumentNullException("fgetcomparable");
bool firsrfound = false;
TSource maxobj = defaultvalue;
foreach (var element in source)
{
if (element == null) continue;
if (!firsrfound)
{
firsrfound = true;
maxobj = element;
continue;
}
var comp1 = fgetcomparable(element);
var comp2 = fgetcomparable(maxobj);
if (comp1.CompareTo(comp2) > 0)
maxobj = element;
}
if (firsrfound) return maxobj;
return defaultvalue;
}
//for example: can remove Click events from ToolStripMenuItem (eventname: EventClick)
public static void ClearEventInvocations(object obj, string eventName)
{
PropertyInfo prop = GetProp(obj.GetType(), "Events");
if (prop == null) return;
EventHandlerList el = prop.GetValue(obj, null) as EventHandlerList;
if (el == null) return;
FieldInfo field = GetField(obj.GetType(), eventName);
if (field == null) return;
object o = field.GetValue(obj);
Delegate d = el[o];
//el.RemoveHandler(o, el[o]);
el[o] = null;
}
public static bool HasProperty(object obj, string propName)
{
PropertyInfo prop = GetProp(obj.GetType(), propName);
return prop != null;
}
public static bool SetProperty(object obj, string propName, object value)
{
PropertyInfo prop = GetProp(obj.GetType(), propName);
if (prop == null) return false;
try
{
prop.SetValue(obj, value, null);
}
catch (Exception)
{
return false;
}
return true;
}
public static object GetProperty(object obj, string propName)
{
PropertyInfo prop = GetProp(obj.GetType(), propName);
if (prop == null) return null;
try
{
return prop.GetValue(obj, null);
}
catch (Exception)
{
return null;
}
}
public static bool GetPublicPropertyValue(object obj, string propname, out object value)
{
value = null;
if (obj == null || string.IsNullOrEmpty(propname)) return false;
var prop = TypeDescriptor.GetProperties(obj).Find(propname, false);
//var prop = obj.GetType().GetProperty(propname);
if (prop == null)
{
var prop2 = obj.GetType().GetProperty(propname);
if (prop != null)
{
Debug.Print("GetProperty shit");
throw new Exception("GetProperty shit");
}
return false;
}
try
{
value = prop.GetValue(obj);
return true;
}
catch (Exception)
{
return false;
}
}
public static int FindValue(IList list, string propname, object value)
{
if (list == null || list.Count == 0 || string.IsNullOrEmpty(propname)) return -1;
object o1;
for (int i = 0; i < list.Count; i++)
{
var o2 = list[i];
if (o2 == null) continue;
if (!GetPublicPropertyValue(list[i], propname, out o1)) continue;
if (object.Equals(o1, value))
return i;
}
return -1;
}
public static object CallMethod(object obj, string methodName)
{
MethodInfo method = GetMethod(obj.GetType(), methodName);
if (method == null) return null;
return method.Invoke(obj, null);
}
public static object CallMethod(object obj, string methodName, params object[] args)
{
MethodInfo method = GetMethod(obj.GetType(), methodName);
if (method == null) return null;
return method.Invoke(obj, args);
}
public static EventInfo GetEvent(Type type, string eventName)
{
EventInfo evinfo = null;
while (type != null)
{
evinfo = type.GetEvent(eventName, BindingFlags.Instance | BindingFlags.NonPublic);
if (evinfo != null) break;
type = type.BaseType;
}
return evinfo;
}
public static PropertyInfo GetProp(this Type type, string propName)
{
PropertyInfo prop = null;
while (type != null)
{
prop = type.GetProperty(propName, BindingFlags.Public |
BindingFlags.Instance | BindingFlags.Static |
BindingFlags.NonPublic);
if (prop != null) break;
type = type.BaseType;
}
return prop;
}
public static FieldInfo GetField(Type type, string fieldName)
{
FieldInfo field = null;
while (type != null)
{
field = type.GetField(fieldName, BindingFlags.Public |
BindingFlags.Static | BindingFlags.Instance |
BindingFlags.NonPublic);
if (field != null) break;
type = type.BaseType;
}
return field;
}
public static MethodInfo GetMethod(Type type, string methodName)
{
MethodInfo method = null;
while (type != null)
{
method = type.GetMethod(methodName, BindingFlags.Public |
BindingFlags.Static | BindingFlags.Instance |
BindingFlags.NonPublic);
if (method != null) break;
type = type.BaseType;
}
return method;
}
private static readonly Dictionary<Type, XmlSerializer> _xmlSerializerCache = new Dictionary<Type, XmlSerializer>();
public static XmlSerializer CreateDefaultXmlSerializer(Type type)
{
XmlSerializer serializer;
if (_xmlSerializerCache.TryGetValue(type, out serializer))
{
return serializer;
}
else
{
var importer = new XmlReflectionImporter();
var mapping = importer.ImportTypeMapping(type, null, null);
serializer = new XmlSerializer(mapping);
return _xmlSerializerCache[type] = serializer;
}
}
public static void SetDGVShowCellToolTipsA(Control c, bool b)
{
if (c == null) return;
if (c is DataGridView)
{
(c as DataGridView).ShowCellToolTips = b;
}
if (c is Form || c is Panel || c is SplitContainer)
{
foreach (var c1 in c.Controls)
{
SetDGVShowCellToolTipsA(c1 as Control, b);
}
}
}
public static void SetDGVShowCellToolTips(this Form f, bool b)
{
SetDGVShowCellToolTipsA(f, b);
}
public static string AsString(this object o)
{
if (o == null || o == DBNull.Value) return null;
return (string) o;
}
public static int AsInt(this object o)
{
if (o == null || o == DBNull.Value) return 0;
return (int)o;
}
public static decimal AsDecimal(this object o)
{
if (o == null || o == DBNull.Value) return 0.00M;
return (decimal)o;
}
public static float AsFloat(this object o)
{
if (o == null || o == DBNull.Value) return 0.00f;
return (float)o;
}
public static int DayOfWeekA(this DateTime dt)
{
int wd = (int)dt.DayOfWeek;
if (wd == 0) wd = 7;
return wd;
}
public static Type GetFirstTypeX(Type type)
{
var asm = System.Reflection.Assembly.GetExecutingAssembly();
return asm.GetTypes().Where(t => t.IsSubclassOf(type)).FirstOrDefault();
}
public static bool DGVParseDateCell(DataGridViewCellParsingEventArgs e)
{
if (e.Value == null || e.Value == DBNull.Value) return false;
if (!(e.Value is string)) return false;
string s = (string) e.Value;
if (string.IsNullOrEmpty(s)) return false;
DateTime dt;
if (!Utils.StringToDate(s, out dt)) return false;
e.Value = dt;
e.ParsingApplied = true;
return true;
}
public static Dictionary<int, List<T>> BreakListInGroups<T>(
IEnumerable<T> list, Func<T, int> getkey)
{
var dic = new Dictionary<int, List<T>>();
List<T> list_k;
foreach (var d in list)
{
int key = getkey(d);
if (!dic.TryGetValue(key, out list_k))
{
list_k = new List<T>();
dic[key] = list_k;
}
list_k.Add(d);
}
return dic;
}
public static object GetDefaultValue(this Type t)
{
if (t.IsValueType && Nullable.GetUnderlyingType(t) == null)
return Activator.CreateInstance(t);
else
return null;
}
}
}