~ubuntu-branches/ubuntu/oneiric/monodevelop/oneiric

« back to all changes in this revision

Viewing changes to contrib/Sharpen/Sharpen/Extensions.cs

  • Committer: Bazaar Package Importer
  • Author(s): Jo Shields
  • Date: 2011-06-27 17:03:13 UTC
  • mto: (1.8.1 upstream)
  • mto: This revision was merged to the branch mainline in revision 54.
  • Revision ID: james.westby@ubuntu.com-20110627170313-6cvz3s19x6e9hqe9
ImportĀ upstreamĀ versionĀ 2.5.92+dfsg

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
using System.Reflection;
 
2
using System.Net;
 
3
using System.Linq;
 
4
using System.Net.Sockets;
 
5
using System.Threading;
 
6
using System.Collections.Specialized;
 
7
 
 
8
namespace Sharpen
 
9
{
 
10
        using ICSharpCode.SharpZipLib.Zip.Compression;
 
11
        using System;
 
12
        using System.Collections;
 
13
        using System.Collections.Generic;
 
14
        using System.Diagnostics;
 
15
        using System.Globalization;
 
16
        using System.IO;
 
17
        using System.Runtime.CompilerServices;
 
18
        using System.Text;
 
19
        using System.Text.RegularExpressions;
 
20
 
 
21
        internal static class Extensions
 
22
        {
 
23
                private static readonly long EPOCH_TICKS;
 
24
 
 
25
                static Extensions ()
 
26
                {
 
27
                        DateTime time = new DateTime (1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
 
28
                        EPOCH_TICKS = time.Ticks;
 
29
                }
 
30
                
 
31
                public static void Add<T> (this IList<T> list, int index, T item)
 
32
                {
 
33
                        list.Insert (index, item);
 
34
                }
 
35
 
 
36
                public static StringBuilder AppendRange (this StringBuilder sb, string str, int start, int end)
 
37
                {
 
38
                        return sb.Append (str, start, end - start);
 
39
                }
 
40
 
 
41
                public static StringBuilder Delete (this StringBuilder sb, int start, int end)
 
42
                {
 
43
                        return sb.Remove (start, end - start);
 
44
                }
 
45
 
 
46
                public static void SetCharAt (this StringBuilder sb, int index, char c)
 
47
                {
 
48
                        sb[index] = c;
 
49
                }
 
50
 
 
51
                public static int IndexOf (this StringBuilder sb, string str)
 
52
                {
 
53
                        return sb.ToString ().IndexOf (str);
 
54
                }
 
55
 
 
56
                public static Iterable<T> AsIterable<T> (this IEnumerable<T> s)
 
57
                {
 
58
                        return new EnumerableWrapper<T> (s);
 
59
                }
 
60
 
 
61
                public static int BitCount (int val)
 
62
                {
 
63
                        uint num = (uint)val;
 
64
                        int count = 0;
 
65
                        for (int i = 0; i < 32; i++) {
 
66
                                if ((num & 1) != 0) {
 
67
                                        count++;
 
68
                                }
 
69
                                num >>= 1;
 
70
                        }
 
71
                        return count;
 
72
                }
 
73
 
 
74
                public static IndexOutOfRangeException CreateIndexOutOfRangeException (int index)
 
75
                {
 
76
                        return new IndexOutOfRangeException ("Index: " + index);
 
77
                }
 
78
 
 
79
                public static CultureInfo CreateLocale (string language, string country, string variant)
 
80
                {
 
81
                        return CultureInfo.GetCultureInfo ("en-US");
 
82
                }
 
83
 
 
84
                public static string Name (this Encoding e)
 
85
                {
 
86
                        return e.BodyName.ToUpper ();
 
87
                }
 
88
                
 
89
                public static string Decode (this Encoding e, byte[] chars, int start, int len)
 
90
                {
 
91
                        try {
 
92
                                byte[] bom = e.GetPreamble ();
 
93
                                if (bom != null && bom.Length > 0) {
 
94
                                        if (len >= bom.Length) {
 
95
                                                int pos = start;
 
96
                                                bool hasBom = true;
 
97
                                                for (int n=0; n<bom.Length && hasBom; n++) {
 
98
                                                        if (bom[n] != chars [pos++])
 
99
                                                                hasBom = false;
 
100
                                                }
 
101
                                                if (hasBom) {
 
102
                                                        len -= pos - start;
 
103
                                                        start = pos;
 
104
                                                }
 
105
                                        }
 
106
                                }
 
107
                                return e.GetString (chars, start, len);
 
108
                        } catch (DecoderFallbackException) {
 
109
                                throw new CharacterCodingException ();
 
110
                        }
 
111
                }
 
112
                
 
113
                public static string Decode (this Encoding e, ByteBuffer buffer)
 
114
                {
 
115
                        return e.Decode (buffer.Array (), buffer.ArrayOffset () + buffer.Position (), buffer.Limit () - buffer.Position ());
 
116
                }
 
117
 
 
118
                public static ByteBuffer Encode (this Encoding e, CharSequence str)
 
119
                {
 
120
                        return ByteBuffer.Wrap (e.GetBytes (str.ToString ()));
 
121
                }
 
122
 
 
123
                public static ByteBuffer Encode (this Encoding e, string str)
 
124
                {
 
125
                        return ByteBuffer.Wrap (e.GetBytes (str));
 
126
                }
 
127
                
 
128
                public static Encoding GetEncoding (string name)
 
129
                {
 
130
//                      Encoding e = Encoding.GetEncoding (name, EncoderFallback.ExceptionFallback, DecoderFallback.ExceptionFallback);
 
131
                        Encoding e = Encoding.GetEncoding (name.Replace ('_','-'));
 
132
                        if (e is UTF8Encoding)
 
133
                                return new UTF8Encoding (false, true);
 
134
                        return e;
 
135
                }
 
136
                
 
137
                public static ICollection<KeyValuePair<T, U>> EntrySet<T, U> (this IDictionary<T, U> s)
 
138
                {
 
139
                        return s;
 
140
                }
 
141
 
 
142
                public static void Finish (this Inflater i)
 
143
                {
 
144
                }
 
145
                
 
146
                public static bool AddItem<T> (this IList<T> list, T item)
 
147
                {
 
148
                        list.Add (item);
 
149
                        return true;
 
150
                }
 
151
 
 
152
                public static bool AddItem<T> (this ICollection<T> list, T item)
 
153
                {
 
154
                        list.Add (item);
 
155
                        return true;
 
156
                }
 
157
 
 
158
                public static U Get<T, U> (this IDictionary<T, U> d, T key)
 
159
                {
 
160
                        U val;
 
161
                        d.TryGetValue (key, out val);
 
162
                        return val;
 
163
                }
 
164
 
 
165
                public static U Put<T, U> (this IDictionary<T, U> d, T key, U value)
 
166
                {
 
167
                        U old;
 
168
                        d.TryGetValue (key, out old);
 
169
                        d [key] = value;
 
170
                        return old;
 
171
                }
 
172
 
 
173
                public static void PutAll<T, U> (this IDictionary<T, U> d, IDictionary<T, U> values)
 
174
                {
 
175
                        foreach (KeyValuePair<T,U> val in values)
 
176
                                d[val.Key] = val.Value;
 
177
                }
 
178
 
 
179
                public static object Put (this Hashtable d, object key, object value)
 
180
                {
 
181
                        object old = d [key];
 
182
                        d[key] = value;
 
183
                        return old;
 
184
                }
 
185
 
 
186
                public static string Put (this StringDictionary d, string key, string value)
 
187
                {
 
188
                        string old = d [key];
 
189
                        d[key] = value;
 
190
                        return old;
 
191
                }
 
192
 
 
193
                public static CultureInfo GetEnglishCulture ()
 
194
                {
 
195
                        return CultureInfo.GetCultureInfo ("en-US");
 
196
                }
 
197
 
 
198
                public static T GetFirst<T> (this IList<T> list)
 
199
                {
 
200
                        return ((list.Count == 0) ? default(T) : list[0]);
 
201
                }
 
202
 
 
203
                public static CultureInfo GetGermanCulture ()
 
204
                {
 
205
                        CultureInfo r =  CultureInfo.GetCultureInfo ("de-DE");
 
206
                        return r;
 
207
                }
 
208
 
 
209
                public static T GetLast<T> (this IList<T> list)
 
210
                {
 
211
                        return ((list.Count == 0) ? default(T) : list[list.Count - 1]);
 
212
                }
 
213
 
 
214
                public static int GetOffset (this TimeZoneInfo tzone, long date)
 
215
                {
 
216
                        return (int)tzone.GetUtcOffset (MillisToDateTimeOffset (date, 0).DateTime).TotalMilliseconds;
 
217
                }
 
218
 
 
219
                public static InputStream GetResourceAsStream (this Type type, string name)
 
220
                {
 
221
                        string str2 = type.Assembly.GetName ().Name;
 
222
                        string[] textArray1 = new string[] { str2, ".resources.", type.Namespace, ".", name };
 
223
                        string str = string.Concat (textArray1);
 
224
                        Stream manifestResourceStream = type.Assembly.GetManifestResourceStream (str);
 
225
                        if (manifestResourceStream == null) {
 
226
                                return null;
 
227
                        }
 
228
                        return InputStream.Wrap (manifestResourceStream);
 
229
                }
 
230
 
 
231
                public static long GetTime (this DateTime dateTime)
 
232
                {
 
233
                        return new DateTimeOffset (DateTime.SpecifyKind (dateTime, DateTimeKind.Utc), TimeSpan.Zero).ToMillisecondsSinceEpoch ();
 
234
                }
 
235
 
 
236
                public static TimeZoneInfo GetTimeZone (string tzone)
 
237
                {
 
238
                        try {
 
239
                                TimeZoneInfo tz = TimeZoneInfo.FindSystemTimeZoneById (tzone);
 
240
                                return tz;
 
241
                        } catch {
 
242
                                // Not found
 
243
                        }
 
244
                        char[] separator = new char[] { ':' };
 
245
                        string[] strArray = tzone.Substring (4).Split (separator);
 
246
                        int hours, minutes;
 
247
                        if (strArray.Length == 1 && strArray[0].Length > 2) {
 
248
                                hours = int.Parse (strArray[0].Substring (0, 2));
 
249
                                minutes = int.Parse (strArray[0].Substring (2));
 
250
                        } else {
 
251
                                hours = int.Parse (strArray[0]);
 
252
                                minutes = (strArray.Length <= 1) ? 0 : int.Parse (strArray[1]);
 
253
                        }
 
254
                        TimeSpan t = new TimeSpan (0, hours, minutes, 0, 0);
 
255
                        if (tzone[3] == '-')
 
256
                                t = -t;
 
257
                        return TimeZoneInfo.CreateCustomTimeZone (tzone, t, tzone, tzone);
 
258
                }
 
259
 
 
260
                public static void InitCause (this Exception ex, Exception cause)
 
261
                {
 
262
                        Console.WriteLine (cause);
 
263
                }
 
264
                
 
265
                public static bool IsEmpty<T> (this ICollection<T> col)
 
266
                {
 
267
                        return (col.Count == 0);
 
268
                }
 
269
 
 
270
                public static bool IsEmpty<T> (this Stack<T> col)
 
271
                {
 
272
                        return (col.Count == 0);
 
273
                }
 
274
 
 
275
                public static bool IsLower (this char c)
 
276
                {
 
277
                        return char.IsLower (c);
 
278
                }
 
279
 
 
280
                public static bool IsUpper (this char c)
 
281
                {
 
282
                        return char.IsUpper (c);
 
283
                }
 
284
 
 
285
                public static Sharpen.Iterator<T> Iterator<T> (this ICollection<T> col)
 
286
                {
 
287
                        return new EnumeratorWrapper<T> (col, col.GetEnumerator ());
 
288
                }
 
289
 
 
290
                public static Sharpen.Iterator<T> Iterator<T> (this IEnumerable<T> col)
 
291
                {
 
292
                        return new EnumeratorWrapper<T> (col, col.GetEnumerator ());
 
293
                }
 
294
 
 
295
                public static T Last<T> (this ICollection<T> col)
 
296
                {
 
297
                        IList<T> list = col as IList<T>;
 
298
                        if (list != null) {
 
299
                                return list[list.Count - 1];
 
300
                        }
 
301
                        return col.Last<T> ();
 
302
                }
 
303
 
 
304
                public static ListIterator<T> ListIterator<T> (this IList<T> col, int n)
 
305
                {
 
306
                        return new ListIterator<T> (col, n);
 
307
                }
 
308
 
 
309
                public static int LowestOneBit (int val)
 
310
                {
 
311
                        return (((int)1) << NumberOfTrailingZeros (val));
 
312
                }
 
313
 
 
314
                public static bool Matches (this string str, string regex)
 
315
                {
 
316
                        Regex regex2 = new Regex (regex);
 
317
                        return regex2.IsMatch (str);
 
318
                }
 
319
                
 
320
                public static DateTime CreateDate (long milliSecondsSinceEpoch)
 
321
                {
 
322
                        long num = EPOCH_TICKS + (milliSecondsSinceEpoch * 10000);
 
323
                        return new DateTime (num);
 
324
                }
 
325
 
 
326
                public static DateTimeOffset MillisToDateTimeOffset (long milliSecondsSinceEpoch, long offsetMinutes)
 
327
                {
 
328
                        TimeSpan offset = TimeSpan.FromMinutes ((double)offsetMinutes);
 
329
                        long num = EPOCH_TICKS + (milliSecondsSinceEpoch * 10000);
 
330
                        return new DateTimeOffset (num + offset.Ticks, offset);
 
331
                }
 
332
 
 
333
                public static CharsetDecoder NewDecoder (this Encoding enc)
 
334
                {
 
335
                        return new CharsetDecoder (enc);
 
336
                }
 
337
 
 
338
                public static CharsetEncoder NewEncoder (this Encoding enc)
 
339
                {
 
340
                        return new CharsetEncoder (enc);
 
341
                }
 
342
 
 
343
                public static int NumberOfLeadingZeros (int val)
 
344
                {
 
345
                        uint num = (uint)val;
 
346
                        int count = 0;
 
347
                        while ((num & 0x80000000) == 0) {
 
348
                                num = num << 1;
 
349
                                count++;
 
350
                        }
 
351
                        return count;
 
352
                }
 
353
 
 
354
                public static int NumberOfTrailingZeros (int val)
 
355
                {
 
356
                        uint num = (uint)val;
 
357
                        int count = 0;
 
358
                        while ((num & 1) == 0) {
 
359
                                num = num >> 1;
 
360
                                count++;
 
361
                        }
 
362
                        return count;
 
363
                }
 
364
 
 
365
                public static int Read (this StreamReader reader, char[] data)
 
366
                {
 
367
                        return reader.Read (data, 0, data.Length);
 
368
                }
 
369
 
 
370
                public static T Remove<T> (this IList<T> list, T item)
 
371
                {
 
372
                        int index = list.IndexOf (item);
 
373
                        if (index == -1) {
 
374
                                return default(T);
 
375
                        }
 
376
                        T local = list[index];
 
377
                        list.RemoveAt (index);
 
378
                        return local;
 
379
                }
 
380
 
 
381
                public static T Remove<T> (this IList<T> list, int i)
 
382
                {
 
383
                        T old;
 
384
                        try {
 
385
                                old = list[i];
 
386
                                list.RemoveAt (i);
 
387
                        } catch (IndexOutOfRangeException) {
 
388
                                throw new NoSuchElementException ();
 
389
                        }
 
390
                        return old;
 
391
                }
 
392
 
 
393
                public static T RemoveFirst<T> (this IList<T> list)
 
394
                {
 
395
                        return list.Remove<T> (0);
 
396
                }
 
397
 
 
398
                public static string ReplaceAll (this string str, string regex, string replacement)
 
399
                {
 
400
                        Regex rgx = new Regex (regex);
 
401
                        
 
402
                        if (replacement.IndexOfAny (new char[] { '\\','$' }) != -1) {
 
403
                                // Back references not yet supported
 
404
                                StringBuilder sb = new StringBuilder ();
 
405
                                for (int n=0; n<replacement.Length; n++) {
 
406
                                        char c = replacement [n];
 
407
                                        if (c == '$')
 
408
                                                throw new NotSupportedException ("Back references not supported");
 
409
                                        if (c == '\\')
 
410
                                                c = replacement [++n];
 
411
                                        sb.Append (c);
 
412
                                }
 
413
                                replacement = sb.ToString ();
 
414
                        }
 
415
                        
 
416
                        return rgx.Replace (str, replacement);
 
417
                }
 
418
                
 
419
                public static bool RegionMatches (this string str, bool ignoreCase, int toOffset, string other, int ooffset, int len)
 
420
                {
 
421
                        if (toOffset < 0 || ooffset < 0 || toOffset + len > str.Length || ooffset + len > other.Length)
 
422
                                return false;
 
423
                        return string.Compare (str, toOffset, other, ooffset, len) == 0;
 
424
                }
 
425
 
 
426
                public static T Set<T> (this IList<T> list, int index, T item)
 
427
                {
 
428
                        T old = list[index];
 
429
                        list[index] = item;
 
430
                        return old;
 
431
                }
 
432
 
 
433
                public static int Signum (long val)
 
434
                {
 
435
                        if (val < 0) {
 
436
                                return -1;
 
437
                        }
 
438
                        if (val > 0) {
 
439
                                return 1;
 
440
                        }
 
441
                        return 0;
 
442
                }
 
443
                
 
444
                public static void RemoveAll<T,U> (this ICollection<T> col, ICollection<U> items) where U:T
 
445
                {
 
446
                        foreach (var u in items)
 
447
                                col.Remove (u);
 
448
                }
 
449
 
 
450
                public static bool ContainsAll<T,U> (this ICollection<T> col, ICollection<U> items) where U:T
 
451
                {
 
452
                        foreach (var u in items)
 
453
                                if (!col.Any (n => (object.ReferenceEquals (n, u)) || n.Equals (u)))
 
454
                                        return false;
 
455
                        return true;
 
456
                }
 
457
 
 
458
                public static bool Contains<T> (this ICollection<T> col, object item)
 
459
                {
 
460
                        if (!(item is T))
 
461
                                return false;
 
462
                        return col.Any (n => (object.ReferenceEquals (n, item)) || n.Equals (item));
 
463
                }
 
464
 
 
465
                public static void Sort<T> (this IList<T> list)
 
466
                {
 
467
                        List<T> sorted = new List<T> (list);
 
468
                        sorted.Sort ();
 
469
                        for (int i = 0; i < list.Count; i++) {
 
470
                                list[i] = sorted[i];
 
471
                        }
 
472
                }
 
473
 
 
474
                public static void Sort<T> (this IList<T> list, IComparer<T> comparer)
 
475
                {
 
476
                        List<T> sorted = new List<T> (list);
 
477
                        sorted.Sort (comparer);
 
478
                        for (int i = 0; i < list.Count; i++) {
 
479
                                list[i] = sorted[i];
 
480
                        }
 
481
                }
 
482
 
 
483
                public static string[] Split (this string str, string regex)
 
484
                {
 
485
                        return str.Split (regex, 0);
 
486
                }
 
487
                
 
488
                public static string[] Split (this string str, string regex, int limit)
 
489
                {
 
490
                        Regex rgx = new Regex (regex);
 
491
                        List<string> list = new List<string> ();
 
492
                        int startIndex = 0;
 
493
                        if (limit != 1) {
 
494
                                int nm = 1;
 
495
                                foreach (Match match in rgx.Matches (str)) {
 
496
                                        list.Add (str.Substring (startIndex, match.Index - startIndex));
 
497
                                        startIndex = match.Index + match.Length;
 
498
                                        if (limit > 0 && ++nm == limit)
 
499
                                                break;
 
500
                                }
 
501
                        }
 
502
                        if (startIndex < str.Length) {
 
503
                                list.Add (str.Substring (startIndex));
 
504
                        }
 
505
                        if (limit >= 0) {
 
506
                                int count = list.Count - 1;
 
507
                                while ((count >= 0) && (list[count].Length == 0)) {
 
508
                                        count--;
 
509
                                }
 
510
                                list.RemoveRange (count + 1, (list.Count - count) - 1);
 
511
                        }
 
512
                        return list.ToArray ();
 
513
                }
 
514
 
 
515
                public static IList<T> SubList<T> (this IList<T> list, int start, int len)
 
516
                {
 
517
                        List<T> sublist = new List<T> (len);
 
518
                        for (int i = start; i < (start + len); i++) {
 
519
                                sublist.Add (list[i]);
 
520
                        }
 
521
                        return sublist;
 
522
                }
 
523
 
 
524
                public static char[] ToCharArray (this string str)
 
525
                {
 
526
                        char[] destination = new char[str.Length];
 
527
                        str.CopyTo (0, destination, 0, str.Length);
 
528
                        return destination;
 
529
                }
 
530
 
 
531
                public static long ToMillisecondsSinceEpoch (this DateTime dateTime)
 
532
                {
 
533
                        if (dateTime.Kind != DateTimeKind.Utc) {
 
534
                                throw new ArgumentException ("dateTime is expected to be expressed as a UTC DateTime", "dateTime");
 
535
                        }
 
536
                        return new DateTimeOffset (DateTime.SpecifyKind (dateTime, DateTimeKind.Utc), TimeSpan.Zero).ToMillisecondsSinceEpoch ();
 
537
                }
 
538
 
 
539
                public static long ToMillisecondsSinceEpoch (this DateTimeOffset dateTimeOffset)
 
540
                {
 
541
                        return (((dateTimeOffset.Ticks - dateTimeOffset.Offset.Ticks) - EPOCH_TICKS) / TimeSpan.TicksPerMillisecond);
 
542
                }
 
543
 
 
544
                public static string ToOctalString (int val)
 
545
                {
 
546
                        return Convert.ToString (val, 8);
 
547
                }
 
548
 
 
549
                public static string ToString (object val)
 
550
                {
 
551
                        return val.ToString ();
 
552
                }
 
553
 
 
554
                public static string ToString (int val, int bas)
 
555
                {
 
556
                        return Convert.ToString (val, bas);
 
557
                }
 
558
 
 
559
                public static IList<U> UpcastTo<T, U> (this IList<T> s) where T : U
 
560
                {
 
561
                        List<U> list = new List<U> (s.Count);
 
562
                        for (int i = 0; i < s.Count; i++) {
 
563
                                list.Add ((U)s[i]);
 
564
                        }
 
565
                        return list;
 
566
                }
 
567
 
 
568
                public static ICollection<U> UpcastTo<T, U> (this ICollection<T> s) where T : U
 
569
                {
 
570
                        List<U> list = new List<U> (s.Count);
 
571
                        foreach (var v in s) {
 
572
                                list.Add ((U)v);
 
573
                        }
 
574
                        return list;
 
575
                }
 
576
 
 
577
                public static T ValueOf<T> (T val)
 
578
                {
 
579
                        return val;
 
580
                }
 
581
 
 
582
                public static int GetTotalInFixed (this Inflater inf)
 
583
                {
 
584
                        if (inf.TotalIn > 0)
 
585
                                return inf.TotalIn + 4;
 
586
                        else
 
587
                                return 0;
 
588
                }
 
589
                
 
590
                public static int GetRemainingInputFixed (this Inflater inf)
 
591
                {
 
592
                        if (inf.RemainingInput >= 4)
 
593
                                return inf.RemainingInput - 4;
 
594
                        else
 
595
                                return 0;
 
596
                }
 
597
                
 
598
                public static string GetTestName (object obj)
 
599
                {
 
600
                        return GetTestName ();
 
601
                }
 
602
                
 
603
                public static string GetTestName ()
 
604
                {
 
605
                        MethodBase met;
 
606
                        int n = 0;
 
607
                        do {
 
608
                                met = new StackFrame (n).GetMethod ();
 
609
                                if (met != null) {
 
610
                                        foreach (Attribute at in met.GetCustomAttributes (true)) {
 
611
                                                if (at.GetType().FullName == "NUnit.Framework.TestAttribute") {
 
612
                                                        // Convert back to camel case
 
613
                                                        string name = met.Name;
 
614
                                                        if (char.IsUpper (name[0]))
 
615
                                                                name = char.ToLower (name[0]) + name.Substring (1);
 
616
                                                        return name;
 
617
                                                }
 
618
                                        }
 
619
                                }
 
620
                                n++;
 
621
                        } while (met != null);
 
622
                        return "";
 
623
                }
 
624
                
 
625
                public static string GetHostAddress (this IPAddress addr)
 
626
                {
 
627
                        return addr.ToString ();
 
628
                }
 
629
                
 
630
                public static IPAddress GetAddressByName (string name)
 
631
                {
 
632
                        if (name == "0.0.0.0")
 
633
                                return IPAddress.Any;
 
634
                        return Dns.GetHostAddresses (name).FirstOrDefault ();
 
635
                }
 
636
                
 
637
                public static string GetImplementationVersion (this System.Reflection.Assembly asm)
 
638
                {
 
639
                        return asm.GetName ().Version.ToString ();
 
640
                }
 
641
                
 
642
                public static string GetHost (this Uri uri)
 
643
                {
 
644
                        return string.IsNullOrEmpty (uri.Host) ? null : uri.Host;
 
645
                }
 
646
                
 
647
                public static string GetUserInfo (this Uri uri)
 
648
                {
 
649
                        return string.IsNullOrEmpty (uri.UserInfo) ? null : uri.UserInfo;
 
650
                }
 
651
                
 
652
                public static string GetQuery (this Uri uri)
 
653
                {
 
654
                        return string.IsNullOrEmpty (uri.Query) ? null : uri.Query;
 
655
                }
 
656
                
 
657
                public static HttpURLConnection OpenConnection (this Uri uri, Proxy p)
 
658
                {
 
659
                        return new HttpsURLConnection (uri, p);
 
660
                }
 
661
                
 
662
                public static Uri ToURI (this Uri uri)
 
663
                {
 
664
                        return uri;
 
665
                }
 
666
                
 
667
                public static Uri ToURL (this Uri uri)
 
668
                {
 
669
                        return uri;
 
670
                }
 
671
                
 
672
                public static InputStream GetInputStream (this Socket socket)
 
673
                {
 
674
                        return new System.Net.Sockets.NetworkStream (socket);
 
675
                }
 
676
                
 
677
                public static OutputStream GetOutputStream (this Socket socket)
 
678
                {
 
679
                        return new System.Net.Sockets.NetworkStream (socket);
 
680
                }
 
681
                
 
682
                public static int GetLocalPort (this Socket socket)
 
683
                {
 
684
                        return ((IPEndPoint)socket.LocalEndPoint).Port;
 
685
                }
 
686
                
 
687
                public static int GetPort (this Socket socket)
 
688
                {
 
689
                        return ((IPEndPoint)socket.RemoteEndPoint).Port;
 
690
                }
 
691
                
 
692
                public static IPAddress GetInetAddress (this Socket socket)
 
693
                {
 
694
                        return ((IPEndPoint)socket.RemoteEndPoint).Address;
 
695
                }
 
696
                
 
697
                public static void Bind2 (this Socket socket, EndPoint ep)
 
698
                {
 
699
                        if (ep == null)
 
700
                                socket.Bind (new IPEndPoint (IPAddress.Any, 0));
 
701
                        else
 
702
                                socket.Bind (ep);
 
703
                }
 
704
                
 
705
                
 
706
                public static void Connect (this Socket socket, EndPoint ep, int timeout)
 
707
                {
 
708
                        try {
 
709
                                IAsyncResult res = socket.BeginConnect (ep,null, null);
 
710
                                if (!res.AsyncWaitHandle.WaitOne (timeout > 0 ? timeout : Timeout.Infinite, true))
 
711
                                        throw new IOException ("Connection timeout");
 
712
                        } catch (SocketException se) {
 
713
                                throw new IOException (se.Message);
 
714
                        }
 
715
                }
 
716
                
 
717
                public static Socket CreateServerSocket (int port, int backlog, IPAddress addr)
 
718
                {
 
719
                        Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
 
720
                        s.Bind (new IPEndPoint (addr, port));
 
721
                        return s;
 
722
                }
 
723
                
 
724
                public static Socket CreateSocket (string host, int port)
 
725
                {
 
726
                        Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
 
727
                        s.Connect (host, port);
 
728
                        return s;
 
729
                }
 
730
                
 
731
                public static Socket CreateSocket ()
 
732
                {
 
733
                        return new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
 
734
                }
 
735
                
 
736
                public static bool RemoveElement (this ArrayList list, object elem)
 
737
                {
 
738
                        int i = list.IndexOf (elem);
 
739
                        if (i == -1)
 
740
                                return false;
 
741
                        else {
 
742
                                list.RemoveAt (i);
 
743
                                return true;
 
744
                        }
 
745
                }
 
746
                
 
747
                public static System.Threading.Semaphore CreateSemaphore (int count)
 
748
                {
 
749
                        return new System.Threading.Semaphore (count, int.MaxValue);
 
750
                }
 
751
                
 
752
                public static void SetCommand (this ProcessStartInfo si, IList<string> args)
 
753
                {
 
754
                        si.FileName = args[0];
 
755
                        si.Arguments = string.Join (" ", args.Skip (1).Select (a => "\"" + a + "\"").ToArray ());
 
756
                }
 
757
                
 
758
                public static SystemProcess Start (this ProcessStartInfo si)
 
759
                {
 
760
                        si.UseShellExecute = false;
 
761
                        si.RedirectStandardInput = true;
 
762
                        si.RedirectStandardError = true;
 
763
                        si.RedirectStandardOutput = true;
 
764
                        si.CreateNoWindow = true;
 
765
                        return SystemProcess.Start (si);
 
766
                }
 
767
        }
 
768
}