コード例 #1
1
        /// <summary>
        /// Loads the image into given imageView using defined parameters.
        /// </summary>
        /// <param name="parameters">Parameters for loading the image.</param>
        /// <param name="imageView">Image view that should receive the image.</param>
        /// <param name="imageScale">Optional scale factor to use when interpreting the image data. If unspecified it will use the device scale (ie: Retina = 2, non retina = 1)</param>
        public static IScheduledWork Into(this TaskParameter parameters, UIImageView imageView, float imageScale = -1f)
        {
            var weakRef = new WeakReference<UIImageView>(imageView);
            Func<UIImageView> getNativeControl = () => {
                UIImageView refView;
                if (!weakRef.TryGetTarget(out refView))
                    return null;
                return refView;
            };

			Action<UIImage, bool> doWithImage = (img, fromCache) => {
                UIImageView refView = getNativeControl();
                if (refView == null)
                    return;

				var isFadeAnimationEnabled = parameters.FadeAnimationEnabled.HasValue ? 
					parameters.FadeAnimationEnabled.Value : ImageService.Config.FadeAnimationEnabled;

				if (isFadeAnimationEnabled && !fromCache)
				{
					// fade animation
					UIView.Transition(refView, 0.4f, 
						UIViewAnimationOptions.TransitionCrossDissolve 
						| UIViewAnimationOptions.BeginFromCurrentState,
						() => { refView.Image = img; },
						() => {  });
				}
				else
				{
					refView.Image = img;
				}
            };

            return parameters.Into(getNativeControl, doWithImage, imageScale);
        }
コード例 #2
0
    void OnTriggerExit(Collider other)
    {
        FoodBehaviour food = other.GetComponent <FoodBehaviour>();
        FoodBehaviour imTouchingThisFood;

        if (ImTouchingThisFood != null && ImTouchingThisFood.TryGetTarget(out imTouchingThisFood) && food == imTouchingThisFood)
        {
            ImTouchingThisFood = null;
        }
    }
コード例 #3
0
ファイル: ViewExtensions.cs プロジェクト: Costo/Xamarin.Forms
		public static Task<bool> LayoutTo(this VisualElement view, Rectangle bounds, uint length = 250, Easing easing = null)
		{
			if (view == null)
				throw new ArgumentNullException("view");
			if (easing == null)
				easing = Easing.Linear;

			var tcs = new TaskCompletionSource<bool>();
			Rectangle start = view.Bounds;
			Func<double, Rectangle> computeBounds = progress =>
			{
				double x = start.X + (bounds.X - start.X) * progress;
				double y = start.Y + (bounds.Y - start.Y) * progress;
				double w = start.Width + (bounds.Width - start.Width) * progress;
				double h = start.Height + (bounds.Height - start.Height) * progress;

				return new Rectangle(x, y, w, h);
			};
			var weakView = new WeakReference<VisualElement>(view);
			Action<double> layout = f =>
			{
				VisualElement v;
				if (weakView.TryGetTarget(out v))
					v.Layout(computeBounds(f));
			};
			new Animation(layout, 0, 1, easing).Commit(view, "LayoutTo", 16, length, finished: (f, a) => tcs.SetResult(a));

			return tcs.Task;
		}
コード例 #4
0
        public static Task<bool> TranslateXTo(this VisualElement view, double x, 
                                              uint length = 250, Easing easing = null) 
        { 
            easing = easing ?? Easing.Linear; 
 	        TaskCompletionSource<bool> taskCompletionSource = new TaskCompletionSource<bool>();
            WeakReference<VisualElement> weakViewRef = new WeakReference<VisualElement>(view);

            Animation animation = new Animation(
                (value) => 
                    {
                        VisualElement viewRef;
                        if (weakViewRef.TryGetTarget(out viewRef))
                        {
                            viewRef.TranslationX = value;
                        }
                    },              // callback
                view.TranslationX,  // start
                x,                  // end
                easing);            // easing

            animation.Commit(
                view,               // owner
                "TranslateXTo",     // name
                16,                 // rate
                length,             // length
                null,               // easing 
                (finalValue, cancelled) => 
                        taskCompletionSource.SetResult(cancelled)); // finished
 			 
 	        return taskCompletionSource.Task; 
        } 
		/// <summary>
		/// Initializes a new instance of the <see cref="DLToolkit.Forms.Controls.FlowListViewInternalCell"/> class.
		/// </summary>
		/// <param name="flowListViewRef">Flow list view reference.</param>
		public FlowListViewInternalCell(WeakReference<FlowListView> flowListViewRef)
		{
			_flowListViewRef = flowListViewRef;
			FlowListView flowListView = null;
			flowListViewRef.TryGetTarget(out flowListView);
			_useGridAsMainRoot = !flowListView.FlowUseAbsoluteLayoutInternally;

			if (!_useGridAsMainRoot)
			{
				_rootLayout = new AbsoluteLayout()
				{
					Padding = 0d,
					BackgroundColor = flowListView.FlowRowBackgroundColor,
				};
				View = _rootLayout;
			}
			else
			{
				_rootLayoutAuto = new Grid()
				{
					RowSpacing = 0d,
					ColumnSpacing = 0d,
					Padding = 0d,
					BackgroundColor = flowListView.FlowRowBackgroundColor,
				};
				View = _rootLayoutAuto;
			}

			_flowColumnTemplate = flowListView.FlowColumnTemplate;
			_desiredColumnCount = flowListView.DesiredColumnCount;
			_flowColumnExpand = flowListView.FlowColumnExpand;
		}
コード例 #6
0
ファイル: Program.cs プロジェクト: beginor/practice
        static void Main(string[] args) {
            var appBuilder = new AppBuilder();
            Nowin.OwinServerFactory.Initialize(appBuilder.Properties);

            appBuilder.Use<ConsoleLogMiddleware>();

            appBuilder.Use<SimpleStaticFileMiddleWare>(System.IO.Path.Combine(Environment.CurrentDirectory, @"../../www"));

            var startup = new WebApi.Startup();
            startup.Configuration(appBuilder);

            var builder = new Nowin.ServerBuilder();
            const string ip = "127.0.0.1";
            const int port = 8888;
            builder.SetAddress(System.Net.IPAddress.Parse(ip)).SetPort(port)
                .SetOwinApp(appBuilder.Build())
                .SetOwinCapabilities((IDictionary<string, object>)appBuilder.Properties[Nowin.OwinKeys.ServerCapabilitiesKey]);

            using (var server = builder.Build()) {

                var serverRef = new WeakReference<Nowin.INowinServer>(server);

                Task.Run(() => {
                    Nowin.INowinServer nowinServer;
                    if (serverRef.TryGetTarget(out nowinServer)) {
                        nowinServer.Start();
                    }
                });

                var baseAddress = "http://" + ip + ":" + port + "/";
                Console.WriteLine("Nowin server listening {0}, press ENTER to exit.", baseAddress);

                Console.ReadLine();
            }
        }
コード例 #7
0
        /// <summary>
        /// Loads the image into given imageView using defined parameters.
        /// </summary>
        /// <param name="parameters">Parameters for loading the image.</param>
        /// <param name="imageView">Image view that should receive the image.</param>
        public static IScheduledWork Into(this TaskParameter parameters, Image imageView)
        {
            var weakRef = new WeakReference<Image>(imageView);

            Func<Image> getNativeControl = () => {
                Image refView = null;

                if (!weakRef.TryGetTarget(out refView))
                    return null;

                return refView;
            };

            Action<WriteableBitmap, bool, bool> doWithImage = (img, isLocalOrFromCache, isLoadingPlaceholder) => {
                Image refView = getNativeControl();
                if (refView == null)
                    return;

                bool imageChanged = (img != refView.Source);
                if (!imageChanged)
                    return;

                bool isFadeAnimationEnabled = parameters.FadeAnimationEnabled.HasValue ?
                    parameters.FadeAnimationEnabled.Value : ImageService.Config.FadeAnimationEnabled;

                bool isFadeAnimationEnabledForCached = isFadeAnimationEnabled && (parameters.FadeAnimationForCachedImages.HasValue ?
                    parameters.FadeAnimationForCachedImages.Value : ImageService.Config.FadeAnimationForCachedImages);

                if (!isLoadingPlaceholder && isFadeAnimationEnabled && (!isLocalOrFromCache || (isLocalOrFromCache && isFadeAnimationEnabledForCached)))
                {
                    // fade animation
                    int fadeDuration = parameters.FadeAnimationDuration.HasValue ?
                        parameters.FadeAnimationDuration.Value : ImageService.Config.FadeAnimationDuration;
                    DoubleAnimation fade = new DoubleAnimation();
                    fade.Duration = TimeSpan.FromMilliseconds(fadeDuration);
					fade.From = 0f;
					fade.To = 1f;
					fade.EasingFunction = new CubicEase() { EasingMode = EasingMode.EaseInOut }; 

					Storyboard fadeInStoryboard = new Storyboard();

#if SILVERLIGHT
                    Storyboard.SetTargetProperty(fade, new PropertyPath("Image.Opacity"));
#else
                    Storyboard.SetTargetProperty(fade, "Image.Opacity");
#endif
                    Storyboard.SetTarget(fade, refView);
					fadeInStoryboard.Children.Add(fade);
					fadeInStoryboard.Begin();
					refView.Source = img;
                }
                else
                {
                    refView.Source = img;
                }
            };

            return parameters.Into(getNativeControl, doWithImage);
        }
コード例 #8
0
ファイル: ViewModelBase.cs プロジェクト: Cybrosys/Sandbox
            public BusyContext(ViewModelBase viewModel)
            {
                _weakViewModelRef = new WeakReference<ViewModelBase>(viewModel);

                ViewModelBase target;
                if (_weakViewModelRef.TryGetTarget(out target))
                    target.IsBusy = true;
            }
コード例 #9
0
ファイル: TrueFalseElement.cs プロジェクト: runt18/CodeHub
 private static EventHandler UpdateValueChanged(WeakReference<BooleanElement> weakThis)
 {
     return new EventHandler((s, _) => {
         BooleanElement parent;
         if (weakThis.TryGetTarget(out parent))
             parent.Value = ((UISwitch)s).On;
     });
 }
コード例 #10
0
ファイル: Program.cs プロジェクト: jiowchern/Regulus
        static void Main(string[] args)
        {
            var a = new object();
            var wa = new WeakReference<object>(a);

            object refa;
            if (wa.TryGetTarget(out refa))
            {
                Console.WriteLine("refa find");
            }
            else
            {
                Console.WriteLine("refa lose");
            }

            a = null;
            a = null;
            a = null;
            a = null;
            System.Threading.Thread.Sleep(1000);
            System.GC.Collect();
            System.Threading.Thread.Sleep(1000);

            if (refa != null)
            {
                Console.WriteLine("refa find");
            }
            else
            {
                Console.WriteLine("refa lose");
            }

            if (wa.TryGetTarget(out refa))
            {
                Console.WriteLine("refa find");
            }
            else
            {
                Console.WriteLine("refa lose");
            }

            Console.ReadKey();
            TestRequester();
        }
コード例 #11
0
        public void UntrackedDisposablesAreNotTracked()
        {
            var resolver = new DefaultDependencyResolver();
            resolver.Register(typeof(MyUntrackedDisposable), () => new MyUntrackedDisposable());

            var untrackedDisposable = resolver.Resolve<MyUntrackedDisposable>();
            var untrackedDisposableWeakRef = new WeakReference<MyUntrackedDisposable>(untrackedDisposable);
            
            untrackedDisposable = null;
            GC.Collect();
            GC.WaitForPendingFinalizers();
            Assert.False(untrackedDisposableWeakRef.TryGetTarget(out untrackedDisposable));
        }
コード例 #12
0
 /// <summary>
 /// Activate the child whenever the parent is activated
 /// </summary>
 /// <example>child.ActivateWith(this)</example>
 /// <param name="child">Child to activate whenever the parent is activated</param>
 /// <param name="parent">Parent to observe</param>
 public static void ActivateWith(this IScreenState child, IScreenState parent)
 {
     var weakChild = new WeakReference<IScreenState>(child);
     EventHandler<ActivationEventArgs> handler = null;
     handler = (o, e) =>
     {
         IScreenState strongChild;
         if (weakChild.TryGetTarget(out strongChild))
             strongChild.Activate();
         else
             parent.Activated -= handler;
     };
     parent.Activated += handler;
 }
コード例 #13
0
        public async Task ItShouldBePossibileToAbandonAnEnumerationWithoutLeaking()
        {
            var outerReference = new Uri("http://tempuri.org");

            //var enumerable = EnumerableStateMachine(outerReference);
            //enumerable.Take(10).ToList();



            var probeWeakReference = new WeakReference<Uri>(outerReference);
            var sequence = AsyncEnumerable.Create<string>(async p =>
            {
                // This will be hoisted in the state machine that is generated 
                // by the compiler.
                Uri hoistedReference;
                Assert.IsTrue(probeWeakReference.TryGetTarget(out hoistedReference));
                int i = 0;
                while (true)
                {
                    await // This will register a callback that reference 
                          // this state machine on the threadpool, that in 
                          // turn will keep alive the instance referenced 
                          // by `hoistedReference`
                        p.Yield(hoistedReference.ToString() + i++);
                }
            });

            // Just a sanity check to verify that the state machine has been created and did what we expected.
            var expectedList = Enumerable.Range(0, 10).Select(i => outerReference.ToString() + i).ToList();
            var asyncList = await sequence.Take(10).ToList();
            CollectionAssert.AreEqual(expectedList, (ICollection)asyncList);


            // Release our reference to the Uri.
            // If the continuation that point to the next step in the asynchronous state machine has not 
            // been removed from the thread pool queue, weakReference.Target  will not be null after the 
            // GC run.
            outerReference = null;

            GC.Collect(2, GCCollectionMode.Forced, true);
            GC.WaitForPendingFinalizers();

            Uri unused;
            Assert.IsFalse(
                probeWeakReference.TryGetTarget(out unused),
                "The reference to the Uri should have been collected.\r\n" +
                "This probably means that the state machine has not been properly disposed and " +
                "is still keep alive by one or more references in the thread pool."
            );
        }
コード例 #14
0
        public void HubReferencesAreNotRetained()
        {
            var resolver = new DefaultDependencyResolver();
            resolver.Register(typeof(DontLeakMeHub), () => new DontLeakMeHub());

            var hub = resolver.Resolve<DontLeakMeHub>();
            Assert.NotNull(hub);

            var hubWeakRef = new WeakReference<DontLeakMeHub>(hub);
            hub.Dispose();
            hub = null;
            GC.Collect();
            GC.WaitForPendingFinalizers();
            Assert.False(hubWeakRef.TryGetTarget(out hub));
        }
コード例 #15
0
        /// <summary>
        /// Loads the image into given UIButton using defined parameters.
        /// </summary>
        /// <param name="parameters">Parameters for loading the image.</param>
        /// <param name="button">UIButton that should receive the image.</param>
        /// <param name="imageScale">Optional scale factor to use when interpreting the image data. If unspecified it will use the device scale (ie: Retina = 2, non retina = 1)</param>
        public static IScheduledWork Into(this TaskParameter parameters, UIButton button, float imageScale = -1f)
        {
            var weakRef = new WeakReference<UIButton>(button);
            Func<UIButton> getNativeControl = () => {
                UIButton refView;
                if (!weakRef.TryGetTarget(out refView))
                    return null;
                return refView;
            };

			Action<UIImage, bool> doWithImage = (img, fromCache) => {
                UIButton refView = getNativeControl();
                if (refView == null)
                    return;
                refView.SetImage(img, UIControlState.Normal);
            };
            return parameters.Into(getNativeControl, doWithImage, imageScale);
        }
コード例 #16
0
        internal DbcStringReference(DbcTable owner, int position)
        {
            if (owner == null)
                throw new ArgumentNullException("owner");
            if (position < 0)
                throw new ArgumentException("position");

            _owner = new WeakReference<DbcTable>(owner);
            _pos = position;
            _val = new Lazy<string>(() =>
            {
                DbcTable table;
                if (!_owner.TryGetTarget(out table))
                    throw new ObjectDisposedException("DbcTable");

                return table.GetString(_pos);
            });
        }
コード例 #17
0
 private static EventHandler<NavigationEventArgs> CreateCallback(WeakReference<ICancellableViewModel> viewModelHandle, WeakReference<IPageLifetimeCallback> pageHandle)
 {
     EventHandler<NavigationEventArgs> callback = null;
     callback = (sender, e) =>
     {
         ICancellableViewModel viewModel;
         IPageLifetimeCallback page;
         if (pageHandle.TryGetTarget(out page))
         {
             page.NavigatedFrom -= callback;
         }
         if (viewModelHandle.TryGetTarget(out viewModel))
         {
             viewModel.Cancel();
         }
     };
     return callback;
 }
コード例 #18
0
ファイル: Program.cs プロジェクト: ufcpp/UfcppSample
        // 1秒に1回、「参照中」メッセージを表示
        static async Task StartLoop(WeakReference<object> r)
        {
            while (true)
            {
                object obj;
                if (r.TryGetTarget(out obj))
                {
                    Console.WriteLine(obj + " を参照中");
                }
                else
                {
                    Console.WriteLine("参照がなくなりました");
                    break;
                }

                await Task.Delay(1000);
            }
        }
コード例 #19
0
        /// <summary>
        /// Loads the image into given imageView using defined parameters.
        /// </summary>
        /// <param name="parameters">Parameters for loading the image.</param>
        /// <param name="imageView">Image view that should receive the image.</param>
        /// <param name="imageScale">Optional scale factor to use when interpreting the image data. If unspecified it will use the device scale (ie: Retina = 2, non retina = 1)</param>
        public static IScheduledWork Into(this TaskParameter parameters, UIImageView imageView, float imageScale = -1f)
        {
            var weakRef = new WeakReference<UIImageView>(imageView);
            Func<UIImageView> getNativeControl = () => {
                UIImageView refView;
                if (!weakRef.TryGetTarget(out refView))
                    return null;
                return refView;
            };

            Action<UIImage> doWithImage = img => {
                UIImageView refView = getNativeControl();
                if (refView == null)
                    return;
                refView.Image = img;
            };

            return parameters.Into(getNativeControl, doWithImage, imageScale);
        }
コード例 #20
0
        /// <summary>
        /// Loads the image into given imageView using defined parameters.
        /// </summary>
        /// <param name="parameters">Parameters for loading the image.</param>
        /// <param name="imageView">Image view that should receive the image.</param>
        public static IScheduledWork Into(this TaskParameter parameters, Image imageView)
        {
            var weakRef = new WeakReference<Image>(imageView);

            Func<Image> getNativeControl = () => {
                Image refView = null;

                if (!weakRef.TryGetTarget(out refView))
                    return null;

                return refView;
            };

            Action<WriteableBitmap, bool> doWithImage = (img, fromCache) => {
                Image refView = getNativeControl();
                if (refView == null)
                    return;

                var isFadeAnimationEnabled = parameters.FadeAnimationEnabled.HasValue ?
                    parameters.FadeAnimationEnabled.Value : ImageService.Config.FadeAnimationEnabled;

                if (isFadeAnimationEnabled && !fromCache)
                {
                    refView.Source = img;

                    //TODO !!!!!!!!!!!!!!
                    // fade animation
                    //DoubleAnimation fadeoutAnimation = new DoubleAnimation();
                    //fadeoutAnimation.Duration = TimeSpan.FromMilliseconds(500);
                    //fadeoutAnimation.From = 1.0d;
                    //fadeoutAnimation.To = 0.0d;
                    //Storyboard storyboard = new Storyboard();
                    //storyboard.Children.Add(fadeoutAnimation);
                    //refView.BeginAnimation(Image.OpacityProperty, fadeoutAnimation);
                }
                else
                {
                    refView.Source = img;
                }
            };

            return parameters.Into(getNativeControl, doWithImage);
        }
コード例 #21
0
        public static Task<bool> BezierPathTo(this VisualElement view, 
                                              Point pt1, Point pt2, Point pt3, 
                                              uint length = 250, 
                                              BezierTangent bezierTangent = BezierTangent.None,
                                              Easing easing = null)
        {
            easing = easing ?? Easing.Linear;
            TaskCompletionSource<bool> taskCompletionSource = new TaskCompletionSource<bool>();
            WeakReference<VisualElement> weakViewRef = new WeakReference<VisualElement>(view);

            Rectangle bounds = view.Bounds;
            BezierSpline bezierSpline = new BezierSpline(bounds.Center, pt1, pt2, pt3);

            Action<double> callback = t =>
                {
                    VisualElement viewRef;
                    if (weakViewRef.TryGetTarget(out viewRef))
                    {
                        Point tangent;
                        Point point = bezierSpline.GetPointAtFractionLength(t, out tangent);
                        double x = point.X - bounds.Width / 2;
                        double y = point.Y - bounds.Height / 2;
                        viewRef.Layout(new Rectangle(new Point(x, y), bounds.Size));

                        if (bezierTangent != BezierTangent.None)
                        {
                            viewRef.Rotation = 180 * Math.Atan2(tangent.Y, tangent.X) / Math.PI;

                            if (bezierTangent == BezierTangent.Reversed)
                            {
                                viewRef.Rotation += 180;
                            }
                        }
                    }
                };

            Animation animation = new Animation(callback, 0, 1, easing);
            animation.Commit(view, "BezierPathTo", 16, length,
                finished: (value, cancelled) => taskCompletionSource.SetResult(cancelled));

            return taskCompletionSource.Task;
        }
コード例 #22
0
ファイル: ViewExtensions.cs プロジェクト: Costo/Xamarin.Forms
		public static Task<bool> FadeTo(this VisualElement view, double opacity, uint length = 250, Easing easing = null)
		{
			if (view == null)
				throw new ArgumentNullException("view");
			if (easing == null)
				easing = Easing.Linear;

			var tcs = new TaskCompletionSource<bool>();
			var weakView = new WeakReference<VisualElement>(view);
			Action<double> fade = f =>
			{
				VisualElement v;
				if (weakView.TryGetTarget(out v))
					v.Opacity = f;
			};

			new Animation(fade, view.Opacity, opacity, easing).Commit(view, "FadeTo", 16, length, finished: (f, a) => tcs.SetResult(a));

			return tcs.Task;
		}
コード例 #23
0
		/// <summary>
		/// Initializes a new instance of the <see cref="DLToolkit.Forms.Controls.FlowListViewInternalCell"/> class.
		/// </summary>
		/// <param name="flowListViewRef">Flow list view reference.</param>
		public FlowListViewInternalCell(WeakReference<FlowListView> flowListViewRef)
		{
			this.flowListViewRef = flowListViewRef;
			FlowListView flowListView = null;
			flowListViewRef.TryGetTarget(out flowListView);

			rootLayout = new AbsoluteLayout() {
				HorizontalOptions = LayoutOptions.FillAndExpand,
				VerticalOptions = LayoutOptions.FillAndExpand,
				Padding = 0d,
				BackgroundColor = flowListView.FlowRowBackgroundColor,
			};

			View = rootLayout;

			flowColumnsTemplates = flowListView.FlowColumnsTemplates;
			desiredColumnCount = flowListView.DesiredColumnCount;
			flowAutoColumnCount = flowListView.FlowAutoColumnCount;
			flowColumnExpand = flowListView.FlowColumnExpand;
		}
コード例 #24
0
        /// <summary>
        /// Loads the image into given imageView using defined parameters.
        /// </summary>
        /// <param name="parameters">Parameters for loading the image.</param>
        /// <param name="imageView">Image view that should receive the image.</param>
        /// <param name="imageScale">Optional scale factor to use when interpreting the image data. If unspecified it will use the device scale (ie: Retina = 2, non retina = 1)</param>
        public static IScheduledWork Into(this TaskParameter parameters, UIImageView imageView, float imageScale = -1f)
        {
            var weakRef = new WeakReference<UIImageView>(imageView);
            Func<UIImageView> getNativeControl = () => {
                UIImageView refView;
                if (!weakRef.TryGetTarget(out refView))
                    return null;
                return refView;
            };

			Action<UIImage, bool, bool> doWithImage = (img, isLocalOrFromCache, isLoadingPlaceholder) => {
                UIImageView refView = getNativeControl();
                if (refView == null)
                    return;

				bool isFadeAnimationEnabled = parameters.FadeAnimationEnabled.HasValue ?
					parameters.FadeAnimationEnabled.Value : ImageService.Config.FadeAnimationEnabled;

				bool isFadeAnimationEnabledForCached = isFadeAnimationEnabled && (parameters.FadeAnimationForCachedImages.HasValue ?
					parameters.FadeAnimationForCachedImages.Value : ImageService.Config.FadeAnimationForCachedImages);

				if (!isLoadingPlaceholder && isFadeAnimationEnabled && (!isLocalOrFromCache || (isLocalOrFromCache && isFadeAnimationEnabledForCached)))
				{
					// fade animation
					double fadeDuration = (double)((parameters.FadeAnimationDuration.HasValue ?
						parameters.FadeAnimationDuration.Value : ImageService.Config.FadeAnimationDuration)) / 1000;
					
					UIView.Transition(refView, fadeDuration, 
						UIViewAnimationOptions.TransitionCrossDissolve 
						| UIViewAnimationOptions.BeginFromCurrentState,
						() => { refView.Image = img; },
						() => {  });
				}
				else
				{
					refView.Image = img;
				}
            };

            return parameters.Into(getNativeControl, doWithImage, imageScale);
        }
コード例 #25
0
        public static Task<bool> TranslateYTo(this VisualElement view, double y,
                                              uint length = 250, Easing easing = null)
        {
            easing = easing ?? Easing.Linear;
            TaskCompletionSource<bool> taskCompletionSource = new TaskCompletionSource<bool>();
            WeakReference<VisualElement> weakViewRef = new WeakReference<VisualElement>(view);

            Animation animation = new Animation((value) =>
                {
                    VisualElement viewRef;
                    if (weakViewRef.TryGetTarget(out viewRef))
                    {
                        viewRef.TranslationY = value;
                    }
                }, view.TranslationY, y, easing);

            animation.Commit(view, "TranslateYTo", 16, length, null,
                             (v, c) => taskCompletionSource.SetResult(c));

            return taskCompletionSource.Task;
        }
コード例 #26
0
        public static void GetValue()
        {
            ConditionalWeakTable<object, object> cwt = new ConditionalWeakTable<object, object>();
            object key = new object();
            object obj = null;

            object value = cwt.GetValue(key, k => new object());

            Assert.True(cwt.TryGetValue(key, out value));
            Assert.Equal(value, cwt.GetOrCreateValue(key));

            WeakReference<object> wrValue = new WeakReference<object>(value, false);
            WeakReference<object> wrkey = new WeakReference<object>(key, false);
            key = null;
            value = null;

            GC.Collect();

            // key and value must be collected
            Assert.False(wrValue.TryGetTarget(out obj));
            Assert.False(wrkey.TryGetTarget(out obj));
        }
コード例 #27
0
        public static Action Bind(
            this UILabel label, 
            INotifyPropertyChanged source, 
            string propertyName, 
            IFormatProvider formatProvider = null)
        {
            var property = source.GetProperty(propertyName);

            var l = new WeakReference<UILabel> (label);
            label.SetText(source, property);

            var handler = new PropertyChangedEventHandler((s, e) =>
            {
                UILabel weakRef;
                if (e.PropertyName == propertyName && l.TryGetTarget(out weakRef))
                {
                    weakRef.InvokeOnMainThread(()=> weakRef.SetText(source, property));
                }
            });

            source.PropertyChanged += handler;

            return new Action(() => source.PropertyChanged -= handler);
        }
コード例 #28
0
 private static EventHandler CreateOnPostsUpdatedHandler(WeakReference<ThreadPage> handle)
 {
     return (sender, e) =>
     {
         ThreadPage obj;
         if (handle.TryGetTarget(out obj))
         {
             obj.OnPostsUpdatedHandler(sender, e);
         }
     };
 }
コード例 #29
0
 private static PropertyChangedEventHandler CreateViewModelOnPropertyChangedHandler(WeakReference<ThreadPage> handle)
 {
     return (sender, e) =>
     {
         ThreadPage obj;
         if (handle.TryGetTarget(out obj))
         {
             obj.ViewModelOnPropertyChangedHandler(sender, e);
         }
     };
 }
コード例 #30
0
		void ActivateMore()
		{
			var displayed = new HashSet<nint>();
			for (var i = 0; i < _buttons.Count; i++)
			{
				var tag = _buttons[i].Tag;
				if (tag >= 0)
					displayed.Add(tag);
			}

			var frame = _moreButton.Frame;
			if (!Forms.IsiOS8OrNewer)
			{
				var container = _moreButton.Superview;
				frame = new RectangleF(container.Frame.X, 0, frame.Width, frame.Height);
			}

			var x = frame.X - _scroller.ContentOffset.X;

			var path = _tableView.IndexPathForCell(this);
			var rowPosition = _tableView.RectForRowAtIndexPath(path);
			var sourceRect = new RectangleF(x, rowPosition.Y, rowPosition.Width, rowPosition.Height);

			if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
			{
				var actionSheet = new MoreActionSheetController();

				for (var i = 0; i < _cell.ContextActions.Count; i++)
				{
					if (displayed.Contains(i))
						continue;

					var item = _cell.ContextActions[i];
					var weakItem = new WeakReference<MenuItem>(item);
					var action = UIAlertAction.Create(item.Text, UIAlertActionStyle.Default, a =>
					{
						_scroller.SetContentOffset(new PointF(0, 0), true);
						MenuItem mi;
						if (weakItem.TryGetTarget(out mi))
							mi.Activate();
					});
					actionSheet.AddAction(action);
				}

				var controller = GetController();
				if (controller == null)
					throw new InvalidOperationException("No UIViewController found to present.");

				if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone)
				{
					var cancel = UIAlertAction.Create(StringResources.Cancel, UIAlertActionStyle.Cancel, null);
					actionSheet.AddAction(cancel);
				}
				else
				{
					actionSheet.PopoverPresentationController.SourceView = _tableView;
					actionSheet.PopoverPresentationController.SourceRect = sourceRect;
				}

				controller.PresentViewController(actionSheet, true, null);
			}
			else
			{
				var d = new MoreActionSheetDelegate { Scroller = _scroller, Items = new List<MenuItem>() };

				var actionSheet = new UIActionSheet(null, d);

				for (var i = 0; i < _cell.ContextActions.Count; i++)
				{
					if (displayed.Contains(i))
						continue;

					var item = _cell.ContextActions[i];
					d.Items.Add(item);
					actionSheet.AddButton(item.Text);
				}

				if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone)
				{
					var index = actionSheet.AddButton(StringResources.Cancel);
					actionSheet.CancelButtonIndex = index;
				}

				actionSheet.ShowFrom(sourceRect, _tableView, true);
			}
		}
コード例 #31
0
        public void SourceReferenceMemoryLeakTest()
        {
            var handler1Success = false;

            var publisherStrongReference = new TestEventPublisher();
            var publisherWeakReference = new WeakReference<TestEventPublisher>(publisherStrongReference);

            var listener = new CollectionChangedEventListener(publisherStrongReference);
            listener.RegisterHandler((sender, e) => handler1Success = true);

            publisherStrongReference.RaiseCollectionChanged(NotifyCollectionChangedAction.Add, null);

            handler1Success.Is(true);
            listener.Dispose();
            publisherStrongReference = null;

            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();

            TestEventPublisher resultPublisher = null;
            publisherWeakReference.TryGetTarget(out resultPublisher).Is(false);
            resultPublisher.IsNull();
        }
コード例 #32
0
 void Update()
 {
     FoodEatingCooldown = Mathf.Max(0.0f, FoodEatingCooldown - Time.deltaTime);
     BarkCooldown       = Mathf.Max(0.0f, BarkCooldown - Time.deltaTime);
     if (SleepyTime > 0.0f)
     {
         float noiseLevel = 0.0f;
         if (noiseLevel > 0.2f)
         {
             // wake up grumpy and go somewhere else quieter つ´Д`)つ
             internalState = "つ´Д`)つ";
             BarkGrumpy();
         }
         else
         {
             // sleepy time ( ु⁎ᴗ_ᴗ⁎)ु.。zZ
             internalState   = "( ु⁎ᴗ_ᴗ⁎)ु.。zZ";
             agent.isStopped = true;
             Energy         += Time.deltaTime * SleepRecovery;
             SleepyTime     -= Time.deltaTime;
         }
     }
     else if (Energy < 0.1f)
     {
         SleepyTime = Mathf.Min(1.0f, SleepyTime + 1.0f);
     }
     else if (Hunger > 0.5f)
     {
         GameObject iWantThisFood = null;
         if (IWantThisFood != null && IWantThisFood.TryGetTarget(out iWantThisFood))
         {
             // walk towards food
             FoodBehaviour imTouchingThisFood = null;
             if (ImTouchingThisFood != null && ImTouchingThisFood.TryGetTarget(out imTouchingThisFood))
             {
                 // yum yum ლ(´ڡ`ლ)
                 internalState = "ლ(´ڡ`ლ)";
                 EatFood(imTouchingThisFood);
                 IWantThisFood      = null;
                 ImTouchingThisFood = null;
             }
             else
             {
                 // go walk towards food ԅ(♡﹃♡ԅ)
                 internalState = "ԅ(♡﹃♡ԅ)";
                 UpdateTarget(iWantThisFood.transform.position, 1.0f);
             }
         }
         else
         {
             System.WeakReference <GameObject> foodObject = SceneManager.GetClosestNonEmptyFood(transform.position);
             if (foodObject.TryGetTarget(out iWantThisFood))
             {
                 IWantThisFood = foodObject;
             }
             else
             {
                 // whaaaa? no food around Щ(º̩̩́Дº̩̩̀щ)
                 internalState = "Щ(º̩̩́Дº̩̩̀щ)";
                 // sulk and bark a bit
                 BarkSad();
             }
         }
     }
     else
     {
         // go play!
         internalState = "(^ω^)";
         Energy       -= Time.deltaTime * EnergySpendingPlaying;
         Hunger       += Time.deltaTime * HungerRate;
         ToyBoredom   += Time.deltaTime * ToyBoredomRate;
         if (ToyBoredom >= 1.0f)
         {
             IWantThisToy = null;
             ToyBoredom   = 0.0f;
         }
         GameObject iWantThisToy = null;
         if (IWantThisToy != null && IWantThisToy.TryGetTarget(out iWantThisToy))
         {
             UpdateTarget(iWantThisToy.transform.position, 2.0f);
             BarkHappy();
             ToyBehaviour toy = null;
             if (ImTouchingThisToy != null && ImTouchingThisToy.TryGetTarget(out toy))
             {
                 toy.ShootUpRandomDirection();
                 ImTouchingThisToy = null;
             }
         }
         else
         {
             System.WeakReference <GameObject> toyObject = SceneManager.GetRandomToy();
             if (toyObject.TryGetTarget(out iWantThisToy))
             {
                 IWantThisToy = toyObject;
             }
             else
             {
             }
         }
     }
 }