public static void SaveToDictionary(this IStateBundle state, NSMutableDictionary bundle)
        {
            var formatter = new BinaryFormatter();

            foreach (var kv in state.Data.Where(x => x.Value != null))
            {
                var value = kv.Value;

                if (value.GetType().IsSerializable)
                {
                    using (var stream = new MemoryStream())
                    {
                        formatter.Serialize(stream, value);
                        stream.Position = 0;
                        var bytes = stream.ToArray();
                        var array = new NSMutableArray();
                        foreach (var b in bytes)
                        {
                            array.Add(NSNumber.FromByte(b));
                        }

                        bundle.Add(new NSString(kv.Key), array);
                    }
                }
            }
        }
		/// <summary>
		/// Navigates the Webview to the given URL string.
		/// </summary>
		/// <param name="url">URL.</param>
		private void NavigateToURL(string url) {

			// Properly formatted?
			if (!url.StartsWith ("http://")) {
				// Add web
				url = "http://" + url;
			}

			// Display the give webpage
			WebView.LoadRequest(new NSUrlRequest(NSUrl.FromString(url)));

			// Invalidate existing Activity
			if (UserActivity != null) {
				UserActivity.Invalidate();
				UserActivity = null;
			}

			// Create a new user Activity to support this tab
			UserActivity = new NSUserActivity (ThisApp.UserActivityTab4);
			UserActivity.Title = "Coffee Break Tab";

			// Update the activity when the tab's URL changes
			var userInfo = new NSMutableDictionary ();
			userInfo.Add (new NSString ("Url"), new NSString (url));
			UserActivity.AddUserInfoEntries (userInfo);

			// Inform Activity that it has been updated
			UserActivity.BecomeCurrent ();

			// Log User Activity
			Console.WriteLine ("Creating User Activity: {0} - {1}", UserActivity.Title, url);
		}
		public CMMemoryPool (TimeSpan ageOutPeriod)
		{
			using (var dict = new NSMutableDictionary ()) {
				dict.LowlevelSetObject (AgeOutPeriodSelector, new NSNumber (ageOutPeriod.TotalSeconds).Handle);
				handle = CMMemoryPoolCreate (dict.Handle);
			}
		}
        /// <inheritdoc/>
        public ICryptographicKey CreateKeyPair(int keySize)
        {
            Requires.Range(keySize > 0, "keySize");

            string keyIdentifier = Guid.NewGuid().ToString();
            string publicKeyIdentifier = RsaCryptographicKey.GetPublicKeyIdentifierWithTag(keyIdentifier);
            string privateKeyIdentifier = RsaCryptographicKey.GetPrivateKeyIdentifierWithTag(keyIdentifier);

            // Configure parameters for the joint keypair.
            var keyPairAttr = new NSMutableDictionary();
            keyPairAttr[KSec.AttrKeyType] = KSec.AttrKeyTypeRSA;
            keyPairAttr[KSec.AttrKeySizeInBits] = NSNumber.FromInt32(keySize);

            // Configure parameters for the private key
            var privateKeyAttr = new NSMutableDictionary();
            privateKeyAttr[KSec.AttrIsPermanent] = NSNumber.FromBoolean(true);
            privateKeyAttr[KSec.AttrApplicationTag] = NSData.FromString(privateKeyIdentifier, NSStringEncoding.UTF8);

            // Configure parameters for the public key
            var publicKeyAttr = new NSMutableDictionary();
            publicKeyAttr[KSec.AttrIsPermanent] = NSNumber.FromBoolean(true);
            publicKeyAttr[KSec.AttrApplicationTag] = NSData.FromString(publicKeyIdentifier, NSStringEncoding.UTF8);

            // Parent the individual key parameters to the keypair one.
            keyPairAttr[KSec.PublicKeyAttrs] = publicKeyAttr;
            keyPairAttr[KSec.PrivateKeyAttrs] = privateKeyAttr;

            // Generate the RSA key.
            SecKey publicKey, privateKey;
            SecStatusCode code = SecKey.GenerateKeyPair(keyPairAttr, out publicKey, out privateKey);
            Verify.Operation(code == SecStatusCode.Success, "status was " + code);

            return new RsaCryptographicKey(publicKey, privateKey, keyIdentifier, this.algorithm);
        }
Example #5
0
 public void logEvent (string eventName, object[] args) {
   if (args.Length == 0) {
     try {
       FA.Flurry.LogEvent(eventName);
     } catch (Exception e) {
       PlayN.log().warn("Failed to log event to Flurry [event=" + eventName + "]", e);
     }
   } else {
     var dict = new NSMutableDictionary();
     for (int ii = 0; ii < args.Length; ii += 2) {
       var key = (string)args[ii];
       var value = args[ii+1];
       if (value is string) {
         dict.Add(new NSString(key), new NSString((string)value));
       } else if (value is java.lang.Boolean) {
         dict.Add(new NSString(key), new NSNumber(((java.lang.Boolean)value).booleanValue()));
       } else if (value is java.lang.Integer) {
         dict.Add(new NSString(key), new NSNumber(((java.lang.Integer)value).intValue()));
       } else {
         var vclass = (value == null) ? "null" : value.GetType().ToString();
         PlayN.log().warn("Got unknown Flurry event parameter type [key=" + key +
                          ", value=" + value + ", vclass=" + vclass + "]");
       }
     }
     try {
       FA.Flurry.LogEvent(eventName, dict);
     } catch (Exception e) {
       PlayN.log().warn("Failed to log event to Flurry [event=" + eventName +
                        ", argCount=" + args.Length + "]", e);
     }
   }
 }
Example #6
0
        internal NSDictionary ToDictionary()
        {
            int n = 0;
            if (Enhance.HasValue && Enhance.Value == false)
                n++;
            if (RedEye.HasValue && RedEye.Value == false)
                n++;
            if (ImageOrientation.HasValue)
                n++;
            if (Features != null && Features.Length != 0)
                n++;
            if (n == 0)
                return null;

            NSMutableDictionary dict = new NSMutableDictionary ();

            if (Enhance.HasValue && Enhance.Value == false){
                dict.LowlevelSetObject (CFBoolean.False.Handle, CIImage.AutoAdjustEnhanceKey.Handle);
            }
            if (RedEye.HasValue && RedEye.Value == false){
                dict.LowlevelSetObject (CFBoolean.False.Handle, CIImage.AutoAdjustRedEyeKey.Handle);
            }
            if (Features != null && Features.Length != 0){
                dict.LowlevelSetObject (NSArray.FromObjects (Features), CIImage.AutoAdjustFeaturesKey.Handle);
            }
            if (ImageOrientation.HasValue){
                dict.LowlevelSetObject (new NSNumber ((int)ImageOrientation.Value), CIImage.ImagePropertyOrientation.Handle);
            }
            #if false
            for (i = 0; i < n; i++){
                Console.WriteLine ("{0} {1}-{2}", i, keys [i], values [i]);
            }
            #endif
            return dict;
        }
        public void SetupLiveCameraStream()
        {
            captureSession = new AVCaptureSession();

            var viewLayer = liveCameraStream.Layer;

            Console.WriteLine(viewLayer.Frame.Width);

            var videoPreviewLayer = new AVCaptureVideoPreviewLayer(captureSession)
            {
                Frame = liveCameraStream.Bounds
            };
            liveCameraStream.Layer.AddSublayer(videoPreviewLayer);

            Console.WriteLine(liveCameraStream.Layer.Frame.Width);

            var captureDevice = AVCaptureDevice.DefaultDeviceWithMediaType(AVMediaType.Video);
            ConfigureCameraForDevice(captureDevice);
            captureDeviceInput = AVCaptureDeviceInput.FromDevice(captureDevice);

            var dictionary = new NSMutableDictionary();
            dictionary[AVVideo.CodecKey] = new NSNumber((int)AVVideoCodec.JPEG);
            stillImageOutput = new AVCaptureStillImageOutput()
            {
                OutputSettings = new NSDictionary()
            };

            captureSession.AddOutput(stillImageOutput);
            captureSession.AddInput(captureDeviceInput);
            captureSession.StartRunning();

            ViewWillLayoutSubviews();
        }
        public void AddBeerToIndex(Beer beer)
        {
            var activity = new NSUserActivity("com.micjames.beerdrinkin.beerdetails");

            if (!string.IsNullOrEmpty(beer.Description))
            {
                var info = new NSMutableDictionary();
                info.Add(new NSString("name"), new NSString(beer.Name));
                info.Add(new NSString("description"), new NSString(beer.Description));

                if (beer?.Image?.MediumUrl != null)
                {
                    info.Add(new NSString("imageUrl"), new NSString(beer.Image.LargeUrl));
                }

                var attributes = new CSSearchableItemAttributeSet();
                attributes.DisplayName = beer.Name;
                attributes.ContentDescription = beer.Description;

                var keywords = new NSString[] { new NSString(beer.Name), new NSString("beerName") };
                activity.Keywords = new NSSet<NSString>(keywords);
                activity.ContentAttributeSet = attributes;

                activity.Title = beer.Name;
                activity.UserInfo = info;

                activity.EligibleForSearch = true;
                activity.EligibleForPublicIndexing = true;
                activity.BecomeCurrent();
            }

        }
Example #9
0
        public WarningWindow()
        {
            // Interface Builder won't allow us to create a window with no title bar
            // so we have to create it manually. But we could use IB if we display
            // the window with a sheet...
            NSRect rect = new NSRect(0, 0, 460, 105);
            m_window = NSWindow.Alloc().initWithContentRect_styleMask_backing_defer(rect, 0, Enums.NSBackingStoreBuffered, false);

            m_window.setHasShadow(false);

            // Initialize the text attributes.
            var dict = NSMutableDictionary.Create();

            NSFont font = NSFont.fontWithName_size(NSString.Create("Georgia"), 64.0f);
            dict.setObject_forKey(font, Externs.NSFontAttributeName);

            NSMutableParagraphStyle style = NSMutableParagraphStyle.Create();
            style.setAlignment(Enums.NSCenterTextAlignment);
            dict.setObject_forKey(style, Externs.NSParagraphStyleAttributeName);

            m_attrs = dict.Retain();

            // Initialize the background bezier.
            m_background = NSBezierPath.Create().Retain();
            m_background.appendBezierPathWithRoundedRect_xRadius_yRadius(m_window.contentView().bounds(), 20.0f, 20.0f);

            m_color = NSColor.colorWithDeviceRed_green_blue_alpha(250/255.0f, 128/255.0f, 114/255.0f, 1.0f).Retain();

            ActiveObjects.Add(this);
        }
        public static Dictionary<String, Object> ConvertToDictionary(NSMutableDictionary dictionary)
        {
            Dictionary<String,Object> prunedDictionary = new Dictionary<String,Object>();
            foreach (NSString key in dictionary.Keys) {
                NSObject dicValue = dictionary.ObjectForKey(key);

                if (dicValue is NSDictionary) {
                    prunedDictionary.Add (key.ToString(), ConvertToDictionary(new NSMutableDictionary(dicValue as NSDictionary)));
                } else {
                    //SystemLogger.Log(SystemLogger.Module.PLATFORM, "***** key["+key.ToString ()+"] is instance of: " + dicValue.GetType().FullName);
                    if ( ! (dicValue is NSNull)) {
                        if(dicValue is NSString) {
                            prunedDictionary.Add (key.ToString(), ((NSString)dicValue).Description);
                        } else if(dicValue is NSNumber) {
                            prunedDictionary.Add (key.ToString(), ((NSNumber)dicValue).Int16Value);
                        } else if(dicValue is NSArray) {
                            prunedDictionary.Add (key.ToString(), ConvertToArray((NSArray)dicValue));
                        } else {
                            prunedDictionary.Add (key.ToString(), dicValue);
                        }
                    }
                }
            }
            return prunedDictionary;
        }
			public TwitterRequest (string method, Uri url, IDictionary<string, string> paramters, Account account)
				: base (method, url, paramters, account)
			{
				var ps = new NSMutableDictionary ();
				if (paramters != null) {
					foreach (var p in paramters) {
						ps.SetValueForKey (new NSString (p.Value), new NSString (p.Key));
					}
				}

				var m = TWRequestMethod.Get;
				switch (method.ToLowerInvariant()) {
				case "get":
					m = TWRequestMethod.Get;
					break;
				case "post":
					m = TWRequestMethod.Post;
					break;
				case "delete":
					m = TWRequestMethod.Delete;
					break;
				default:
					throw new NotSupportedException ("Twitter does not support the HTTP method '" + method + "'");
				}

				request = new TWRequest (new NSUrl (url.AbsoluteUri), ps, m);

				Account = account;
			}
Example #12
0
        /// <summary>Sets custom options</summary>
        /// <param name="options">Option mask containing the options you want to set. Available 
        /// options are described 
        /// below at Options enum</param>
        public static void SetOptions(Options options, bool bValue = true)
        {
            var optionsDict = new NSMutableDictionary();
            var strValue = bValue ? new NSString("YES") : new NSString("NO");

            if ((options & Options.DisableAutoDeviceIdentifying) == 0 && isFirstTime) {
                TestFlight.SetDeviceIdentifier(UIDevice.CurrentDevice.UniqueIdentifier);
                isFirstTime = false;
            }

            if ((options & Options.AttachBacktraceToFeedback) != 0) {
                optionsDict.Add (strValue, OptionKeys.AttachBacktraceToFeedback);
            }
            if ((options & Options.DisableInAppUpdates) != 0) {
                optionsDict.Add (strValue, OptionKeys.DisableInAppUpdates);
            }
            if ((options & Options.LogToConsole) != 0) {
                optionsDict.Add (strValue, OptionKeys.LogToSTDERR);
            }
            if ((options & Options.LogToSTDERR) != 0) {
                optionsDict.Add (strValue, OptionKeys.ReinstallCrashHandlers);
            }
            if ((options & Options.SendLogOnlyOnCrash) != 0) {
                optionsDict.Add (strValue, OptionKeys.SendLogOnlyOnCrash);
            }

            TestFlight.SetOptionsRaw(optionsDict);
        }
Example #13
0
		public static void RegisterDefaultSettings ()
		{
			var path = Path.Combine(NSBundle.MainBundle.PathForResource("Settings", "bundle"), "Root.plist");

			using (NSString keyString = new NSString ("Key"), defaultString = new NSString ("DefaultValue"), preferenceSpecifiers = new NSString ("PreferenceSpecifiers"))
			using (var settings = NSDictionary.FromFile(path))
			using (var preferences = (NSArray)settings.ValueForKey(preferenceSpecifiers))
			using (var registrationDictionary = new NSMutableDictionary ()) {
				for (nuint i = 0; i < preferences.Count; i++)
					using (var prefSpecification = preferences.GetItem<NSDictionary>(i))
					using (var key = (NSString)prefSpecification.ValueForKey(keyString))
						if (key != null)
							using (var def = prefSpecification.ValueForKey(defaultString))
								if (def != null)
									registrationDictionary.SetValueForKey(def, key);

				NSUserDefaults.StandardUserDefaults.RegisterDefaults(registrationDictionary);

				#if DEBUG
				SetSetting(SettingsKeys.UserReferenceKey, debugReferenceKey);
				#else
				SetSetting(SettingsKeys.UserReferenceKey, UIDevice.CurrentDevice.IdentifierForVendor.AsString());
				#endif

				Synchronize();
			}
		}
Example #14
0
		public override async void HandleWatchKitExtensionRequest
	   (UIApplication application, NSDictionary userInfo, Action<NSDictionary> reply)
		{
			if (userInfo.Values[0].ToString() == "gettasks")
			{
				string userId = NSUserDefaults.StandardUserDefaults.StringForKey("UserId");

				List<CrmTask> tasks = await GetCrmTasks(userId);

				var nativeDict = new NSMutableDictionary();
				foreach (CrmTask task in tasks)
				{
					nativeDict.Add((NSString)task.TaskId, (NSString)task.Subject);
				}

				reply(new NSDictionary(
					"count", NSNumber.FromInt32(tasks.Count),
					"tasks", nativeDict
					));
			}
			else if (userInfo.Values[0].ToString() == "closetask")
			{
				string taskId = userInfo.Values[1].ToString();
				CloseTask(taskId);

				reply(new NSDictionary(
					"count", 0,
					"something", 0
					));
			}
		}
Example #15
0
		internal NSDictionary ToDictionary ()
		{
			var ret = new NSMutableDictionary ();

			if (AffineMatrix.HasValue){
				var a = AffineMatrix.Value;
				var affine = new NSNumber [6];
				affine [0] = NSNumber.FromFloat (a.xx);
				affine [1] = NSNumber.FromFloat (a.yx);
				affine [2] = NSNumber.FromFloat (a.xy);
				affine [3] = NSNumber.FromFloat (a.yy);
				affine [4] = NSNumber.FromFloat (a.x0);
				affine [5] = NSNumber.FromFloat (a.y0);
				ret.SetObject (NSArray.FromNSObjects (affine), CISampler.AffineMatrix);
			}
			if (WrapMode.HasValue){
				var k = WrapMode.Value == CIWrapMode.Black ? CISampler.WrapBlack : CISampler.FilterNearest;
				ret.SetObject (k, CISampler.WrapMode);
			}
			if (FilterMode.HasValue){
				var k = FilterMode.Value == CIFilterMode.Nearest ? CISampler.FilterNearest : CISampler.FilterLinear;
				ret.SetObject (k, CISampler.FilterMode);
			}
			return ret;
		}
Example #16
0
 // These are the prefs associated with the app's preferences panel
 // (DirectoryController handles the prefs associated with a directory).
 // Note that we don't include the standard user targets. See:
 // http://www.gnu.org/software/automake/manual/standards/Standard-Targets.html#Standard-Targets
 private void DoInitPrefs(NSMutableDictionary dict)
 {
     string ignores = @"all-am
     am--refresh
     bin
     check-am
     clean-am
     clean-generic
     clean-libtool
     ctags-recursive
     ctags
     CTAGS
     distclean-am
     distclean-generic
     distclean-tags
     distdir
     dist-bzip2
     dist-gzip
     dist-hook
     dist-lzma
     dist-shar
     dist-tarZ
     dist-zip
     distclean-hdr
     distclean-libtool
     dvi-am
     extra-bin
     GTAGS
     ID
     info-am
     install-am
     install-binSCRIPTS
     install-data-am
     install-data
     install-exec-am
     install-exec
     install-pixmapDATA
     installcheck-am
     installdirs-am
     maintainer-clean-am
     maintainer-clean-generic
     maintainer-clean-recursive
     Makefile
     mostlyclean-am
     mostlyclean-generic
     mostlyclean-libtool
     pdf-am
     push
     ps-am
     stamp-h1
     tags-recursive
     uninstall-am
     uninstall-binSCRIPTS
     uninstall-info-am
     uninstall-info
     uninstall-pixmapDATA
     zip-bin";
     dict.setObject_forKey(NSString.Create(ignores), NSString.Create("globalIgnores"));
 }
		// Shared initialization code
		void Initialize ()
		{
			repeatCount = 1;

			var font = NSFont.UserFixedPitchFontOfSize (16);
			textAttrs = new NSMutableDictionary ();
			textAttrs.SetValueForKey (font, NSAttributedString.FontAttributeName);
		}
		public void submitAchievement(string identifier, double percentComplete, string achievementName)
		{
			if(earnedAchievementCache == null)
			{
				GKAchievement.LoadAchievements (new GKCompletionHandler (delegate(GKAchievement[] achievements, NSError error) {
					NSMutableDictionary tempCache = new NSMutableDictionary();
					if(achievements !=null)
					{
						foreach(var achievement in achievements)
						{
							tempCache.Add(new NSString(achievement.Identifier), achievement);
						}
					}
					earnedAchievementCache = tempCache;
					submitAchievement(identifier,percentComplete,achievementName);
				}));
			}
			else
			{
				GKAchievement achievement =(GKAchievement) earnedAchievementCache.ValueForKey (new NSString(identifier));
				if (achievement != null)
				{

					if (achievement.PercentComplete >= 100.0 || achievement.PercentComplete >= percentComplete) 
					{
						achievement = null;
					}
					else
						achievement.PercentComplete = percentComplete;
				}
				else
				{
					achievement = new GKAchievement(identifier);
					achievement.PercentComplete = percentComplete;
					earnedAchievementCache.Add(new NSString(achievement.Identifier),achievement);
				}
				if(achievement != null)
				{
					achievement.ReportAchievement (new GKNotificationHandler (delegate(NSError error) {
						if(error == null && achievement != null)
						{
							if(percentComplete == 100)
							{
								new UIAlertView ("Achievement Earned", "Great job!  You earned an achievement: " + achievementName, null, "OK", null).Show ();
							}
							else if(percentComplete >0)
							{
								new UIAlertView ("Achievement Progress", "Great job!  You're "+percentComplete+" % of the way to " + achievementName, null, "OK", null).Show ();
							}
						}
						else
						{
							new UIAlertView ("Achievement submittion failed", "Submittion failed because: " + error, null, "OK", null).Show ();
						}
					}));
				}
			}
		}
		//========================================================================================================================================
		//  PUBLIC CLASS PROPERTIES
		//========================================================================================================================================
		//========================================================================================================================================
		//  Constructor
		//========================================================================================================================================
		/// <summary>
		/// Initializes a new instance of the <see cref="TableViewSource"/> class.
		/// </summary>
		public TableViewSource ()
		{
			this.dpc = new DatePickerCell ();
			this.dsc = new DateShowerCell ();
			dpc.didUpdateDatePicker += dsc.updateCellText;
			heightAtIndexPath = new Foundation.NSMutableDictionary ();
			this.showDatePicker = false;
			numRows = 2;
		}
		//public bool? ProtectedFile { get; set; }
		
		internal NSDictionary ToDictionary ()
		{
			var dict = new NSMutableDictionary ();
			if (AppendOnly.HasValue)
				dict.SetObject (NSNumber.FromBoolean (AppendOnly.Value), NSFileManager.AppendOnly);
			if (Busy.HasValue)
				dict.SetObject (NSNumber.FromBoolean (Busy.Value), NSFileManager.Busy);
			if (CreationDate != null)
				dict.SetObject (CreationDate, NSFileManager.CreationDate);
			if (ModificationDate != null)
				dict.SetObject (ModificationDate, NSFileManager.ModificationDate);
			if (OwnerAccountName != null)
				dict.SetObject (new NSString (OwnerAccountName), NSFileManager.OwnerAccountName);
			if (DeviceIdentifier.HasValue)
				dict.SetObject (NSNumber.FromUInt32 (DeviceIdentifier.Value), NSFileManager.DeviceIdentifier);
			if (FileExtensionHidden.HasValue)
				dict.SetObject (NSNumber.FromBoolean (FileExtensionHidden.Value), NSFileManager.ExtensionHidden);
			if (FileGroupOwnerAccountID.HasValue)
				dict.SetObject (NSNumber.FromUInt32 (FileGroupOwnerAccountID.Value), NSFileManager.GroupOwnerAccountID);
			if (FileOwnerAccountID.HasValue)
				dict.SetObject (NSNumber.FromUInt32 (FileOwnerAccountID.Value), NSFileManager.OwnerAccountID);
			if (HfsTypeCode.HasValue)
				dict.SetObject (NSNumber.FromUInt32 (HfsTypeCode.Value), NSFileManager.HfsTypeCode);
			if (PosixPermissions.HasValue)
				dict.SetObject (NSNumber.FromUInt32 (PosixPermissions.Value), NSFileManager.PosixPermissions);
			if (FileReferenceCount.HasValue)
				dict.SetObject (NSNumber.FromUInt32 (FileReferenceCount.Value), NSFileManager.ReferenceCount);
			if (FileSystemFileNumber.HasValue)
				dict.SetObject (NSNumber.FromUInt32 (FileSystemFileNumber.Value), NSFileManager.SystemFileNumber);
			if (FileSize.HasValue)
				dict.SetObject (NSNumber.FromUInt64 (FileSize.Value), NSFileManager.Size);
			if (Immutable.HasValue)
				dict.SetObject (NSNumber.FromBoolean (Immutable.Value), NSFileManager.Immutable);
			//if (ProtectedFile.HasValue)
			//dict.SetObject (NSNumber.FromBoolean (ProtectedFile.Value), NSFileManager.ProtectedFile);
			if (FileType.HasValue){
				NSString v = null;
				switch (FileType.Value){
				case NSFileType.Directory:
					v = NSFileManager.TypeDirectory; break;
				case NSFileType.Regular:
					v = NSFileManager.TypeRegular; break;
				case NSFileType.SymbolicLink:
					v = NSFileManager.TypeSymbolicLink; break;
				case NSFileType.Socket:
					v = NSFileManager.TypeSocket; break;
				case NSFileType.CharacterSpecial:
					v = NSFileManager.TypeCharacterSpecial; break;
				case NSFileType.BlockSpecial:
					v = NSFileManager.TypeBlockSpecial; break;
				default:
					v = NSFileManager.TypeUnknown; break;
				}
				dict.SetObject (v, NSFileManager.NSFileType);
			}
			return dict;
		}
        /// <summary>
        /// Creates an instance of the PDF viewer.
        /// </summary>
        /// <returns>
        /// The PDF viewer.
        /// </returns>
        /// <param name='sFilename'>
        /// Name of the PDF to open.
        /// </param>
        /// <param name='iInitialPage'>
        /// The initial pae number to go to.
        /// </param>
        /// <param name='bAllowsPrinting'>
        /// True to enable the print menu.
        /// </param>
        /// <param name='bAllowsExport'>
        /// True to allow exporting the document to other apps.
        /// </param>
        public static PSPDFViewController CreatePDFViewer(string sFilename, uint iInitialPage, bool bAllowsPrinting, bool bAllowsExport)
        {
            // Use PSPDFKit to view PDFs.
            var document = new PSPDFKitDocument(NSUrl.FromFilename(sFilename), bAllowsExport && bAllowsPrinting, bAllowsExport && bAllowsPrinting);

            var oClassDic = new NSMutableDictionary();
            //oClassDic [new NSString("PSPDFFileAnnotationProvider")] = new NSString("CustomFileAnnnotationsProvider");
            oClassDic.LowlevelSetObject(new Class(typeof(CustomFileAnnnotationsProvider)).Handle, new Class(typeof(PSPDFFileAnnotationProvider)).Handle);
            document.OverrideClassNames = oClassDic;

            // Read PDF properties from config.
            PSPDFPageTransition ePageTransition = PSPDFPageTransition.Curl;
            PSPDFPageMode ePageMode = PSPDFPageMode.Automatic;
            PSPDFScrollDirection eScrollDirection = PSPDFScrollDirection.Horizontal;

            var oPdfViewer = new PSPDFViewController(document)
            {
                ModalPresentationStyle = MonoTouch.UIKit.UIModalPresentationStyle.FullScreen,
                ModalTransitionStyle = MonoTouch.UIKit.UIModalTransitionStyle.CoverVertical,
                LinkAction = PSPDFLinkAction.OpenSafari,
                PageTransition = ePageTransition,
                PageMode = ePageMode,
                ScrollDirection = eScrollDirection,
                RenderAnnotationTypes = PSPDFAnnotationType.Highlight | PSPDFAnnotationType.Ink | PSPDFAnnotationType.Note | PSPDFAnnotationType.Text | PSPDFAnnotationType.Link,
                Delegate = new PSPDFKitViewControllerDelegate()
            };

            var oControllerClassDic = new NSMutableDictionary();
            oControllerClassDic.LowlevelSetObject(new Class(typeof(CustomNoteAnnotationController)).Handle, new Class(typeof(PSPDFNoteAnnotationController)).Handle);
            oControllerClassDic.LowlevelSetObject(new Class(typeof(CustomLinkAnnotationView)).Handle, new Class(typeof(PSPDFLinkAnnotationView)).Handle);
            oPdfViewer.OverrideClassNames = oControllerClassDic;

            List<PSPDFBarButtonItem> aButtons = new List<PSPDFBarButtonItem>()
            {
                oPdfViewer.AnnotationButtonItem,
                oPdfViewer.BookmarkButtonItem,
                oPdfViewer.SearchButtonItem,
                oPdfViewer.OutlineButtonItem
            };

            if(bAllowsPrinting && bAllowsExport)
            {
                //aButtons.Add(this.oPdfViewer.EmailButtonItem);
                aButtons.Add(oPdfViewer.PrintButtonItem);
                aButtons.Add(oPdfViewer.OpenInButtonItem);
            }

            aButtons.Add(oPdfViewer.ViewModeButtonItem);

            oPdfViewer.RightBarButtonItems = aButtons.ToArray();
            aButtons = null;

            oPdfViewer.SetPageAnimated(iInitialPage, false);

            return oPdfViewer;
        }
Example #22
0
		protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
		{
			if (e.PropertyName.Equals("Text") && Control != null)
			{
				// http://forums.xamarin.com/discussion/15530/nsattributedstringdocumentattributes-exception-on-ios-6

				NSParagraphStyle ps = NSParagraphStyle.Default;

				NSDictionary dict = new NSMutableDictionary() { {
						UIStringAttributeKey.Font,
						((ExtendedLabel)Element).Font.ToUIFont()
					},
				};

				var attr = new NSAttributedStringDocumentAttributes(dict);
				var nsError = new NSError();

				// This line announces, that content is html.
				attr.DocumentType = NSDocumentType.HTML;
				attr.StringEncoding = NSStringEncoding.UTF8;

				var html = ((ExtendedLabel)Element).TextExt + Environment.NewLine;

				NSString htmlString = new NSString(html); 
				NSData htmlData = htmlString.Encode(NSStringEncoding.UTF8); 

				NSAttributedString attrStr = new NSAttributedString(htmlData, attr, out dict, ref nsError);

				Control.AttributedText = attrStr;
				Control.SizeToFit();
				Control.SetNeedsLayout();

				Element.HeightRequest = Control.Bounds.Height;

				return;
			}

			if (e.PropertyName == "Height" || e.PropertyName == "Width")
			{
				// We calculate the correct height, because of the attributed string, Xamarin.Forms don't do it correct
				var width = (float)((ExtendedLabel)Element).Width;

				// Only do this, if we have a valid width
				if (width != -1)
				{
					var rect = Control.AttributedText.GetBoundingRect(new CoreGraphics.CGSize(width, float.MaxValue), NSStringDrawingOptions.UsesLineFragmentOrigin | NSStringDrawingOptions.UsesFontLeading, null);

					if (rect.Height != ((ExtendedLabel)Element).Height)
					{
						((ExtendedLabel)Element).HeightRequest = rect.Height;
					}
				}
			}

			base.OnElementPropertyChanged(sender, e);
		}
		public void ResetAchievement ()
		{
			earnedAchievementCache = null;
			GKAchievement.ResetAchivements (error => {
				if (error == null)
					new UIAlertView ("Achievement reset", "Achievement reset successfully", null, "OK", null).Show ();
				else
					new UIAlertView ("Reset failed", string.Format("Reset failed because: {0}", error), null, "OK", null).Show ();
			});
		}
		internal virtual NSMutableDictionary ToDictionary ()
		{
			var ret = new NSMutableDictionary ();
			Add (ret, kCGPDFContextMediaBox, MediaBox);
			Add (ret, kCGPDFContextCropBox, CropBox);
			Add (ret, kCGPDFContextBleedBox, BleedBox);
			Add (ret, kCGPDFContextTrimBox, TrimBox);
			Add (ret, kCGPDFContextArtBox, ArtBox);
			return ret;
		}
Example #25
0
 public void Add(NSScriptCommandArgumentDescription arg)
 {
     if (arg == null)
         throw new ArgumentNullException ("arg");
     if (Arguments == null)
         Arguments = new NSMutableDictionary ();
     using (var nsName = new NSString (arg.Name)) {
         Arguments.Add (nsName, arg.Dictionary);
     }
 }
		// On load, construct the CIRawFilter
		public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();

			var asset = Asset;
			if (asset == null)
				return;

			// Setup options to request original image.
			var options = new PHImageRequestOptions {
				Version = PHImageRequestOptionsVersion.Original,
				Synchronous = true
			};

			// Request the image data and UTI type for the image.
			PHImageManager.DefaultManager.RequestImageData (asset, options, (imageData, dataUTI, _, __) => {
				if (imageData == null || dataUTI == null)
					return;

				// Create a CIRawFilter from original image data.
				// UTI type is passed in to provide the CIRawFilter with a hint about the UTI type of the Raw file.
				//var rawOptions = [String (kCGImageSourceTypeIdentifierHint) : dataUTI ]
				var rawOptions = new NSMutableDictionary ();
				var imageIOLibrary = Dlfcn.dlopen ("/System/Library/Frameworks/ImageIO.framework/ImageIO", 0);
				var key = Dlfcn.GetIntPtr (imageIOLibrary, "kCGImageSourceTypeIdentifierHint");
				rawOptions.LowlevelSetObject (dataUTI, key);

				ciRawFilter = CIFilter.CreateRawFilter (imageData, rawOptions);
				if (ciRawFilter == null)
					return;

				// Get the native size of the image produced by the CIRawFilter.
				var sizeValue = ciRawFilter.ValueForKey (Keys.kCIOutputNativeSizeKey) as CIVector;
				if (sizeValue != null)
					imageNativeSize = new CGSize (sizeValue.X, sizeValue.Y);

				// Record the original value of the temperature, and setup the editing slider.
				var tempValue = (NSNumber)ciRawFilter.ValueForKey (Keys.kCIInputNeutralTemperatureKey);
				if (tempValue != null) {
					originalTemp = tempValue.FloatValue;
					TempSlider.SetValue (tempValue.FloatValue, animated: false);
				}

				// Record the original value of the tint, and setup the editing slider.
				var tintValue = (NSNumber)ciRawFilter.ValueForKey (Keys.kCIInputNeutralTintKey);
				if (tintValue != null) {
					originalTint = tintValue.FloatValue;
					TintSlider.SetValue (tintValue.FloatValue, animated: false);
				}
			});

			// Create EAGL context used to render the CIImage produced by the CIRawFilter to display.
			ImageView.Context = new EAGLContext (EAGLRenderingAPI.OpenGLES3);
			ciContext = CIContext.FromContext (ImageView.Context, new CIContextOptions { CIImageFormat = CIImage.FormatRGBAh });
		}
Example #27
0
		static public NSLayoutConstraint [] FromVisualFormat (string format, NSLayoutFormatOptions formatOptions, params object [] viewsAndMetrics)
		{
			NSMutableDictionary views = null, metrics = null;
			var count = viewsAndMetrics.Length;
			if (count != 0){
				if ((count % 2) != 0)
					throw new ArgumentException ("You should provide pairs and values, the parameter passed is not even", "viewsAndMetrics");

				for (int i = 0; i < count; i+=2){
					var key = viewsAndMetrics [i];
					NSString nskey;

					if (key is string)
						nskey = new NSString ((string)key);
					else if (key is NSString)
						nskey = (NSString) key;
					else 
						throw new ArgumentException (String.Format ("Item at {0} is not a string or an NSString", i), "viewsAndMetrics");
					
					var value = viewsAndMetrics [i+1];
					if (value is View){
						if (views == null)
							views = new NSMutableDictionary ();
						views [nskey] = (NSObject) value;
						continue;
					} else if (value is INativeObject && Messaging.bool_objc_msgSend_IntPtr (((INativeObject) value).Handle, Selector.GetHandle ("isKindOfClass:"), Class.GetHandle (typeof (View)))) {
						if (views == null)
							views = new NSMutableDictionary ();
						views.LowlevelSetObject (((INativeObject) value).Handle, nskey.Handle);
						continue;
					}
#if !MONOMAC
					// This requires UILayoutSupport class which is not exist on Mac
					else if (value is INativeObject && Messaging.bool_objc_msgSend_IntPtr (((INativeObject) value).Handle, Selector.GetHandle ("conformsToProtocol:"), Protocol.GetHandle (typeof (UILayoutSupport).Name))) {
						if (views == null)
							views = new NSMutableDictionary ();
						views.LowlevelSetObject (((INativeObject) value).Handle, nskey.Handle);
						continue;
					}
#endif // !MONOMAC

					var number = AsNumber (value);
					if (number == null)
						throw new ArgumentException (String.Format ("Item at {0} is not a number or a view", i+1), "viewsAndMetrics");
					if (metrics == null)
						metrics = new NSMutableDictionary ();
					metrics [nskey] = number;
				}
			}
			if (views == null)
				throw new ArgumentException ("You should at least provide a pair of name, view", "viewAndMetrics");
			
			return FromVisualFormat (format, formatOptions, metrics, views);
		}
Example #28
0
 public NSDictionary ToDictionary()
 {
     var dict = new NSMutableDictionary ();
     if (CodecType != null)
         dict.SetObject (new NSString (CodecType), QTMovie.ImageCodecType);
     if (Quality.HasValue)
         dict.SetObject (NSNumber.FromInt32 ((int) Quality.Value), QTMovie.ImageCodecQuality);
     if (TimeScale.HasValue)
         dict.SetObject (NSNumber.FromInt32 (TimeScale.Value), QTTrack.TimeScaleAttribute);
     return dict;
 }
Example #29
0
		public static CGRect GetBoundingRect (this NSString This, CGSize size, NSStringDrawingOptions options, UIStringAttributes attributes, NSStringDrawingContext context)
		{
			// Define attributes
			var attr = new NSMutableDictionary ();
			attr.Add (NSFont.NameAttribute, attributes.Font.NSFont);

			var rect = This.BoundingRectWithSize (size, options, attr);

			// HACK: Cheating on the height
			return new CGRect(rect.Left, rect.Top , rect.Width, rect.Height * 1.5f);
		}
		// received response to RequestProductData - with price,title,description info
		public override void ReceivedResponse (SKProductsRequest request, SKProductsResponse response)
		{
			SKProduct[] products = response.Products;

			NSMutableDictionary userInfo = new NSMutableDictionary ();
			for (int i = 0; i < products.Length; i++)
				userInfo.Add ((NSString)products [i].ProductIdentifier, products [i]);
			NSNotificationCenter.DefaultCenter.PostNotificationName (InAppPurchaseManagerProductsFetchedNotification, this, userInfo);

			foreach (string invalidProductId in response.InvalidProducts)
				Console.WriteLine ("Invalid product id: {0}", invalidProductId);
		}
Example #31
0
        public void StartDownload(NSUrlSession session, bool allowsCellularAccess)
        {
            using (var downloadUrl = NSUrl.FromString(Url))
                using (var request = new NSMutableUrlRequest(downloadUrl)) {
                    if (Headers != null)
                    {
                        var headers = new NSMutableDictionary();
                        foreach (var header in Headers)
                        {
                            headers.SetValueForKey(
                                new NSString(header.Value),
                                new NSString(header.Key)
                                );
                        }
                        request.Headers = headers;
                    }

                    request.AllowsCellularAccess = allowsCellularAccess;

                    Task = session.CreateDownloadTask(request);
                    Task.Resume();
                }
        }
        public static SecStatusCode GenerateKeyPair(SecKeyType type, int keySizeInBits, SecPublicPrivateKeyAttrs publicKeyAttrs, SecPublicPrivateKeyAttrs privateKeyAttrs, out SecKey publicKey, out SecKey privateKey)
        {
            if (type == SecKeyType.Invalid)
            {
                throw new ArgumentException("invalid 'SecKeyType'", nameof(type));
            }

            using (var dic = new NSMutableDictionary()) {
                dic.LowlevelSetObject(type.GetConstant(), SecAttributeKey.Type);
                using (var ksib = new NSNumber(keySizeInBits)) {
                    dic.LowlevelSetObject(ksib, SecKeyGenerationAttributeKeys.KeySizeInBitsKey.Handle);
                    if (publicKeyAttrs != null)
                    {
                        dic.LowlevelSetObject(publicKeyAttrs.GetDictionary(), SecKeyGenerationAttributeKeys.PublicKeyAttrsKey.Handle);
                    }
                    if (privateKeyAttrs != null)
                    {
                        dic.LowlevelSetObject(privateKeyAttrs.GetDictionary(), SecKeyGenerationAttributeKeys.PrivateKeyAttrsKey.Handle);
                    }
                    return(GenerateKeyPair(dic, out publicKey, out privateKey));
                }
            }
        }
Example #33
0
            public TwitterRequest(string method, Uri url, IDictionary <string, string> paramters, Account account)
                : base(method, url, paramters, account)
            {
                var ps = new NSMutableDictionary();

                if (paramters != null)
                {
                    foreach (var p in paramters)
                    {
                        ps.SetValueForKey(new NSString(p.Value), new NSString(p.Key));
                    }
                }

                var m = TWRequestMethod.Get;

                switch (method.ToLowerInvariant())
                {
                case "get":
                    m = TWRequestMethod.Get;
                    break;

                case "post":
                    m = TWRequestMethod.Post;
                    break;

                case "delete":
                    m = TWRequestMethod.Delete;
                    break;

                default:
                    throw new NotSupportedException("Twitter does not support the HTTP method '" + method + "'");
                }

                request = new TWRequest(new NSUrl(url.AbsoluteUri), ps, m);

                Account = account;
            }
		public void XForY_Autorelease ()
		{
			using (var k = new NSString ("keyz")) 
				using (var v = new NSString ("valuez")) {
					var k1 = k.RetainCount;
					if (k1 >= int.MaxValue)
						Assert.Ignore ("RetainCount unusable for testing");
					var k2 = k1;
					Assert.That (k.RetainCount, Is.EqualTo ((nint) 1), "Key.RetainCount-a");
					var v1 = v.RetainCount;
					var v2 = v1;
					Assert.That (v.RetainCount, Is.EqualTo ((nint) 1), "Value.RetainCount-a");
					using (var d = new NSMutableDictionary<NSString, NSString> (k, v)) {
						k2 = k.RetainCount;
						Assert.That (k2, Is.GreaterThan (k1), "Key.RetainCount-b");
						v2 = v.RetainCount;
						Assert.That (v2, Is.GreaterThan (v1), "Value.RetainCount-b");

						var x = d.KeysForObject (v);
						Assert.That (x [0], Is.SameAs (k), "KeysForObject");

						var y = d.ObjectForKey (k);
						Assert.NotNull (y, "ObjectForKey");

						using (var a = new NSMutableArray ()) {
							a.Add (k);
							var z = d.ObjectsForKeys (a, k);
							Assert.That (z [0], Is.SameAs (v), "ObjectsForKeys");
						}

						Assert.That (k.RetainCount, Is.EqualTo (k2), "Key.RetainCount-c");
						Assert.That (v.RetainCount, Is.EqualTo (v2), "Value.RetainCount-c");
					}
					Assert.That (k.RetainCount, Is.LessThan (k2), "Key.RetainCount-d");
					Assert.That (v.RetainCount, Is.LessThan (v2), "Value.RetainCount-d");
				}
		}
Example #35
0
        public static NSDictionary GetPhotoLibraryMetadata(NSUrl url)
        {
            NSDictionary meta = null;

            var image          = PHAsset.FetchAssets(new NSUrl[] { url }, new PHFetchOptions()).firstObject as PHAsset;
            var imageManager   = PHImageManager.DefaultManager;
            var requestOptions = new PHImageRequestOptions
            {
                Synchronous          = true,
                NetworkAccessAllowed = true,
                DeliveryMode         = PHImageRequestOptionsDeliveryMode.HighQualityFormat,
            };

            imageManager.RequestImageData(image, requestOptions, (data, dataUti, orientation, info) =>
            {
                try
                {
                    var fullimage = CIImage.FromData(data);
                    if (fullimage?.Properties != null)
                    {
                        meta = new NSMutableDictionary();
                        meta[ImageIO.CGImageProperties.Orientation]    = new NSString(fullimage.Properties.Orientation.ToString());
                        meta[ImageIO.CGImageProperties.ExifDictionary] = fullimage.Properties.Exif?.Dictionary ?? new NSDictionary();
                        meta[ImageIO.CGImageProperties.TIFFDictionary] = fullimage.Properties.Tiff?.Dictionary ?? new NSDictionary();
                        meta[ImageIO.CGImageProperties.GPSDictionary]  = fullimage.Properties.Gps?.Dictionary ?? new NSDictionary();
                        meta[ImageIO.CGImageProperties.IPTCDictionary] = fullimage.Properties.Iptc?.Dictionary ?? new NSDictionary();
                        meta[ImageIO.CGImageProperties.JFIFDictionary] = fullimage.Properties.Jfif?.Dictionary ?? new NSDictionary();
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
            });

            return(meta);
        }
Example #36
0
        public void Save()
        {
            DocumentReference doc;
            var      user = Auth.DefaultInstance.CurrentUser;
            NSString meal = new NSString(this.Identifier);
            NSDictionary <NSString, NSObject> dictio;
            var mealDictionary = new NSMutableDictionary <NSString, NSObject>();

            var dishes = new NSMutableDictionary();

            for (int i = 0; i < this.Items.Count; i++)
            {
                dishes.Add(new NSString("" + (i + 1)), NSObject.FromObject(this.Items[i]));
            }

            if (this.DocumentId == String.Empty)
            {
                doc             = Firestore.SharedInstance.GetCollection(collection).CreateDocument();
                this.DocumentId = doc.Id;
                MainViewController.DocumentId = doc.Id;
                NSString userNS = new NSString(MealDocument.UserKey);
                NSString dateNS = new NSString(MealDocument.DateKey);
                mealDictionary.SetValueForKey(NSObject.FromObject(this.SourceDay), dateNS);
                mealDictionary.SetValueForKey(NSObject.FromObject(user.Uid), userNS);
                mealDictionary.SetValueForKey(dishes, meal);
                dictio = new NSDictionary <NSString, NSObject>(mealDictionary.Keys, mealDictionary.Values);
                doc.SetDataAsync(dictio);
            }
            else
            {
                doc = Firestore.SharedInstance.GetCollection(collection).GetDocument(this.DocumentId);
                mealDictionary.SetValueForKey(dishes, meal);
                var data = new Dictionary <object, object>();
                data.Add(this.Identifier, dishes);
                doc.UpdateDataAsync(data);
            }
        }
Example #37
0
        internal NSDictionary ToDictionary()
        {
            var ret = new NSMutableDictionary();

            if (AffineMatrix.HasValue)
            {
                var a      = AffineMatrix.Value;
                var affine = new NSNumber [6];
                                #if MAC64
                affine [0] = NSNumber.FromDouble(a.xx);
                affine [1] = NSNumber.FromDouble(a.yx);
                affine [2] = NSNumber.FromDouble(a.xy);
                affine [3] = NSNumber.FromDouble(a.yy);
                affine [4] = NSNumber.FromDouble(a.x0);
                affine [5] = NSNumber.FromDouble(a.y0);
                                #else
                affine [0] = NSNumber.FromFloat(a.xx);
                affine [1] = NSNumber.FromFloat(a.yx);
                affine [2] = NSNumber.FromFloat(a.xy);
                affine [3] = NSNumber.FromFloat(a.yy);
                affine [4] = NSNumber.FromFloat(a.x0);
                affine [5] = NSNumber.FromFloat(a.y0);
                                #endif
                ret.SetObject(NSArray.FromNSObjects(affine), CISampler.AffineMatrix);
            }
            if (WrapMode.HasValue)
            {
                var k = WrapMode.Value == CIWrapMode.Black ? CISampler.WrapBlack : CISampler.FilterNearest;
                ret.SetObject(k, CISampler.WrapMode);
            }
            if (FilterMode.HasValue)
            {
                var k = FilterMode.Value == CIFilterMode.Nearest ? CISampler.FilterNearest : CISampler.FilterLinear;
                ret.SetObject(k, CISampler.FilterMode);
            }
            return(ret);
        }
Example #38
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();
            // Perform any additional setup after loading the view, typically from a nib.
            var samplePlugin = new sample();

            _cdv = new CDVViewController();
            _cdv.Init();

            //_cdv.CommandDelegate = new CDVCommandDelegateImpl(_cdv);
            _cdv.RegisterPluginClassName(samplePlugin, "sample");
            _cdv.WwwFolderName = "www";
            _cdv.StartPage     = "index.html";

            var constraints = new [] { NSLayoutAttribute.Top, NSLayoutAttribute.Bottom, NSLayoutAttribute.Left, NSLayoutAttribute.Right }
            .Select(attr => NSLayoutConstraint.Create(_cdv.View, attr, NSLayoutRelation.Equal, View, attr, 1, 0)).ToArray();


            var maps   = _cdv.PluginsMap;
            var mapDic = new NSMutableDictionary(maps);

            mapDic.Add((NSString)"sample", (NSString)"sample");

            _cdv.PluginsMap = mapDic;

            var demo = _cdv.PluginObjects;

            //demo.Add((NSString)"sample", (NSString)"sample");

            demo.Add((NSString)"sample", samplePlugin);
            samplePlugin.PluginInitialize();
            samplePlugin.CommandDelegate = _cdv.CommandDelegate;


            Add(_cdv.View);
            View.AddConstraints(constraints);
        }
        public void IssueNotificationAsync(string title, string message, string id, string protocolId, bool alertUser, DisplayPage displayPage, TimeSpan delay, NSMutableDictionary info, Action <UNNotificationRequest> requestCreated = null)
        {
            if (info == null)
            {
                info = new NSMutableDictionary();
            }

            info.SetValueForKey(new NSString(id), new NSString(NOTIFICATION_ID_KEY));
            info.SetValueForKey(new NSString(displayPage.ToString()), new NSString(DISPLAY_PAGE_KEY));

            UNMutableNotificationContent content = new UNMutableNotificationContent
            {
                UserInfo = info
            };

            // the following properties are allowed to be null, but they cannot be set to null.

            if (!string.IsNullOrWhiteSpace(title))
            {
                content.Title = title;
            }

            if (!string.IsNullOrWhiteSpace(message))
            {
                content.Body = message;
            }

            // the following calculation isn't perfect because we use DateTime.Now and then use it again in the subsequent call to IssueNotificationAsync.
            // these two values will be slightly different due to execution time, but the risk is small:  the user might hear or not hear the notification
            // when it comes through, and it's very unlikely that the result will be incorrect.
            if (alertUser && !Protocol.TimeIsWithinAlertExclusionWindow(protocolId, (DateTime.Now + delay).TimeOfDay))
            {
                content.Sound = UNNotificationSound.Default;
            }

            IssueNotificationAsync(id, content, delay, requestCreated);
        }
Example #40
0
        public static NSAttributedString GetAttributedString(string s, char?hotKey = '&', Font font = null, ContentAlignment?alignment = null)
        {
            var attributes = new NSMutableDictionary();

            if (font != null)
            {
                attributes.Add(NSStringAttributeKey.Font, font.ToNSFont());
            }

            if (alignment.HasValue)
            {
                var style = new NSMutableParagraphStyle();
                style.Alignment = alignment.Value.ToNSTextAlignment();

                attributes.Add(NSStringAttributeKey.ParagraphStyle, style);
            }

            int hotKeyIndex = -1;

            if (hotKey.HasValue)
            {
                hotKeyIndex = s.IndexOf(hotKey.Value);
                if (hotKeyIndex != -1)
                {
                    s = s.Substring(0, hotKeyIndex) + s.Substring(1 + hotKeyIndex);
                }
            }

            var astr = new NSMutableAttributedString(s, attributes);

            if (hotKeyIndex != -1)
            {
                astr.AddAttribute(NSStringAttributeKey.UnderlineStyle, new NSNumber((int)NSUnderlineStyle.Single), new NSRange(hotKeyIndex, 1));
            }

            return(astr);
        }
        public void ClearQueue_Clears_QueuedHits()
        {
            // setup
            var   latch     = new CountdownEvent(1);
            nuint queueSize = 0;
            var   config    = new NSMutableDictionary <NSString, NSObject>
            {
                ["analytics.batchLimit"] = new NSNumber(5)
            };

            ACPCore.UpdateConfiguration(config);
            ACPCore.TrackAction("action", null);
            ACPCore.TrackAction("action", null);
            ACPCore.TrackAction("action", null);
            // test
            ACPAnalytics.GetQueueSize(callback =>
            {
                queueSize = callback;
                latch.Signal();
            });
            latch.Wait();
            latch.Dispose();
            // verify
            Assert.That(queueSize, Is.EqualTo(3));
            // test
            ACPAnalytics.ClearQueue();
            latch = new CountdownEvent(1);
            ACPAnalytics.GetQueueSize(callback =>
            {
                queueSize = callback;
                latch.Signal();
            });
            latch.Wait();
            latch.Dispose();
            // verify
            Assert.That(queueSize, Is.EqualTo(0));
        }
        public override bool OpenUrl(UIApplication application, NSUrl url, string sourceApplication, NSObject annotation)
        {
            if (url.Scheme.Equals("iosParking") || url.Scheme.Equals("iosparking"))
            {
                string[]            paramters    = url.Query.Split(new char[] { '&' }, 1000);
                NSMutableDictionary urlParamters = new NSMutableDictionary();

                foreach (string paramterValuePair in paramters)
                {
                    string[] arr = paramterValuePair.Split(new char[] { '=' }, 1000);
                    urlParamters.SetValueForKey(new NSString(arr [1]), new NSString(arr [0]));
                }

                NSString value = (NSString)urlParamters.ObjectForKey(new NSString("response"));
                if (value.Compare(new NSString("ok")) == NSComparisonResult.Same)
                {
                    //Show messaage saying that the payment was ok
                    Console.WriteLine("Payment OK");
                }
                else if (value.Compare(new NSString("cancel")) == NSComparisonResult.Same)
                {
                    //Show messaage saying that the payment was rejected by the user
                    Console.WriteLine("Payment Cancelled");
                }
                else
                {
                    //Here an error ocurred proccessing the payment
                    Console.WriteLine("Payment Error");
                }

                return(true);
            }
            else
            {
                return(false);
            }
        }
Example #43
0
        public override Task <RequestResult> SendTagsAsync(TagsBundle tags)
        {
            if (tags == null)
            {
                return(null);
            }
            var source = new TaskCompletionSource <RequestResult>();
            var dict   = tags.ToDictionary;
            NSMutableDictionary tagsDict = new NSMutableDictionary();

            foreach (var kv in dict)
            {
                if (kv.Value is Nullable <int> )
                {
                    tagsDict[kv.Key] = NSNumber.FromInt32((kv.Value as Nullable <int>).Value);
                }
                else if (kv.Value is string)
                {
                    tagsDict[kv.Key] = new NSString(kv.Value as string);
                }
                else if (kv.Value is TagsBundle.IncrementalInteger)
                {
                    tagsDict[kv.Key] = PWTags.IncrementalTagWithInteger((kv.Value as TagsBundle.IncrementalInteger).Value);
                }
                else if (kv.Value is IList <string> )
                {
                    tagsDict[kv.Key] = NSArray.FromNSObjects <string>((string arg) => new NSString(arg), (kv.Value as IList <string>).ToArray());
                }
            }
            nativeManager.SetTags(tagsDict, (NSError error) =>
            {
                source.SetResult(new RequestResult {
                    Error = ErrorFromNSError(error)
                });
            });
            return(source.Task);
        }
        private void LoadInternetContent()
        {
            if (Control == null || Element == null)
            {
                return;
            }

            var headers = new NSMutableDictionary();

            foreach (var header in Element.LocalRegisteredHeaders)
            {
                var key = new NSString(header.Key);
                if (!headers.ContainsKey(key))
                {
                    headers.Add(key, new NSString(header.Value));
                }
            }

            if (Element.EnableGlobalHeaders)
            {
                foreach (var header in HybridWebViewControl.GlobalRegisteredHeaders)
                {
                    var key = new NSString(header.Key);
                    if (!headers.ContainsKey(key))
                    {
                        headers.Add(key, new NSString(header.Value));
                    }
                }
            }
            var url     = new NSUrl(Element.Source);
            var request = new NSMutableUrlRequest(url)
            {
                Headers = headers
            };

            Control.LoadRequest(request);
        }
Example #45
0
        static async Task <ENExposureConfiguration> GetConfigurationAsync()
        {
            var c = await Handler.GetConfigurationAsync();

            var nc = new ENExposureConfiguration
            {
                AttenuationLevelValues           = c.AttenuationScores,
                DurationLevelValues              = c.DurationScores,
                DaysSinceLastExposureLevelValues = c.DaysSinceLastExposureScores,
                TransmissionRiskLevelValues      = c.TransmissionRiskScores,
                AttenuationWeight           = c.AttenuationWeight,
                DaysSinceLastExposureWeight = c.DaysSinceLastExposureWeight,
                DurationWeight         = c.DurationWeight,
                TransmissionRiskWeight = c.TransmissionWeight,
                MinimumRiskScore       = (byte)c.MinimumRiskScore,
            };

            var metadata = new NSMutableDictionary();

            metadata.SetValueForKey(new NSNumber(c.MinimumRiskScore), new NSString("minimumRiskScoreFullRange"));

            if (c.DurationAtAttenuationThresholds != null)
            {
                if (c.DurationAtAttenuationThresholds.Length < 2)
                {
                    throw new ArgumentOutOfRangeException(nameof(c.DurationAtAttenuationThresholds), "Must be an array of length 2");
                }

                var attKey   = new NSString("attenuationDurationThresholds");
                var attValue = NSArray.FromObjects(2, c.DurationAtAttenuationThresholds[0], c.DurationAtAttenuationThresholds[1]);
                metadata.SetValueForKey(attValue, attKey);
            }

            nc.Metadata = metadata;

            return(nc);
        }
Example #46
0
        public INotificationResult Notify(INotificationOptions options)
        {
            // create the notification
            var notification = new UILocalNotification
            {
                // set the fire date (the date time in which it will fire)
                FireDate = options.DelayUntil == null ? NSDate.Now : options.DelayUntil.Value.ToNSDate(),

                // configure the alert
                AlertTitle = options.Title,
                AlertBody  = options.Description,

                // set the sound to be the default sound
                SoundName = UILocalNotification.DefaultSoundName
            };

            if (options.CustomArgs != null)
            {
                NSMutableDictionary dictionary = new NSMutableDictionary();
                foreach (var arg in options.CustomArgs)
                {
                    dictionary.SetValueForKey(NSObject.FromObject(arg.Value), new NSString(arg.Key));
                }

                // Don't document, this feature is most likely to change
                dictionary.SetValueForKey(NSObject.FromObject(System.Guid.NewGuid().ToString()), new NSString("Identifier"));

                notification.UserInfo = dictionary;
            }
            // schedule it
            UIApplication.SharedApplication.ScheduleLocalNotification(notification);

            return(new NotificationResult()
            {
                Action = NotificationAction.NotApplicable
            });
        }
Example #47
0
        static NSDictionary recordToDict()
        {
            var allItemsDict = new NSMutableDictionary();

            foreach (RecordClass item in AppData.offlineRecordList)
            {
                NSMutableDictionary eachItemDict = new NSMutableDictionary();

                eachItemDict.SetValueForKey((NSString)item.AgeGroup,
                                            (NSString)"age_group");
                eachItemDict.SetValueForKey((NSString)item.CourseID.ToString(),
                                            (NSString)"course_id");
                eachItemDict.SetValueForKey((NSString)(item.Date.ToShortDateString().ToString()),
                                            (NSString)"date");
                eachItemDict.SetValueForKey((NSString)(item.FirstName),
                                            (NSString)"first_name");
                eachItemDict.SetValueForKey((NSString)(item.LastName),
                                            (NSString)"last_name");
                eachItemDict.SetValueForKey((NSString)(item.Gender),
                                            (NSString)"gender");
                eachItemDict.SetValueForKey((NSString)(item.Line.ToString()),
                                            (NSString)"line");
                eachItemDict.SetValueForKey((NSString)(item.Location),
                                            (NSString)"location");
                eachItemDict.SetValueForKey((NSString)(item.MemberNo.ToString()),
                                            (NSString)"member_no");
                eachItemDict.SetValueForKey((NSString)(item.OpenRecord.ToString()),
                                            (NSString)"openrecord");
                eachItemDict.SetValueForKey((NSString)(item.Time),
                                            (NSString)"time");

                allItemsDict.SetValueForKey(eachItemDict,
                                            (NSString)(item.FirstName + " " + item.LastName));
            }

            return(allItemsDict);
        }
Example #48
0
        //strongly typed window accessor
        //public new TableEdit Window {
        //	get { return (TableEdit)base.Window; }
        //}

        public NSMutableDictionary edit(NSDictionary startingValues, TestWindowController sender)
        {
            NSWindow window = this.Window;

            cancelled = false;

            var editFields = editForm.Cells;

            if (startingValues != null)
            {
                savedFields = NSMutableDictionary.FromDictionary(startingValues);

                editFields[FIRST_NAME].StringValue = startingValues[TestWindowController.FIRST_NAME].ToString();
                editFields[LAST_NAME].StringValue  = startingValues[TestWindowController.LAST_NAME].ToString();
                editFields[PHONE].StringValue      = startingValues[TestWindowController.PHONE].ToString();
            }
            else
            {
                // we are adding a new entry,
                // make sure the form fields are empty due to the fact that this controller is recycled
                // each time the user opens the sheet -
                editFields[FIRST_NAME].StringValue = string.Empty;
                editFields[LAST_NAME].StringValue  = string.Empty;
                editFields[PHONE].StringValue      = string.Empty;
            }

            NSApp.BeginSheet(window, sender.Window);             //,null,null,IntPtr.Zero);
            NSApp.RunModalForWindow(window);
            // sheet is up here.....

            // when StopModal is called will continue here ....
            NSApp.EndSheet(window);
            window.OrderOut(this);

            return(savedFields);
        }
Example #49
0
        protected override void OnAttached()
        {
            var effect = (Kerning)Element.Effects.FirstOrDefault(x => x is Kerning);

            if (effect == null)
            {
                return;
            }

            if (Control is UILabel)
            {
                var label = Control as UILabel;

                if (label.AttributedText != null && !string.IsNullOrEmpty(label.AttributedText.Value))
                {
                    NSRange effectiveRange;
                    var     attr = new NSMutableDictionary(label.AttributedText.GetAttributes(0, out effectiveRange));
                    attr.SetValueForKey(new NSNumber(effect.LetterSpacing), UIStringAttributeKey.KerningAdjustment);

                    label.AttributedText = new NSAttributedString(label.AttributedText.Value, attr);
                }
            }
            else if (Control is UITextView)
            {
                var textView = Control as UITextView;

                if (textView.AttributedText != null && !string.IsNullOrEmpty(textView.AttributedText.Value))
                {
                    NSRange effectiveRange;
                    var     attr = new NSMutableDictionary(textView.AttributedText.GetAttributes(0, out effectiveRange));
                    attr.SetValueForKey(new NSNumber(effect.LetterSpacing), UIStringAttributeKey.KerningAdjustment);

                    textView.AttributedText = new NSAttributedString(textView.AttributedText.Value, attr);
                }
            }
        }
        void Initialize()
        {
            CaptureSession = new AVCaptureSession();
            CaptureSession.SessionPreset = AVCaptureSession.PresetPhoto;
            previewLayer = new AVCaptureVideoPreviewLayer(CaptureSession)
            {
                Frame        = Bounds,
                VideoGravity = AVLayerVideoGravity.ResizeAspectFill
            };

            var videoDevices   = AVCaptureDevice.DevicesWithMediaType(AVMediaType.Video);
            var cameraPosition = (cameraOptions == CameraOptions.Front) ? AVCaptureDevicePosition.Front : AVCaptureDevicePosition.Back;
            var device         = videoDevices.FirstOrDefault(d => d.Position == cameraPosition);

            if (device == null)
            {
                return;
            }

            NSError error;
            var     input = new AVCaptureDeviceInput(device, out error);

            var dictionary = new NSMutableDictionary();

            dictionary[AVVideo.CodecKey] = new NSNumber((int)AVVideoCodec.JPEG);
            CaptureOutput = new AVCaptureStillImageOutput()
            {
                OutputSettings = new NSDictionary()
            };
            CaptureSession.AddOutput(CaptureOutput);

            CaptureSession.AddInput(input);
            Layer.AddSublayer(previewLayer);
            CaptureSession.StartRunning();
            IsPreviewing = true;
        }
Example #51
0
        public NSDictionary ToDictionary()
        {
            var dict = new NSMutableDictionary();

            if (Flatten)
            {
                dict.SetObject(NSNumber.FromInt32(1), QTMovie.KeyFlatten);
            }
            if (ExportType.HasValue)
            {
                dict.SetObject(NSNumber.FromInt32(1), QTMovie.KeyExport);
                dict.SetObject(NSNumber.FromInt32((int)ExportType.Value), QTMovie.KeyExportType);
            }
            if (ExportSettings != null)
            {
                dict.SetObject(ExportSettings, QTMovie.KeyExportSettings);
            }
            if (ManufacturerCode.HasValue)
            {
                dict.SetObject(NSNumber.FromInt32((int)ManufacturerCode.Value), QTMovie.KeyExportManufacturer);
            }

            return(dict);
        }
Example #52
0
        bool IsTransactionIdUnique(string transactionId)
        {
            Console.WriteLine("IsTransactionIdUnique " + transactionId + " in NSUserDefaults");

            var defaults = NSUserDefaults.StandardUserDefaults;
            var transactionDictionary = new NSString(KNOWN_TRANSACTIONS_KEY);

            defaults.Synchronize();

            if (defaults [transactionDictionary] == null)
            {
                var d = new NSMutableDictionary();
                defaults.SetValueForKey(d, transactionDictionary);
                defaults.Synchronize();
            }
            var t = defaults [KNOWN_TRANSACTIONS_KEY] as NSDictionary;

            if (t [transactionId] == null)
            {
                Console.WriteLine("IsTransactionIdUnique failed");
                return(true);
            }
            return(false);
        }
        public void InvalidType()
        {
            var    kv    = (NSString)"a";
            var    dt    = NSDate.FromTimeIntervalSinceNow(1);
            var    obj   = new NSDictionary(kv, kv);
            NSDate value = NSDate.FromTimeIntervalSinceNow(3);

            // dict where TValue is wrong
            var dict = new NSMutableDictionary <NSString, NSDate> ();

            dict.Add(kv, kv);
            Assert.Throws <InvalidCastException> (() => GC.KeepAlive(dict [kv]), "idx 1");
            Assert.Throws <InvalidCastException> (() => dict.ObjectForKey(kv), "ObjectForKey");
            Assert.Throws <InvalidCastException> (() => dict.ObjectsForKeys(new NSString [] { kv }, value), "ObjectsForKeys");
            Assert.Throws <InvalidCastException> (() => dict.TryGetValue(kv, out value), "TryGetValue");
            Assert.Throws <InvalidCastException> (() => GC.KeepAlive(dict.Values), "Values");

            // dict where TKey is wrong
            var dictK = new NSMutableDictionary <NSDate, NSString> ();

            dictK.Add(kv, kv);
            Assert.Throws <InvalidCastException> (() => GC.KeepAlive(dictK.Keys), "K Keys");
            Assert.Throws <InvalidCastException> (() => dictK.KeysForObject(kv), "K KeysForObject");
        }
        public override void ProvidePlaceholderAtUrl(NSUrl url, Action <NSError> completionHandler)
        {
            Console.WriteLine("FileProvider ProvidePlaceholderAtUrl");

            var     fileName    = Path.GetFileName(url.Path);
            var     placeholder = NSFileProviderExtension.GetPlaceholderUrl(DocumentStorageUrl.Append(fileName, false));
            NSError error;

            // TODO: get file size for file at <url> from model

            FileCoordinator.CoordinateWrite(placeholder, 0, out error, (newUrl) => {
                NSError err = null;

                var metadata = new NSMutableDictionary();
                metadata.Add(NSUrl.FileSizeKey, new NSNumber(0));

                NSFileProviderExtension.WritePlaceholder(placeholder, metadata, ref err);
            });

            if (completionHandler != null)
            {
                completionHandler(null);
            }
        }
Example #55
0
        CATextLayer SetupTextLayer()
        {
            _textLayer = new CATextLayer
            {
                ForegroundColor = ProgressPieColors.TextLayerForegroundColor.AsResourceCgColor(),
                AlignmentMode   = CATextLayer.AlignmentCenter,
            };

            _textLayer.SetFont(ProgressPieFonts.TextFont.AsResourceNsFont());

            var attrs = new NSMutableDictionary
            {
                {
                    NSAttributedString.FontAttributeName,
                    NSFont.FromFontName(ProgressPieFonts.TextFont.AsResourceNsFont().FontName, ProgressPieFonts.TextFont.AsResourceNsFont().PointSize)
                },
            };

            var applicationName = new NSAttributedString("100%", attrs);
            var textSize        = applicationName.Size;

            _textLayer.Frame = new RectangleF(ProgressPieFloats.Radius.AsResourceFloat() - textSize.Width / 2 + ProgressPieFloats.TextLayerMargin.AsFloat(), ProgressPieFloats.Radius.AsResourceFloat() - textSize.Height / 2, textSize.Width, textSize.Height);
            return(_textLayer);
        }
Example #56
0
        private CTFontDescriptor getDescriptor(FontStyle style)
        {
            if (!style.HasFlag(FontStyle.Underline) && !style.HasFlag(FontStyle.Strikeout))
            {
                return(null);
            }

            NSMutableDictionary dict = new NSMutableDictionary();

            if (style.HasFlag(FontStyle.Underline))
            {
                NSString underline = UIStringAttributeKey.UnderlineStyle;
                dict[underline] = NSNumber.FromInt32((int)NSUnderlineStyle.Single);
            }
            if (style.HasFlag(FontStyle.Strikeout))
            {
                NSString strike = UIStringAttributeKey.StrikethroughStyle;
                dict[strike] = NSNumber.FromInt32((int)NSUnderlineStyle.Single);
            }
            CTFontDescriptorAttributes attrs = new CTFontDescriptorAttributes(dict);
            CTFontDescriptor           desc  = new CTFontDescriptor(attrs);

            return(desc);
        }
Example #57
0
        /// <summary>
        /// Parces HTML headers string to a NSDictionary object
        /// </summary>
        /// <param name="additionalHeaders"></param>
        /// <returns></returns>
        private static NSDictionary ParceAdditionalHeaders(string additionalHeaders)
        {
            if (string.IsNullOrEmpty(additionalHeaders))
            {
                return(null);
            }

            var pairList = from line in additionalHeaders.Split('\n')
                           where !string.IsNullOrEmpty(line)
                           let colonPos = line.IndexOf(':')
                                          where colonPos >= 0
                                          let key                         = line.Remove(colonPos)
                                                                let value = line.Substring(colonPos + 1)
                                                                            select new { key, value };

            var res = new NSMutableDictionary();

            foreach (var pair in pairList)
            {
                res.SetValueForKey(new NSString(pair.key), new NSString(pair.value));
            }

            return(res);
        }
        public void AddTest()
        {
            var value1 = NSDate.FromTimeIntervalSinceNow(1);
            var value2 = NSDate.FromTimeIntervalSinceNow(2);
            var key1   = new NSString("key1");
            var key2   = new NSString("key2");

            var dict = new NSMutableDictionary <NSString, NSDate> ();

            Assert.Throws <ArgumentNullException> (() => dict.Add(null, value1), "ANE 1");
            Assert.Throws <ArgumentNullException> (() => dict.Add(key1, null), "ANE 2");

            dict.Add(key1, value1);
            Assert.AreEqual(1, dict.Count, "a Count");
            Assert.AreSame(value1, dict [key1], "a idx");

            dict.Add(key1, value1);
            Assert.AreEqual(1, dict.Count, "b Count");
            Assert.AreSame(value1, dict [key1], "b idx");

            dict.Add(key2, value1);
            Assert.AreEqual(2, dict.Count, "c Count");
            Assert.AreSame(value1, dict [key2], "c idx");
        }
        void InitializeCameraLayer()
        {
            this.captureSession = new AVCaptureSession()
            {
                SessionPreset = AVCaptureSession.PresetMedium                 // TODO investigate that
            };
            var captureDevice = AVCaptureDevice.DevicesWithMediaType(AVMediaType.Video).Where(dev => dev.Position == AVCaptureDevicePosition.Front).FirstOrDefault();

            if (captureDevice == null)
            {
                Console.WriteLine("No captureDevice - this won't work on the simulator, try a physical device");
                return;
            }
            var input = AVCaptureDeviceInput.FromDevice(captureDevice);

            if (input == null)
            {
                Console.WriteLine("No input - this won't work on the simulator, try a physical device");
                return;
            }
            this.captureSession.AddInput(input);

            // set up the output
            output = new AVCaptureStillImageOutput();
            var dict = new NSMutableDictionary();

            dict [AVVideo.CodecKey] = new NSNumber((int)AVVideoCodec.JPEG);
            captureSession.AddOutput(output);

            this.previewLayer = AVCaptureVideoPreviewLayer.FromSession(this.captureSession);
            this.previewLayer.LayerVideoGravity = AVLayerVideoGravity.ResizeAspectFill;
            this.previewLayer.Frame             = this.View.Frame;
            this.captureSession.StartRunning();

            this.cameraInitialized = true;
        }
Example #60
0
        public static string RunTask(string task, params string[] args)
        {
            var r = string.Empty;

            try
            {
                var pipeOut = new NSPipe();

                var t = new NSTask();
                t.LaunchPath = task;
                if (args != null)
                {
                    t.Arguments = args;
                }

                var path = "/usr/local/bin";
                var env  = new NSMutableDictionary();
                env.SetValueForKey(new NSString(path), new NSString("PATH"));

                t.Environment = env;

                t.StandardOutput = pipeOut;
                t.StandardError  = pipeOut;

                t.Launch();
                t.WaitUntilExit();
                //t.Release ();

                r = pipeOut.ReadHandle.ReadDataToEndOfFile().ToString();
            }
            catch (Exception ex)
            {
                Console.WriteLine(task + " failed: " + ex);
            }
            return(r);
        }