public Game(float width, float height) : base(width, height) { using (NSAutoreleasePool pool = new NSAutoreleasePool ()) { AddChild (SPImage.ImageWithContentsOfFile ("Default.png")); mMainMenu = new SPSprite(); AddChild (mMainMenu); mMainMenu.AddChild (SPImage.ImageWithContentsOfFile ("logo.png")); SPTexture sceneButtonTexture = SPTexture.TextureWithContentsOfFile ("button_big.png"); atlasButton = SPButton.ButtonWithUpState (sceneButtonTexture, "Texture Atlas"); atlasButton.AddEventListener (onAtlasButtonTriggered, SPEvents.ButtonTriggered); addSceneButton (atlasButton); SPTexture backButtonTexture = SPTexture.TextureWithContentsOfFile ("button_back.png"); mBackButton = new SPButton (backButtonTexture, "back"); mBackButton.Visible = false; mBackButton.X = (int)(Stage.Width - mBackButton.Width) / 2; mBackButton.Y = Stage.Height - mBackButton.Height + 1; mBackButton.AddEventListener (onBackButtonTriggered, SPEvents.ButtonTriggered); AddChild (mBackButton); // SPJuggler jug = this.Stage.Juggler; // jug.DelayInvocationAtTarget (this, 5.0).PerformSelector (new Selector ("onAtlasButtonTriggered:"), null, 0); } }
// This event handler deals with the results of the // background operation. private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { NSAutoreleasePool pool = new NSAutoreleasePool(); // First, handle the case where an exception was thrown. if (e.Error != null) { // TODO } else if (e.Cancelled) { this.labelResult.StringValue = "Canceled"; } else { this.labelResult.StringValue = "Fibonacci result for " + this.numberToCompute + " iterations is " + e.Result; } this.progressIndicator.DoubleValue = 0.0d; this.buttonStart.IsEnabled = true; this.buttonStop.IsEnabled = false; pool.Release(); }
public override ICallControl Call(string phoneNumber, CallType type) { if (CallType.Voice.Equals (type)) { using (var pool = new NSAutoreleasePool ()) { StringBuilder filteredPhoneNumber = new StringBuilder(); if (phoneNumber!=null && phoneNumber.Length>0) { foreach (char c in phoneNumber) { if (Char.IsNumber(c) || c == '+' || c == '-' || c == '.') { filteredPhoneNumber.Append(c); } } } String textURI = "tel:" + filteredPhoneNumber.ToString(); var thread = new Thread (InitiateCall); thread.Start (textURI); } ; } else { INotification notificationService = (INotification)IPhoneServiceLocator.GetInstance ().GetService ("notify"); if (notificationService != null) { notificationService.StartNotifyAlert ("Phone Alert", "The requested call type is not enabled or supported on this device.", "OK"); } } return null; }
public void RefreshCustomers() { this.Root.Clear(); this.Root.Add(new Section("") { new StringElement("Refresh", RefreshCustomers) }); var json = NSUserDefaults.StandardUserDefaults.StringForKey("customers"); if(string.IsNullOrWhiteSpace(json) == false) { Customers = JsonSerializer.DeserializeFromString<IEnumerable<Customer>>(json).ToList(); } if(Customers.Any()) { var section = new Section("Customers"); foreach(var customer in Customers) { var desc = string.Format("Customer Name: {0} -- Address: {1}", customer.Name, customer.Address); section.Add(new StringElement(desc)); } this.Root.Add(section); } using (var pool = new NSAutoreleasePool()) { pool.BeginInvokeOnMainThread(()=>{ this.ReloadData(); }); } }
private void Startup() { using (var pool = new NSAutoreleasePool()) { InvokeOnMainThread(delegate { foreach(var view in MonoMobileApplication.Views) { var title = MonoMobileApplication.Title; if (view is IView) title = ((IView)view).Caption; var binding = new BindingContext(view, title); MonoMobileApplication.DialogViewControllers.Add(new DialogViewController(UITableViewStyle.Grouped, binding, true) { Autorotate = true } ); } _Navigation.ViewControllers = MonoMobileApplication.DialogViewControllers.ToArray(); MonoMobileApplication.CurrentDialogViewController = _Navigation.ViewControllers.First() as DialogViewController; UIView.BeginAnimations("fadeIn"); UIView.SetAnimationDuration(0.3f); _Navigation.View.Alpha = 1.0f; UIView.CommitAnimations(); }); } }
public override void DidOutputSampleBuffer (AVCaptureOutput captureOutput, CMSampleBuffer sampleBuffer, AVCaptureConnection connection) { try { connection.VideoOrientation = AVCaptureVideoOrientation.Portrait; using (var image = ImageFromSampleBuffer (sampleBuffer)){ if(_CurrentState.didKnock){ KnockCount++; if(KnockCount==1){ _CurrentState.CountDown = 5; InvokeOnMainThread (delegate { _CurrentState.TopLabel.Text = "Knock Again to Post!!"; _CurrentState.BottomLabel.Text = "Knock to Post: 5 sec"; }); }else if(KnockCount==40){ _CurrentState.CountDown = 4; InvokeOnMainThread (delegate { _CurrentState.BottomLabel.Text = "Knock to Post: 4 sec"; }); }else if(KnockCount==80){ _CurrentState.CountDown = 3; InvokeOnMainThread (delegate { _CurrentState.BottomLabel.Text = "Knock to Post: 3 sec"; }); }else if(KnockCount==120){ _CurrentState.CountDown = 2; InvokeOnMainThread (delegate { _CurrentState.BottomLabel.Text = "Knock to Post: 2 sec"; }); }else if(KnockCount==160){ _CurrentState.CountDown = 1; InvokeOnMainThread (delegate { _CurrentState.BottomLabel.Text = "Knock to Post: 1 sec"; }); }else if(KnockCount>200){ InvokeOnMainThread (delegate { _CurrentState.TopLabel.Text = "Follow @JoesDoor on Twitter"; _CurrentState.BottomLabel.Text = "Knock to take a photo"; }); KnockCount=0; _CurrentState.CountDown = 0; _CurrentState.didKnock=false; } }else{ InvokeOnMainThread(delegate { using (var pool = new NSAutoreleasePool ()) { _CurrentState.DisplayImageView.Image = image; } }); } } sampleBuffer.Dispose (); } catch (Exception e){ Console.WriteLine (e); } }
/// <summary> /// Encodes a frame. /// </summary> /// <param name="frame">The frame.</param> /// <returns></returns> public override byte[] Encode(AudioBuffer frame) { if (_Encoder == null) { _Encoder = new CocoaOpusEncoder(ClockRate, Channels, PacketTime); _Encoder.Quality = 1.0; _Encoder.Bitrate = 125; } using (var pool = new NSAutoreleasePool()) { GCHandle dataHandle = GCHandle.Alloc(frame.Data, GCHandleType.Pinned); try { IntPtr dataPointer = dataHandle.AddrOfPinnedObject(); using (var buffer = new CocoaOpusBuffer { Data = NSData.FromBytesNoCopy(dataPointer, (uint)frame.Data.Length, false), Index = frame.Index, Length = frame.Length }) { using (var encodedFrameData = _Encoder.EncodeBuffer(buffer)) { return encodedFrameData.ToArray(); } } } finally { dataHandle.Free(); } } }
public static void ShowProgressDialog(string title, string message, Action action, Action finalize) { UIAlertView dialog = new UIAlertView(title, message, null, null); dialog.Show(); _indicatorViewLeftCorner.Hidden = false; ThreadPool.QueueUserWorkItem(delegate { // Run the given Async task action(); // Run the completion handler on the UI thread and remove the spinner using (var pool = new NSAutoreleasePool()) { try { pool.InvokeOnMainThread(() => { dialog.DismissWithClickedButtonIndex(0, true); _indicatorViewLeftCorner.Hidden = true; finalize(); }); } catch (Exception ex){ Insights.Report(ex); } } }); }
// This method is invoked when the application has loaded its UI and its ready to run public override bool FinishedLaunching(UIApplication app, NSDictionary options) { //HttpDebug.Start (); MonoMobileApplication.NavigationController = new NavigationController(); MonoMobileApplication.Window = new UIWindow(UIScreen.MainScreen.Bounds); MonoMobileApplication.Window.AddSubview(MonoMobileApplication.NavigationController.View); MonoMobileApplication.Window.MakeKeyAndVisible(); MonoMobileApplication.NavigationController.View.Alpha = 0.0f; #if DEBUG var thread = new System.Threading.Thread(() => { using (NSAutoreleasePool pool = new NSAutoreleasePool()) { InvokeOnMainThread(()=> { Startup(); }); } }); thread.Start(); #else InvokeOnMainThread(()=> { Startup(); }); #endif return true; }
private void Init() { if (_instance == null) { _instance = this; } _id++; }
// Uncomment to demonstrate UIActiviyIndicatorView // void HandleShowActivityButtonTouchUpInside (object sender, EventArgs e) // { // _activityView = new UIActivityIndicatorView (); // // _activityView.Frame = new RectangleF (0, 0, 50, 50); // _activityView.Center = View.Center; // // _activityView.ActivityIndicatorViewStyle = UIActivityIndicatorViewStyle.WhiteLarge; // View.AddSubview (_activityView); // _activityView.StartAnimating (); // // Thread t = new Thread (DoSomething); // t.Start (); // } void DoSomething () { Thread.Sleep (3000); using (var pool = new NSAutoreleasePool ()) { this.InvokeOnMainThread (delegate { _activityView.StopAnimating (); }); } }
/// <summary> /// Populates a <see cref="T:System.Runtime.Serialization.SerializationInfo"/> with the data needed to serialize the target object. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo"/> to populate with data.</param> /// <param name="context">The destination (see <see cref="T:System.Runtime.Serialization.StreamingContext"/>) for this serialization.</param> /// <exception cref="T:System.Security.SecurityException"> /// The caller does not have the required permission. /// </exception> public void GetObjectData (SerializationInfo info, StreamingContext context) { // As pool are scoped, it does not hurt if we create ours during the method call. using (NSAutoreleasePool pool = new NSAutoreleasePool()) { NSData data = this.TIFFRepresentation; info.AddValue ("Data", data.GetBuffer (), typeof(byte[])); } }
private static void Run() { NSAutoreleasePool pool = new NSAutoreleasePool (); Console.WriteLine ("Hello World !!!"); pool.Release (); }
/// <summary> /// The main entry point for the application. /// </summary> static void Main (string[] args) { NSApplication.Init (); using (var p = new NSAutoreleasePool ()) { NSApplication.SharedApplication.Delegate = new AppDelegate (); NSApplication.Main (args); } }
protected override void HandleThreadMethod() { using(var pool = new NSAutoreleasePool()) { // Run code in new thread clientInfo.BeginReceive(); } }
public override bool SetRequestInterval(double intervalInSeconds) { using (var pool = new NSAutoreleasePool ()) { Thread thread = new Thread (SetRequestIntervalThread); thread.Priority = ThreadPriority.AboveNormal; thread.Start ((object)intervalInSeconds); } return true; }
public void Start() { using(var pool = new NSAutoreleasePool()) { ThreadStart threadDelegate = new ThreadStart (HandleThreadMethod); Thread thread = new Thread (threadDelegate); thread.Start (); } }
public override bool StartTracking(string webServerUrl, string trackId) { using (var pool = new NSAutoreleasePool ()) { Thread thread = new Thread (StartTrackingThread); thread.Priority = ThreadPriority.AboveNormal; thread.Start (new object[]{webServerUrl, trackId}); } return true; }
public override bool DownloadFile(string url) { using (var pool = new NSAutoreleasePool ()) { NSUrl urlParam = new NSUrl (Uri.EscapeUriString(url)); var thread = new Thread (OpenUrlOnThread); thread.Start (urlParam); } return true; }
public void HideSearchingView() { using(var pool = new NSAutoreleasePool()) { pool.BeginInvokeOnMainThread(() => { IsSearching = false; _SearchingView.Hidden = true; }); } }
private void Startup () { using (var pool = new NSAutoreleasePool ()) { InvokeOnMainThread (delegate { var binding = new BindingContext (new MovieListView (), "Movie List View"); navigation.ViewControllers = new UIViewController[] { new DialogViewController (binding.Root, true) }; }); } }
// This event handler updates the progress bar. private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e) { NSAutoreleasePool pool = new NSAutoreleasePool(); this.progressIndicator.DoubleValue = e.ProgressPercentage; this.labelResult.StringValue = "Progress is " + e.ProgressPercentage + "%"; pool.Release(); }
public override bool FinishedLaunching(UIApplication app, NSDictionary options) { using (var pool = new NSAutoreleasePool()) { _window = CreateMainWindow(); _window.MakeKeyAndVisible(); } return true; }
private void PlayVibration () { using (var pool = new NSAutoreleasePool ()) { // Run code in new thread while (PLAYING_VIBRATION) { SystemSound.Vibrate.PlaySystemSound (); Thread.Sleep (VIBRATION_FREQUENCY); } } }
private void Startup() { using (var pool = new NSAutoreleasePool()) { InvokeOnMainThread(delegate { var binding = new BindingContext(new MovieListView(), "MVVM Sample"); navigation.ViewControllers = new UIViewController[] { new DialogViewController(UITableViewStyle.Grouped, binding, true) };//{Autorotate = true } }; }); } }
private void Notify() { using(NSAutoreleasePool pool = new NSAutoreleasePool()) { GC.WaitForPendingFinalizers(); GC.Collect(); GC.WaitForPendingFinalizers(); NSNotificationCenter.DefaultCenter.PostNotificationNameObject(MyListener.SELECTOR_NOTIFICATION, null); mre.Set(); } }
// iOS specific function to sync to main thread void SyncToMain (List<SearchResultItem> results) { this.InvokeOnMainThread (delegate { using (var pool = new NSAutoreleasePool ()) { _results = results; TableView.ReloadData (); UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false; } }); }
static void Main(string[] args) { #if !MACOS Game = new CastleGame(); Game.Run(); #else NSApplication.Init (); using (var p = new NSAutoreleasePool ()) { NSApplication.SharedApplication.Delegate = new AppDelegate (); NSApplication.Main (args); } #endif }
private void FetchAndBindTweets() { using (var networkActivity = new NetworkActivity()) { using (var threadAutoRelease = new NSAutoreleasePool()) { var twitterXml = XDocument.Load("http://search.twitter.com/search.atom?q=%23NDC2010"); BindTweetsToTable(twitterXml); } } UnblockUI(); }
// Private Callback function for CVDisplayLink private CVReturn MyDisplayLinkOutputCallback(CVDisplayLink displayLink, ref CVTimeStamp inNow, ref CVTimeStamp inOutputTime, CVOptionFlags flagsIn, ref CVOptionFlags flagsOut) { //CVReturn result = GetFrameForTime (inOutputTime); CVReturn result = CVReturn.Error; // There is no autorelease pool when this method is called because it will be called from a background thread // It's important to create one or you will leak objects using (NSAutoreleasePool pool = new NSAutoreleasePool()) { // Update the animation BeginInvokeOnMainThread(RenderScene); result = CVReturn.Success; } return(result); }
private void InsertAlertNotification(string title, string msg) { using (var a = new NSAutoreleasePool()) { notificationCenter.BeginInvokeOnMainThread(delegate { NSUserNotification notification = new NSUserNotification(); notification.Title = title; notification.InformativeText = msg; NSMutableDictionary userInfo = new NSMutableDictionary(); userInfo.Add((NSString)notificationType, (NSString)notificationTypeAlert); notification.UserInfo = userInfo; notification.DeliveryDate = NSDate.Now; notificationCenter.DeliverNotification(notification); }); } }
//[Export("InitializeUnity")] private void InitializeUnity() { if (performSecurityChecks()) { #if DEBUG log("Security checks passed... initializing Appverse..."); #endif using (var pool = new NSAutoreleasePool()) { Thread thread = new Thread(InitializeUnityServer); // as ThreadStart thread.Priority = ThreadPriority.AboveNormal; thread.Start(); } } }
void DoSomethingElse() { int n = 3; for (int i = 0; i < n; i++) { Thread.Sleep(1000); using (var pool = new NSAutoreleasePool()) { this.InvokeOnMainThread(delegate { _progressView.Progress = (float)(i + 1) / n; }); } } }
static void Main(string[] args) { #if MONOMAC NSApplication.Init(); using (var p = new NSAutoreleasePool()) { NSApplication.SharedApplication.Delegate = new AppDelegate(); NSApplication.Main(args); } #elif __IOS__ UIApplication.Main(args, null, "AppDelegate"); #else RunGame(); #endif }
void HandleGetMenuLastUpdateCompleted (object sender, GetMenuLastUpdateCompletedEventArgs args) { bool error = ServiceAgent.HandleAsynchCompletedError (args, "GetMenuLastUpdate"); using (var pool = new NSAutoreleasePool()) { pool.InvokeOnMainThread (delegate { Busy = false; if (error) return; var updateDate = args.Result; this.Display(updateDate); }); } }
/// <summary> /// Probably could not connect to the App Store (network unavailable?) /// </summary> public override void RequestFailed(SKRequest request, NSError error) { try { using (var pool = new NSAutoreleasePool()) { NSDictionary userInfo = NSDictionary.FromObjectsAndKeys(new NSObject[] { error }, new NSObject[] { new NSString("error") }); NSNotificationCenter.DefaultCenter.PostNotificationName(InAppPurchaseManagerRequestFailedNotification, this, userInfo); } } catch (Exception ex) { Logger.Log("ERROR: RequestFailed: " + ex); } }
public static void Main(string[] args) { NSApplication.Init(); using (var p = new NSAutoreleasePool()) { NSApplication.SharedApplication.Delegate = new AppDelegate(); // TODO: Offer a way of setting the application icon. //NSImage appIcon = NSImage.ImageNamed("monogameicon.png"); //NSApplication.SharedApplication.ApplicationIconImage = appIcon; NSApplication.Main(args); } }
private void ExecuteCommandThread() { using (var pool = new NSAutoreleasePool()) { InvokeOnMainThread(delegate { if (Command.CanExecute(CommandParameter)) { Command.Execute(CommandParameter); } Animating = false; }); } }
/// <summary> /// Checks if is available for monitoring /// </summary> /// <returns></returns> public bool AvailableForMonitoring() { bool retVal = false; RequestAlwaysAuthorization(); if (!CLLocationManager.LocationServicesEnabled) { string message = string.Format("{0} - {1}", CrossGeofence.Id, "You need to enable Location Services"); System.Diagnostics.Debug.WriteLine(message); CrossGeofence.GeofenceListener.OnError(message); } else if (CLLocationManager.Status == CLAuthorizationStatus.Denied || CLLocationManager.Status == CLAuthorizationStatus.Restricted) { string message = string.Format("{0} - {1}", CrossGeofence.Id, "You need to authorize Location Services"); System.Diagnostics.Debug.WriteLine(message); CrossGeofence.GeofenceListener.OnError(message); } else if (CLLocationManager.IsMonitoringAvailable(typeof(CLRegion))) { if (RequestNotificationPermission) { using (var pool = new NSAutoreleasePool()) { pool.InvokeOnMainThread(() => { var settings = UIUserNotificationSettings.GetSettingsForTypes( UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound, new NSSet()); UIApplication.SharedApplication.RegisterUserNotificationSettings(settings); }); } } retVal = true; } else { string message = string.Format("{0} - {1}", CrossGeofence.Id, "Not available for monitoring"); System.Diagnostics.Debug.WriteLine(message); CrossGeofence.GeofenceListener.OnError(message); } return(retVal); }
private void CreateAbout() { using (var a = new NSAutoreleasePool()) { string about_image_path = UIHelpers.GetImagePathname("about"); this.about_image = new NSImage(about_image_path) { Size = new SizeF(640, 260) }; this.about_image_view = new NSImageView() { Image = this.about_image, Frame = new RectangleF(0, 0, 640, 260) }; this.version_text_field = new NSTextField() { StringValue = string.Format(Properties_Resources.Version, Controller.RunningVersion, Controller.CreateTime.GetValueOrDefault().ToString("d")), Frame = new RectangleF(295, 140, 318, 22), BackgroundColor = NSColor.White, Bordered = false, Editable = false, DrawsBackground = false, TextColor = NSColor.FromCalibratedRgba(0.45f, 0.62f, 0.81f, 1.0f), Font = NSFontManager.SharedFontManager.FontWithFamily("Lucida Grande", NSFontTraitMask.Unbold, 0, 11) }; this.credits_text_field = new NSTextField() { StringValue = @"Copyright © 2013-" + DateTime.Now.Year + " GRAU DATA AG, Hylke Bons and others." + "\n" + "\n" + "DataSpace Sync is Open Source software. You are free to use, modify, and redistribute it " + "under the GNU General Public License version 3 or later.", Frame = new RectangleF(295, Frame.Height - 260, 318, 98), TextColor = NSColor.FromCalibratedRgba(0.45f, 0.62f, 0.81f, 1.0f), DrawsBackground = false, Bordered = false, Editable = false, Font = NSFontManager.SharedFontManager.FontWithFamily("Lucida Grande", NSFontTraitMask.Unbold, 0, 11), }; ContentView.AddSubview(this.about_image_view); ContentView.AddSubview(this.version_text_field); ContentView.AddSubview(this.credits_text_field); } }
/// <summary> /// Decodes an encoded frame. /// </summary> /// <param name="encodedFrame">The encoded frame.</param> /// <returns></returns> public override VideoBuffer Decode(byte[] encodedFrame) { if (_Decoder == null) { _Decoder = new CocoaVp8Decoder(); } if (_Padep.SequenceNumberingViolated) { _Decoder.NeedsKeyFrame = true; return(null); } using (var pool = new NSAutoreleasePool()) { GCHandle encodedFrameHandle = GCHandle.Alloc(encodedFrame, GCHandleType.Pinned); try { IntPtr encodedFramePointer = encodedFrameHandle.AddrOfPinnedObject(); using (var encodedFrameData = NSData.FromBytesNoCopy(encodedFramePointer, (uint)encodedFrame.Length, false)) { using (var buffer = new CocoaVp8Buffer()) { if (_Decoder.DecodeFrame(encodedFrameData, buffer)) { var planeYData = new byte[buffer.PlaneY.Length]; var planeUData = new byte[buffer.PlaneU.Length]; var planeVData = new byte[buffer.PlaneV.Length]; Marshal.Copy(buffer.PlaneY.Bytes, planeYData, 0, (int)buffer.PlaneY.Length); Marshal.Copy(buffer.PlaneU.Bytes, planeUData, 0, (int)buffer.PlaneU.Length); Marshal.Copy(buffer.PlaneV.Bytes, planeVData, 0, (int)buffer.PlaneV.Length); return(new VideoBuffer(buffer.Width, buffer.Height, new[] { new VideoPlane(planeYData, buffer.StrideY), new VideoPlane(planeUData, buffer.StrideU), new VideoPlane(planeVData, buffer.StrideV) }, VideoFormat.I420)); } return(null); } } } finally { encodedFrameHandle.Free(); } } }
public override bool OpenBrowserWithOptions(SecondaryBrowserOptions browserOptions) { using (var pool = new NSAutoreleasePool()) { var thread = new Thread(OpenBrowserWithOptionsOnThread); if (browserOptions == null) { browserOptions = new SecondaryBrowserOptions(); } else { browserOptions.CheckNullsAndSetDefaults(); } thread.Start(browserOptions); } return(true); }
private CVReturn GetFrameForTime(CVTimeStamp outputTime) { // There is no autorelease pool when this method is called because it will be called from a background thread // It's important to create one or you will leak objects using (NSAutoreleasePool pool = new NSAutoreleasePool()) { // Update the animation double current = DateTime.Now.TimeOfDay.TotalMilliseconds; controller.Scene.advanceTimeBy((float)(current - controller.RenderTime)); controller.RenderTime = (float)current; BeginInvokeOnMainThread(DrawView); } return(CVReturn.Success); }
public void FinishTransaction(SKPaymentTransaction transaction, bool wasSuccessful) { SKPaymentQueue.DefaultQueue.FinishTransaction(transaction); using (var pool = new NSAutoreleasePool()) { NSDictionary userInfo = NSDictionary.FromObjectsAndKeys(new NSObject[] { transaction }, new NSObject[] { new NSString("transaction") }); if (wasSuccessful) { NSNotificationCenter.DefaultCenter.PostNotificationName(InAppPurchaseManagerTransactionSucceededNotification, this, userInfo); } else { NSNotificationCenter.DefaultCenter.PostNotificationName(InAppPurchaseManagerTransactionFailedNotification, this, userInfo); } } }
public UI() { using (var a = new NSAutoreleasePool()) { NSApplication.SharedApplication.ApplicationIconImage = NSImage.ImageNamed("cmissync-app.icns"); SetFolderIcon(); Setup = new SetupWizardController(); About = new About(); StatusIcon = new StatusIcon(); Settings = new GeneralSettingsController(); Program.Controller.UIHasLoaded(); } }
void PostToTwitter() { //Goto https://apps.twitter.com/ and create a new app to post to. using (var pool = new NSAutoreleasePool()) { using (NSData imageData = _state.DisplayImageView.Image.AsPNG()) { Byte[] myByteArray = new Byte[imageData.Length]; System.Runtime.InteropServices.Marshal.Copy(imageData.Bytes, myByteArray, 0, Convert.ToInt32(imageData.Length)); var client = new RestClient("https://api.twitter.com"); //Get all 4 token and secret vallues from your twitter add @ https://apps.twitter.com/ client.Authenticator = RestSharp.Authenticators.OAuth1Authenticator.ForProtectedResource("CustomerKey", "CustomerSecret", "Token", "TokenSecret"); var request = new RestRequest("/1.1/statuses/update_with_media.json", Method.POST); request.AddFile("media[]", myByteArray, "share.jpg"); client.Execute(request); } } }
void RequestAlwaysAuthorization() { if (!RequestLocationPermission) { return; } if (isPromptingLocationPermission) { return; } isPromptingLocationPermission = true; CLAuthorizationStatus status = CLLocationManager.Status; if (status == CLAuthorizationStatus.AuthorizedWhenInUse || status == CLAuthorizationStatus.Denied) { using (var pool = new NSAutoreleasePool()) { pool.InvokeOnMainThread(() => { UIAlertView alertView = new UIAlertView() { Title = (status == CLAuthorizationStatus.Denied) ? "Location services are off" : "Background location is not enabled", Message = "To use background location you must turn on 'Always' in the Location Services Settings" }; alertView.AddButton("OK"); alertView.Clicked += (sender, buttonArgs) => { if (buttonArgs.ButtonIndex == 1) { // Send the user to the Settings for this app NSUrl settingsUrl = new NSUrl(UIApplication.OpenSettingsUrlString); UIApplication.SharedApplication.OpenUrl(settingsUrl); } isPromptingLocationPermission = false; }; alertView.Show(); }); } } else if (status == CLAuthorizationStatus.NotDetermined) { locationManager.RequestAlwaysAuthorization(); } }
public CGImage CreateImageWithAutoReleasePool(int c = 1) { using (var pool = new NSAutoreleasePool()) { var colorSpace = CGColorSpace.CreateDeviceRGB(); var width = 1000; var height = 1000; var bitsPerSample = 8; var components = 3;//RGB var bitsPerPixel = bitsPerSample * components; var bytesPerRow = bitsPerPixel / 8 * width; var bufferToDisplay = new byte[width * height * components]; var bufferDontUse = new byte[width * height * components * 2]; System.Diagnostics.Debug.WriteLine($" Allocated buffer size {bufferToDisplay.Length} + {bufferDontUse.Length}"); System.Diagnostics.Debug.WriteLine($" before local GC {GC.GetTotalMemory(false) - baseMemory}"); bufferDontUse = null; GC.Collect(); System.Diagnostics.Debug.WriteLine($" after local GC {GC.GetTotalMemory(false) - baseMemory}"); int a = 0; for (int cnt = 0; cnt < width * height; cnt++) { bufferToDisplay[a++] = c % 3 == 0 ? (byte)0xFF : (byte)0x00; bufferToDisplay[a++] = c % 3 == 1 ? (byte)0xFF : (byte)0x00; bufferToDisplay[a++] = c % 3 == 2 ? (byte)0xFF : (byte)0x00; } using (var data = new CGDataProvider(bufferToDisplay)) { var cgImage = new CGImage( width, height, bitsPerSample, bitsPerPixel, bytesPerRow, colorSpace, CGBitmapFlags.ByteOrderDefault, data, decode: null, shouldInterpolate: false, intent: CGColorRenderingIntent.Default); bufferToDisplay = null; return(cgImage); } } }
public override void Published(NSNetService sender) { ThreadStart ts = new ThreadStart(delegate { using (var pool = new NSAutoreleasePool()) { try { string hostName = String.Format("{0}.local", Dns.GetHostName()); IPHostEntry hostEntry = Dns.GetHostEntry(hostName); IPAddress serverAddress = hostEntry.AddressList[1]; _controller._tcpServer = new TcpListener(serverAddress, sender.Port); _controller._tcpServer.Start(); Log("server started"); int maxReadSize = 1024; byte[] requestBuffer = new Byte[maxReadSize]; while (true) { TcpClient connectingClient = _controller._tcpServer.AcceptTcpClient(); using (NetworkStream netStream = connectingClient.GetStream()) { int size = netStream.Read(requestBuffer, 0, requestBuffer.Length); string request = Encoding.ASCII.GetString(requestBuffer, 0, size); Log(String.Format("server received: {0}", request)); string response = String.Format("server echoed: {0}", request); byte[] responseBuffer = Encoding.ASCII.GetBytes(response); netStream.Write(responseBuffer, 0, responseBuffer.Length); Log(response); } connectingClient.Close(); } } catch (SocketException e) { Log(String.Format("SocketException: {0}, Native Error Code = {0}", e.Message, e.NativeErrorCode)); } } }); Thread t = new Thread(ts); t.Start(); }
private void InitializeGameComponents() { // There is no autorelease pool when this method is called because it will be called from a background thread // It's important to create one or you will leak objects using (NSAutoreleasePool pool = new NSAutoreleasePool()) { // Leave the following code there just in case there are problems // with the intialization hack. //foreach (GameComponent gc in _gameComponentCollection) { //foreach (IGameComponent gc in _gameComponentsToInitialize) { // foreach (IGameComponent gc in _gameComponentCollection) { // // We may be drawing on a secondary thread through the display link or timer thread. // // Add a mutex around to avoid the threads accessing the context simultaneously // _view.OpenGLContext.CGLContext.Lock (); // // // set our current context // _view.MakeCurrent (); // // gc.Initialize (); // // // now unlock it // _view.OpenGLContext.CGLContext.Unlock (); // _gameComponentsToInitialize.Remove(gc); // } // Changed from foreach to for loop in case the GameComponents's Update method // modifies the component collection. With a foreach it causes an error: // "Collection was modified; enumeration operation may not execute." // .Net 4.0 I thought got around this but in Mono 2.10.2 we still get this error. for (int x = 0; x < _gameComponentCollection.Count; x++) { var gc = (GameComponent)_gameComponentCollection[x]; // We may be drawing on a secondary thread through the display link or timer thread. // Add a mutex around to avoid the threads accessing the context simultaneously _gameWindow.OpenGLContext.CGLContext.Lock(); // set our current context _gameWindow.MakeCurrent(); gc.Initialize(); // now unlock it _gameWindow.OpenGLContext.CGLContext.Unlock(); _gameComponentsToInitialize.Remove(gc); } } }
static void Main(string[] args) { NSApplication.Init(); //NSApplication.Main(args); SciterBootstrap.Mono.Setup(); using (var p = new NSAutoreleasePool()) { NSApplication.SharedApplication.Delegate = new AppDelegate(); // Set our Application Icon //NSImage appIcon = NSImage.ImageNamed ("monogameicon.png"); //NSApplication.SharedApplication.ApplicationIconImage = appIcon; NSApplication.SharedApplication.Run(); } }
public void WorkerThread() { using (NSAutoreleasePool autoReleasePool = new NSAutoreleasePool()) { if (!DownloadPathExists) { Directory.CreateDirectory(Path.Combine(BasePath, DownloadFilepath)); } Program.ThumbnailPath = DownloadImageToFile(Path.Combine(BasePath, DownloadFilepath), Program.ProgramId, Program.ThumbnailUrl); Program.ThumbnailPath = Program.ProgramId + "/" + Program.ThumbnailPath; Program.MoviePath = OutputFilename; DownloadToFile(StreamingUrl, Path.Combine(BasePath, Program.MoviePath), OnDownloadProgress, OnDownloadFinished); } }
private protected override void SwapBuffersCore(Swapchain swapchain) { MTLSwapchain mtlSC = Util.AssertSubtype <Swapchain, MTLSwapchain>(swapchain); IntPtr currentDrawablePtr = mtlSC.CurrentDrawable.NativePtr; if (currentDrawablePtr != IntPtr.Zero) { using (NSAutoreleasePool.Begin()) { MTLCommandBuffer submitCB = _commandQueue.commandBuffer(); submitCB.presentDrawable(currentDrawablePtr); submitCB.commit(); } } mtlSC.GetNextDrawable(); }
static void Main(string[] args) { #if MONOMAC NSApplication.Init(); using (var p = new NSAutoreleasePool()) { NSApplication.SharedApplication.Delegate = new AppDelegate(); NSApplication.Main(args); } #elif __IOS__ || __TVOS__ UIApplication.Main(args, null, "AppDelegate"); #else //RunGame(); Comentado temporalmente para facer pruebas de paso de mensaje new PingPong(); #endif }
private void InsertNotificationCredentials(string reponame) { RemoveNotificationCredentials(reponame); using (var a = new NSAutoreleasePool()) { notificationCenter.BeginInvokeOnMainThread(delegate { NSUserNotification notification = new NSUserNotification(); notification.Title = reponame; notification.Subtitle = String.Format(Properties_Resources.NotificationCredentialsError, reponame); notification.InformativeText = Properties_Resources.NotificationChangeCredentials; NSMutableDictionary userInfo = new NSMutableDictionary(); userInfo.Add((NSString)notificationType, (NSString)notificationTypeCredentials); notification.UserInfo = userInfo; notification.DeliveryDate = NSDate.Now; notificationCenter.DeliverNotification(notification); }); } }
public void NoStrongCycles() { bool finalizedAnyCtor = false; bool finalizedAnyAddTarget1 = false; bool finalizedAnyAddTarget2 = false; // Add the gesture recognizers to a list so that they're not collected until after the test // This is to avoid false positives (the callback should be collectible already after disposing the gesture recognizer). var list = new List <UIGestureRecognizer> (); var pool = new NSAutoreleasePool(); for (var k = 0; k < 10; k++) { { var notifier = new FinalizerNotifier(() => finalizedAnyCtor = true); using (var gr = new UIGestureRecognizer(() => { GC.KeepAlive(notifier); // Make sure the 'notifier' instance is only collected if the delegate to UIGestureRecognizer is collectable. })) { list.Add(gr); } } { var notifier = new FinalizerNotifier(() => finalizedAnyAddTarget1 = true); using (var gr = new UIGestureRecognizer()) { gr.AddTarget(() => { GC.KeepAlive(notifier); }); list.Add(gr); } } { var notifier = new FinalizerNotifier(() => finalizedAnyAddTarget2 = true); using (var gr = new UIGestureRecognizer()) { gr.AddTarget((obj) => { GC.KeepAlive(notifier); }); list.Add(gr); } } } pool.Dispose(); TestRuntime.RunAsync(DateTime.Now.AddSeconds(1), () => { GC.Collect(); }, () => finalizedAnyCtor && finalizedAnyAddTarget1 && finalizedAnyAddTarget2); Assert.IsTrue(finalizedAnyCtor, "Any finalized"); Assert.IsTrue(finalizedAnyAddTarget1, "AddTarget1 finalized"); Assert.IsTrue(finalizedAnyAddTarget2, "AddTarget2 finalized"); GC.KeepAlive(list); }
public void Invoke(Action action) { using (var pool = new NSAutoreleasePool()) { try { pool.InvokeOnMainThread(delegate { action.Invoke(); }); } catch (Exception) { //TODO : Error msg ? } } }
private void QueueDownloads(List <Item> items) { using (NSAutoreleasePool pool = new NSAutoreleasePool()) { try { _isWorking = true; _waithandle = new AutoResetEvent(false); for (int i = 0; i < items.Count; i++) { // Check if the image is there (repair mode) if (File.Exists(Util.GetImageFullPath(items[i].ImageUrl))) { items[i].ImageFilename = GetImageFilename(items[i]); items[i].SetImageDownloaded(); continue; } ThreadInfo info = new ThreadInfo(); info.Item = items[i]; info.WaitHandle = _waithandle; ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadEntry), info); bool success = _waithandle.WaitOne(_timeout); if (!success) { Logger.Info("[Warning] ImageDownloader WaitOne timed out for {0}", items[i].Id); } // Call regardless of success OnImageSaved(EventArgs.Empty); } } catch (Exception ex) { Logger.Warn("Exception in ImageDownloader.DownloadStart: {0}", ex.ToString()); } finally { OnComplete(EventArgs.Empty); _isWorking = false; } } }
/// <summary> /// Plaies the NS URL. /// </summary> /// <returns> /// <c>true</c>, if NS URL was played, <c>false</c> otherwise. /// </returns> /// <param name='nsUrl'> /// Ns URL. /// </param> private bool PlayNSUrl(NSUrl nsUrl) { if (nsUrl != null) { if (playerController != null && this.State == MediaState.Playing) { // if player is already playing, stop it. Stop(); } // TODO check if we are paused on the same file or not, to re-start player data. if (playerController == null) { try { using (var pool = new NSAutoreleasePool()) { var thread = new Thread(ShowMediaPlayer); thread.Start(nsUrl); }; } catch (Exception) { SystemLogger.Log(SystemLogger.Module.PLATFORM, "Error trying to get media file [" + nsUrl + "]"); } } /* * if(playerController != null) { * // Start Playing. * bool playing = playerController.Play(); * if(playing) { * this.State = MediaState.Playing; * } * return playing; * } */ return(true); } else { INotification notificationService = (INotification)IPhoneServiceLocator.GetInstance().GetService("notify"); if (notificationService != null) { notificationService.StartNotifyAlert("Media Alert", "Media file cannot be reproduced on on this device.", "OK"); } return(false); } }
private void StartThread() { using (NSAutoreleasePool pool = new NSAutoreleasePool()) { FeedUpdater updater = new FeedUpdater(); updater.FeedSaved += new EventHandler(FeedSaved); try { List <Item> newItems = updater.Update(); // Show the progress bar InvokeOnMainThread(delegate { _activityIndicator.StopAnimating(); _progressView.Alpha = 1f; }); // Save all the items to SQLite if (newItems.Count > 0) { _newFeedCount = newItems.Count; updater.SaveItems(newItems); } // Download images if (_newFeedCount > 0 && Settings.Current.UserSettings.ImagesEnabled) { _saveCount = 0; ImageDownloader.Current.ImageSaved += DownloaderImageSaved; ImageDownloader.Current.PreDownloadForCategories(); UpdateProgressAmount(1); } } catch (ThreadAbortException) { // Stop downloads ImageDownloader.Current.TryStop(); } finally { OnLoadingComplete(EventArgs.Empty); } } }