private void allocateMemoryWithLoopSize(UInt32 loopSize, UInt32 blockSize)
 {
     for (UInt32 i = 0; i < loopSize; i++) {
         NSData data = new NSMutableData(blockSize);
         NSArray array = new NSMutableArray((Int32)blockSize);
         NSSet set = new NSMutableSet((Int32)blockSize);
         this.dataProp = data;
         this.arrayProp = array;
         this.setProp = set;
     }
 }
		/// <summary>
		/// Gets the categories to be registered for push notifications.
		/// </summary>
		/// <returns></returns>
		public async Task<NSSet> GetCategoriesAsync()
		{
			var set = new NSMutableSet();

			var config = await GetConfigurationAsync();
			
			// The configuration of the categories has to be on the main thread so we'll need to wait for
			// this to finish

			var waitHandle = new ManualResetEvent(false);
			
			UIApplication.SharedApplication.InvokeOnMainThread(() =>
			{
				if (config != null)
				{
					foreach (var buttonSet in config)
					{
						foreach (var suffix in _suffixes)
						{
							var category = new UIMutableUserNotificationCategory
							{
								Identifier = buttonSet.ButtonSetId + suffix
							};

							var currentSuffix = suffix;
							var index = -1;
							var actions = buttonSet.ButtonValues.Select(v =>
								new UIMutableUserNotificationAction
								{
									ActivationMode = GetActivationMode(currentSuffix[index += 2]),
									Identifier = v,
									Title = v,
									Destructive = false,
									AuthenticationRequired = false
								})
								.Cast<UIUserNotificationAction>()
								.ToArray();
							category.SetActions(actions, UIUserNotificationActionContext.Default);
							category.SetActions(actions, UIUserNotificationActionContext.Minimal);

							set.Add(category);
						}
					}
				}

				waitHandle.Set();
			});

			// this will block the background thread, but only for a short period
			waitHandle.WaitOne();

			return set;
		}
Пример #3
0
        public void OperatorAddTest3()
        {
            var str1 = "1";
            var str2 = "2";
            var str3 = "3";

            using (var set1 = new NSOrderedSet(str1))
                using (var set2 = new NSMutableSet(str2, str3))
                    using (var result = set1 + set2) {
                        Assert.AreEqual(3, result.Count, "AddTest Count");
                        Assert.IsTrue(result.Contains(str1), "AddTest Contains 1");
                        Assert.IsTrue(result.Contains(str2), "AddTest Contains 2");
                        Assert.IsTrue(result.Contains(str3), "AddTest Contains 3");
                    }
        }
        public void OperatorAddTest()
        {
            var v1 = (NSString)"1";
            var v2 = (NSString)"2";

            using (var first = new NSMutableSet <NSString> (v1)) {
                using (var second = new NSMutableSet <NSString> (v2)) {
                    using (var third = first + second) {
                        Assert.AreEqual(2, third.Count, "+ Count");
                        Assert.IsTrue(third.Contains(v1), "+ 1");
                        Assert.IsTrue(third.Contains(v2), "+ 2");
                    }
                }
            }
        }
Пример #5
0
        private void RegisterHandoff(SpeakerModel speakerModel)
        {
            var userInfo = new NSMutableDictionary
            {
                {
                    new NSString("Url"),
                    new NSString(
                        speakerModel.GetAppLink().AppLinkUri.AbsoluteUri)
                }
            };

            var keywords = new NSMutableSet <NSString>(
                new NSString(speakerModel.FullName));

            if (speakerModel.Talks != null)
            {
                foreach (var session in speakerModel.Talks)
                {
                    keywords.Add(new NSString(session.Title));
                }
            }

            this.activity.Keywords   = new NSSet <NSString>(keywords);
            this.activity.WebPageUrl = NSUrl.FromString(speakerModel.GetWebUrl());

            this.activity.EligibleForHandoff = false;

            this.activity.AddUserInfoEntries(userInfo);

            // Provide context
            var attributes =
                new CSSearchableItemAttributeSet($"{AboutThisApp.PackageName}.speaker")
            {
                Keywords =
                    keywords.ToArray()
                    .Select(
                        k =>
                        k.ToString())
                    .ToArray(),
                Url = NSUrl.FromString(
                    speakerModel
                    .GetAppLink()
                    .AppLinkUri
                    .AbsoluteUri)
            };

            this.activity.ContentAttributeSet = attributes;
        }
		public override void LoadView ()
		{
			base.LoadView ();

			ActiveRequests = new NSMutableSet ();
			HighQualityImageCache = new NIImageMemoryCache ();
			ThumbnailImageCache = new NIImageMemoryCache ();

			HighQualityImageCache.MaxNumberOfPixels = 1024 * 1024 * 10;
			ThumbnailImageCache.MaxNumberOfPixels = 1024 * 1024 * 3;

			Queue = new NSOperationQueue ();
			Queue.MaxConcurrentOperationCount = 5;

			PhotoAlbumView.LoadingImage = UIImage.FromFile ("NimbusPhotos.bundle/gfx/default.png");
		}
		public async Task<NSSet> GetRegisteredCategoriesAsync()
		{
			var categories = new NSMutableSet();
			List<IApnsCategoryProvider> providers;
			lock (_lock)
			{
				providers = _providers.ToList();
			}

			foreach (var provider in providers.ToList())
			{
				categories.AddObjects((await provider.GetCategoriesAsync()).ToArray());
			}

			return categories;
		}
Пример #8
0
        public void OperatorSubtractTest()
        {
            var str1 = "1";
            var str2 = "2";
            var str3 = "3";
            var str4 = "4";

            var first  = new NSMutableSet(str1, str2, str3, str4);
            var second = new NSMutableSet(str3, str4);
            var third  = first - second;

            Assert.AreEqual((nuint)2, third.Count, "OperatorSubtract Count");
            Assert.IsTrue(third.Contains(str1), "OperatorSubtract 1");
            Assert.IsTrue(third.Contains(str2), "OperatorSubtract 2");
            Assert.IsFalse(third.Contains(str3), "OperatorSubtract 3");
            Assert.IsFalse(third.Contains(str4), "OperatorSubtract 4");
        }
Пример #9
0
        NSSet <NSString> SelectableLayersFromSources(string [] layersId)
        {
            if (layersId == null)
            {
                return(null);
            }

            NSMutableSet <NSString> output = new NSMutableSet <NSString>();

            foreach (string layerId in layersId)
            {
                var acceptedId = layerId.Replace("_", "-");
                output.Add((NSString)acceptedId);
                output.Add((NSString)(acceptedId + " (1)"));
            }
            return(output.Copy() as NSSet <NSString>);
        }
Пример #10
0
        public void RemoveTest()
        {
            var v1 = (NSString)"1";
            var v2 = (NSString)"2";

            using (var st = new NSMutableSet <NSString> (v1)) {
                Assert.Throws <ArgumentNullException> (() => st.Remove((NSString)null), "Remove ANE 1");

                st.Remove(v2);
                Assert.AreEqual((nuint)1, st.Count, "Remove 1 Count");
                Assert.IsTrue(st.Contains(v1), "Remove 1 Contains");
                Assert.AreSame(v1, st.AnyObject, "Remove 1 AnyObject");

                st.Remove(v1);
                Assert.AreEqual((nuint)0, st.Count, "Remove 2 Count");
            }
        }
        public static void RegisterNotifications()
        {
            var action = new UIMutableUserNotificationAction
                {
                    Title = "Launch",
                    Identifier = "trade",
                    ActivationMode = UIUserNotificationActivationMode.Foreground,
                    AuthenticationRequired = false
                };

            var actionCategory = new UIMutableUserNotificationCategory { Identifier = "trade" };

            var categories = new NSMutableSet();
            categories.Add(actionCategory);

            actionCategory.SetActions(new UIUserNotificationAction[] { action }, UIUserNotificationActionContext.Default);

            var settings = UIUserNotificationSettings.GetSettingsForTypes(UIUserNotificationType.Alert | UIUserNotificationType.Sound, categories);
            UIApplication.SharedApplication.RegisterUserNotificationSettings(settings);
        }
Пример #12
0
        void RegisterHandoff(Session session)
        {
            var userInfo = new NSMutableDictionary();
            var uri      = new NSString(session.GetAppLink().AppLinkUri.AbsoluteUri);

            userInfo.Add(new NSString("link"), uri);
            userInfo.Add(new NSString("Url"), uri);

            var keywords = new NSMutableSet <NSString>(new NSString(session.Title));

            foreach (var speaker in session.Speakers)
            {
                keywords.Add(new NSString(speaker.FullName));
            }
            foreach (var category in session.Categories)
            {
                keywords.Add(new NSString(category.Name));
            }

            _activity.Keywords   = new NSSet <NSString>(keywords);
            _activity.WebPageUrl = NSUrl.FromString(session.GetWebUrl());
            _activity.UserInfo   = userInfo;

            // Provide context
            var attributes = new CSSearchableItemAttributeSet($"{AboutThisApp.PackageName}.session");

            attributes.Keywords = keywords.ToArray().Select(k => k.ToString()).ToArray();
            attributes.Url      = NSUrl.FromString(session.GetAppLink().AppLinkUri.AbsoluteUri);
            if (session.StartTime.HasValue && session.StartTime > DateTime.MinValue)
            {
                attributes.DueDate   = session.StartTime.Value.ToNSDate();
                attributes.StartDate = session.StartTime.Value.ToNSDate();
                attributes.EndDate   = session.EndTime.Value.ToNSDate();

                attributes.ImportantDates = new[] { attributes.StartDate, attributes.EndDate };
            }
            _activity.ContentAttributeSet = attributes;
            _activity.EligibleForHandoff  = true;
        }
Пример #13
0
        void RegisterHandoff(MiniHack entity)
        {
            var userInfo = new NSMutableDictionary();
            var uri      = new NSString(entity.GetAppLink().AppLinkUri.AbsoluteUri);

            userInfo.Add(new NSString("link"), uri);
            userInfo.Add(new NSString("Url"), uri);

            var keywords = new NSMutableSet <NSString>(new NSString(entity.Name));

            _activity.Keywords = new NSSet <NSString>(keywords);
            _activity.UserInfo = userInfo;

            // Provide context
            var attributes = new CSSearchableItemAttributeSet($"{AboutThisApp.PackageName}.minihack");

            attributes.Keywords = keywords.ToArray().Select(k => k.ToString()).ToArray();
            attributes.Url      = NSUrl.FromString(entity.GetAppLink().AppLinkUri.AbsoluteUri);

            _activity.ContentAttributeSet = attributes;
            _activity.EligibleForHandoff  = false;
        }
Пример #14
0
        static public NSSet GetSet(PKContactFields values)
        {
            var set = new NSMutableSet();

            if (values == PKContactFields.None)
            {
                return(set);
            }

            foreach (PKContactFields value in Enum.GetValues(typeof(PKContactFields)))
            {
                if (values.HasFlag(value))
                {
                    var constant = value.GetConstant();
                    // None does not have an associated native value and Contains would throw an ANE
                    if (constant != null)
                    {
                        set.Add(constant);
                    }
                }
            }
            return(set);
        }
Пример #15
0
        public void IEnumerableTest()
        {
            const int C      = 16 * 2 + 3;        // NSFastEnumerator has a array of size 16, use more than that, and not an exact multiple.
            var       values = new NSString [C];

            for (int i = 0; i < C; i++)
            {
                values [i] = (NSString)i.ToString();
            }

            using (var st = new NSMutableSet <NSString> (values)) {
                Assert.AreEqual((nuint)C, st.Count, "Count 1");

                var lst = new List <NSString> ();
                foreach (NSString a in (IEnumerable)st)
                {
                    Assert.IsNotNull(a, "null item iterator");
                    Assert.IsFalse(lst.Contains(a), "duplicated item iterator");
                    lst.Add(a);
                    Assert.IsTrue(Array.IndexOf(values, a) >= 0, "different object");
                }
                Assert.AreEqual(C, lst.Count, "iterator count");
            }
        }
Пример #16
0
        public static void RegisterNotifications()
        {
            var action = new UIMutableUserNotificationAction
            {
                Title                  = "Launch",
                Identifier             = "trade",
                ActivationMode         = UIUserNotificationActivationMode.Foreground,
                AuthenticationRequired = false
            };

            var actionCategory = new UIMutableUserNotificationCategory {
                Identifier = "trade"
            };

            var categories = new NSMutableSet();

            categories.Add(actionCategory);

            actionCategory.SetActions(new UIUserNotificationAction[] { action }, UIUserNotificationActionContext.Default);

            var settings = UIUserNotificationSettings.GetSettingsForTypes(UIUserNotificationType.Alert | UIUserNotificationType.Sound, categories);

            UIApplication.SharedApplication.RegisterUserNotificationSettings(settings);
        }
Пример #17
0
        public static SKNode?Create(string filename, Type [] types, out NSError error)
        {
            // Let's fail early.
            if (filename == null)
            {
                ObjCRuntime.ThrowHelper.ThrowArgumentNullException(nameof(filename));
            }
            if (types == null)
            {
                ObjCRuntime.ThrowHelper.ThrowArgumentNullException(nameof(types));
            }
            if (types.Length == 0)
            {
                ObjCRuntime.ThrowHelper.ThrowArgumentException(nameof(types), "Length must be greater than zero.");
            }

            using (var classes = new NSMutableSet <Class> (types.Length)) {
                foreach (var type in types)
                {
                    classes.Add(new Class(type));
                }
                return(Create(filename, classes.Handle, out error));
            }
        }
Пример #18
0
        public static SKNode Create(string filename, Type [] types, out NSError error)
        {
            // Let's fail early.
            if (filename == null)
            {
                throw new ArgumentNullException(nameof(filename));
            }
            if (types == null)
            {
                throw new ArgumentNullException(nameof(filename));
            }
            if (types.Length == 0)
            {
                throw new InvalidOperationException($"'{nameof (filename)}' length must be greater than zero.");
            }

            using (var classes = new NSMutableSet <Class> (types.Length)) {
                foreach (var type in types)
                {
                    classes.Add(new Class(type));
                }
                return(Create(filename, classes.Handle, out error));
            }
        }
Пример #19
0
        /// <summary>
        /// Overridden from the base Game.Initialize. Once the GraphicsDevice is setup,
        /// we'll use the viewport to initialize some values.
        /// </summary>
        protected override void Initialize()
        {
            State = GameState.Menu;

            hookHeight = Math.Min (GraphicsDevice.Viewport.Height, MaxHookheight);
            player = new Player ();
            floor = new Floor ();

            playSound = true;
            hasPlayedSound = false;
            untilSpeedUpdate = GamePhysics.WhenToUpdateHookSpeed;

            previousTouches = new TouchCollection ();
            currentTouches = new TouchCollection ();

            // ad stuff
            UIViewController view = this.Services.GetService (typeof(UIViewController)) as UIViewController;
            adView = new ADBannerView ();

            NSMutableSet nsM = new NSMutableSet ();
            nsM.Add (ADBannerView.SizeIdentifierPortrait);
            adView.RequiredContentSizeIdentifiers = nsM;

            // delegate for ad is loaded
            adView.AdLoaded += delegate {
                adView.Frame = new System.Drawing.RectangleF(0, (UIScreen.MainScreen.Bounds.Height - adView.Frame.Height),
                    adView.Frame.Width, adView.Frame.Height);
                adView.Hidden = false;
            };

            // delegate for failed ad receive
            adView.FailedToReceiveAd += delegate(object sender, AdErrorEventArgs e) {
                Console.WriteLine(e.Error);
                adView.Hidden = true;
            };

            // delegate for click on ad
            adView.ActionShouldBegin = delegate(ADBannerView banner, bool willLeaveApp) {
                // pause game here
                State = GameState.Paused;
                return true;
            };

            // delegate for ad interaction finished
            adView.ActionFinished += delegate {
                // continue game now
                State = GameState.Menu;
            };

            view.Add (adView);
            base.Initialize ();
        }
Пример #20
0
 public void Ctor()
 {
     using (var arr = new NSMutableSet <NSDate> ()) {
         Assert.AreEqual((nuint)0, arr.Count, "Count");
     }
 }
Пример #21
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            linePickerModel = new LinePickerModel();
            lineSelector.Model = linePickerModel;
            lineSelector.ShowSelectionIndicator = true;

            lineButton.TouchUpInside += SelectLines;

            // Profile Picture View may already been set when the Camera closes.
            if(profilePictureView == null)
            {
                profilePictureView = new UIImageView();
            }
            else
            {
                // Set up Scroll View again when we have a new picture from the camera.
                var size = scrollView.Frame.Size;
                scrollView.ContentSize = profilePictureView.Frame.Size;
                scrollView.ContentInset = new UIEdgeInsets(size.Height * 0.8f, size.Width * 0.8f, size.Height * 0.8f, size.Width * 0.8f);
                scrollView.ContentOffset = new PointF(0, 0);
            }

            scrollView.AddSubview(profilePictureView);
            scrollView.MaximumZoomScale = 5f;
            scrollView.MinimumZoomScale = 0.2f;
            scrollView.Bounces = false;
            scrollView.BouncesZoom = false;
            scrollView.IndicatorStyle = UIScrollViewIndicatorStyle.Black;

            scrollView.ViewForZoomingInScrollView = (sender) => { return profilePictureView; };

            if(profilePictureView.Image == null)
                LoadImage(UIImage.FromFile("ProfilePicture.jpg"));

            overlayImage = UIImage.FromFile(string.Format("FacebookOverlay{0}.png", numberOfLines));
            facebookOverlay.Image = overlayImage;

            picker = new UIImagePickerController();
            picker.Delegate = new ImagePickerDelegate(this);

            InitializePhotoButton();

            facebookButton.Clicked += (o, e) => LoginToFacebook(true);
            mirrorButton.Clicked += (o, e) => MirrorImage();

            hud = new ATMHud();
            View.AddSubview(hud.View);

            AddCropHelpers();

            var contentIdentifiers = new NSMutableSet();
            contentIdentifiers.Add(new NSString("ADBannerContentSize320x50"));
            adView.RequiredContentSizeIdentifiers = contentIdentifiers;

            adView.Hidden = true;
            adView.AdLoaded += (o, e) => {
                adView.Hidden = false;
                Console.WriteLine("AdLoaded");
            };

            adView.FailedToReceiveAd += (object o, AdErrorEventArgs e) => {
                adView.Hidden = true;
                Console.WriteLine("FailedToReceiveAd: " + e.Error.ToString());
            };
        }
Пример #22
0
        public KSCatalogViewController() : base(UITableViewStyle.Grouped, null)
        {
            PSPDFKitGlobal.LogLevel = PSPDFLogLevel.Verbose;

            // Add some custom localization to ensure the bindings work.
            PSPDFKitGlobal.Localize("en", new NameValueCollection
            {
                { "Outline", "File Content" },
                { "Bookmarks", "Remember" }
            });

            // Call cache method to ensure the bindings for the cache work.
            var oPdfCache = PSPDFCache.SharedCache;

            oPdfCache.ClearCache( );

            PSPDFKitGlobal.LogLevel = PSPDFLogLevel.Info;

            NSUrl samplesURL   = NSBundle.MainBundle.ResourceUrl.Append("Samples", true);
            NSUrl hackerMagURL = samplesURL.Append(HackerMagazineExample, false);
            NSUrl annotTestURL = samplesURL.Append(AnnotTestExample, false);


            this.Root = new RootElement("KSCatalogViewController")
            {
                new Section("Full example apps", "Can be used as a template for your own apps.")
                {
                    // PDF playground.
                    new StringElement("PSPDFViewController playground", () =>
                    {
                        var doc             = new PSPDFDocument(hackerMagURL);
                        var kioskController = new KSKioskViewController(doc);

                        kioskController.StatusBarStyleSetting = PSPDFStatusBarStyleSetting.Default;
                        this.NavigationController.PushViewController(kioskController, true);
                    }),
                },

                new Section("Customizing")
                {
                    // Combines various view controllers in a tab bar controller.
                    new StringElement("Combine search, TOC and bookmarks", () =>
                    {
                        var doc = new PSPDFDocument(hackerMagURL);

                        // Don't use PSPDFVieController directly but a subclass that allows attaching to ViewDidDisappear in order to clear
                        // the RightBarButtonItems property. Otherwise the tabBarBtn would keep a reference to the PSPDFViewController and the instances
                        // would never be freed.

                        //var controller = new PSPDFViewController(doc);
                        var controller = new KSKioskViewController(doc);
                        //controller.ViewDisappeared += (sender, args) => controller.RightBarButtonItems = new PSPDFBarButtonItem[0];

                        var tabBarController = new KSCombinedTabBarController(controller, doc);

                        var tabBarBtn = new KSBarButtonItem(controller)
                        {
                            Title = "UITabBarController",
                            Style = UIBarButtonItemStyle.Bordered
                        };
                        tabBarBtn.Clicked += (object sender, EventArgs e) => controller.PresentViewControllerModalOrPopover(tabBarController, true, false, true, tabBarBtn, null);

                        controller.RightBarButtonItems = new PSPDFBarButtonItem[] { controller.AnnotationButtonItem, controller.BookmarkButtonItem, tabBarBtn };

                        var classDic = new NSMutableDictionary();
                        classDic.LowlevelSetObject(new Class(typeof(KSInkAnnotation)).Handle, new Class(typeof(PSPDFInkAnnotation)).Handle);
                        classDic.LowlevelSetObject(new Class(typeof(KSNoteAnnotation)).Handle, new Class(typeof(PSPDFNoteAnnotation)).Handle);
                        classDic.LowlevelSetObject(new Class(typeof(KSHighlightAnnotation)).Handle, new Class(typeof(PSPDFHighlightAnnotation)).Handle);
                        doc.OverrideClassNames = classDic;

                        this.NavigationController.PushViewController(controller, true);
                    }),

                    // Shows an alert when tapping a link annotation.
                    new StringElement("Custom reaction on annotation links", () =>
                    {
                        var doc             = new PSPDFDocument(hackerMagURL);
                        var controller      = new PSPDFViewController(doc);
                        controller.Delegate = new KSCatchTappingLinkDelegate();
                        // There are link annotations on page 2.
                        controller.SetPageAnimated(1, false);
                        this.NavigationController.PushViewController(controller, true);
                    })
                },

                new Section("Subclassing")
                {
                    // Subclassing PSPDFAnnotationToolbar
                    new StringElement("Subclass annotation toolbar and drawing toolbar", () =>
                    {
                        var doc        = new PSPDFDocument(hackerMagURL);
                        var controller = new PSPDFViewController(doc);

                        var barButtons = new List <PSPDFBarButtonItem>(controller.RightBarButtonItems);
                        barButtons.Add(controller.AnnotationButtonItem);
                        controller.RightBarButtonItems = barButtons.ToArray();

                        var classDic = new NSMutableDictionary();
                        classDic.LowlevelSetObject(new Class(typeof(KSAnnotationToolbar)).Handle, new Class(typeof(PSPDFAnnotationToolbar)).Handle);
                        controller.OverrideClassNames = classDic;

                        this.NavigationController.PushViewController(controller, true);
                    }),

                    // Demonstrates always visible vertical toolbar.
                    new StringElement("Vertical always-visible annotation bar", () =>
                    {
                        var doc        = new PSPDFDocument(hackerMagURL);
                        var controller = new KSExampleAnnotationViewController(doc);

                        this.NavigationController.PushViewController(controller, true);
                    }),

                    // Tests potential binding issue when subclassing PSPDFViewController
                    new StringElement("PSPDFViewController with NULL document", () =>
                    {
                        var doc             = new PSPDFDocument(hackerMagURL);
                        var controller      = new KSNoDocumentPDFViewController();
                        controller.Document = doc;
                        this.NavigationController.PushViewController(controller, true);
                    }),

                    // Demonstrates capturing bookmark set/remove.
                    new StringElement("Capture bookmarks", () =>
                    {
                        var doc = new PSPDFDocument(hackerMagURL);

                        // Create an entry for overriding the default bookmark parser.
                        var classDic = new NSMutableDictionary();
                        classDic.LowlevelSetObject(new Class(typeof(KSBookmarkParser)).Handle, new Class(typeof(PSPDFBookmarkParser)).Handle);
                        doc.OverrideClassNames = classDic;

                        var controller = new PSPDFViewController(doc);
                        controller.RightBarButtonItems = new PSPDFBarButtonItem[]
                        {
                            controller.BookmarkButtonItem,
                            controller.SearchButtonItem,
                            controller.OutlineButtonItem,
                            controller.ViewModeButtonItem
                        };
                        this.NavigationController.PushViewController(controller, true);
                    }),

                    // Demonstrates custom annotation provider.
                    new StringElement("Custom Annotation Provider", () =>
                    {
                        var doc = new PSPDFDocument(hackerMagURL);
                        doc.SetDidCreateDocumentProviderBlock(delegate(PSPDFDocumentProvider documentProvider)
                        {
                            documentProvider.AnnotationParser.AnnotationProviders = new NSObject[]
                            {
                                new KSCustomAnnotationProvider(),
                                documentProvider.AnnotationParser.FileAnnotationProvider
                            };
                        });

                        var controller = new PSPDFViewController(doc);
                        this.NavigationController.PushViewController(controller, true);
                    }),

                    // Subclasses PDPFFileAnnotationProvider and injects additional annotations.
                    // This example demonstrates:
                    // * Make all built in annotations (those embedded in the PDF) immutable.
                    // * All annotations added by the user can be modified.
                    // * Workaround for PSPDFKit bug where the text of a non-editable annotation can still be changed.
                    // * Immediate callback if an annotation has been changed.
                    new StringElement("Subclass PSPDFFileAnnotationProvider", () =>
                    {
                        var controller = new PSPDFViewController();
                        var barButtons = new List <PSPDFBarButtonItem>(controller.RightBarButtonItems);
                        barButtons.Add(controller.AnnotationButtonItem);
                        controller.RightBarButtonItems = barButtons.ToArray();
                        controller.SetPageAnimated(2, false);

                        controller.PageMode        = PSPDFPageMode.Automatic;
                        controller.PageTransition  = PSPDFPageTransition.ScrollContinuous;
                        controller.ScrollDirection = PSPDFScrollDirection.Horizontal;

                        var classDic = new NSMutableDictionary();
                        classDic.LowlevelSetObject(new Class(typeof(KSNoteAnnotationController)).Handle, new Class(typeof(PSPDFNoteAnnotationController)).Handle);
                        controller.OverrideClassNames = classDic;

                        this.NavigationController.PushViewController(controller, true);

                        var doc = new KSPDFDocument(hackerMagURL);
                        //var doc = new PSPDFDocument();
                        //var doc = new PSPDFDocument(annotTestURL);

                        // Create an entry for overriding the file annotation provider.
                        classDic = new NSMutableDictionary();
                        classDic.LowlevelSetObject(new Class(typeof(KSFileAnnotationProvider)).Handle, new Class(typeof(PSPDFFileAnnotationProvider)).Handle);
                        classDic.LowlevelSetObject(new Class(typeof(KSInkAnnotation)).Handle, new Class(typeof(PSPDFInkAnnotation)).Handle);
                        classDic.LowlevelSetObject(new Class(typeof(KSNoteAnnotation)).Handle, new Class(typeof(PSPDFNoteAnnotation)).Handle);
                        classDic.LowlevelSetObject(new Class(typeof(KSHighlightAnnotation)).Handle, new Class(typeof(PSPDFHighlightAnnotation)).Handle);
                        doc.OverrideClassNames = classDic;

                        controller.Document = doc;
                    }),

                    // Set editable annotation types
                    new StringElement("Set editable annotation types", () =>
                    {
                        var doc        = new PSPDFDocument(hackerMagURL);
                        var controller = new PSPDFViewController(doc);
                        controller.RightBarButtonItems = new PSPDFBarButtonItem[]
                        {
                            controller.AnnotationButtonItem
                        };

                        var set = new NSMutableSet();
                        set.Add(PSPDFAnnotation.PSPDFAnnotationTypeStringInk);
                        set.Add(PSPDFAnnotation.PSPDFAnnotationTypeStringNote);
                        set.Add(PSPDFAnnotation.PSPDFAnnotationTypeStringUnderline);

                        controller.AnnotationButtonItem.AnnotationToolbar.EditableAnnotationTypes = set.ToNSOrderedSet();
                        this.NavigationController.PushViewController(controller, true);
                    })
                }
            };
        }
        public KSCatalogViewController()
            : base(UITableViewStyle.Grouped, null)
        {
            PSPDFKitGlobal.LogLevel = PSPDFLogLevel.Verbose;

            // Add some custom localization to ensure the bindings work.
            PSPDFKitGlobal.Localize("en", new NameValueCollection
            {
                {"Outline", "File Content"},
                {"Bookmarks", "Remember"}
            });

            // Call cache method to ensure the bindings for the cache work.
            var oPdfCache = PSPDFCache.SharedCache;
            oPdfCache.ClearCache ( );

            PSPDFKitGlobal.LogLevel = PSPDFLogLevel.Info;

            NSUrl samplesURL = NSBundle.MainBundle.ResourceUrl.Append ("Samples", true);
            NSUrl hackerMagURL = samplesURL.Append(HackerMagazineExample, false);
            NSUrl annotTestURL = samplesURL.Append(AnnotTestExample, false);

            this.Root = new RootElement ("KSCatalogViewController")
            {
                new Section ("Full example apps", "Can be used as a template for your own apps.")
                {
                    // PDF playground.
                    new StringElement ("PSPDFViewController playground", () =>
                    {
                        var doc = new PSPDFDocument(hackerMagURL);
                        var kioskController = new KSKioskViewController(doc);

                        kioskController.StatusBarStyleSetting = PSPDFStatusBarStyleSetting.Default;
                        this.NavigationController.PushViewController(kioskController, true);
                    }),
                },

                new Section("Customizing")
                {
                    // Combines various view controllers in a tab bar controller.
                    new StringElement("Combine search, TOC and bookmarks", () =>
                    {
                        var doc = new PSPDFDocument(hackerMagURL);

                        // Don't use PSPDFVieController directly but a subclass that allows attaching to ViewDidDisappear in order to clear
                        // the RightBarButtonItems property. Otherwise the tabBarBtn would keep a reference to the PSPDFViewController and the instances
                        // would never be freed.

                        //var controller = new PSPDFViewController(doc);
                        var controller = new KSKioskViewController(doc);
                        //controller.ViewDisappeared += (sender, args) => controller.RightBarButtonItems = new PSPDFBarButtonItem[0];

                        var tabBarController = new KSCombinedTabBarController(controller, doc);

                        var tabBarBtn = new KSBarButtonItem(controller)
                        {
                            Title = "UITabBarController",
                            Style = UIBarButtonItemStyle.Bordered
                        };
                        tabBarBtn.Clicked += (object sender, EventArgs e) => controller.PresentViewControllerModalOrPopover(tabBarController, true, false, true, tabBarBtn, null);

                        controller.RightBarButtonItems = new PSPDFBarButtonItem[] { controller.AnnotationButtonItem, controller.BookmarkButtonItem, tabBarBtn };

                        var classDic = new NSMutableDictionary();
                        classDic.LowlevelSetObject( new Class(typeof(KSInkAnnotation)).Handle, new Class(typeof(PSPDFInkAnnotation)).Handle);
                        classDic.LowlevelSetObject( new Class(typeof(KSNoteAnnotation)).Handle, new Class(typeof(PSPDFNoteAnnotation)).Handle);
                        classDic.LowlevelSetObject( new Class(typeof(KSHighlightAnnotation)).Handle, new Class(typeof(PSPDFHighlightAnnotation)).Handle);
                        doc.OverrideClassNames = classDic;

                        this.NavigationController.PushViewController(controller, true);
                    }),

                    // Shows an alert when tapping a link annotation.
                    new StringElement("Custom reaction on annotation links", () =>
                    {
                        var doc = new PSPDFDocument(hackerMagURL);
                        var controller = new PSPDFViewController(doc);
                        controller.Delegate = new KSCatchTappingLinkDelegate();
                        // There are link annotations on page 2.
                        controller.SetPageAnimated(1, false);
                        this.NavigationController.PushViewController(controller, true);
                    })
                },

                new Section ("Subclassing")
                {
                    // Subclassing PSPDFAnnotationToolbar
                    new StringElement ("Subclass annotation toolbar and drawing toolbar", () =>
                    {
                        var doc = new PSPDFDocument(hackerMagURL);
                        var controller = new PSPDFViewController(doc);

                        var barButtons = new List<PSPDFBarButtonItem>(controller.RightBarButtonItems);
                        barButtons.Add(controller.AnnotationButtonItem);
                        controller.RightBarButtonItems = barButtons.ToArray();

                        var classDic = new NSMutableDictionary();
                        classDic.LowlevelSetObject( new Class(typeof(KSAnnotationToolbar)).Handle, new Class(typeof(PSPDFAnnotationToolbar)).Handle);
                        controller.OverrideClassNames = classDic;

                        this.NavigationController.PushViewController(controller, true);
                    }),

                    // Demonstrates always visible vertical toolbar.
                    new StringElement ("Vertical always-visible annotation bar", () =>
                    {
                        var doc = new PSPDFDocument(hackerMagURL);
                        var controller = new KSExampleAnnotationViewController(doc);

                        this.NavigationController.PushViewController(controller, true);
                    }),

                    // Tests potential binding issue when subclassing PSPDFViewController
                    new StringElement ("PSPDFViewController with NULL document", () =>
                    {
                        var doc = new PSPDFDocument(hackerMagURL);
                        var controller = new KSNoDocumentPDFViewController();
                        controller.Document = doc;
                        this.NavigationController.PushViewController(controller, true);
                    }),

                    // Demonstrates capturing bookmark set/remove.
                    new StringElement ("Capture bookmarks", () =>
                    {
                        var doc = new PSPDFDocument(hackerMagURL);

                        // Create an entry for overriding the default bookmark parser.
                        var classDic = new NSMutableDictionary();
                        classDic.LowlevelSetObject( new Class(typeof(KSBookmarkParser)).Handle, new Class(typeof(PSPDFBookmarkParser)).Handle);
                        doc.OverrideClassNames = classDic;

                        var controller = new PSPDFViewController(doc);
                        controller.RightBarButtonItems = new PSPDFBarButtonItem[]
                        {
                            controller.BookmarkButtonItem,
                            controller.SearchButtonItem,
                            controller.OutlineButtonItem,
                            controller.ViewModeButtonItem
                        };
                        this.NavigationController.PushViewController(controller, true);
                    }),

                    // Demonstrates custom annotation provider.
                    new StringElement ("Custom Annotation Provider", () =>
                    {
                        var doc = new PSPDFDocument(hackerMagURL);
                        doc.SetDidCreateDocumentProviderBlock(delegate(PSPDFDocumentProvider documentProvider)
                        {
                            documentProvider.AnnotationParser.AnnotationProviders = new NSObject[]
                            {
                                new KSCustomAnnotationProvider(),
                                documentProvider.AnnotationParser.FileAnnotationProvider
                            };
                        });

                        var controller = new PSPDFViewController(doc);
                        this.NavigationController.PushViewController(controller, true);
                    }),

                    // Subclasses PDPFFileAnnotationProvider and injects additional annotations.
                    // This example demonstrates:
                    // * Make all built in annotations (those embedded in the PDF) immutable.
                    // * All annotations added by the user can be modified.
                    // * Workaround for PSPDFKit bug where the text of a non-editable annotation can still be changed.
                    // * Immediate callback if an annotation has been changed.
                    new StringElement ("Subclass PSPDFFileAnnotationProvider", () =>
                    {
                        var controller = new PSPDFViewController();
                        var barButtons = new List<PSPDFBarButtonItem>(controller.RightBarButtonItems);
                        barButtons.Add(controller.AnnotationButtonItem);
                        controller.RightBarButtonItems = barButtons.ToArray();
                        controller.SetPageAnimated(2, false);

                        controller.PageMode = PSPDFPageMode.Automatic;
                        controller.PageTransition = PSPDFPageTransition.ScrollContinuous;
                        controller.ScrollDirection = PSPDFScrollDirection.Horizontal;

                        var classDic = new NSMutableDictionary();
                        classDic.LowlevelSetObject(new Class(typeof(KSNoteAnnotationController)).Handle, new Class(typeof(PSPDFNoteAnnotationController)).Handle);
                        controller.OverrideClassNames = classDic;

                        this.NavigationController.PushViewController(controller, true);

                        var doc = new KSPDFDocument(hackerMagURL);
                        //var doc = new PSPDFDocument();
                        //var doc = new PSPDFDocument(annotTestURL);

                        // Create an entry for overriding the file annotation provider.
                        classDic = new NSMutableDictionary();
                        classDic.LowlevelSetObject( new Class(typeof(KSFileAnnotationProvider)).Handle, new Class(typeof(PSPDFFileAnnotationProvider)).Handle);
                        classDic.LowlevelSetObject( new Class(typeof(KSInkAnnotation)).Handle, new Class(typeof(PSPDFInkAnnotation)).Handle);
                        classDic.LowlevelSetObject( new Class(typeof(KSNoteAnnotation)).Handle, new Class(typeof(PSPDFNoteAnnotation)).Handle);
                        classDic.LowlevelSetObject( new Class(typeof(KSHighlightAnnotation)).Handle, new Class(typeof(PSPDFHighlightAnnotation)).Handle);
                        doc.OverrideClassNames = classDic;

                        controller.Document = doc;
                    }),

                    // Set editable annotation types
                    new StringElement ("Set editable annotation types", () =>
                    {
                        var doc = new PSPDFDocument(hackerMagURL);
                        var controller = new PSPDFViewController(doc);
                        controller.RightBarButtonItems = new PSPDFBarButtonItem[]
                        {
                            controller.AnnotationButtonItem
                        };

                        var set = new NSMutableSet();
                        set.Add(PSPDFAnnotation.PSPDFAnnotationTypeStringInk);
                        set.Add(PSPDFAnnotation.PSPDFAnnotationTypeStringNote);
                        set.Add(PSPDFAnnotation.PSPDFAnnotationTypeStringUnderline);

                        controller.AnnotationButtonItem.AnnotationToolbar.EditableAnnotationTypes = set.ToNSOrderedSet();
                        this.NavigationController.PushViewController(controller, true);
                    })
                }
            };
        }
Пример #24
0
        private void CommonInit()
        {
            recog = new GridGestureRecognizer(this);

            tapGesture = new UITapGestureRecognizer(this,new Selector("tapGestureUpdated:"));
            tapGesture.Delegate = recog;
            tapGesture.NumberOfTapsRequired = 1;
            tapGesture.NumberOfTouchesRequired = 1;
            tapGesture.CancelsTouchesInView = false;
            AddGestureRecognizer(tapGesture);

            /////////////////////////////
            // Transformation gestures :
            pinchGesture = new UIPinchGestureRecognizer(this,new Selector("pinchGestureUpdated:"));
            pinchGesture.Delegate = recog;
            AddGestureRecognizer(pinchGesture);

            rotationGesture = new UIRotationGestureRecognizer(this,new Selector("rotationGestureUpdated:"));
            rotationGesture.Delegate = recog;
            AddGestureRecognizer(rotationGesture);

            panGesture = new UIPanGestureRecognizer(this,new Selector("panGestureUpdated:"));
            panGesture.Delegate = recog;
            panGesture.MaximumNumberOfTouches=2;
            panGesture.MinimumNumberOfTouches=2;
            AddGestureRecognizer(panGesture);

            //////////////////////
            // Sorting gestures :
            sortingPanGesture = new UIPanGestureRecognizer(this,new Selector("sortingPanGestureUpdated:"));
            sortingPanGesture.Delegate = recog;
            AddGestureRecognizer(sortingPanGesture);

            longPressGesture = new UILongPressGestureRecognizer(this,new Selector("longPressGestureUpdated:"));
            longPressGesture.NumberOfTouchesRequired = 1;
            longPressGesture.Delegate = recog;
            longPressGesture.CancelsTouchesInView = false;
            longPressGesture.DelaysTouchesBegan = true;
            longPressGesture.DelaysTouchesEnded = true;
            AddGestureRecognizer(longPressGesture);

            ////////////////////////
            // Gesture dependencies
            UIPanGestureRecognizer panGestureRecognizer = null;
            if (this.RespondsToSelector(new Selector("panGestureRecognizer")))// iOS5 only
            {
                panGestureRecognizer = this.PanGestureRecognizer;
            }
            else
            {
                foreach (UIGestureRecognizer gestureRecognizer in GestureRecognizers)
                {
                    //if ([gestureRecognizer  isKindOfClass:NSClassFromString(@"UIScrollViewPanGestureRecognizer")])
                    if (gestureRecognizer.ClassHandle.ToString().Equals("UIScrollViewPanGestureRecognizer")) // TODO: Test this!
                    {
                        panGestureRecognizer = (UIPanGestureRecognizer) gestureRecognizer;
                    }
                }
            }
            panGestureRecognizer.MaximumNumberOfTouches = 1;
            panGestureRecognizer.RequireGestureRecognizerToFail(sortingPanGesture);
            //layoutStrategy = GMGridViewLayoutStrategyFactory.StrategyFromType(GMGridViewLayoutStrategyType.Vertical);
            SetLayoutStrategy(GridViewLayoutStrategyFactory.StrategyFromType(GridViewLayoutStrategyType.Vertical));

            mainSuperView = this;
            editing = false;
            itemSpacing = 10;
            style = GridViewStyle.Swap;
            MinimumPressDuration = 0.2;
            showFullSizeViewWithAlphaWhenTransforming = true;
            minEdgeInsets = new UIEdgeInsets(5, 5, 5, 5);
            ClipsToBounds = false;

            sortFuturePosition = GMGV_INVALID_POSITION;
            itemSize = new SizeF();
            centerGrid = true;

            lastScale = 1.0f;
            lastRotation = 0.0f;

            minPossibleContentOffset = new PointF(0,0);
            maxPossibleContentOffset = new PointF(0,0);

            //reusableCells = new HashSet<GMGridViewCell>();
            reusableCells = new NSMutableSet();

            NSNotificationCenter.DefaultCenter.AddObserver(this,new Selector("receivedMemoryWarningNotification:"),UIApplication.DidReceiveMemoryWarningNotification,null);
            NSNotificationCenter.DefaultCenter.AddObserver(this,new Selector("receivedWillRotateNotification:"),UIApplication.WillChangeStatusBarOrientationNotification,null);
        }
        public KSCatalogViewController()
            : base(UITableViewStyle.Grouped, null)
        {
            PSPDFKitGlobal.LogLevel = PSPDFLogLevel.Verbose;

            // Add some custom localization to ensure the bindings work.
            PSPDFKitGlobal.Localize("en", new NameValueCollection
            {
                {"Outline", "File Content"},
                {"Bookmarks", "Remember"}
            });

            // Call cache method to ensure the bindings for the cache work.
            var oPdfCache = PSPDFCache.SharedCache;
            oPdfCache.ClearCache ( );

            PSPDFKitGlobal.LogLevel = PSPDFLogLevel.Info;

            NSUrl samplesURL = NSBundle.MainBundle.ResourceUrl.Append ("Samples", true);
            NSUrl hackerMagURL = samplesURL.Append(HackerMagazineExample, false);
            NSUrl aesEncryptedURL = samplesURL.Append(AesEncryptedDoc, false);

            this.Root = new RootElement ("KSCatalogViewController")
            {
                new Section ("Full example apps", "Can be used as a template for your own apps.")
                {
                    // PDF playground.
                    new StringElement ("PSPDFViewController playground", () =>
                    {
                        var doc = new PSPDFDocument(hackerMagURL);
                        var kioskController = new KSKioskViewController(doc);

                        kioskController.StatusBarStyleSetting = PSPDFStatusBarStyleSetting.Default;
                        this.NavigationController.PushViewController(kioskController, true);
                    }),
                },

                new Section("Customizing")
                {
                    // Combines various view controllers in a tab bar controller.
                    new StringElement("Combine search, TOC and bookmarks", () =>
                    {
                        var doc = new PSPDFDocument(hackerMagURL);

                        // Don't use PSPDFVieController directly but a subclass that allows attaching to ViewDidDisappear in order to clear
                        // the RightBarButtonItems property. Otherwise the tabBarBtn would keep a reference to the PSPDFViewController and the instances
                        // would never be freed.

                        //var controller = new PSPDFViewController(doc);
                        var controller = new KSKioskViewController(doc);
                        //controller.ViewDisappeared += (sender, args) => controller.RightBarButtonItems = new PSPDFBarButtonItem[0];

                        var tabBarController = new KSCombinedTabBarController(controller, doc);

                        var tabBarBtn = new KSBarButtonItem(controller)
                        {
                            Title = "UITabBarController",
                            Style = UIBarButtonItemStyle.Bordered
                        };
                        tabBarBtn.Clicked += (object sender, EventArgs e) => controller.PresentViewControllerModalOrPopover(tabBarController, true, false, true, tabBarBtn, null);

                        controller.RightBarButtonItems = new PSPDFBarButtonItem[] { controller.AnnotationButtonItem, controller.BookmarkButtonItem, tabBarBtn };

                        var classDic = new NSMutableDictionary();
                        classDic.LowlevelSetObject( new Class(typeof(KSInkAnnotation)).Handle, new Class(typeof(PSPDFInkAnnotation)).Handle);
                        classDic.LowlevelSetObject( new Class(typeof(KSNoteAnnotation)).Handle, new Class(typeof(PSPDFNoteAnnotation)).Handle);
                        classDic.LowlevelSetObject( new Class(typeof(KSHighlightAnnotation)).Handle, new Class(typeof(PSPDFHighlightAnnotation)).Handle);
                        doc.OverrideClassNames = classDic;

                        this.NavigationController.PushViewController(controller, true);
                    }),

                    // Shows an alert when tapping a link annotation.
                    new StringElement("Custom reaction on annotation links", () =>
                    {
                        var doc = new PSPDFDocument(hackerMagURL);
                        var controller = new PSPDFViewController(doc);
                        controller.Delegate = new KSCatchTappingLinkDelegate();
                        // There are link annotations on page 2.
                        controller.SetPageAnimated(1, false);
                        this.NavigationController.PushViewController(controller, true);
                    })
                },

                new Section ("Subclassing")
                {
                    // Subclassing PSPDFAnnotationToolbar
                    new StringElement ("Subclass annotation toolbar and drawing toolbar", () =>
                    {
                        var doc = new PSPDFDocument(hackerMagURL);
                        var controller = new PSPDFViewController(doc);

                        var barButtons = new List<PSPDFBarButtonItem>(controller.RightBarButtonItems);
                        barButtons.Add(controller.AnnotationButtonItem);
                        controller.RightBarButtonItems = barButtons.ToArray();

                        var classDic = new NSMutableDictionary();
                        classDic.LowlevelSetObject( new Class(typeof(KSAnnotationToolbar)).Handle, new Class(typeof(PSPDFAnnotationToolbar)).Handle);
                        controller.OverrideClassNames = classDic;

                        this.NavigationController.PushViewController(controller, true);
                    }),

                    // Demonstrates always visible vertical toolbar.
                    new StringElement ("Vertical always-visible annotation bar", () =>
                    {
                        var doc = new PSPDFDocument(hackerMagURL);
                        var controller = new KSExampleAnnotationViewController(doc);

                        this.NavigationController.PushViewController(controller, true);
                    }),

                    // Tests potential binding issue when subclassing PSPDFViewController
                    new StringElement ("PSPDFViewController with NULL document", () =>
                    {
                        var doc = new PSPDFDocument(hackerMagURL);
                        var controller = new KSNoDocumentPDFViewController();
                        controller.Document = doc;
                        this.NavigationController.PushViewController(controller, true);
                    }),

                    // Demonstrates capturing bookmark set/remove.
                    new StringElement ("Capture bookmarks", () =>
                    {
                        var doc = new PSPDFDocument(hackerMagURL);

                        // Create an entry for overriding the default bookmark parser.
                        var classDic = new NSMutableDictionary();
                        classDic.LowlevelSetObject( new Class(typeof(KSBookmarkParser)).Handle, new Class(typeof(PSPDFBookmarkParser)).Handle);
                        doc.OverrideClassNames = classDic;

                        var controller = new PSPDFViewController(doc);
                        controller.RightBarButtonItems = new PSPDFBarButtonItem[]
                        {
                            controller.BookmarkButtonItem,
                            controller.SearchButtonItem,
                            controller.OutlineButtonItem,
                            controller.ViewModeButtonItem
                        };
                        this.NavigationController.PushViewController(controller, true);
                    }),

                    // Demonstrates custom annotation provider.
                    new StringElement ("Custom Annotation Provider", () =>
                    {
                        var doc = new PSPDFDocument(hackerMagURL);
                        doc.SetDidCreateDocumentProviderBlock(delegate(PSPDFDocumentProvider documentProvider)
                        {
                            documentProvider.AnnotationParser.AnnotationProviders = new NSObject[]
                            {
                                new KSCustomAnnotationProvider(),
                                documentProvider.AnnotationParser.FileAnnotationProvider
                            };
                        });

                        var controller = new PSPDFViewController(doc);
                        this.NavigationController.PushViewController(controller, true);
                    }),

                    // Subclasses PDPFFileAnnotationProvider and injects additional annotations.
                    // This example demonstrates:
                    // * Make all built in annotations (those embedded in the PDF) immutable.
                    // * All annotations added by the user can be modified.
                    // * Workaround for PSPDFKit bug where the text of a non-editable annotation can still be changed.
                    // * Immediate callback if an annotation has been changed.
                    new StringElement ("Subclass PSPDFFileAnnotationProvider", () =>
                    {
                        var controller = new PSPDFViewController();
                        var barButtons = new List<PSPDFBarButtonItem>(controller.RightBarButtonItems);
                        barButtons.Add(controller.AnnotationButtonItem);
                        controller.RightBarButtonItems = barButtons.ToArray();
                        controller.SetPageAnimated(2, false);

                        controller.PageMode = PSPDFPageMode.Automatic;
                        controller.PageTransition = PSPDFPageTransition.ScrollContinuous;
                        controller.ScrollDirection = PSPDFScrollDirection.Horizontal;

                        var classDic = new NSMutableDictionary();
                        classDic.LowlevelSetObject(new Class(typeof(KSNoteAnnotationController)).Handle, new Class(typeof(PSPDFNoteAnnotationController)).Handle);
                        controller.OverrideClassNames = classDic;

                        this.NavigationController.PushViewController(controller, true);

                        var doc = new KSPDFDocument(hackerMagURL);
                        //var doc = new PSPDFDocument();
                        //var doc = new PSPDFDocument(annotTestURL);

                        // Create an entry for overriding the file annotation provider.
                        classDic = new NSMutableDictionary();
                        classDic.LowlevelSetObject( new Class(typeof(KSFileAnnotationProvider)).Handle, new Class(typeof(PSPDFFileAnnotationProvider)).Handle);
                        classDic.LowlevelSetObject( new Class(typeof(KSInkAnnotation)).Handle, new Class(typeof(PSPDFInkAnnotation)).Handle);
                        classDic.LowlevelSetObject( new Class(typeof(KSNoteAnnotation)).Handle, new Class(typeof(PSPDFNoteAnnotation)).Handle);
                        classDic.LowlevelSetObject( new Class(typeof(KSHighlightAnnotation)).Handle, new Class(typeof(PSPDFHighlightAnnotation)).Handle);
                        doc.OverrideClassNames = classDic;

                        controller.Document = doc;
                    }),

                    // Set editable annotation types
                    new StringElement ("Set editable annotation types", () =>
                    {
                        var doc = new PSPDFDocument(hackerMagURL);
                        var controller = new PSPDFViewController(doc);
                        controller.RightBarButtonItems = new PSPDFBarButtonItem[]
                        {
                            controller.AnnotationButtonItem
                        };

                        var set = new NSMutableSet();
                        set.Add(PSPDFAnnotation.PSPDFAnnotationTypeStringInk);
                        set.Add(PSPDFAnnotation.PSPDFAnnotationTypeStringNote);
                        set.Add(PSPDFAnnotation.PSPDFAnnotationTypeStringUnderline);

                        controller.AnnotationButtonItem.AnnotationToolbar.EditableAnnotationTypes = set.ToNSOrderedSet();
                        this.NavigationController.PushViewController(controller, true);
                    })
                },

                new Section("Security")
                {
                    // This shows and tests decryption and viewing of a pre-encrypted document.
                    new StringElement("Read AES encrypted document", () => {
                        // Note: For shipping apps, you need to protect this string better, making it harder for hacker to simply disassemble and receive the key from the binary. Or add an internet service that fetches the key from an SSL-API. But then there's still the slight risk of memory dumping with an attached gdb. Or screenshots. Security is never 100% perfect; but using AES makes it way harder to get the PDF. You can even combine AES and a PDF password.
                        string passphrase = @"afghadöghdgdhfgöhapvuenröaoeruhföaeiruaerub";
                        string salt = @"ducrXn9WaRdpaBfMjDTJVjUf3FApA6gtim0e61LeSGWV9sTxB0r26mPs59Lbcexn";

                        var cryptoWrapper = new PSPDFAESCryptoDataProvider(aesEncryptedURL, passphrase, salt);

                        var provider = cryptoWrapper.DataProvider;
                        var document = PSPDFDocument.PDFDocumentWithDataProvider(provider);
                        document.Uid = AesEncryptedDoc; // manually set an UID for encrypted documents.

                        // When PSPDFAESCryptoDataProvider is used, the cacheStrategy of PSPDFDocument is *automatically* set to PSPDFCacheNothing.
                        // If you use your custom crypto solution, don't forget to set this to not leak out encrypted data as cached images.
                        // document.cacheStrategy = PSPDFCacheNothing;

                        var controller = new PSPDFViewController(document);
                        this.NavigationController.PushViewController(controller, true);
                    }),

                    // This encrypts a PDF, saves it and then opens it.
                    new StringElement("Encrypt a PDF and decrypt it again", () => {
                        var targetFilePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "encrypted.pdf.aes");

                        // The passphrase is a secret! Keep it secret!
                        string passphrase = "Hello World, I'm the secret!";

                        // The salt has to be at least 8 bytes. It should change for every encrypted document, just like the IV.
                        // You can store it in cleartext together with your encrypted record, it's not a secret but used to prevent that
                        // two identical passwords generate the same hash.
                        // The salt should NOT be "12345678"! This is just for testing! Use something random.
                        string salt = "132456789";

                        // PSPDFKit v2 does not allow passing the key directly. Instead it regegenerates the key using native PBKDF2.
                        // PSPDFKit v3 will have different API where you can use the key directly.
                        // Also note that PSPDFKit internally uses 50000 hashing iterations, so we have to use exactly the same algorithm.
                        // Rfc2898DeriveBytes only supports SHA1, so we have a flexible version of it here where you can specify the hashing alogorithm.
                        var deriveBytes = new Rfc2898DeriveBytesFlexible(passphrase, Encoding.UTF8.GetBytes(salt), 50000, new HMACSHA256());

                        // Encrypt the PDF.
                        using (var rijndael = new RijndaelManaged())
                        {
                            rijndael.KeySize = 256;

                            rijndael.Key = deriveBytes.GetBytes ( rijndael.KeySize / 8 );
                            rijndael.IV = deriveBytes.GetBytes ( rijndael.BlockSize / 8 );

                            using(var readStream = File.Open("./Samples/" + HackerMagazineExample, FileMode.Open))
                            using(var writeStream = File.Open(targetFilePath, FileMode.Create))
                            using(var cryptoTrans = rijndael.CreateEncryptor ())
                            using(var encryptedStream = new CryptoStream (writeStream, cryptoTrans, CryptoStreamMode.Write))
                            {
                                // Write the IV unencrypted first.
                                writeStream.Write(rijndael.IV, 0, rijndael.IV.Length);
                                // Then the encrypted PDF.
                                readStream.CopyTo(encryptedStream);
                            }
                        }

                        // Decrypt the just encrypted file and view it.
                        var cryptoWrapper = new PSPDFAESCryptoDataProvider(NSUrl.FromFilename(targetFilePath), passphrase, salt);

                        var provider = cryptoWrapper.DataProvider;
                        var document = PSPDFDocument.PDFDocumentWithDataProvider(provider);
                        document.Uid = AesEncryptedDoc; // manually set an UID for encrypted documents.

                        // When PSPDFAESCryptoDataProvider is used, the cacheStrategy of PSPDFDocument is *automatically* set to PSPDFCacheNothing.
                        // If you use your custom crypto solution, don't forget to set this to not leak out encrypted data as cached images.
                        // document.cacheStrategy = PSPDFCacheNothing;

                        var controller = new PSPDFViewController(document);
                        this.NavigationController.PushViewController(controller, true);
                    })
                }
            };
        }