forked from RobertKozak/MonoMobile.Views
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Util.cs
690 lines (548 loc) · 17 KB
/
Util.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
/*
Copyright (c) 2010 Novell Inc.
Author: Miguel de Icaza
Updates: Warren Moxley
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
using System;
using System.IO;
using System.Text;
using System.Threading;
using MonoTouch.UIKit;
using MonoTouch.Foundation;
using System.Collections;
using System.Net;
using System.Net.Sockets;
using System.Security;
using System.Security.Cryptography;
using System.Reflection;
using System.Xml.Serialization;
using System.Text.RegularExpressions;
using MonoTouch;
using System.Diagnostics;
using MonoTouch.CoreLocation;
using System.Globalization;
using System.Drawing;
namespace MonoMobile.Views
{
public static class Util
{
/// <summary>
/// A shortcut to the main application
/// </summary>
public static UIApplication MainApp = UIApplication.SharedApplication;
public readonly static string BaseDir = Path.Combine (Environment.GetFolderPath (Environment.SpecialFolder.Personal), "..");
//
// Since we are a multithreaded application and we could have many
// different outgoing network connections (api.twitter, images,
// searches) we need a centralized API to keep the network visibility
// indicator state
//
static object networkLock = new object ();
static int active;
public static void PushNetworkActive ()
{
lock (networkLock){
active++;
MainApp.NetworkActivityIndicatorVisible = true;
}
}
public static void PopNetworkActive ()
{
lock (networkLock){
active--;
if (active == 0)
MainApp.NetworkActivityIndicatorVisible = false;
}
}
public static DateTime LastUpdate (string key)
{
var s = Defaults.StringForKey (key);
if (s == null)
return DateTime.MinValue;
long ticks;
if (Int64.TryParse (s, out ticks))
return new DateTime (ticks, DateTimeKind.Utc);
else
return DateTime.MinValue;
}
public static bool NeedsUpdate (string key, TimeSpan timeout)
{
return DateTime.UtcNow - LastUpdate (key) > timeout;
}
public static void RecordUpdate (string key)
{
Defaults.SetString (key, DateTime.UtcNow.Ticks.ToString ());
}
public static NSUserDefaults Defaults = NSUserDefaults.StandardUserDefaults;
const long TicksOneDay = 864000000000;
const long TicksOneHour = 36000000000;
const long TicksMinute = 600000000;
public static string StripHtml (string str)
{
if (str.IndexOf ('<') == -1)
return str;
var sb = new StringBuilder ();
for (int i = 0; i < str.Length; i++){
char c = str [i];
if (c != '<'){
sb.Append (c);
continue;
}
for (i++; i < str.Length; i++){
c = str [i];
if (c == '"' || c == '\''){
var last = c;
for (i++; i < str.Length; i++){
c = str [i];
if (c == last)
break;
if (c == '\\')
i++;
}
} else if (c == '>')
break;
}
}
return sb.ToString ();
}
public static string ObscureString (string value)
{
StringBuilder sb = new StringBuilder ();
if (value.Length >= 4) {
sb.Append (char.Parse ("*"), value.Length - 4);
sb.Append (value.Substring (value.Length - 4));
} else {
sb.Append (value);
}
return sb.ToString ();
}
public static void SuccessfulMessage ()
{
UIApplication.SharedApplication.InvokeOnMainThread (delegate {
var msg = new UIAlertView ("Success", "Saved Succcessfully", null, "Ok");
msg.Transform = MonoTouch.CoreGraphics.CGAffineTransform.MakeTranslation (0f, 110f);
msg.Show ();
});
}
public static void SuccessfulMessage (string message)
{
UIApplication.SharedApplication.InvokeOnMainThread (delegate {
var msg = new UIAlertView ("Success", message, null, "Ok");
msg.Transform = MonoTouch.CoreGraphics.CGAffineTransform.MakeTranslation (0f, 110f);
msg.Show ();
});
}
public static void UnsuccessfulMessage ()
{
UIApplication.SharedApplication.InvokeOnMainThread (delegate {
var msg = new UIAlertView ("Error", "Save UnSuccessful, Please try again", null, "Ok");
msg.Transform = MonoTouch.CoreGraphics.CGAffineTransform.MakeTranslation (0f, 110f);
msg.Show ();
});
}
public static void UnsuccessfulMessage (string message)
{
UIApplication.SharedApplication.InvokeOnMainThread (delegate {
var msg = new UIAlertView ("Error", message, null, "Ok");
msg.Transform = MonoTouch.CoreGraphics.CGAffineTransform.MakeTranslation (0f, 110f);
msg.Show ();
});
}
public static void MessageAndRedirect (string message, NSAction action)
{
UIApplication.SharedApplication.InvokeOnMainThread (delegate {
var msg = new UIAlertView ("Info", message, null, "Ok");
msg.Clicked += delegate { UIApplication.SharedApplication.InvokeOnMainThread (action); };
msg.Transform = MonoTouch.CoreGraphics.CGAffineTransform.MakeTranslation (0f, 110f);
msg.Show ();
});
}
static UIActionSheet sheet;
public static UIActionSheet GetSheet (string title)
{
sheet = new UIActionSheet (title);
return sheet;
}
public static bool IsEmail(string inputEmail)
{
if(string.IsNullOrEmpty(inputEmail))
return false;
string strRegex = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
@"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
@".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";
Regex re = new Regex(strRegex);
if (re.IsMatch(inputEmail))
return (true);
else
return (false);
}
}
public static class Device
{
public static string DeviceID ()
{
return UIDevice.CurrentDevice.UniqueIdentifier;
}
public static string IPAddress ()
{
IPHostEntry host;
string localIP = "?";
host = Dns.GetHostEntry (Dns.GetHostName ());
foreach (IPAddress ip in host.AddressList) {
if (ip.AddressFamily == AddressFamily.InterNetwork) {
localIP = ip.ToString ();
}
}
return localIP;
}
public static string Documents = Environment.GetFolderPath (Environment.SpecialFolder.Personal);
}
public static class Encryption
{
public static string EncryptString (string toEncrypt, string bkey)
{
byte[] keyArray;
byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes (toEncrypt);
MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider ();
keyArray = hashmd5.ComputeHash (UTF8Encoding.UTF8.GetBytes (bkey));
TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider ();
tdes.Key = keyArray;
tdes.Mode = CipherMode.ECB;
tdes.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = tdes.CreateEncryptor ();
byte[] resultArray = cTransform.TransformFinalBlock (toEncryptArray, 0, toEncryptArray.Length);
return Convert.ToBase64String (resultArray, 0, resultArray.Length);
}
public static string EncryptString (int value, string bkey)
{
return EncryptString (value.ToString (), bkey);
}
public static string DecryptString (string toDecrypt, string bkey)
{
byte[] keyArray;
byte[] toEncryptArray = Convert.FromBase64String (toDecrypt);
MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider ();
keyArray = hashmd5.ComputeHash (UTF8Encoding.UTF8.GetBytes (bkey));
TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider ();
tdes.Key = keyArray;
tdes.Mode = CipherMode.ECB;
tdes.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = tdes.CreateDecryptor ();
byte[] resultArray = cTransform.TransformFinalBlock (toEncryptArray, 0, toEncryptArray.Length);
return UTF8Encoding.UTF8.GetString (resultArray);
}
}
public class Password
{
public static string GetNewPassword (int passwordLength)
{
return GetNewPassword (passwordLength, "");
}
public static string GetNewPassword (int passwordLength, string exclusions)
{
Password pw = new Password (passwordLength);
pw.Exclusions = exclusions;
return pw.Generate ();
}
public static string GetNewPassword (int passwordLength, bool excludeSpecialCharacters)
{
Password pw = new Password (passwordLength);
pw.ExcludeSymbols = true;
return pw.Generate ();
}
public static bool ValidatePassword (string password)
{
Regex reg = new Regex ("^(?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).{10,16}$");
return reg.IsMatch (password);
}
public Password (int passwordLength)
{
pwdCharArray = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789@#$%^&()-_=+[]{}\\,<.>/?".ToCharArray ();
Minimum = passwordLength;
if (int.MaxValue - 2 >= passwordLength)
Maximum = passwordLength + 2;
ConsecutiveCharacters = false;
RepeatCharacters = true;
ExcludeSymbols = false;
Exclusions = null;
rng = new RNGCryptoServiceProvider ();
}
protected int GetCryptographicRandomNumber (int lowerBound, int upperBound)
{
int urndnum;
byte[] rndnum = new byte[] { 0, 0, 0, 0 };
if (upperBound >= 1) {
if (lowerBound == upperBound - 1) {
return lowerBound;
}
}
int xcludeRndBase = int.MaxValue - (int.MaxValue % System.Convert.ToInt32 (upperBound - lowerBound));
do {
rng.GetBytes (rndnum);
urndnum = System.BitConverter.ToInt32 (rndnum, 0);
} while (urndnum >= xcludeRndBase);
return System.Convert.ToInt32 ((urndnum % (upperBound - lowerBound)) + lowerBound);
}
protected char GetRandomCharacter ()
{
int upperBound = pwdCharArray.GetUpperBound (0);
if (this.ExcludeSymbols) {
upperBound = Password.UBoundDigit;
}
int randomCharPosition = GetCryptographicRandomNumber (pwdCharArray.GetLowerBound (0), upperBound);
if (randomCharPosition < 0) {
randomCharPosition = randomCharPosition * -1;
}
char randomChar = pwdCharArray[randomCharPosition];
return randomChar;
}
protected string Generate ()
{
//// Pick random length between minimum and maximum
int pwdLength = GetCryptographicRandomNumber (this.Minimum, this.Maximum);
StringBuilder pwdBuffer = new StringBuilder ();
pwdBuffer.Capacity = this.Maximum;
//// Generate random characters
char lastCharacter;
char nextCharacter;
//// Initial dummy character flag
lastCharacter = (char)10;
nextCharacter = (char)10;
int i = 0;
for (i = 0; i <= pwdLength; i++) {
nextCharacter = GetRandomCharacter ();
if (!this.ConsecutiveCharacters) {
while (lastCharacter == nextCharacter) {
nextCharacter = GetRandomCharacter ();
}
}
if (!this.RepeatCharacters) {
string temp = pwdBuffer.ToString ();
int duplicateIndex = temp.IndexOf (nextCharacter);
while (-1 != duplicateIndex) {
nextCharacter = GetRandomCharacter ();
duplicateIndex = temp.IndexOf (nextCharacter);
}
}
if (this.Exclusions != null) {
while (-1 != this.Exclusions.IndexOf (nextCharacter)) {
nextCharacter = GetRandomCharacter ();
}
}
pwdBuffer.Append (nextCharacter);
lastCharacter = nextCharacter;
}
if (null != pwdBuffer) {
return pwdBuffer.ToString ();
} else {
return string.Empty;
}
}
public string Exclusions {
get { return this.exclusionSet; }
set { this.exclusionSet = value; }
}
public int Minimum {
get { return this.minSize; }
set {
this.minSize = value;
if (Password.DefaultMinimum > this.minSize) {
this.minSize = Password.DefaultMinimum;
}
}
}
public int Maximum {
get { return this.maxSize; }
set {
this.maxSize = value;
if (this.minSize >= this.maxSize) {
this.maxSize = Password.DefaultMaximum;
}
}
}
public bool ExcludeSymbols {
get { return this.hasSymbols; }
set { this.hasSymbols = value; }
}
public bool RepeatCharacters {
get { return this.hasRepeating; }
set { this.hasRepeating = value; }
}
public bool ConsecutiveCharacters {
get { return this.hasConsecutive; }
set { this.hasConsecutive = value; }
}
private const int DefaultMinimum = 8;
private const int DefaultMaximum = 10;
private const int UBoundDigit = 61;
private RNGCryptoServiceProvider rng;
private int minSize;
private int maxSize;
private bool hasRepeating;
private bool hasConsecutive;
private bool hasSymbols;
private string exclusionSet;
private char[] pwdCharArray;
}
public static class Util1
{
public static DateTime LastUpdate (string key)
{
var s = Defaults.StringForKey (key);
if (s == null)
return DateTime.MinValue;
long ticks;
if (Int64.TryParse (s, out ticks))
return new DateTime (ticks, DateTimeKind.Utc);
else
return DateTime.MinValue;
}
public static bool NeedsUpdate (string key, TimeSpan timeout)
{
return DateTime.UtcNow - LastUpdate (key) > timeout;
}
public static void RecordUpdate (string key)
{
Defaults.SetString (key, DateTime.UtcNow.Ticks.ToString ());
}
public static NSUserDefaults Defaults = NSUserDefaults.StandardUserDefaults;
public static string StripHtml (string str)
{
if (str.IndexOf ('<') == -1)
return str;
var sb = new StringBuilder ();
for (int i = 0; i < str.Length; i++){
char c = str [i];
if (c != '<'){
sb.Append (c);
continue;
}
for (i++; i < str.Length; i++){
c = str [i];
if (c == '"' || c == '\''){
var last = c;
for (i++; i < str.Length; i++){
c = str [i];
if (c == last)
break;
if (c == '\\')
i++;
}
} else if (c == '>')
break;
}
}
return sb.ToString ();
}
public static string CleanName (string name)
{
if (name.Length == 0)
return "";
bool clean = true;
foreach (char c in name){
if (Char.IsLetterOrDigit (c) || c == '_')
continue;
clean = false;
break;
}
if (clean)
return name;
var sb = new StringBuilder ();
foreach (char c in name){
if (!Char.IsLetterOrDigit (c))
break;
sb.Append (c);
}
return sb.ToString ();
}
public static RootElement MakeProgressRoot (string caption)
{
return new RootElement (caption){
new Section (){
new ActivityElement ()
}
};
}
static long lastTime;
[Conditional ("TRACE")]
public static void ReportTime (string s)
{
long now = DateTime.UtcNow.Ticks;
Console.WriteLine ("[{0}] ticks since last invoke: {1}", s, now-lastTime);
lastTime = now;
}
[Conditional ("TRACE")]
public static void Log (string format, params object [] args)
{
Console.WriteLine (String.Format (format, args));
}
public static void LogException (string text, Exception e)
{
using (var s = System.IO.File.AppendText (Util.BaseDir + "/Documents/crash.log")){
var msg = String.Format ("On {0}, message: {1}\nException:\n{2}", DateTime.Now, text, e.ToString());
s.WriteLine (msg);
Console.WriteLine (msg);
}
}
static CultureInfo americanCulture;
public static CultureInfo AmericanCulture {
get {
if (americanCulture == null)
americanCulture = new CultureInfo ("en-US");
return americanCulture;
}
}
#region Location
internal class MyCLLocationManagerDelegate : CLLocationManagerDelegate {
Action<CLLocation> callback;
public MyCLLocationManagerDelegate (Action<CLLocation> callback)
{
this.callback = callback;
}
public override void UpdatedLocation (CLLocationManager manager, CLLocation newLocation, CLLocation oldLocation)
{
manager.StopUpdatingLocation ();
locationManager = null;
callback (newLocation);
}
public override void Failed (CLLocationManager manager, NSError error)
{
callback (null);
}
}
static CLLocationManager locationManager;
static public void RequestLocation (Action<CLLocation> callback)
{
locationManager = new CLLocationManager () {
DesiredAccuracy = CLLocation.AccuracyBest,
Delegate = new MyCLLocationManagerDelegate (callback),
DistanceFilter = 1000f
};
if (CLLocationManager.LocationServicesEnabled)
locationManager.StartUpdatingLocation ();
}
#endregion
}
public static class StringUtil
{
public static string SeperateCamelCase(string value)
{
return Regex.Replace(value, "((?<=[a-z])[A-Z]|[A-Z](?=[a-z]))", " $1").Trim();
}
}
}