示例#1
0
        /// <summary>
        /// Import the specified certificate and its associated private key.
        /// </summary>
        /// <param name="certificate">The certificate and key, in PKCS12 format.</param>
        /// <param name="passphrase">The passphrase that protects the private key.</param>
        public void Import(byte[] certificate, string passphrase)
        {
            NSDictionary opt;

            if (string.IsNullOrEmpty(passphrase))
            {
                opt = new NSDictionary();
            }
            else
            {
                opt = NSDictionary.FromObjectAndKey(new NSString(passphrase), SecImportExport.Passphrase);
            }

            var status = SecImportExport.ImportPkcs12(certificate, opt, out NSDictionary[] array);

            if (status == SecStatusCode.Success)
            {
                var              identity = new SecIdentity(array[0]["identity"].Handle);
                NSArray          chain    = array[0]["chain"] as NSArray;
                SecCertificate[] certs    = new SecCertificate[chain.Count];
                for (System.nuint i = 0; i < chain.Count; i++)
                {
                    certs[i] = chain.GetItem <SecCertificate>(i);
                }
                Credential = new NSUrlCredential(identity, certs, NSUrlCredentialPersistence.ForSession);
            }
        }
示例#2
0
        internal void updateBaseView()
        {
            UIFont       arialFont = UIFont.SystemFontOfSize(45);
            NSDictionary arialDict = NSDictionary.FromObjectAndKey(arialFont, UIStringAttributeKey.Font);
            NSMutableAttributedString aAttrString = new NSMutableAttributedString(model.Temp, arialDict);

            NSMutableAttributedString aAttrString1 = new NSMutableAttributedString("°/", arialDict);

            aAttrString.Append(aAttrString1);
            UIFont       VerdanaFont = UIFont.SystemFontOfSize(30);
            NSString     tel         = (NSString)"12";
            NSDictionary verdanaDict = NSDictionary.FromObjectAndKey(VerdanaFont, UIStringAttributeKey.Font);
            NSMutableAttributedString vAttrString = new NSMutableAttributedString(tel, verdanaDict);


            aAttrString.Append(vAttrString);



            label.AttributedText = aAttrString;

            image.Image = new UIImage(model.Type);

            label1.Text = model.Date;

            //selectedView.unSelectView();
        }
示例#3
0
        public void SetAlarm(AppModels.UserCondition condition)
        {
            long waitTime = condition.ReminderIntervalMillis();

            if (waitTime <= 0)
            {
                return;
            }

            CancelAlarm(condition);

            UIApplication.SharedApplication.CancelAllLocalNotifications();

            UILocalNotification notif = new UILocalNotification();

            notif.FireDate = NSDate.FromTimeIntervalSinceNow(waitTime / 1000);

            notif.RepeatCalendar              = NSCalendar.CurrentCalendar;
            notif.RepeatInterval              = GetCalUnit(waitTime);
            notif.AlertAction                 = string.Format("{0} Reminder", condition.Condition);
            notif.AlertBody                   = string.Format("Remember to take a photo of your condition '{0}'!", condition.Condition);
            notif.UserInfo                    = NSDictionary.FromObjectAndKey(new NSString(condition.Id.ToString()), new NSString(condition.Id.ToString()));
            notif.ApplicationIconBadgeNumber += 1;
            notif.SoundName                   = UILocalNotification.DefaultSoundName;

            UIApplication.SharedApplication.ScheduleLocalNotification(notif);
        }
        //
        // This method is invoked when the application has loaded and is ready to run. In this
        // method you should instantiate the window, load the UI into it and then make the window
        // visible.
        //
        // You have 17 seconds to return from this method, or iOS will terminate your application.
        //
        public override bool FinishedLaunching(UIApplication app, NSDictionary options)
        {
            string userAgent = "Mozilla/5.0 (Linux; Android 5.1.1; Nexus 5 Build/LMY48B; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/43.0.2357.65 Mobile Safari/537.36";

            // set default useragent
            NSDictionary dictionary = NSDictionary.FromObjectAndKey(NSObject.FromObject(userAgent), NSObject.FromObject("UserAgent"));

            NSUserDefaults.StandardUserDefaults.RegisterDefaults(dictionary);

            global::Xamarin.Forms.Forms.Init();
            Xamarin.FormsMaps.Init();
            CachedImageRenderer.Init();
            LoadApplication(new App());

            AppDomain.CurrentDomain.UnhandledException += async(sender, e) =>
            {
                await SendExceptionInformationToTheServer((Exception)e.ExceptionObject, "AppDomain.CurrentDomain.UnhandledException");
            };

            TaskScheduler.UnobservedTaskException += async(sender, e) =>
            {
                await SendExceptionInformationToTheServer(e.Exception, "TaskScheduler.UnobservedTaskException");
            };

            return(base.FinishedLaunching(app, options));
        }
示例#5
0
            public override void DrawWithFrame(CGRect cellFrame, NSView inView)
            {
                var progress = FloatValue;

                if (float.IsNaN((float)progress))
                {
                    return;
                }

                base.DrawWithFrame(cellFrame, inView);

                string progressText = (int)(progress * 100f) + "%";
                var    str          = new NSMutableAttributedString(progressText, NSDictionary.FromObjectAndKey(ForegroundColor.ToNSUI(), NSAttributedString.ForegroundColorAttributeName));
                var    range        = new NSRange(0, str.Length);

                if (Font != null)
                {
                    str.AddAttributes(NSDictionary.FromObjectAndKey(Font, NSAttributedString.FontAttributeName), range);
                }
                var size = FontExtensions.MeasureString(str, cellFrame.Size.ToEto());
                var rect = cellFrame.ToEto();

                rect.Offset((rect.Size - size) / 2);

                str.DrawString(rect.ToNS());
            }
示例#6
0
 public override int ScheduleLocalNotification(string body, int delay)
 {
     if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0))
     {
         UNUserNotificationCenter     center  = UNUserNotificationCenter.Current;
         UNMutableNotificationContent content = new UNMutableNotificationContent();
         content.Body  = body;
         content.Sound = UNNotificationSound.Default;
         UNTimeIntervalNotificationTrigger trigger = UNTimeIntervalNotificationTrigger.CreateTrigger(delay, false);
         UNNotificationRequest             request = UNNotificationRequest.FromIdentifier(StringIdentifierFromInt(LocalNotificationUid), content, trigger);
         center.AddNotificationRequest(request, (NSError error) =>
         {
             if (error != null)
             {
                 Console.WriteLine("Something went wrong:" + error);
             }
         });
     }
     else
     {
         UILocalNotification localNotification = new UILocalNotification();
         localNotification.FireDate  = NSDate.FromTimeIntervalSinceNow(delay);
         localNotification.AlertBody = body;
         localNotification.TimeZone  = NSTimeZone.DefaultTimeZone;
         localNotification.UserInfo  = NSDictionary.FromObjectAndKey(NSNumber.FromInt32(LocalNotificationUid), new NSString(PWMLocalNotificationUidKey));
         UIApplication.SharedApplication.ScheduleLocalNotification(localNotification);
     }
     return(LocalNotificationUid++);
 }
示例#7
0
        private CGSize MessageSize()
        {
            if (!HasMessage)
            {
                return(CGSize.Empty);
            }

            var    boundedSize = new CGSize(AvailableWidth, float.MaxValue);
            CGSize descriptionLabelSize;

            if (!IsRunningiOS7OrLater())
            {
                var attr = new UIStringAttributes(NSDictionary.FromObjectAndKey(MessageFont, (NSString)MessageFont.Name));
                descriptionLabelSize = Message.GetBoundingRect(
                    boundedSize,
                    NSStringDrawingOptions.TruncatesLastVisibleLine,
                    attr,
                    null).Size;
            }
            else
            {
                descriptionLabelSize = Message.StringSize(
                    MessageFont,
                    boundedSize,
                    UILineBreakMode.TailTruncation);
            }

            return(descriptionLabelSize);
        }
示例#8
0
        NSData ImageAsJPEG(NSImage i)
        {
            NSData           d   = i.AsTiff();
            NSBitmapImageRep rep = new NSBitmapImageRep(d);

            return(rep.RepresentationUsingTypeProperties(NSBitmapImageFileType.Jpeg, NSDictionary.FromObjectAndKey(NSNumber.FromInt32(1), NSBitmapImageRep.CompressionFactor)));
        }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();
            textStorage = new InteractiveTextColoringTextStorage();
            RectangleF newTextViewRect = View.Bounds;

            newTextViewRect.X     += 8;
            newTextViewRect.Width -= 16;

            var layoutManager = new NSLayoutManager();
            var container     = new NSTextContainer(new SizeF(newTextViewRect.Size.Width, float.MaxValue));

            container.WidthTracksTextView = true;

            layoutManager.AddTextContainer(container);
            textStorage.AddLayoutManager(layoutManager);


            var newTextView = new UITextView(newTextViewRect, container);

            newTextView.AutoresizingMask    = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth;
            newTextView.ScrollEnabled       = true;
            newTextView.KeyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag;

            View.Add(newTextView);

            var tokens = new Dictionary <string, NSDictionary> ();

            tokens.Add("Alice", NSDictionary.FromObjectAndKey(UIColor.Red, UIStringAttributeKey.ForegroundColor));
            tokens.Add("Rabbit", NSDictionary.FromObjectAndKey(UIColor.Orange, UIStringAttributeKey.ForegroundColor));
            tokens.Add("DefaultTokenName", NSDictionary.FromObjectAndKey(UIColor.Black, UIStringAttributeKey.ForegroundColor));
            textStorage.Tokens = tokens;

            SetText();
        }
示例#10
0
        public void check(double lon, double lat)
        {
            var mapCenter = new CLLocationCoordinate2D(lat, lon);
            var mapRegion = MKCoordinateRegion.FromDistance(mapCenter, 3000, 3000);

            map.CenterCoordinate = mapCenter;
            map.Region           = mapRegion;
            if ((lon <= ((-34 * 0.0005) - 106.48694)) && (lat >= ((15 * 0.0005) + 31.739444)) && fuera)
            {
                fuera = false;

                var notification = new UILocalNotification();

                // set the fire date (the date time in which it will fire)
                notification.FireDate = NSDate.Now.AddSeconds(5);                 //DateTime.Now.AddSeconds(10));
                notification.TimeZone = NSTimeZone.DefaultTimeZone;
                // configure the alert stuff
                notification.AlertTitle  = "Peligro";
                notification.AlertAction = "Alert Action";
                notification.AlertBody   = "¡Has entrado en una zona de peligro!";

                notification.UserInfo = NSDictionary.FromObjectAndKey(new NSString("UserInfo for notification"), new NSString("Notification"));

                notification.SoundName = UILocalNotification.DefaultSoundName;

                // schedule it
                UIApplication.SharedApplication.ScheduleLocalNotification(notification);
            }
        }
        /// <summary>
        /// Gets the size of the title.
        /// </summary>
        /// <returns>
        /// The <see cref="CGSize"/>.
        /// </returns>
        private CGSize TitleSize()
        {
            if (!this.HasTitle)
            {
                return(CGSize.Empty);
            }

            var    boundedSize = new SizeF((float)this.AvailableWidth, float.MaxValue);
            CGSize titleLabelSize;

            if (!IsRunningiOS7OrLater())
            {
                var attr = new UIStringAttributes(NSDictionary.FromObjectAndKey(TitleFont, (NSString)TitleFont.Name));
                titleLabelSize = this.Title.GetBoundingRect(
                    boundedSize,
                    NSStringDrawingOptions.TruncatesLastVisibleLine,
                    attr,
                    null).Size;
            }
            else
            {
                titleLabelSize = this.Title.StringSize(TitleFont, boundedSize, UILineBreakMode.TailTruncation);
            }

            return(titleLabelSize);
        }
示例#12
0
        public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
        {
            // create a new window instance based on the screen size
            Window = new UIWindow(UIScreen.MainScreen.Bounds);
            Window.RootViewController = new Table();

            // make the window visible
            Window.MakeKeyAndVisible();

            //GIMBAL - encapsulate gimbal service management and ios location into following class
            gimbalManager = new GimbalManager();
            //need an empty dictionary for the overload...just doesn't seem right, does it?
            var dict = NSDictionary.FromObjectAndKey((NSString)"nada", (NSString)"nidi");

            //sub out your api key here
            GimbalFramework.Gimbal.SetAPIKey("YOUR_API_KEY_HERE", dict);
            //if app was previously authorized, start up gimbal services
            if (CLLocationManager.Status == CLAuthorizationStatus.AuthorizedAlways)
            {
                gimbalManager.Start();
            }

            //request always auth for location - need a listener since this happens async on start esp on first run
            CLLocationManager manager = new CLLocationManager();

            manager.Delegate = gimbalManager;
            manager.RequestAlwaysAuthorization();

            return(true);
        }
示例#13
0
        public async Task <NotificationFeedback> Show(Notification notification)
        {
            var guid = Guid.NewGuid();
            var not  = new NSUserNotification
            {
                Title             = notification.Title,
                InformativeText   = notification.Description,
                DeliveryDate      = NSDate.Now,
                SoundName         = NSUserNotification.NSUserNotificationDefaultSoundName,
                ActionButtonTitle = notification.PrimaryAction.Or(""),
                HasActionButton   = notification.PrimaryAction.HasValue,
                UserInfo          = NSDictionary.FromObjectAndKey(new NSString(guid.ToString()), Key),
            };

            // Approach described by http://stackoverflow.com/questions/21110714/mac-os-x-nsusernotificationcenter-notification-get-dismiss-event-callback/21365269#21365269
            var dismissed = _currentNotifications
                            .SkipWhile(s => !s.Contains(guid))
                            .SkipWhile(s => s.Contains(guid))
                            .Take(1);

            var activated = _notificationActivated
                            .Where(n => n.Equals(guid));

            var status = Observable.Merge(
                dismissed.Select(_ => NotificationFeedback.Dismissed),
                activated.Select(_ => NotificationFeedback.PrimaryActionTaken));

            var task = status.FirstAsync().ToTask();

            await MainThread.BeginInvoke(() => _center.DeliverNotification(not));

            return(await task);
        }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            // Setup collection view
            CollectionView.AlwaysBounceHorizontal  = true;
            CollectionView.AllowsMultipleSelection = false;
            CollectionView.AllowsSelection         = true;

            FetchAvailableFilters();

            ciContext = CIContext.FromOptions(null);

            // Add the background image and UIEffectView for the blur
            UIVisualEffectView effectView = new UIVisualEffectView(UIBlurEffect.FromStyle(UIBlurEffectStyle.Dark));

            effectView.TranslatesAutoresizingMaskIntoConstraints = false;
            View.InsertSubviewAbove(effectView, BackgroundImageView);

            var views = NSDictionary.FromObjectAndKey(effectView, new NSString("effectView"));

            View.AddConstraints(NSLayoutConstraint.FromVisualFormat("V:|[effectView]|",
                                                                    (NSLayoutFormatOptions)0, null, views));
            View.AddConstraints(NSLayoutConstraint.FromVisualFormat("H:|[effectView]|",
                                                                    (NSLayoutFormatOptions)0, null, views));
        }
        CABasicAnimation MoveItAnimation()
        {
            if (moveAnimation == null)
            {
                moveAnimation = new CABasicAnimation()
                {
                    Duration       = 2,
                    TimingFunction = new CAMediaTimingFunction(0.5f, 1, 0.5f, 0)
                }
            }
            ;
            return(moveAnimation);
        }

        void Move()
        {
            var animations = NSDictionary.FromObjectAndKey(MoveItAnimation(), (NSString)"frameOrigin");

            mover.Animations = animations;
            PointF origin = mover.Frame.Location;

            origin.X += mover.Frame.Width;
            ((NSView)mover.Animator).SetFrameOrigin(origin);
        }
    }
示例#16
0
        public override bool FinishedLaunching(UIApplication app, NSDictionary options)
        {
            global::Xamarin.Forms.Forms.Init();

            // Code for starting up the Xamarin Test Cloud Agent
#if DEBUG
            Xamarin.Calabash.Start();
            #endif


            UIApplication.SharedApplication.SetStatusBarStyle(UIStatusBarStyle.LightContent, false);
            UIApplication.SharedApplication.SetStatusBarHidden(false, false);

            NSDictionary userDefautls = NSDictionary.FromObjectAndKey(new NSNumber(0.5f), new NSString("font_size"));
            NSUserDefaults.StandardUserDefaults.RegisterDefaults(userDefautls);
            NSUserDefaults.StandardUserDefaults.Synchronize();

            Shared.conditionals = new Conditionals();

            if (!Resolver.IsSet)
            {
                SetIoc();
            }

            LoadApplication(new App());

            return(base.FinishedLaunching(app, options));
        }
示例#17
0
        /// <summary>
        /// Notifies the specified notification.
        /// </summary>
        /// <param name="notification">The notification.</param>
        public object Notify(LocalNotification notification)
        {
            var id = Guid.NewGuid().ToString();
            var nativeNotification = new UILocalNotification
            {
                AlertAction = notification.Title,
                AlertBody   = notification.Text,
                FireDate    = notification.NotifyTime.ToNSDate(),
                //ApplicationIconBadgeNumber = 1,
                //UserInfo = NSDictionary.FromObjectAndKey(NSObject.FromObject(id), NSObject.FromObject(NotificationKey))
            };

            if (!string.IsNullOrEmpty(notification.Parameter))
            {
                nativeNotification.UserInfo = NSDictionary.FromObjectsAndKeys(
                    new NSObject[] { NSObject.FromObject(notification.Parameter), NSObject.FromObject(id) },
                    new NSObject[] { NSObject.FromObject(ArgumentKey), NSObject.FromObject(NotificationKey) }
                    );
            }
            else
            {
                nativeNotification.UserInfo = NSDictionary.FromObjectAndKey(NSObject.FromObject(id), NSObject.FromObject(NotificationKey));
            }

            UIApplication.SharedApplication.ScheduleLocalNotification(nativeNotification);

            return(id);
        }
        // Save the data in Firebase Database.
        void SaveNote()
        {
            ReplaceImagesWithinTextWithImagesIds();

            // Create data to be saved in FIrebase Database.
            var title        = txtTitle.Text.Trim();
            var content      = TxtContent.Text;
            var lastModified = AppDelegate.GetUtcTimestamp();
            var created      = Note.CreatedUnformatted ?? lastModified.ToString();

            title   = string.IsNullOrWhiteSpace(title) ? null : title;
            content = string.IsNullOrWhiteSpace(content) ? null : content;

            var imagesInfo = new NSMutableDictionary();

            foreach (var imageInfo in Note.ImagesInfo)
            {
                var location = NSNumber.FromNInt(imageInfo.Location);
                imagesInfo [imageInfo.Id] = NSDictionary.FromObjectAndKey(location, new NSString("location"));
            }

            object [] keys   = { "content", "created", "lastModified", "negativeLastModified", "title", "imagesInfo" };
            object [] values = { content, double.Parse(created), lastModified, -lastModified, title, imagesInfo };
            var       data   = NSDictionary.FromObjectsAndKeys(values, keys, keys.Length);

            // Save data in note node.
            noteNode.SetValue(data);
            // Increment notes count in folder.
            notesCountNode.SetValue(NSNumber.FromNUInt(NotesCount));
        }
示例#19
0
        public static int LaunchApplicationForPath(string path, string[] args, bool activate = true)
        {
            var options       = new NSWorkspaceLaunchOptions();
            var arguments     = NSArray.FromObjects(args);
            var configuration = NSDictionary.FromObjectAndKey(arguments, NSWorkspaceLaunchConfigurationArguments);
            var url           = new NSUrl(path, false);

            NSError error = new NSError();

#if MONOMAC
            var app = NSWorkspace.SharedWorkspace.LaunchApplication(url, options, configuration, error);
#else
            var app = NSWorkspace.SharedWorkspace.OpenURL(url, options, configuration, out error);
#endif
            if (error != null)
            {
                throw new ApplicationException("NSWorkspace failed to open URL: " + url);
            }

            if (app == null)
            {
                return(0);
            }

            if (activate)
            {
                app.Activate(NSApplicationActivationOptions.ActivateIgnoringOtherWindows);
            }

            return(app.ProcessIdentifier);
        }
        private NSError ComposeError(string message, string domain, int statusCode)
        {
            var errorMessage = new NSString(message);
            var userInfo     = NSDictionary.FromObjectAndKey(errorMessage, NSError.LocalizedDescriptionKey);

            return(new NSError(new NSString(domain), statusCode, userInfo));
        }
        public override void SendAsync(NSUrl url, NSString method, NSDictionary <NSString, NSString> headers, NSData data, MSHttpRequestCompletionHandler completionHandler)
        {
            _httpClientDelegate?.WillSendHTTPRequestToURL(url, headers);
            var managedHeaders = new Dictionary <string, string>();

            foreach (KeyValuePair <NSObject, NSObject> header in headers)
            {
                managedHeaders[header.Key.ToString()] = header.Value.ToString();
            }
            _httpNetworkAdapter.SendAsync(url.ToString(), method, managedHeaders, data.ToString(), CancellationToken.None).ContinueWith(t =>
            {
                var innerException = t.Exception?.InnerException;
                if (innerException is HttpException)
                {
                    var response = (innerException as HttpException).HttpResponse;
                    completionHandler(NSData.FromString(response.Content), new NSHttpUrlResponse(url, response.StatusCode, "1.1", new NSDictionary()), null);
                }
                else if (innerException != null)
                {
                    var userInfo = NSDictionary.FromObjectAndKey(new NSString("stackTrace"), new NSString(innerException.ToString()));
                    completionHandler(null, null, new NSError(new NSString(".NET SDK"), 1, userInfo));
                }
                else
                {
                    var response = t.Result;
                    completionHandler(NSData.FromString(response.Content), new NSHttpUrlResponse(url, response.StatusCode, "1.1", new NSDictionary()), null);
                }
            });
        }
示例#22
0
        //
        // This method is invoked when the application has loaded and is ready to run. In this
        // method you should instantiate the window, load the UI into it and then make the window
        // visible.
        //
        // You have 17 seconds to return from this method, or iOS will terminate your application.
        //
        public override bool FinishedLaunching(UIApplication app, NSDictionary options)
        {
            window = new UIWindow(UIScreen.MainScreen.Bounds);

            // We use NSUserDefaults to store a bool value if we are tracking the user or not
            var optionsDict = NSDictionary.FromObjectAndKey(new NSString("YES"), new NSString(AllowTrackingKey));

            NSUserDefaults.StandardUserDefaults.RegisterDefaults(optionsDict);

            // User must be able to opt out of tracking
            GAI.SharedInstance.OptOut = !NSUserDefaults.StandardUserDefaults.BoolForKey(AllowTrackingKey);

            // Initialize Google Analytics with a 5-second dispatch interval (Use a higher value when in production). There is a
            // tradeoff between battery usage and timely dispatch.
            GAI.SharedInstance.DispatchInterval        = 5;
            GAI.SharedInstance.TrackUncaughtExceptions = true;

            Tracker = GAI.SharedInstance.GetTracker("CuteAnimals", TrackingId);

            viewController            = new DVCMenu();
            navController             = new UINavigationController(viewController);
            window.RootViewController = navController;
            window.MakeKeyAndVisible();

            return(true);
        }
示例#23
0
        public void AddFoodItem(FoodItem item)
        {
            var quantityType = HKQuantityType.GetQuantityType(HKQuantityTypeIdentifierKey.DietaryEnergyConsumed);
            var quantity     = HKQuantity.FromQuantity(HKUnit.Joule, item.Joules);

            var now = NSDate.Now;

            var metadata       = NSDictionary.FromObjectAndKey(new NSString(item.Name), HKMetadataKey.FoodType);
            var caloriesSample = HKQuantitySample.FromType(quantityType, quantity, now, now, metadata);

            HealthStore.SaveObject(caloriesSample, (success, error) => {
                if (success)
                {
                    FoodItems.Insert(item, 0);
                    var indexPathForInsertedFoodItem = NSIndexPath.FromRowSection(0, 0);
                    InvokeOnMainThread(() => {
                        TableView.InsertRows(new NSIndexPath[] { indexPathForInsertedFoodItem }, UITableViewRowAnimation.Automatic);
                    });
                }
                else
                {
                    Console.WriteLine("An error occured saving the food {0}. In your app, try to handle this gracefully. " +
                                      "The error was: {1}.", item.Name, error);
                }
            });
        }
示例#24
0
        //
        // Load support:
        //    Override one of ReadFromData, ReadFromFileWrapper or ReadFromUrl
        //
        public override bool ReadFromData(NSData data, string typeName, out NSError outError)
        {
            outError = null;
            Console.WriteLine("About to read data of type {0}", typeName);

            NSMutableArray newArray = null;

            try {
                newArray = (NSMutableArray)NSKeyedUnarchiver.UnarchiveObject(data);
            }
            catch (Exception ex) {
                Console.WriteLine("Error loading file: Exception: {0}", ex.Message);
                if (outError != null)
                {
                    NSDictionary d = NSDictionary.FromObjectAndKey(new NSString("The data is corrupted."), NSError.LocalizedFailureReasonErrorKey);
                    outError = NSError.FromDomain(NSError.OsStatusErrorDomain, -4, d);
                }
                return(false);
            }
            this.Employees = newArray;
            return(true);

            // Default template code
//			outError = NSError.FromDomain(NSError.OsStatusErrorDomain, -4);
//			return false;
        }
示例#25
0
        //
        // Load support:
        //    Override one of ReadFromData, ReadFromFileWrapper or ReadFromUrl
        //
        public override bool ReadFromData(NSData data, string typeName, out NSError outError)
        {
            outError = null;
            Console.WriteLine("About to read data of type {0}", typeName);

            NSMutableArray newArray = null;

            try {
                newArray = (NSMutableArray)NSKeyedUnarchiver.UnarchiveObject(data);
            }
            catch (Exception ex) {
                Console.WriteLine("Error loading file: Exception: {0}", ex.Message);
                if (outError != null)
                {
                    NSDictionary d = NSDictionary.FromObjectAndKey(new NSString("The data is corrupted."), NSError.LocalizedFailureReasonErrorKey);
                    outError = NSError.FromDomain(NSError.OsStatusErrorDomain, -4, d);
                }
                return(false);
            }
            this.Cars = newArray;
            // For Revert to Saved. Have to point the array controller to the new array.
            if (arrayController != null)
            {
                arrayController.Content = this.Cars;
            }
            return(true);
        }
        public void DrawInnerLabels(CGContext ctx)
        {
            // Only draw labels if they have been set
            var labelsCount = _innerMarkingLabels.Count;

            if (labelsCount > 0)
            {
                //#if __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_7_0
                NSDictionary attributes = NSDictionary.FromObjectAndKey(_labelFont, UIStringAttributeKey.Font);
                //#endif
                for (var i = 0; i < labelsCount; i++)
                {
                    // Enumerate through labels clockwise
                    var label = _innerMarkingLabels[i];

                    CGRect labelFrame = contextCoordinatesForLabelAtIndex(i);

                    //#if __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_7_0
                    label.DrawString(labelFrame.Location, _labelFont);
                    //[label drawInRect:labelFrame withAttributes:attributes];
                    ////#else
                    //            _labelColor.SetFill();
                    //            //[self.labelColor setFill];
                    //            label.DrawString(labelFrame withFont:self.labelFont];
                    ////#endif
                }
            }
        }
示例#27
0
        async Task GetUserInfo(VKUserModel vkUserModel)
        {
            var request  = VKApi.Users.Get(NSDictionary.FromObjectAndKey((NSString)@"photo_400_orig", VKApiConst.Fields));
            var response = await request.ExecuteAsync();

            var users   = response.ParsedModel as VKUsersArray;
            var account = users?.FirstObject as VKUser;

            if (account != null)
            {
                vkUserModel.Name = account.first_name + " " + account.last_name;
                if (!string.IsNullOrEmpty(account.photo_400_orig))
                {
                    vkUserModel.Picture = new Uri(account.photo_400_orig);
                }
            }

            //Depends user image quality is the User profile of the VK account, the photo might be in different fields
            //var request100 = VKApi.Users.Get(NSDictionary.FromObjectAndKey((NSString)@"photo_100", VKApiConst.Fields));
            //var response100 = await request100.ExecuteAsync();
            //var account100 = (response100.ParsedModel as VKUsersArray)?.FirstObject as VKUser;

            //var request200 = VKApi.Users.Get(NSDictionary.FromObjectAndKey((NSString)@"photo_200", VKApiConst.Fields));
            //var response200 = await request200.ExecuteAsync();
            //var account200 = (response200.ParsedModel as VKUsersArray)?.FirstObject as VKUser;

            //var request201 = VKApi.Users.Get(NSDictionary.FromObjectAndKey((NSString)@"photo_200_orig", VKApiConst.Fields));
            //var response201 = await request201.ExecuteAsync();
            //var account201 = (response201.ParsedModel as VKUsersArray)?.FirstObject as VKUser;

            //var request50 = VKApi.Users.Get(NSDictionary.FromObjectAndKey((NSString)@"photo_50", VKApiConst.Fields));
            //var response50 = await request50.ExecuteAsync();
            //var account50 = (response50.ParsedModel as VKUsersArray)?.FirstObject as VKUser;
        }
示例#28
0
        public OverlayView()
        {
            var effect         = UIBlurEffect.FromStyle(UIBlurEffectStyle.Light);
            var backgroundView = new UIVisualEffectView(effect);

            backgroundView.ContentView.BackgroundColor = UIColor.FromWhiteAlpha(0.7f, 0.3f);
            backgroundView.TranslatesAutoresizingMaskIntoConstraints = false;
            Add(backgroundView);

            var views       = NSDictionary.FromObjectAndKey(backgroundView, new NSString("backgroundView"));
            var constraints = NSLayoutConstraint.FromVisualFormat("|[backgroundView]|",
                                                                  NSLayoutFormatOptions.DirectionLeadingToTrailing, null, views);

            AddConstraints(constraints);
            constraints = NSLayoutConstraint.FromVisualFormat("V:|[backgroundView]|",
                                                              NSLayoutFormatOptions.DirectionLeadingToTrailing, null, views);
            AddConstraints(constraints);

            label = new UILabel();
            label.TranslatesAutoresizingMaskIntoConstraints = false;
            Add(label);

            AddConstraint(NSLayoutConstraint.Create(label, NSLayoutAttribute.CenterX, NSLayoutRelation.Equal,
                                                    backgroundView, NSLayoutAttribute.CenterX, 1.0f, 0.0f));
            AddConstraint(NSLayoutConstraint.Create(label, NSLayoutAttribute.CenterY, NSLayoutRelation.Equal,
                                                    backgroundView, NSLayoutAttribute.CenterY, 1.0f, 0.0f));
        }
        public static NSUserActivity CreateNSUserActivity(Restaurant userInfo)
        {
            var activityType = ActivityTypes.View;
            var activity     = new NSUserActivity(activityType);

            activity.EligibleForSearch         = true;     // HACK: can result in duplicates with CoreSpotlight
            activity.EligibleForPublicIndexing = false;
            activity.EligibleForHandoff        = false;

            activity.Title = "Restaurant " + userInfo.Name;

            //			var keywords = new NSString[] {new NSString("Add"), new NSString("Todo"), new NSString("Empty"), new NSString("Task") };
            //			activity.Keywords = new NSSet<NSString>(keywords);

            var attributeSet = new CoreSpotlight.CSSearchableItemAttributeSet();

            attributeSet.DisplayName        = userInfo.Name;
            attributeSet.ContentDescription = userInfo.Cuisine + " " + userInfo.Chef;

            // Handoff https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/Handoff/AdoptingHandoff/AdoptingHandoff.html
//			attributeSet.RelatedUniqueIdentifier = userInfo.Number.ToString(); // CoreSpotlight "id"


            activity.AddUserInfoEntries(NSDictionary.FromObjectAndKey(new NSString(userInfo.Number.ToString()), ActivityKeys.Id));

            activity.ContentAttributeSet = attributeSet;

            activity.BecomeCurrent();              // don't forget to ResignCurrent()

            return(activity);
        }
        //
        // This method is invoked when the application has loaded and is ready to run. In this
        // method you should instantiate the window, load the UI into it and then make the window
        // visible.
        //
        // You have 17 seconds to return from this method, or iOS will terminate your application.
        //
        public override bool FinishedLaunching(UIApplication app, NSDictionary options)
        {
            string userAgent =
                "Mozilla/5.0 (Linux; Android 5.1.1; Nexus 5 Build/LMY48B; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/43.0.2357.65 Mobile Safari/537.36";

            // set default useragent
            NSDictionary dictionary = NSDictionary.FromObjectAndKey(NSObject.FromObject(userAgent),
                                                                    NSObject.FromObject("UserAgent"));

            NSUserDefaults.StandardUserDefaults.RegisterDefaults(dictionary);
            var userDefaults = NSUserDefaults.StandardUserDefaults.StringForKey("FirstRun");

            if (string.IsNullOrEmpty(userDefaults))
            {
                var account = AccountStore.Create().FindAccountsForService("Google").FirstOrDefault();
                if (account != null)
                {
                    AccountStore.Create().Delete(account, "Google");
                }
                NSUserDefaults.StandardUserDefaults.SetString("Yes", "FirstRun");
            }
            global::Xamarin.Forms.Forms.Init();
            CustomFabRenderer.Init();
            LoadApplication(new App());

            return(base.FinishedLaunching(app, options));
        }