Ejemplo n.º 1
0
 private void ShowClosedQRCode(string qr)
 {
     MainThread.BeginInvokeOnMainThread(async() => {
         StackLayout rootStack = new StackLayout()
         {
             WidthRequest      = 350,
             HeightRequest     = 350,
             VerticalOptions   = LayoutOptions.FillAndExpand,
             HorizontalOptions = LayoutOptions.FillAndExpand
         };
         GenerateButton.IsVisible = false;
         rootLayout.Children.Add(rootStack);
         qrCode = null;
         qrCode = GenerateQR(qr);
         rootStack.Children.Add(qrCode);
     });
 }
Ejemplo n.º 2
0
        private async void RefreshStatusData(object statusInfo)
        {
            try
            {
                string data = string.Empty;

                using (var wc = new WebClient())
                {
                    data = await wc.DownloadStringTaskAsync(Path.Combine(AppEnvironment.serverRoot, "api", "iothub", "devices", "status", "info", Device.MACAddress));
                }

                Device.StatusArgument = data;

                MainThread.BeginInvokeOnMainThread(() => { RefreshStatus(); });
            }
            catch { }
        }
Ejemplo n.º 3
0
        public static void LoadMap()
        {
            var strRoute = string.Empty;

            MainThread.BeginInvokeOnMainThread(async() =>
            {
                try
                {
                    var options = new PickOptions
                    {
                        PickerTitle = "Please select a map file",
                        FileTypes   = new FilePickerFileType(new Dictionary <DevicePlatform, IEnumerable <string> >
                        {
                            /**///What is mime type for mbtiles ?!?
                            //{ DevicePlatform.Android, new string[] { "mbtiles"} },
                            { DevicePlatform.Android, null },
                        })
                    };

                    var sourceFile = await FilePicker.PickAsync(options);
                    if (sourceFile != null)
                    {
                        string destinationFile = MainActivity.rootPath + "/MBTiles/" + sourceFile.FileName;

                        if (File.Exists(destinationFile))
                        {
                            Show_Dialog msg1 = new Show_Dialog(MainActivity.mContext);
                            if (await msg1.ShowDialog($"Overwrite", $"Overwrite '{sourceFile.FileName}'", Android.Resource.Attribute.DialogIcon, true, Show_Dialog.MessageResult.NO, Show_Dialog.MessageResult.YES) == Show_Dialog.MessageResult.NO)
                            {
                                return;
                            }
                        }

                        File.Copy(sourceFile.FullPath, destinationFile, true);
                        Fragments.Fragment_map.map.Layers.Add(CreateMbTilesLayer(destinationFile, sourceFile.FileName));

                        Show_Dialog msg2 = new Show_Dialog(MainActivity.mContext);
                        await msg2.ShowDialog($"Done", $"Map Imported and Loaded", Android.Resource.Attribute.DialogIcon, true, Show_Dialog.MessageResult.NONE, Show_Dialog.MessageResult.OK);
                    }
                }
                catch (Exception ex)
                {
                    Log.Information($"Failed to import map file: '{ex}'");
                }
            });
        }
Ejemplo n.º 4
0
        public static async Task <UserActivitySession> AddToTimeLine(string area, ModelBase theModel, string bodyText)
        {
            UserActivitySession returnedFromUIThread = await MainThread.InvokeOnMainThreadAsync(async() =>
            {
                UserActivitySession activitySession = null;

                try
                {
                    // Record in the TimeLine
                    UserActivityChannel channel = UserActivityChannel.GetDefault();

                    UserActivity _ModelUserActivity = await channel.GetOrCreateUserActivityAsync(theModel.HLinkKey.Value);

                    if (theModel.Valid)
                    {
                        _ModelUserActivity.VisualElements.DisplayText     = area.ToUpper();
                        _ModelUserActivity.VisualElements.Description     = bodyText;
                        _ModelUserActivity.VisualElements.BackgroundColor = ColorExtensions.ToPlatformColor(theModel.ModelItemGlyph.SymbolColour);

                        // _ModelUserActivity.VisualElements.Content =
                        // AdaptiveCardBuilder.CreateAdaptiveCardFromJson(CreateAdaptiveCardForTimeline(area,
                        // theModel, bodyText).ToJson());

                        _ModelUserActivity.ActivationUri = new Uri("gramps://" + area + @"/handle/" + theModel.HLinkKey);

                        //Save
                        await _ModelUserActivity.SaveAsync();

                        if (_ModelUserActivity != null)
                        {
                            activitySession = _ModelUserActivity.CreateSession();
                        }
                    }
                }
                catch (Exception ex)
                {
                    DataStore.Instance.CN.NotifyException("Timeline Add", ex);

                    throw;
                }

                return(activitySession);
            }).ConfigureAwait(false);

            return(returnedFromUIThread);
        }
Ejemplo n.º 5
0
        public MainView(MainViewModel viewModel)
        {
            InitializeComponent();
            BindingContext = viewModel;

            MainThread.BeginInvokeOnMainThread(async() =>
            {
                var location = await Geolocation.GetLastKnownLocationAsync();

                if (location == null)
                {
                    location = await Geolocation.GetLocationAsync();
                }

                Map.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(location.Latitude, location.Longitude), Distance.FromKilometers(5)));
            });
        }
Ejemplo n.º 6
0
 public void StopRead()
 {
     try
     {
         StopReadUI();
         if (_app.IsRFIDReady())
         {
             MainThread.BeginInvokeOnMainThread(() =>
             {
                 StopReadInternal();
             });
         }
     }
     catch (Exception e)
     {
     }
 }
Ejemplo n.º 7
0
        public void Init()
        {
            bool isFirstLaunch = Properties.LauncherSettings.Default.CurrentProfile == "" || Properties.LauncherSettings.Default.IsFirstLaunch;

            MainFrame_KeyboardNavigationMode_Default = KeyboardNavigation.GetTabNavigation(MainThread.MainFrame);

            ConfigManager.Init();
            ConfigManager.OnConfigStateChanged(this, Events.ConfigStateArgs.Empty);

            // show first launch window if no profile
            if (isFirstLaunch)
            {
                SetOverlayFrame(new WelcomePage(), false);
            }
            MainThread.NavigateToMainPage();
            ProgressBarStateChanged += ViewModel_ProgressBarStateChanged;
        }
Ejemplo n.º 8
0
    public void EstablishConnection(LoginClientLL login_service, RepeatedField <LoginServices.Server> servers)
    {
        Debug.Assert(servers.Count > 0);
        Debug.Assert(base_service == null, "A base service operation is already taking place...");
        Debug.Assert(login_service == null, "Internal error. login service and base service always has to be in sync...");

        login_service.OnDisconnected       += on_login_client_disconnected;
        login_service.OnServerDisconnected += on_main_server_caused_disconnection;

        var selected_server_idx = MainThread <System.Random> .Get().Next(0, servers.Count - 1);

        selected_server                        = servers[selected_server_idx];
        base_service                           = new BaseClientLL(new Channel(selected_server.Url, ChannelCredentials.Insecure)); //TODO: SSL, Compression
        base_service.OnDisconnected           += on_base_server_disconnected;
        base_service.OnSuccessfulSubscription += on_successful_subscription;
        base_service.ConnectAsync();
    }
Ejemplo n.º 9
0
        static void ThreadSaveMethod(string path, object graph, Action onComplete = null)
        {
            BinaryFormatter bf   = new BinaryFormatter();
            FileStream      file = File.Open(path, FileMode.OpenOrCreate);

            bf.Serialize(file, graph);
            file.Close();

            if (MainThread.instance == null)
            {
                UnityEngine.Debug.Log("MainThread.cs not in the scene.");
            }
            lock (MainThread.instance)
            {
                MainThread.AddAction(onComplete);
            }
        }
        public async void LoginByUserNameAndPassword( )
        {
            string              url      = "https://api.shikkhanobish.com/api/Master/GetInfoByLogin";
            HttpClient          client   = new HttpClient();
            string              jsonData = JsonConvert.SerializeObject(new { UserName = studentm.UserName, Password = studentm.Password });
            StringContent       content  = new StringContent(jsonData, Encoding.UTF8, "application/json");
            HttpResponseMessage response = await client.PostAsync(url, content).ConfigureAwait(false);

            string result = await response.Content.ReadAsStringAsync();

            Student student = JsonConvert.DeserializeObject <Student> (result);

            MainThread.BeginInvokeOnMainThread(async( ) =>
            {
                await Application.Current.MainPage.Navigation.PushModalAsync(new StudentProfile(student)).ConfigureAwait(false);
            });
        }
Ejemplo n.º 11
0
    public void StartRecording(UnityAction <AudioClip> completeCallback, int maxClipLenth = 99)
    {
        mOnCompleteCallback = completeCallback;
        mRecordingClip      = Microphone.Start(null, true, maxClipLenth, mSampleRate);

        mIsRecording = true;

        System.Threading.Timer timer = null;
        timer = new System.Threading.Timer((obj) =>
        {
            if (mIsRecording)
            {
                MainThread.invoke(EndRecording);
                timer.Dispose();
            }
        }, null, 1000 * maxClipLenth, System.Threading.Timeout.Infinite);
    }
Ejemplo n.º 12
0
        async void LoadContact()
        {
            bottomLayout.IsVisible = true;
            await Task.Run(async() =>
            {
                var keyValuePairs = contact.GetAllContact();
                MainThread.BeginInvokeOnMainThread(() =>
                {
                    bottomLayout.IsVisible = false;
                    // Code to run on the main thread

                    totalContactItems = (IEnumerable <ContactGroup>)keyValuePairs["Group"];
                    totalContactItemsWithoutGrouping = (IEnumerable <ContactItem>)keyValuePairs["List"];
                    contactList.ItemsSource          = totalContactItems;
                });
            });
        }
        public async Task LoadData()
        {
            var request  = new GeolocationRequest(GeolocationAccuracy.Medium);
            var location = await Geolocation.GetLocationAsync(request);

            if (location != null)
            {
                var response = await ISSDataService.GetISSFlyByTime(location.Latitude, location.Longitude, 10);

                MainThread.BeginInvokeOnMainThread(() =>
                {
                    ISSFlyByTimesResponse = response;

                    ISSFlyByResponses = new ObservableCollection <Response>(ISSFlyByTimesResponse.Response);
                });
            }
        }
Ejemplo n.º 14
0
 private void WalkTimerLoop(object sender, ElapsedEventArgs e)
 {
     MainThread.BeginInvokeOnMainThread(() => {
         // Check if audio is not playing
         if (!am.IsMusicActive)
         {
             TimeSpan gameDuration = e.SignalTime - startTimeGame;
             // Detect Shock
             if (accelerometerReader.shacked)
             {
                 stateMachine.Fire(Trigger.Shocking);
             }
             // Detect roll or pitch
             else if (PitchOrRoll())
             {
                 stateMachine.Fire(Trigger.Rolling);
             }
             // Detect End
             else if (OnTable() && (gameDuration.Seconds > 20))
             {
                 stateMachine.Fire(Trigger.Finish);
             }
             // Check time for well
             else
             {
                 TimeSpan nbTime = e.SignalTime - startTimeWalk;
                 if (nbTime.Seconds > timeForWell && lastWell != 2)
                 {
                     mediaPlayer = MediaPlayer.Create(this, voiceChoose[8]);
                     tvInfo.Text = alternativeText[8];
                     mediaPlayer.Start();
                     lastWell      = 2;
                     startTimeWalk = DateTime.Now;
                 }
                 else if (nbTime.Seconds > timeForWell / 2 && lastWell != 1)
                 {
                     mediaPlayer = MediaPlayer.Create(this, voiceChoose[7]);
                     tvInfo.Text = alternativeText[7];
                     mediaPlayer.Start();
                     lastWell      = 1;
                     startTimeWalk = DateTime.Now;
                 }
             }
         }
     });
 }
Ejemplo n.º 15
0
 public PullCommand(
     MainThread mainThread,
     IRepository repository,
     IEventStream eventStream,
     CredentialsHandler credentials,
     ICommandService commandService,
     IShell shell,
     SyncView view)
 {
     this.mainThread     = mainThread;
     this.repository     = repository;
     this.eventStream    = eventStream;
     this.credentials    = credentials;
     this.commandService = commandService;
     this.shell          = shell;
     this.view           = view;
 }
Ejemplo n.º 16
0
        /// <inheritdoc/>
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            CrossCurrentActivity.Current.Init(this, savedInstanceState);
            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            Xamarin.Forms.Forms.Init(this, savedInstanceState);
            CachedImageRenderer.Init(true);
            var ignore = typeof(SvgCachedImage);

            if (Build.VERSION.SdkInt >= BuildVersionCodes.Kitkat && this.Window != null)
            {
                this.Window.SetFlags(WindowManagerFlags.LayoutNoLimits, WindowManagerFlags.LayoutNoLimits);
            }

            MainThread.BeginInvokeOnMainThread(() => this.LoadApplication(Startup.Init(this.ConfigureServices, CrossCurrentActivity.Current.Activity)));
        }
Ejemplo n.º 17
0
        public ChartSamples()
        {
            // Sample 1
            MainThread.BeginInvokeOnMainThread(async() =>
            {
                var streamImageSource = ImageSource.FromResource("UrhoCharts.Forms.Example.Resources.sample1.jpg") as StreamImageSource;
                using (var imageStream = await streamImageSource.Stream(CancellationToken.None))
                {
                    var jpegImage = new JpegImage(imageStream);
                    var imageData = new byte[jpegImage.Width * jpegImage.Height];
                    for (var i = 0; i < jpegImage.Height; i++)
                    {
                        var row = jpegImage.GetRow(i);
                        Buffer.BlockCopy(src: row.ToBytes(),
                                         srcOffset: 0,
                                         dst: imageData,
                                         dstOffset: (i * jpegImage.Width),
                                         count: jpegImage.Width);
                    }

                    Sample1 = new SurfaceChart
                    {
                        XSize = jpegImage.Width,
                        YSize = jpegImage.Height,
                        ZData = imageData,
                    };
                }
            });

            // Sample 2
            Sample2 = new SurfaceChart
            {
                XSize = 100,
                YSize = 100,
            };

            Sample2.ZData = new byte[Sample2.XSize * Sample2.YSize];
            for (var x = 0; x < Sample2.XSize; x++)
            {
                for (var y = 0; y < Sample2.YSize; y++)
                {
                    Sample2.ZData[x * Sample2.XSize + y]
                        = (byte)(240 * ((Math.Sin(x * Math.PI / Sample2.XSize) * Math.Cos(y * Math.PI / Sample2.YSize) + 1) / 2) + 8);
                }
            }
        }
Ejemplo n.º 18
0
        /** Adds new messages on top. */
        private void OnNewMessageItem(DebugViewModel.MessageItem msg)
        {
            MainThread.BeginInvokeOnMainThread(() => {
                var label    = new Label();
                label.Margin = 10;
                label.Text   = msg.Text;

                if (msg.TextColor != null)
                {
                    label.TextColor = Color.FromHex(msg.TextColor);
                }

                var cell  = new ViewCell();
                cell.View = label;
                Messages.Insert(0, cell);
            });
        }
Ejemplo n.º 19
0
        private void UpdateDashBoard()
        {
            MainThread.BeginInvokeOnMainThread(() => {
                NormalModeDashBoard info = _normalModeInfo;
                _onceCntTv.Text          = info.OnceCount + "";
                _onceNumTv.Text          = info.OnceNum + "";
                _onceTimeTv.Text         = info.OnceTime + "ms";

                if (info.TotalTime > 500)
                {
                    _totalCntTv.Text     = info.TotalCount + "";
                    _totalNumTv.Text     = TotalNum + "";
                    _totalTimeTv.Text    = info.TotalTime + "ms";
                    _averageSpeedTv.Text = info.NumPerSecond + "pcs/s";
                }
            });
        }
Ejemplo n.º 20
0
        protected virtual void OnAgentConnected()
        {
            ClientSession.Agent.Api.Messages.Subscribe(new Observer <object> (HandleAgentMessage));

            void HandleAgentMessage(object message)
            {
                if (message is CapturedOutputSegment segment)
                {
                    MainThread.Post(() => RenderCapturedOutputSegment(segment));
                }

                if (message is Evaluation result)
                {
                    MainThread.Post(() => RenderResult(result));
                }
            }
        }
Ejemplo n.º 21
0
 private bool EntrenarLloyd()
 {
     try
     {
         App.Lloyd = new Lloyd()
         {
             Tolerancia  = float.Parse(LloydTolerancia.Text.Replace('.', ',')),
             Iteraciones = int.Parse(LloydIteraciones.Text),
             Aprendizaje = float.Parse(LloydAprendizaje.Text.Replace('.', ',')),
             Centros     = new List <Muestra>()
             {
                 new Muestra()
                 {
                     Medidas = new List <double>()
                     {
                         double.Parse(Clase1Centro1.Text.Replace('.', ',')),
                         double.Parse(Clase1Centro2.Text.Replace('.', ',')),
                         double.Parse(Clase1Centro3.Text.Replace('.', ',')),
                         double.Parse(Clase1Centro4.Text.Replace('.', ','))
                     }
                 },
                 new Muestra()
                 {
                     Medidas = new List <double>()
                     {
                         double.Parse(Clase2Centro1.Text.Replace('.', ',')),
                         double.Parse(Clase2Centro2.Text.Replace('.', ',')),
                         double.Parse(Clase2Centro3.Text.Replace('.', ',')),
                         double.Parse(Clase2Centro4.Text.Replace('.', ','))
                     }
                 }
             },
             Datos    = CopiarDatos(App.Data),
             Muestras = App.Muestras
         };
         App.Lloyd.Entrenar();
         return(true);
     }
     catch (Exception ex)
     {
         MainThread.BeginInvokeOnMainThread(() =>
                                            DisplayAlert("Error", ex.Message, "OK"));
         return(false);
     }
 }
Ejemplo n.º 22
0
        public CaptionReaderViewModel()
        {
            userId        = Guid.NewGuid().ToString();
            fullLanguages = new List <string>();
            Languages     = new ObservableRangeCollection <string>();
            Captions      = new ObservableRangeCollection <FullCaption>();

            GetLanguagesCommand   = new Command(async() => await ExecuteGetLanguagesCommand());
            ChangeLanguageCommand = new Command(async() => await ExecuteChangeLanguageCommand());

            var url = $"{Constants.ApiBaseUrl}/api/{userId}";

            hubConnection = new HubConnectionBuilder()
                            .WithUrl($"{Constants.ApiBaseUrl}/api/{userId}")
                            .Build();

            hubConnection.On <JObject>("newCaption", (caption) =>
            {
                var fullCaption = caption.ToObject <Caption>();

                var text   = fullCaption.Text;
                var offset = fullCaption.Offset;

                if (string.IsNullOrWhiteSpace(text))
                {
                    return;
                }

                MainThread.BeginInvokeOnMainThread(() =>
                {
                    var current = Captions.FirstOrDefault(c => c.Offset == offset);
                    if (current == null)
                    {
                        Captions.Insert(0, new FullCaption {
                            Offset = offset, Text = text
                        });
                        OnPropertyChanged(nameof(Captions));
                    }
                    else
                    {
                        current.Text = text;
                    }
                });
            });
        }
Ejemplo n.º 23
0
        static void Main(string[] args)
        {
            Console.WriteLine("请输入命令开启功能");
            Console.WriteLine("1.更新问题总页数:P");
            Console.WriteLine("2.开始获取问题:Q");
            Console.WriteLine("3.开始获取收藏夹答案列表:A");
            Console.WriteLine("4.退出:EXIT");
            string consoleCode = Console.ReadLine().ToLower().Trim();

            while (consoleCode != "exit")
            {
                if (consoleCode == "p")
                {
                    QuestionBusiness.RefreshQuestionPageCount();
                }
                if (consoleCode == "q")
                {
                    Console.WriteLine("输入线程数量");
                    string threadCount        = Console.ReadLine().ToLower().Trim();
                    int    threadCountDefault = 5;
                    int.TryParse(threadCount, out threadCountDefault);
                    MainThread mainThread = new MainThread();
                    mainThread.GetQuestionInfo(threadCountDefault);
                }
                if (consoleCode == "a")
                {
                    Console.WriteLine("输入线程数量");
                    string threadCount        = Console.ReadLine().ToLower().Trim();
                    int    threadCountDefault = 5;
                    int.TryParse(threadCount, out threadCountDefault);
                    MainThread mainThread = new MainThread();
                    mainThread.GetCollectionDetail(threadCountDefault);
                }
                if (consoleCode == "m")
                {
                    MongoBusiness.CollectionBusiness.ConvertCollectionInfoToMongoDB();
                }
                else
                {
                    Console.WriteLine("未知命令...\r\n请重新输入...");
                    //CollectionBusiness.LoadCollectionIDsFormFile();
                }
                consoleCode = Console.ReadLine();
            }
        }
Ejemplo n.º 24
0
        void IToastPlatformService.Show(string text, int duration)
        {
            try
            {
                if (MainThread.IsMainThread)
                {
                    Show_();
                }
                else
                {
                    MainThread.BeginInvokeOnMainThread(Show_);
                }

                void Show_()
                {
                    var context   = Application.Context;
                    var duration2 = (ToastLength)duration;

                    // https://blog.csdn.net/android157/article/details/80267737
                    try
                    {
                        if (toast == null)
                        {
                            toast = AndroidToast.MakeText(context, text, duration2);
                            if (toast == null)
                            {
                                throw new NullReferenceException("toast markeText Fail");
                            }
                        }
                        else
                        {
                            toast.Duration = duration2;
                        }
                        SetTextAndShow(toast, text);
                    }
                    catch (Exception e)
                    {
                        Log.Error(TAG, $"text: {text}{Environment.NewLine}{e}");
                        // 解决在子线程中调用Toast的异常情况处理
                        Looper.Prepare();
                        var _toast = AndroidToast.MakeText(context, text, duration2)
                                     ?? throw new NullReferenceException("toast markeText Fail(2)");
                        SetTextAndShow(_toast, text);
                        Looper.Loop();
                    }
        private void UpdateThumbnailDisplay()
        {
            // Ensure to be on Main UI Thread
            if (!MainThread.IsMainThread)
            {
                MainThread.BeginInvokeOnMainThread(() => UpdateThumbnailDisplay());
                return;
            }

            string filePath = Helper.SdkWrapper.GetThumbnailFullFilePath(attachmentId);

            try
            {
                log.LogDebug("[DisplayThumbnail] FileId:[{0}] - Use filePath:[{1}]", attachmentId, filePath);
                System.Drawing.Size size = ImageTools.GetImageSize(filePath);
                if ((size.Width > 0) && (size.Height > 0))
                {
                    double density = Helper.GetDensity();

                    // Avoid to have a thumbnail too big
                    float scaleWidth  = (float)(MAX_IMAGE_SIZE * density) / (float)size.Width;
                    float scaleHeight = (float)(MAX_IMAGE_SIZE * density) / (float)size.Height;
                    float scale       = Math.Min(scaleHeight, scaleWidth);

                    // Don't increase size of the thumbnail
                    if (scale > 1)
                    {
                        scale = 1;
                    }

                    // Calculate size of the thumbnail
                    int w = (int)(size.Width * scale);
                    int h = (int)(size.Height * scale);

                    Image.HeightRequest = (int)Math.Round(h / density);
                    Image.WidthRequest  = (int)Math.Round(w / density);
                    Image.Source        = ImageSource.FromFile(filePath);
                    Image.IsVisible     = true;

                    //if we have a thumbnail, we don't display the file name
                    LabelBody.Text = "";
                }
            }
            catch { }
        }
Ejemplo n.º 26
0
        public static void OnSettingsChanged(ChangeType changeType, string persistenceId, string persistenceContext, string objectContent)
        {
            if (changeType != ChangeType.Saved)
            {
                return;
            }

            if (DetectSettingsChanges)
            {
                lock (_settingsChangesLock)
                {
                    try
                    {
                        switch (persistenceId)
                        {
                        case "LanguageID":
                        {
                            string langId = objectContent;
                            if (langId != _languageId)
                            {
                                _languageId = langId;
                                MainThread.Post((c) => Translator.SetInterfaceLanguage(_languageId));
                            }
                        }
                        break;

                        case "SkinType":
                        {
                            string skinType = objectContent;
                            if (skinType != _skinType)
                            {
                                _skinType = skinType;
                                MainThread.Post((c) => EventDispatch.DispatchEvent(EventNames.ThemeUpdated));
                            }
                        }
                        break;
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.LogException(ex);
                    }
                }
            }
        }
Ejemplo n.º 27
0
        protected override void OnAppearing()
        {
            base.OnAppearing();

            // Thread de background
            Task.Run(async() =>
            {
                // Buffer para a inicialização
                await Task.Delay(500);

                // Animação inicial
                MainThread.BeginInvokeOnMainThread(() =>
                {
                    stack.FadeTo(1, 1000, Easing.CubicOut);
                    stack.TranslateTo(0, 48, 1000, Easing.CubicOut);
                    image.TranslateTo(0, -48, 1000, Easing.CubicOut);
                });

                // Aguarda as animações
                await Task.Delay(2000);

                // Inicializando os serviços necessários
                var applicationService = DependencyService.Get <IApplicationService>();
                var httpService        = DependencyService.Get <IHttpService>();

                // Checa as informações de usuário no cache do dispositivo
                var accessToken = Preferences.Get(PreferenceKeys.AccessToken, null);
                var cpf         = Preferences.Get(PreferenceKeys.UsuarioCpf, null);
                var senhaHash   = Preferences.Get(PreferenceKeys.UsuarioSenhaHash, null);

                // Caso não exista nada, ir para autenticacao
                MainThread.BeginInvokeOnMainThread(async() =>
                {
                    if (string.IsNullOrWhiteSpace(cpf) || string.IsNullOrWhiteSpace(senhaHash) || string.IsNullOrWhiteSpace(accessToken))
                    {
                        await Shell.Current.GoToAsync($"//{Rotas.Autenticacao}");
                        return;
                    }

                    // Caso exista algo, ir para tela inicial após definir o access token no header padrão do HttpClient
                    httpService.SetBearer(accessToken);
                    await Shell.Current.GoToAsync($"//{Rotas.MeuPerfil}");
                });
            });
        }
Ejemplo n.º 28
0
        private async void updatePoiCommand(object obj)
        {
            string resultValidateText = getValidatePoiText();

            if (string.IsNullOrEmpty(resultValidateText))
            {
                PoiApiRequest poiApi = new PoiApiRequest(_authToken);
                _vpoi.UpdateDate = DateTimeOffset.Now;
                bool resultUpload = await poiApi.UploadPoiAsync(_vpoi.GetJsonStructure());

                if (resultUpload)
                {
                    applyChanges();

                    string msgText = CommonResource.PoiMsg_Warning;
                    if (!string.IsNullOrEmpty(_vpoi.ByRouteId))
                    {
                        var route = new ViewRoute(_vpoi.ByRouteId);
                        if ((!route.IsPublished) && (_vpoi.IsPublished))
                        {
                            msgText = CommonResource.PoiMsg_RouteAvailableOnlyForMe;
                        }
                    }

                    MessagingCenter.Send <PoiUpdatedMessage>(new PoiUpdatedMessage()
                    {
                        PoiId = _vpoi.Id
                    }, string.Empty);
                    MainThread.BeginInvokeOnMainThread(() =>
                    {
                        UserDialogs.Instance.Alert(msgText, CommonResource.PoiMsg_Saved, CommonResource.CommonMsg_Ok);
                    });


                    await Navigation.PopModalAsync();
                }
            }
            else
            {
                MainThread.BeginInvokeOnMainThread(() =>
                {
                    UserDialogs.Instance.Alert(resultValidateText, CommonResource.CommonMsg_Warning, CommonResource.CommonMsg_Ok);
                });
            }
        }
Ejemplo n.º 29
0
        public void UpdateLyrics(string artist, string song)
        {
            string message;

            try
            {
                var search     = artist + " " + song;
                var lyricsInfo = lyricsClient.SearchLyricsAsync(artist, song);
                songTextView.SetText(lyricsInfo.Song, TextView.BufferType.Normal);
                artistTextView.SetText(lyricsInfo.Artist, TextView.BufferType.Normal);
                lyricsTextView.SetText(lyricsInfo.Lyrics, TextView.BufferType.Normal);

                if (lyricsInfo.ThumbnailUrl != null)
                {
                    Thread thread = new Thread(() =>
                    {
                        HttpClient client = new HttpClient();
                        var stream        = client.GetStreamAsync(lyricsInfo.ThumbnailUrl).GetAwaiter().GetResult();
                        Drawable d        = Drawable.CreateFromStream(stream, "src");
                        MainThread.BeginInvokeOnMainThread(() => {
                            thumbnailImageView.SetImageDrawable(d);
                        });
                        stream.Dispose();
                        client.Dispose();
                    });
                    thread.Start();
                }

                message = $"{lyricsInfo.Artist} {lyricsInfo.Song}";
                //  ShowNotification(message);
            }
            catch (Exception e)
            {
                message = $"Exception: {e.Message}";
            }

            try
            {
                Toast.MakeText(this, message, ToastLength.Short)
                .Show();
            }
            catch (Exception)
            {
            }
        }
        private void DisplayAd(VisxAdManager visxAdManager)
        {
            /// Adding Vis.X Universal Ad to the created Android
            /// native View and invoced on the main Xamarin thread
            Android.Widget.RelativeLayout container = new Android.Widget.RelativeLayout(_context);

            MainThread.BeginInvokeOnMainThread(() =>
            {
                container = _adContainer.FindViewById <Android.Widget.RelativeLayout>(Resource.Id.inlineContainer);

                if (visxAdManager.AdContainer.Parent != null)
                {
                    visxAdManager.AdContainer.RemoveFromParent();
                }

                container.AddView(visxAdManager.AdContainer);
            });
        }
Ejemplo n.º 31
0
 static void Main(string[] args)
 {
     Console.WriteLine("请输入命令开启功能");
     Console.WriteLine("1.更新问题总页数:P");
     Console.WriteLine("2.开始获取问题:Q");
     Console.WriteLine("3.开始获取收藏夹答案列表:A");
     Console.WriteLine("4.退出:EXIT");
     string consoleCode = Console.ReadLine().ToLower().Trim();
     while (consoleCode != "exit")
     {
         if (consoleCode == "p")
         {
             QuestionBusiness.RefreshQuestionPageCount();
         }
         if (consoleCode == "q")
         {
             Console.WriteLine("输入线程数量");
             string threadCount = Console.ReadLine().ToLower().Trim();
             int threadCountDefault = 5;
             int.TryParse(threadCount, out threadCountDefault);
             MainThread mainThread = new MainThread();
             mainThread.GetQuestionInfo(threadCountDefault);
         }
         if (consoleCode == "a")
         {
             Console.WriteLine("输入线程数量");
             string threadCount = Console.ReadLine().ToLower().Trim();
             int threadCountDefault = 5;
             int.TryParse(threadCount, out threadCountDefault);
             MainThread mainThread = new MainThread();
             mainThread.GetCollectionDetail(threadCountDefault);
         }
         if (consoleCode == "m")
         {
             MongoBusiness.CollectionBusiness.ConvertCollectionInfoToMongoDB();
         }
         else
         {
             Console.WriteLine("未知命令...\r\n请重新输入...");
             //CollectionBusiness.LoadCollectionIDsFormFile();
         }
         consoleCode = Console.ReadLine();
     }
 }
Ejemplo n.º 32
0
        private void Compare(bool compareAgain , bool withFilter)
        {
            statusBarPanel.ProgressBar.Value = statusBarPanel.ProgressBar.Minimum;

            if(!compareAgain)
            {
                OpenFileDialog theOpenFileDialog = new OpenFileDialog();

                theOpenFileDialog.Filter = "DCM files (*.dcm) |*.dcm|All files (*.*)|*.*";
                theOpenFileDialog.Title = "Select first DCM file";
                theOpenFileDialog.Multiselect = false;
                theOpenFileDialog.ReadOnlyChecked = true;

                // Show the file dialog.
                // If the user pressed the OK button...
                if (theOpenFileDialog.ShowDialog() == DialogResult.OK)
                {
                    // Add all DCM files selected.
                    firstDCMFile = theOpenFileDialog.FileName;
                    theOpenFileDialog.Filter = "DCM files (*.dcm) |*.dcm|All files (*.*)|*.*";
                    theOpenFileDialog.Title = "Select second DCM file";
                    theOpenFileDialog.Multiselect = false;
                    theOpenFileDialog.ReadOnlyChecked = true;

                    if (theOpenFileDialog.ShowDialog() == DialogResult.OK)
                    {
                        secondDCMFile = theOpenFileDialog.FileName;
                    }
                    else
                    {
                        return;
                    }
                }
                else
                {
                    return;
                }
            }

            //Update the title of the form
            string theNewText = "DCMCompare Tool - ";
            theNewText+= string.Format("Comparing {0} and {1}", firstDCMFile, secondDCMFile);
            Text = theNewText;

            //Initialize and Execute the script session
            if(theMainSessionThread == null)
            {
                dvtThreadMgr = new ThreadManager();

                theMainSessionThread = new MainThread();
                theMainSessionThread.Initialize(dvtThreadMgr);
                theMainSessionThread.Options.Identifier = "DCM_Compare";
                theMainSessionThread.Options.LogThreadStartingAndStoppingInParent = false;
                theMainSessionThread.Options.LogChildThreadsOverview = false;

                // Load the Dvtk Script session
                theMainSessionThread.Options.LoadFromFile(Application.StartupPath + @"\Script.ses");

                DirectoryInfo resultDirectory = new DirectoryInfo(theMainSessionThread.Options.ResultsDirectory);
                if(!resultDirectory.Exists)
                {
                    resultDirectory.Create();
                }

                theMainSessionThread.Options.StrictValidation = true;

                theMainSessionThread.Options.StartAndStopResultsGatheringEnabled = true;
                theMainSessionThread.Options.ResultsFileNameOnlyWithoutExtension =
                    string.Format("{0:000}", theMainSessionThread.Options.SessionId) +
                    "_" + theMainSessionThread.Options.Identifier + "_res";

                detailXmlFullFileName = theMainSessionThread.Options.DetailResultsFullFileName;
                summaryXmlFullFileName = theMainSessionThread.Options.SummaryResultsFullFileName;

                menuItemCompareAgain.Visible = true;
            }

            if(withFilter)
            {
                //Populate the Filtered Attributes List
                if(listBoxFilterAttr.Items.Count != 0)
                {
                    foreach( object listItem in listBoxFilterAttr.Items)
                    {
                        string attributeStr = listItem.ToString().Trim();
                        attributesTagList.Add(attributeStr);
                    }
                }
            }

            //Start the execution
            theMainSessionThread.Start();
            for(int i=0; i< 10; i++)
            {
                statusBarPanel.ProgressBar.PerformStep();
                System.Threading.Thread.Sleep(250);
            }

            dvtThreadMgr.WaitForCompletionThreads();

            //Stop the thread
            if(theMainSessionThread  != null)
            {
                theMainSessionThread.Stop();
                theMainSessionThread = null;
                dvtThreadMgr = null;
            }

            //Display the results
            this.ShowResults();
        }
Ejemplo n.º 33
0
		public DICOMEditor()
		{
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();

			// Initialize the Dvtk library
			Dvtk.Setup.Initialize();

			_DCMdataset = new HLI.DataSet();
			_FileMetaInfo = new FileMetaInformation();

			_AttributesInfoForDataGrid = new ArrayList();
			_FMIForDataGrid = new ArrayList();
			InitializeDatasetGrid();
			InitializeFMIGrid();

			// Get the session context 
			ThreadManager threadMgr = new ThreadManager();
			_MainThread = new MainThread();
			_MainThread.Initialize(threadMgr);
	
			// Subscribe to Dvtk Activity report handler
			activityReportEventHandler = new Dvtk.Events.ActivityReportEventHandler(OnActivityReportEvent);

			// Subscribe to Sniffer Activity report handler
			activityLoggingDelegate = new appendTextToActivityLogging_ThreadSafe_Delegate(this.AppendTextToActivityLogging_ThreadSafe);

            // Provide functionality to open application with Media file or Directory
            // which contains Media files
			if(dcmFileOrDirToBeOpened != "")
			{
				DirectoryInfo userDirInfo = new DirectoryInfo(dcmFileOrDirToBeOpened.Trim());
				if(userDirInfo.Exists)
				{
                    //It's a directory contains Media files
					this.dirListBox.Path = userDirInfo.FullName;
					this.fileListBox.Path = this.dirListBox.Path;
				}
				else
				{
                    //It's a Media file
					FileInfo dcmFileInfo = new FileInfo(dcmFileOrDirToBeOpened.Trim());

					this.dirListBox.Path = dcmFileInfo.DirectoryName;
					this.fileListBox.Path = this.dirListBox.Path;
					this.fileListBox.SelectedItem = dcmFileInfo.Name;
				}				
			}
		}
Ejemplo n.º 34
0
		private void GetDetailedLogging()
		{
			ThreadManager threadMgr = new ThreadManager();
			MainThread loggingThread = new MainThread(DCMFile);
			loggingThread.Initialize(threadMgr);

			loggingThread.Options.CopyFrom(_MainThread.Options);
			loggingThread.Options.Identifier = "DICOM Editor";
			loggingThread.Options.DvtkScriptSession.LogLevelFlags = LogLevelFlags.Error | LogLevelFlags.Warning | LogLevelFlags.Info;
			loggingThread.Options.LogThreadStartingAndStoppingInParent = false;
			loggingThread.Options.LogChildThreadsOverview = false;
			loggingThread.Options.StrictValidation = true;
			loggingThread.Options.StartAndStopResultsGatheringEnabled = true;
			loggingThread.Options.ResultsFileNameOnlyWithoutExtension = 
				string.Format("{0:000}", loggingThread.Options.SessionId) +
				"_" + loggingThread.Options.Identifier + "_res";

			string detailXmlFullFileName = loggingThread.Options.DetailResultsFullFileName;
			string summaryXmlFullFileName = loggingThread.Options.SummaryResultsFullFileName;

			//Start the execution
			loggingThread.Start();

			threadMgr.WaitForCompletionThreads();

			//Stop the thread
			if(loggingThread  != null)
			{
				loggingThread.Stop();
				loggingThread = null;
				threadMgr = null;
			}

			//Display the results
			DetailLogging loggingDlg = new DetailLogging();
			loggingDlg.ShowResults(detailXmlFullFileName,summaryXmlFullFileName);
			loggingDlg.ShowDialog();
		}