summaryrefslogtreecommitdiff
path: root/Tizen.Applications.Common/Tizen.Applications/Bundle.cs
blob: eafb3073c12b4949ff2310c469d6d7339c0e22dc (plain)
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
/*
 * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
 *
 * Licensed under the Apache License, Version 2.0 (the License);
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an AS IS BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

using System;
using System.Reflection;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using Tizen.Internals.Errors;

namespace Tizen.Applications
{
    /// <summary>
    /// A Bundle object represents a bundle.
    /// A bundle holds items (key-value pairs) and can be used with other Tizen APIs.
    /// Keys can be used to access values.
    /// This class is accessed by using a constructor to create a new instance of this object.
    /// A bundle instance is not guaranteed to be thread safe if the instance is modified by multiple threads.
    /// </summary>
    public class Bundle : IDisposable
    {
        private SafeBundleHandle _handle;
        private bool _disposed = false;
        private readonly HashSet<string> _keys;

        /// <summary>
        /// The Bundle constructor.
        /// </summary>
        /// <exception cref="System.InvalidOperationException">Thrown when out of memory</exception>
        /// <code>
        /// Tizen.Applications.Bundle bundle = new Tizen.Applications.Bundle();
        /// </code>
        public Bundle()
        {
            _handle = Interop.Bundle.Create();
            BundleErrorFactory.CheckAndThrowException(ErrorFacts.GetLastResult(), _handle);
            _keys = new HashSet<string>();
        }

        /// <summary>
        /// The Bundle constructor.
        /// </summary>
        /// <param name="handle">The SafeBundleHandle instance.</param>
        /// <exception cref="System.ArgumentNullException">Thrown when the handle is null or invalid.</exception>
        public Bundle(SafeBundleHandle handle)
        {
            if (handle == null || handle.IsInvalid)
            {
                throw new ArgumentNullException("handle");
            }

            _handle = Interop.Bundle.DangerousClone(handle.DangerousGetHandle());
            _keys = new HashSet<string>();
            Interop.Bundle.Iterator iterator = (string key, int type, IntPtr keyval, IntPtr userData) =>
            {
                _keys.Add(key);
            };

            Interop.Bundle.Foreach(_handle, iterator, IntPtr.Zero);
            if ((BundleErrorFactory.BundleError)ErrorFacts.GetLastResult() == BundleErrorFactory.BundleError.InvalidParameter)
            {
                throw new ArgumentException("Invalid parameter - cannot create bundle instance");
            }
        }

        private enum BundleTypeProperty
        {
            Array = 0x0100,
            Primitive = 0x0200,
            Measurable = 0x0400
        }

        private enum BundleType
        {
            None = -1,
            Any = 0,
            String = 1 | BundleTypeProperty.Measurable,
            StringArray = String | BundleTypeProperty.Array | BundleTypeProperty.Measurable,
            Byte = 2,
            ByteArray = Byte | BundleTypeProperty.Array
        }

        /// <summary>
        /// The number of items in a Bundle object.
        /// </summary>
        /// <code>
        /// Tizen.Applications.Bundle bundle = new Tizen.Applications.Bundle();
        /// bundle.AddItem("string", "a_string");
        /// Console.WriteLine("There are {0} items in the bundle", bundle.Count);
        /// </code>
        public int Count
        {
            get
            {
                return _keys.Count;
            }
        }

        /// <summary>
        /// The keys in a Bundle object.
        /// </summary>
        /// <code>
        /// Tizen.Applications.Bundle bundle = new Tizen.Applications.Bundle();
        /// bundle.AddItem("string1", "a_string1");
        /// bundle.AddItem("string2", "a_string2");
        /// bundle.AddItem("string3", "a_string3");
        /// Console.WriteLine("The bundle contains the following keys:");
        /// foreach(string key in bundle.Keys)
        /// {
        ///     Console.WriteLine(key);
        /// }
        /// </code>
        public IEnumerable<string> Keys
        {
            get
            {
                return _keys;
            }
        }

        /// <summary>
        /// Gets the SafeBundleHandle instance.
        /// </summary>
        public SafeBundleHandle SafeBundleHandle
        {
            get { return _handle; }
        }

        /// <summary>
        /// Releases any unmanaged resources used by this object.
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        /// <summary>
        /// Checks whether the bundle contains an item with a specified key.
        /// </summary>
        /// <param name="key">The key to check for.</param>
        /// <returns>true if the bundle contains the key. false otherwise.</returns>
        /// <code>
        /// Tizen.Applications.Bundle bundle = new Tizen.Applications.Bundle();
        /// bundle.AddItem("string", "a_string");
        /// if (bundle.Contains("string"))
        /// {
        ///     string aValue = bundle.GetItem<string>("string");
        ///     Console.WriteLine(aValue);
        /// }
        /// </code>
        public bool Contains(string key)
        {
            return _keys.Contains(key);
        }

        /// <summary>
        /// Adds an item into the bundle.
        /// </summary>
        /// <param name="key">The key to identify the item with. If an item with the key already exists in the Bundle, this method will not succeed.</param>
        /// <param name="value">The value of the item.</param>
        /// <exception cref="System.ArgumentException">Thrown when the key already exists or when there is an invalid parameter.</exception>
        /// <exception cref="System.ArgumentNullException">Thrown when value is null.</exception>
        /// <exception cref="System.InvalidOperationException">Thrown when out of memory or when the Bundle instance has been disposed.</exception>
        /// <code>
        /// Tizen.Applications.Bundle bundle = new Tizen.Applications.Bundle();
        /// byte[] byteArray = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
        /// bundle.AddItem("byte_array", byteArray);
        /// </code>
        public void AddItem(string key, byte[] value)
        {
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }
            AddItem(key, value, 0, value.Length);
        }

        /// <summary>
        /// Adds an item into the bundle.
        /// </summary>
        /// <param name="key">The key to identify the item with. If an item with the key already exists in the Bundle, this method will not succeed.</param>
        /// <param name="value">The value of the item.</param>
        /// <param name="offset">The zero-based byte offset in value from which to add to the bundle.</param>
        /// <param name="count">The maximum number of bytes to add to the bundle starting with offset.</param>
        /// <exception cref="System.ArgumentOutOfRangeException">Thrown when the offset or count is out of range.</exception>
        /// <exception cref="System.ArgumentException">Thrown when the key already exists or when there is an invalid parameter.</exception>
        /// <exception cref="System.ArgumentNullException">Thrown when value is null.</exception>
        /// <exception cref="System.InvalidOperationException">Thrown when out of memory or when the Bundle instance has been disposed.</exception>
        /// <code>
        /// Tizen.Applications.Bundle bundle = new Tizen.Applications.Bundle();
        /// byte[] byteArray = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
        /// bundle.AddItem("byte_array", byteArray, 2, 3);
        /// </code>
        public void AddItem(string key, byte[] value, int offset, int count)
        {
            if (!_keys.Contains(key))
            {
                if (value == null)
                {
                    throw new ArgumentNullException("value");
                }
                if (offset < 0)
                {
                    throw new ArgumentOutOfRangeException("offset", offset, "Cannot be less than 0");
                }
                if (offset > value.Length - 1)
                {
                    throw new ArgumentOutOfRangeException("offset", offset, "Greater than last index of array");
                }
                if (count < 1)
                {
                    throw new ArgumentOutOfRangeException("count", count, "Must be at least 1");
                }
                if (offset + count > value.Length)
                {
                    throw new ArgumentException("The count is too large for the specified offset");
                }
                // Code is in Interop file because it is unsafe
                int ret = Interop.Bundle.UnsafeCode.AddItem(_handle, key, value, offset, count);
                BundleErrorFactory.CheckAndThrowException(ret, _handle);
                _keys.Add(key);
            }
            else
            {
                throw new ArgumentException("Key already exists", "key");
            }
        }

        /// <summary>
        /// Adds an item into the bundle.
        /// </summary>
        /// <param name="key">The key to identify the item with. If an item with the key already exists in the Bundle, this method will not succeed.</param>
        /// <param name="value">The value of the item.</param>
        /// <exception cref="System.ArgumentException">Thrown when the key already exists or when there is an invalid parameter.</exception>
        /// <exception cref="System.InvalidOperationException">Thrown when out of memory or when the Bundle instance has been disposed.</exception>
        /// <code>
        /// Tizen.Applications.Bundle bundle = new Tizen.Applications.Bundle();
        /// bundle.AddItem("string", "a_string");
        /// </code>
        public void AddItem(string key, string value)
        {
            if (!_keys.Contains(key))
            {
                int ret = Interop.Bundle.AddString(_handle, key, value);
                BundleErrorFactory.CheckAndThrowException(ret, _handle);
                _keys.Add(key);
            }
            else
            {
                throw new ArgumentException("Key already exists", "key");
            }
        }

        /// <summary>
        /// Adds an item into the bundle.
        /// </summary>
        /// <param name="key">The key to identify the item with. If an item with the key already exists in the Bundle, this method will not succeed.</param>
        /// <param name="value">The value of the item.</param>
        /// <exception cref="System.ArgumentException">Thrown when the key already exists or when there is an invalid parameter.</exception>
        /// <exception cref="System.InvalidOperationException">Thrown when out of memory or when the Bundle instance has been disposed.</exception>
        /// <code>
        /// Tizen.Applications.Bundle bundle = new Tizen.Applications.Bundle();
        /// string[] stringArray = { "a", "b", "c" };
        /// bundle.AddItem("string_array", stringArray);
        /// </code>
        public void AddItem(string key, IEnumerable<string> value)
        {
            if (!_keys.Contains(key))
            {
                string[] valueArray = value.Select(v => v == null ? string.Empty : v).ToArray();
                int ret = Interop.Bundle.AddStringArray(_handle, key, valueArray, valueArray.Count());
                BundleErrorFactory.CheckAndThrowException(ret, _handle);
                _keys.Add(key);
            }
            else
            {
                throw new ArgumentException("Key already exists", "key");
            }
        }

        /// <summary>
        /// Gets the value of a bundle item with a specified key.
        /// </summary>
        /// <param name="key">The key of the bundle item whose value is desired.</param>
        /// <returns>The value of the bundle item.</returns>
        /// <exception cref="System.ArgumentException">Thrown when the key does not exist or when there is an invalid parameter.</exception>
        /// <exception cref="System.InvalidOperationException">Thrown when the Bundle instance has been disposed.</exception>
        /// <code>
        /// Tizen.Applications.Bundle bundle = new Tizen.Applications.Bundle();
        /// bundle.AddItem("string", "a_string");
        /// if (bundle.Contains("string"))
        /// {
        ///     object aValue = bundle.GetItem("string");
        ///     if (bundle.Is<string>("string");)
        ///     {
        ///         string aString = (string)aValue;
        ///         Console.WriteLine(aString);
        ///     }
        /// }
        /// </code>
        public object GetItem(string key)
        {
            if (_keys.Contains(key))
            {
                int type = Interop.Bundle.GetType(_handle, key);
                BundleErrorFactory.CheckAndThrowException(ErrorFacts.GetLastResult(), _handle);
                switch (type)
                {
                    case (int)BundleType.String:
                        // get string
                        IntPtr stringPtr;
                        int retString = Interop.Bundle.GetString(_handle, key, out stringPtr);
                        BundleErrorFactory.CheckAndThrowException(retString, _handle);
                        string stringValue = Marshal.PtrToStringAnsi(stringPtr);
                        if (stringValue == null)
                            return string.Empty;
                        return stringValue;

                    case (int)BundleType.StringArray:
                        // get string array
                        int stringArraySize;
                        IntPtr stringArrayPtr = Interop.Bundle.GetStringArray(_handle, key, out stringArraySize);
                        BundleErrorFactory.CheckAndThrowException(ErrorFacts.GetLastResult(), _handle);
                        string[] stringArray;
                        IntPtrToStringArray(stringArrayPtr, stringArraySize, out stringArray);
                        return stringArray;

                    case (int)BundleType.Byte:
                        // get byte array
                        IntPtr byteArrayPtr;
                        int byteArraySize;
                        int retByte = Interop.Bundle.GetByte(_handle, key, out byteArrayPtr, out byteArraySize);
                        BundleErrorFactory.CheckAndThrowException(retByte, _handle);
                        byte[] byteArray = new byte[byteArraySize];
                        Marshal.Copy(byteArrayPtr, byteArray, 0, byteArraySize);
                        return byteArray;

                    default:
                        throw new ArgumentException("Key does not exist in the bundle", "key");
                }
            }
            else
            {
                throw new ArgumentException("Key does not exist in the bundle (may be null or empty string)", "key");
            }
        }

        /// <summary>
        /// Gets the value of a bundle item with a specified key.
        /// Note that this is a generic method.
        /// </summary>
        /// <typeparam name="T">The generic type to return.</typeparam>
        /// <param name="key">The key of the bundle item whose value is desired.</param>
        /// <returns>The value of the bundle item if it is of the specified generic type.</returns>
        /// <exception cref="System.ArgumentException">Thrown when the key does not exist or when there is an invalid parameter.</exception>
        /// <exception cref="System.InvalidCastException">Thrown when the value of the bundle item cannot be converted to the specified generic type.</exception>
        /// <exception cref="System.InvalidOperationException">Thrown when the Bundle instance has been disposed.</exception>
        /// <code>
        /// Tizen.Applications.Bundle bundle = new Tizen.Applications.Bundle();
        /// string[] stringArray = { "a", "b", "c" };
        /// bundle.AddItem("string_array", stringArray);
        /// if (bundle.Is<string>("string_array"))
        /// {
        ///     Console.WriteLine("It is a string");
        ///     Console.WriteLine(bundle.GetItem<string>("string_array"));
        /// }
        /// else if (bundle.Is<string[]>("string_array"))
        /// {
        ///     Console.WriteLine("It is a string[]");
        ///     string[] anArray = bundle.GetItem<string[]>("string_array");
        ///     foreach (string value in anArray)
        ///     {
        ///         Console.WriteLine(value);
        ///     }
        /// }
        /// </code>
        public T GetItem<T>(string key)
        {
            return (T)GetItem(key);
        }

        /// <summary>
        /// Gets the value of a bundle item with a specified key.
        /// </summary>
        /// <param name="key">The key of the bundle item whose value is desired.</param>
        /// <param name="value">The value of the bundle item. If the key does not exist or the type of this parameter is incorrect, it is the default value for the value parameter type.</param>
        /// <returns>true if an item with the key exists and if the value is the same type as the output value parameter. false otherwise.</returns>
        /// <exception cref="System.InvalidOperationException">Thrown when the Bundle instance has been disposed.</exception>
        /// <code>
        /// Tizen.Applications.Bundle bundle = new Tizen.Applications.Bundle();
        /// byte[] byteArray = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
        /// bundle.AddItem("byte_array", byteArray);
        /// byte[] aByteArray;
        /// if (bundle.TryGetItem("byte_array", out aByteArray))
        /// {
        ///     Console.WriteLine("First item in the byte array: {0}", aByteArray[0]);
        /// }
        /// </code>
        public bool TryGetItem(string key, out byte[] value)
        {
            if (_keys.Contains(key) && Interop.Bundle.GetType(_handle, key) == (int)BundleType.Byte)
            {
                value = GetItem<byte[]>(key);
                return true;
            }
            else
            {
                if (_keys.Contains(key) && ErrorFacts.GetLastResult() == (int)BundleErrorFactory.BundleError.InvalidParameter)
                {
                    throw new InvalidOperationException("Invalid bundle instance (object may have been disposed or released)");
                }
                value = default(byte[]);
                return false;
            }
        }

        /// <summary>
        /// Gets the value of a bundle item with a specified key.
        /// </summary>
        /// <param name="key">The key of the bundle item whose value is desired.</param>
        /// <param name="value">The value of the bundle item. If the key does not exist or the type of this parameter is incorrect, it is the default value for the value parameter type.</param>
        /// <returns>true if an item with the key exists and if the value is the same type as the output value parameter. false otherwise.</returns>
        /// <exception cref="System.InvalidOperationException">Thrown when the Bundle instance has been disposed.</exception>
        /// <code>
        /// Tizen.Applications.Bundle bundle = new Tizen.Applications.Bundle();
        /// bundle.AddItem("string", "a_string");
        /// string aString;
        /// if (bundle.TryGetItem("string", out aString))
        /// {
        ///     Console.WriteLine(aString);
        /// }
        /// </code>
        public bool TryGetItem(string key, out string value)
        {
            if (_keys.Contains(key) && Interop.Bundle.GetType(_handle, key) == (int)BundleType.String)
            {
                value = GetItem<string>(key);
                return true;
            }
            else
            {
                if (_keys.Contains(key) && ErrorFacts.GetLastResult() == (int)BundleErrorFactory.BundleError.InvalidParameter)
                {
                    throw new InvalidOperationException("Invalid bundle instance (object may have been disposed or released)");
                }
                value = default(string);
                return false;
            }
        }

        /// <summary>
        /// Gets the value of a bundle item with a specified key.
        /// </summary>
        /// <param name="key">The key of the bundle item whose value is desired.</param>
        /// <param name="value">The value of the bundle item. If the key does not exist or the type of this parameter is incorrect, it is the default value for the value parameter type.</param>
        /// <returns>true if an item with the key exists and if the value is the same type as the output value parameter. false otherwise.</returns>
        /// <exception cref="System.InvalidOperationException">Thrown when the Bundle instance has been disposed.</exception>
        /// <code>
        /// Tizen.Applications.Bundle bundle = new Tizen.Applications.Bundle();
        /// string[] stringArray = { "a", "b", "c" };
        /// bundle.AddItem("string_array", stringArray);
        /// System.Collections.Generic.IEnumerable<string> aStringEnumerable;
        /// if (bundle.TryGetItem("string", out aStringEnumerable))
        /// {
        ///     foreach (string value in aStringEnumerable)
        ///     {
        ///         Console.WriteLine(value);
        ///     }
        /// }
        /// </code>
        public bool TryGetItem(string key, out IEnumerable<string> value)
        {
            if (_keys.Contains(key) && Interop.Bundle.GetType(_handle, key) == (int)BundleType.StringArray)
            {
                value = GetItem<IEnumerable<string>>(key);
                return true;
            }
            else
            {
                if (_keys.Contains(key) && ErrorFacts.GetLastResult() == (int)BundleErrorFactory.BundleError.InvalidParameter)
                {
                    throw new InvalidOperationException("Invalid bundle instance (object may have been disposed or released)");
                }
                value = default(IEnumerable<string>);
                return false;
            }
        }

        /// <summary>
        /// Checks whether an item is of a specific type.
        /// </summary>
        /// <typeparam name="T">The generic type to check for.</typeparam>
        /// <param name="key">The key whose type wants to be checked.</param>
        /// <returns>true if the item is of the specified type. false otherwise.</returns>
        /// <exception cref="System.ArgumentException">Thrown when the key does not exist or when there is an invalid parameter.</exception>
        /// <exception cref="System.InvalidOperationException">Thrown when the Bundle instance has been disposed.</exception>
        /// <code>
        /// Tizen.Applications.Bundle bundle = new Tizen.Applications.Bundle();
        /// string[] stringArray = { "a", "b", "c" };
        /// bundle.AddItem("string_array", stringArray);
        /// if (bundle.Is<string[]>("string_array"))
        /// {
        ///     Console.WriteLine("It is a string[]");
        ///     string[] anArray = bundle.GetItem<string[]>("string_array");
        ///     foreach (string value in anArray)
        ///     {
        ///         Console.WriteLine(value);
        ///     }
        /// }
        /// </code>
        public bool Is<T>(string key)
        {
            if (_keys.Contains(key))
            {
                int type = Interop.Bundle.GetType(_handle, key);
                switch (type)
                {
                    case (int)BundleType.String:
                        return typeof(string) == typeof(T);

                    case (int)BundleType.StringArray:
                        return typeof(T).GetTypeInfo().IsAssignableFrom(typeof(string[]).GetTypeInfo());

                    case (int)BundleType.Byte:
                        return typeof(byte[]) == typeof(T);

                    default:
                        throw new ArgumentException("Key does not exist in the bundle", "key");
                }
            }
            else
            {
                throw new ArgumentException("Key does not exist in the bundle (may be null or empty string)", "key");
            }
        }

        /// <summary>
        /// Removes a a bundle item with a specific key from a Bundle.
        /// </summary>
        /// <param name="key">The key of the item to delete.</param>
        /// <returns>true if the item is successfully found and removed. false otherwise (even if the item is not found).</returns>
        /// <exception cref="System.ArgumentException">Thrown when there is an invalid parameter.</exception>
        /// <exception cref="System.InvalidOperationException">Thrown when the Bundle instance has been disposed.</exception>
        /// <code>
        /// Tizen.Applications.Bundle bundle = new Tizen.Applications.Bundle();
        /// bundle.AddItem("string", "a_string");
        /// if (bundle.Contains("string"))
        /// {
        ///     if (bundle.RemoveItem("string"))
        ///     {
        ///         Console.WriteLine("Removed");
        ///     }
        /// }
        /// </code>
        public bool RemoveItem(string key)
        {
            if (_keys.Contains(key))
            {
                int ret = Interop.Bundle.RemoveItem(_handle, key);
                if (ret == (int)BundleErrorFactory.BundleError.KeyNotAvailable)
                {
                    return false;
                }
                BundleErrorFactory.CheckAndThrowException(ret, _handle);
                _keys.Remove(key);
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// Releases any unmanaged resources used by this object. Can also dispose any other disposable objects.
        /// </summary>
        /// <param name="disposing">If true, disposes any disposable objects. If false, does not dispose disposable objects.</param>
        protected virtual void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                if (disposing)
                {
                    if (_handle != null && !_handle.IsInvalid)
                        _handle.Dispose();
                }

                _disposed = true;
            }
        }

        /// <summary>
        /// Destructor of the Bundle class.
        /// </summary>
        ~Bundle()
        {
            Dispose(false);
        }

        static private void IntPtrToStringArray(IntPtr unmanagedArray, int size, out string[] managedArray)
        {
            managedArray = new string[size];
            IntPtr[] IntPtrArray = new IntPtr[size];

            Marshal.Copy(unmanagedArray, IntPtrArray, 0, size);

            for (int iterator = 0; iterator < size; iterator++)
            {
                managedArray[iterator] = Marshal.PtrToStringAnsi(IntPtrArray[iterator]);
            }
        }
    }

    internal static class BundleErrorFactory
    {
        internal enum BundleError
        {
            None = ErrorCode.None,
            OutOfMemory = ErrorCode.OutOfMemory,
            InvalidParameter = ErrorCode.InvalidParameter,
            KeyNotAvailable = ErrorCode.KeyNotAvailable,
            KeyExists = -0x01180000 | 0x01
        }

        static internal void CheckAndThrowException(int error, SafeBundleHandle handle)
        {
            if ((BundleError)error == BundleError.None)
            {
                return;
            }
            else if ((BundleError)error == BundleError.OutOfMemory)
            {
                throw new InvalidOperationException("Out of memory");
            }
            else if ((BundleError)error == BundleError.InvalidParameter)
            {
                if (handle.IsInvalid)
                {
                    throw new InvalidOperationException("Invalid bundle instance (object may have been disposed or released)");
                }
                throw new ArgumentException("Invalid parameter");
            }
            else if ((BundleError)error == BundleError.KeyNotAvailable)
            {
                throw new ArgumentException("Key does not exist in the bundle");
            }
            else if ((BundleError)error == BundleError.KeyExists)
            {
                throw new ArgumentException("Key already exists");
            }
        }
    }
}