Exemple #1
0
        public static ChessMove GetBestMove(ChessBoard board, int depth, Progress progress)
        {
            Evaluator e = new Evaluator();
             EvaluatedMove root = new EvaluatedMove(null, board);
             e.Minimax(root, depth, progress);
             EvaluatedMove[] bestMoves = root.Next.Where(m => (m != null) && (m.BestNextMoveValue == root.BestNextMoveValue)).ToArray();
             IOrderedEnumerable<EvaluatedMove> orderedMoves = bestMoves.OrderBy(m => m.MateDepth); //.ThenBy(m => board[m.Move.Source]);
             if (board.IsBlacksTurn)
            orderedMoves = orderedMoves.ThenBy(m=>m.AccumulatedMoveValues);
             else
            orderedMoves = orderedMoves.ThenByDescending(m => m.AccumulatedMoveValues);
             EvaluatedMove[] bestOrderedMoves = orderedMoves.ToArray();

             if (random == null) random = new Random();
             int moveIndex = -1;
             for (int i = 1; i < bestOrderedMoves.Length; i++ )
             {
            if ((bestOrderedMoves[i].AccumulatedMoveValues != bestOrderedMoves[i - 1].AccumulatedMoveValues)
               /*|| (board[bestOrderedMoves[i].Move.Source] != board[bestOrderedMoves[i - 1].Move.Source])*/
               || (bestOrderedMoves[i].MateDepth != bestOrderedMoves[i-1].MateDepth))
            {
               moveIndex = random.Next(i);
               break;
            }
             }
             if (moveIndex < 0)
            moveIndex = random.Next(bestOrderedMoves.Length);
             return bestOrderedMoves[moveIndex].Move;
        }
Exemple #2
0
        private async void btnCompare_Click(object sender, EventArgs e)
        {
            if (!Directory.Exists(txtFolder1.Text))
                throw new ApplicationException("Directory does not exist");

            if (!Directory.Exists(txtFolder2.Text))
                throw new ApplicationException("Directory does not exist");

            if (CurrentWorkspace != null)
            {
                traverse.ExcludeFolders.AddRange(CurrentWorkspace.Exclusions);
                traverse.ExcludePatterns.AddRange(CurrentWorkspace.ExclusionPatterns);
            }

            var progressIndicator = new Progress<string>(ReportScanProgress);
            await traverse.Compare(txtFolder1.Text, txtFolder2.Text, progressIndicator);

            differences = traverse.Differences;
            //view = new BindingListView<FileDiff>(differences);
            //dataGridView1.DataSource = view;

            lblStatus.Text = string.Format("Scanned {0} directories, {1} differences", traverse.TotalDirectories, traverse.Differences.Count());

            DrawTree(DiffType.Lenght | DiffType.LastWritten | DiffType.ExistInSourceOnly | DiffType.ExistInDestinationOnly);
        }
		private async void MeasureButton_Click(object sender, RoutedEventArgs e)
		{
			string message = null;
			try
			{
				var symbol = this.Resources["PolylineSymbol"] as LineSymbol;
				var progress = new Progress<GeometryEditStatus>(OnStatusUpdated);
				var geometry = await MyMapView.Editor.RequestShapeAsync(DrawShape.Polyline, symbol, progress);
				var layer = MyMapView.Map.Layers["ResultLayer"] as GraphicsLayer;
				if (layer == null)
					return;
				layer.Graphics.Clear();
				_measurements.Clear();
				TotalLength.Text = TotalArea.Text = string.Empty;
			}
			catch (TaskCanceledException)
			{
			}
			catch (Exception ex)
			{
				message = ex.Message;
			}
			if (!string.IsNullOrWhiteSpace(message))
				await new MessageDialog(message).ShowAsync();
		}
 public DbOperationThread(etDbOperation eOpType, TestApplet formParent, string sPath)
 {
     m_eOperationType = eOpType;
     m_formParent = formParent;
     m_sPath = sPath;
     m_Progress = m_formParent.UpdateProgressBar;
 }
        public async Task TakeSnapshot(IProgress<Tuple<BackupStage, int>> Progress) {
            Contract.Requires(Progress != null);


            Progress.Report(Tuple.Create(BackupStage.AppData, 0));

            var currentSettings = Settings.CurrentSettings;

            var currentProfile = Profile.CurrentProfilePath();
            var snapshotDir = GetSnapshotPath(currentSettings);

            var appDataProgress = new Progress<int>(p => Progress.Report(Tuple.Create(BackupStage.AppData, p)));

            try {
                using (var isoStore = IsolatedStorageFile.GetUserStoreForApplication()) {
                    await isoStore.CopyDirectoryAsync(currentProfile, snapshotDir, appDataProgress);

                    await SaveMultimedia(isoStore, snapshotDir, Progress);

                    SaveCompletedTimeStamp(snapshotDir, isoStore);
                }
            }
            catch (IsolatedStorageException) {
                //Log
                throw;
            }
        }
        private async void button1_Click(object sender, EventArgs e)
        {
            cancelSource = new CancellationTokenSource();
            IProgress<int> progress = new Progress<int>((processValue) => { this.progressBar1.Value = processValue; });


            this.textBox1.AppendText("Starting work, please wait...");
            this.button1.Enabled = false;
            this.button2.Enabled = true;

            WasteTimeObject ad = new WasteTimeObject();
            ad.ShowProcess += UpdateProgress;

            try
            {
                Task<string> task = Task.Run(() => ad.GetSlowString(1, 10, progress, cancelSource.Token));

                DoingSomethings();

                this.textBox1.AppendText("\r\nDoingSomethings is over....");

                string result = await task;

                this.textBox1.AppendText(result);

                this.button2.Enabled = false;
            }
            catch (OperationCanceledException)
            {
                textBox1.AppendText("\r\nYou canceled the operation....");
            }
        }
        /// <summary>
        /// Train the network using specialized strategies.
        /// </summary>
        /// <returns>Whether the training was successful.</returns>
        public bool Train(IControler controler, Progress progress)
        {
            TrainingConfig config = controler.TrainingConfiguration;

            int patternCount = controler.PatternCount;
            int epochs = config.AutoTrainingEpochs.Value;
            int success = (int)(patternCount * config.AutoTrainingPercentSuccessful.Value);
            int howmany = controler.CountSuccessfulPatterns();

            if(howmany >= success)
                return true;

            int timeout = epochs;
            while(timeout-- >= 0)
            {
                if(progress != null)
                    progress((int)(100 * (epochs - (double)timeout) / epochs));

                for(int i=0;i<patternCount;i++)
                {
                    controler.SelectShuffledPattern(i);
                    controler.NeuralNetwork.TrainCurrentPattern(true, false);
                }

                howmany = controler.CountSuccessfulPatterns();
                if(howmany >= success)
                    return true;
            }

            // CLEAN UP:
            //controler.CalculateCurrentNetwork();
            return false;
        }
        public MainWindow()
        {
            AppInfo.Instance.Value.IsClosing = false;

            Crypto.LoadKey();

            progress = new Progress(this);

            InitializeComponent();

            if (!string.IsNullOrWhiteSpace(Properties.Settings.Default.username))
                AppInfo.Instance.Value.Username = Crypto.Decrypt(Properties.Settings.Default.username);
            if (!string.IsNullOrWhiteSpace(Properties.Settings.Default.password))
                AppInfo.Instance.Value.Password = Crypto.Decrypt(Properties.Settings.Default.password);

            login = new Login();

            if (string.IsNullOrWhiteSpace(AppInfo.Instance.Value.Username))
            {
                login.ShowDialog();
            }

            git = new Github(AppInfo.Instance.Value.Username, AppInfo.Instance.Value.Password);

            Initialize();
        }
        public static async Task Download(this IBlobStorage blob, string key, Action<BlobProgress> progress, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (string.IsNullOrEmpty(key)) return;

            progress(new BlobProgress(null, BlobProgressState.Running, default(ProgressInBytes)));
            
            try
            {
                var sizeInBytes = 0;
                var progressReporter = new Progress<ProgressInBytes>(p => progress(new BlobProgress(null, BlobProgressState.Running, p)));
                using (var stream = await blob.Get(key, progressReporter, cancellationToken).ConfigureAwait(false))
                {
                    try
                    {
                        sizeInBytes = (int)stream.Length;
                    }
                    catch (NotSupportedException) { }
                }

                var uri = await blob.GetUri(key).ConfigureAwait(false);
                progress(new BlobProgress(uri, BlobProgressState.Succeeded, new ProgressInBytes(sizeInBytes, sizeInBytes)));
            }
            catch
            {
                progress(new BlobProgress(null, BlobProgressState.Failed, default(ProgressInBytes)));
            }
        }
        private async void StartSpam(object sender, RoutedEventArgs e)
        {
            var progress = new Progress<string>(s => TextBoxSpam.AppendText(s));
            await Task.Factory.StartNew(() => LongWork(progress));

            TextBoxSpam.AppendText(Environment.NewLine + "Complete");
        }
Exemple #11
0
        public async Task<TempPackage> FetchAsync(Package pkg, Progress progress)
        {
            var user = pkg.Location.Host;
            var project = pkg.Location.Segments.Skip(1).SingleOrDefault()?.Trim('/');
            var props = pkg.Location.ParseQueryString();
            var url = $"https://api.github.com/repos/{user}/{project}/releases/latest";

            using (var httpClient = NetUtils.HttpClient())
            {
                var content = await httpClient.GetStringAsync(url);

                var json = fastJSON.JSON.Parse(content) as IDictionary<string, object>;
                var assets = json["assets"] as IList<object>;
                var asset = NarrowAssets(assets, props);
                var pkgUrlString = asset["browser_download_url"] as string;
                Uri pkgUri;
                if (!Uri.TryCreate(pkgUrlString, UriKind.Absolute, out pkgUri))
                {
                    throw new UriFormatException($"Could not parse output from Github API, failed to parse URI: '{pkgUrlString}'");
                }
                var result = new TempPackage
                {
                    Package = pkg,
                    WorkDirectory = new TempDirectory("winston"),
                    FileName = pkgUri.LastSegment()
                };

                using (var download = File.Open(result.FullPath, FileMode.Create, FileAccess.ReadWrite))
                {
                    await httpClient.DownloadFileAsync(pkgUri, download, progress);
                }
                progress?.CompletedDownload();
                return result;
            }
        }
Exemple #12
0
        /// <summary>
        /// Add the folder into the media library.
        /// </summary>
        public void AddFolder(string path)
        {
            // make sure the folder isnt already in the list
            bool exists = false;
            this.Foreach (delegate (TreeModel model, TreePath tree_path, TreeIter iter)
            {
                Folder node = (Folder) model.GetValue (iter, 0);
                if (node.Path == path) exists = true;
                return exists;
            });

            // add the folder if it isnt already in the list
            if (exists)
                library.MainPage.ThrowError ("The folder is already in the library:\n" + path);
            else
            {
                Folder folder = new Folder (path);
                this.AppendValues (root_iter, folder);
                library.MainPage.DataManager.AddFolder (folder);

                // load the files within the directory
                Progress progress = new Progress (library.MediaBox);
                progress.Start (Utils.FileCount (path));
                progress.Push ("Waiting in queue:  " + Utils.GetFolderName (path));

                // queue process
                delegate_queue.Enqueue (delegate {
                    addDirRecurse (path, progress, folder);
                    progress.End ();
                });
            }
        }
        public void InstallUpdateUninstall()
        {
            var service = GetPackageService();
            var progress = new Progress<ProgressMessage>(WriteProgressMessage);

            ListModules(service);

            service.Install(@"source\TestModule2_v1.0.0.zip", progress);
            ListModules(service);

            service.Install(@"source\TestModule1_v1.0.0.zip", progress);
            ListModules(service);

            service.Install(@"source\TestModule2_v1.0.0.zip", progress);
            ListModules(service);

            service.Update("TestModule2", @"source\TestModule2_v1.1.0.zip", progress);
            ListModules(service);

            service.Update("TestModule1", @"source\TestModule1_v1.1.0.zip", progress);
            ListModules(service);

            service.Update("TestModule2", @"source\TestModule2_v1.1.0.zip", progress);
            ListModules(service);

            service.Uninstall("TestModule1", progress);
            ListModules(service);

            service.Uninstall("TestModule2", progress);
            ListModules(service);

            service.Uninstall("TestModule1", progress);
            ListModules(service);
        }
        private async void ImportImages()
        {
            var dialog = new CommonOpenFileDialog();
            dialog.Filters.Add(new CommonFileDialogFilter("Images", "png,gif,jpg,jpeg,bmp"));

            dialog.Title = "Select Images";
            dialog.EnsureFileExists = true;
            dialog.EnsurePathExists = true;
            dialog.EnsureReadOnly = false;
            dialog.EnsureValidNames = true;
            dialog.Multiselect = true;
            dialog.ShowPlacesList = true;

            if (dialog.ShowDialog() != CommonFileDialogResult.Ok)
                return;

            var images = dialog.FileNames
                .Where(p => System.IO.File.Exists(p))
                .Select(p => PromptImage(new BitmapImage(new Uri(p)), p))
                .Where(m => m != null)
                .ToList();
            
            var reporter = new Progress<ProgressDialogState>();
            var stopwatch = new Stopwatch();
            var progress = ProgressDialog.Open(reporter, stopwatch);

            stopwatch.Start();
            await _importer.AddImagesAsync(images, reporter);
            stopwatch.Stop();
            progress.Close();

            RefreshSheet();
        }
Exemple #15
0
 private void bSearch_Click(object sender, EventArgs e)
 {
     var text = tSearch.Text.Trim();
     if(text.Length > 0)
     {
         flpProduct.Controls.Clear();
         Progress<ProductItem> itemProgress = new Progress<ProductItem>(
             pi =>
             {
                 flpProduct.Invoke(
                     (MethodInvoker)delegate
                     {
                         flpProduct.Controls.Add(pi);
                     });
             });
         //await Task.Factory.StartNew(() => LoadingThread.LoadProduct(@"Select * from inventory where title like '%" + text + "%'", itemProgress));
         new Loading("Searching product",
             () => LoadingThread.LoadProduct(@"Select * from inventory where title like '%" + text + "%'", itemProgress));
         flpMessage.Visible = false;
         flpProduct.Visible = true;
     }
     else
     {
         flpMessage.Visible = true;
         flpProduct.Visible = false;
     }
 }
Exemple #16
0
        public async void ReadMyXML(string year, string month)
        {
            Albums = new Albums();

            Progress<int> progress = new Progress<int>((p) => { ProgressPercent = p; });

            BasicFileDownloader bidl = new BasicFileDownloader(ToAbsoluteUri("xmlalbums.aspx?ay=" + year + "&am=" + month));
            IRandomAccessStream s = await bidl.DownloadAsync(progress);

            XmlReaderSettings settings = new XmlReaderSettings();
            settings.ConformanceLevel = ConformanceLevel.Fragment;
            settings.IgnoreWhitespace = true;
            settings.IgnoreComments = true;
            settings.Async = true;
            XmlReader reader = XmlReader.Create(s.AsStream(), settings);
            reader.ReadStartElement("Model");
            reader.ReadStartElement("Albums");
            Count = 0;
            while (reader.IsStartElement())
            {
                string albumid = reader[0];
                string album = reader[2];
                string str = reader[1];
                str = str.Replace("_s.jpg", "");
                uint count = 0;
                if (uint.TryParse(reader[3], out count))
                {
                    Album m = new Album(albumid, album, str, count);
                    Albums.Add(m);
                    Count += m.Count;
                }
                await reader.ReadAsync();
            }
        }
		public async Task WorkWithImageFileByteArrayTestAsync()
		{
			var progressEncrypt = new Progress<StreamCryptorTaskAsyncProgress>();
			var progressDecrypt = new Progress<StreamCryptorTaskAsyncProgress>();
			progressEncrypt.ProgressChanged +=
				(s, e) => { Console.WriteLine("Encrypting: " + e.ProgressPercentage + "%\n"); };
			progressDecrypt.ProgressChanged +=
				(s, e) => { Console.WriteLine("Decrypting: " + e.ProgressPercentage + "%\n"); };
			var rawFile = Path.Combine(TestContext.CurrentContext.TestDirectory, "Testfiles", "MyAwesomeChipmunkKiller.jpg");
			var outputDirectory = Path.Combine(TestContext.CurrentContext.TestDirectory, "Testfiles", "decrypted");
			const string privateKey = "31d9040b00a170532929b37db0afcb989e4175f96e5f9667ee8cbf5706679a71";
			const string publicKey = "6d0deec730700f9f60687a4e6e8755157ca22ea2f3815b9bf14b1fe9ae6a0b4d";
			var keyPair = new KeyPair(Utilities.HexToBinary(publicKey), Utilities.HexToBinary(privateKey));
			Console.Write("Encrypting testfile . . .\n");
			var encryptedFile =
				await
					Cryptor.EncryptFileWithStreamAsync(keyPair.PrivateKey, keyPair.PublicKey,
						Utilities.HexToBinary(publicKey), rawFile, progressEncrypt, outputDirectory, ".test", true);
			Console.Write("Decrypting testfile . . .\n");
			var decryptedFileObject =
				await
					Cryptor.DecryptFileWithStreamAsync(keyPair.PrivateKey,
						Path.Combine(TestContext.CurrentContext.TestDirectory, outputDirectory, encryptedFile),
						progressDecrypt);
			Console.Write("Get checksum of testfiles . . .\n");
			Assert.AreEqual(Utils.GetChecksum(rawFile), Utils.GetChecksum(decryptedFileObject.FileData));
			//clear garbage 
			File.Delete(Path.Combine(TestContext.CurrentContext.TestDirectory, outputDirectory, encryptedFile));
		}
        private async void DoBackgroundWork(Task action, Progress<double> progress)
        {
            if (progress != null)
            {
                progress.ProgressChanged += progress_ProgressChanged;
                this.progressBar.IsIndeterminate = false;
            }
            else
            {
                this.progressBar.IsIndeterminate = true;
            }

            try
            {
                action.Start();
                await action;
            }
            catch (Exception ex)
            {
                Utility.WriteToErrorLog(ex.ToString());
                Dialogs.Error("Error during asynchronous operation (see error log).");
            }
            finally
            {
                if (progress != null)
                {
                    progress.ProgressChanged -= progress_ProgressChanged;
                }
            }

            this.CanClose = true;
            this.Close();
        }
		/// <summary>
		/// Gets a list of paths for all checked plugins, then starts a task to load plugin data.
		/// Handles all work that should be done after task loading.
		/// </summary>
		/// <param name="items">ListView items to check against for plugins to load.</param>
		public static async void StartPluginLoading(IEnumerable items)
		{
			// Build paths using the local data directory and the known plugin names.
			var paths = (from ListViewItem item
						 in items
						 where item.Checked
						 select Path.Combine(Settings.DataPath, item.Text)).ToArray();

			// Used to update the listview each time a plugin loads
			var progress = new Progress<string>(update => 
			{
				PluginListWindow.Instance.UpdateList();
			});

			// Inform the user we're starting to load
			Messenger.AddMessage("Starting plugin loading...");

			// Start loading
			var task = Task.Factory.StartNew(() => OpenPlugins(paths, progress));

			// Continuation events after main plugin loading
			await task.ContinueWith(t => { Messenger.AddMessage("Finished loading plugins."); },
							TaskContinuationOptions.OnlyOnRanToCompletion);

			// Todo: Fire off ESP# function to background load/refresh reference data
		}
        public async void DecryptionCancellationTestAsync()
        {
            var cancellationTokenSource = new CancellationTokenSource();
            var progressEncrypt = new Progress<StreamCryptorTaskAsyncProgress>();
            var progressDecrypt = new Progress<StreamCryptorTaskAsyncProgress>();
            progressEncrypt.ProgressChanged +=
                (s, e) => { Console.WriteLine("Encrypting: " + e.ProgressPercentage + "%\n"); };
            progressDecrypt.ProgressChanged +=
                (s, e) =>
                {
                    if (e.ProgressPercentage > 10)
                    {
                        cancellationTokenSource.Cancel();
                    }
                    Console.WriteLine("Decrypting: " + e.ProgressPercentage + "%\n");
                };
            var RAW_FILE = Path.Combine("Testfiles", "MyAwesomeChipmunkKiller.jpg");
            var OUTPUT_DIRECTORY = Path.Combine("Testfiles", "decrypted");
            const string PRIVATE_KEY = "31d9040b00a170532929b37db0afcb989e4175f96e5f9667ee8cbf5706679a71";
            const string PUBLIC_KEY = "6d0deec730700f9f60687a4e6e8755157ca22ea2f3815b9bf14b1fe9ae6a0b4d";
            var keyPair = new KeyPair(Utilities.HexToBinary(PUBLIC_KEY), Utilities.HexToBinary(PRIVATE_KEY));
            Console.Write("Encrypting testfile . . .\n");
            var encryptedFile =
                await
                    Cryptor.EncryptFileWithStreamAsync(keyPair.PrivateKey, keyPair.PublicKey,
                        Utilities.HexToBinary(PUBLIC_KEY), RAW_FILE, progressEncrypt, OUTPUT_DIRECTORY, ".test", true, cancellationTokenSource.Token);
            Console.Write("Decrypting testfile . . .\n");
            var decryptedFile =
                await
                    Cryptor.DecryptFileWithStreamAsync(keyPair.PrivateKey, Path.Combine(OUTPUT_DIRECTORY, encryptedFile),
                        OUTPUT_DIRECTORY, progressDecrypt, cancellationToken: cancellationTokenSource.Token);

        }
		public void DecryptionCancellationTestAsync()
		{
			var cancellationTokenSource = new CancellationTokenSource();
			var progressEncrypt = new Progress<StreamCryptorTaskAsyncProgress>();
			var progressDecrypt = new Progress<StreamCryptorTaskAsyncProgress>();
			progressEncrypt.ProgressChanged +=
				(s, e) => { Console.WriteLine("Encrypting: " + e.ProgressPercentage + "%\n"); };
			progressDecrypt.ProgressChanged +=
				(s, e) =>
				{
					if (e.ProgressPercentage > 10)
					{
						cancellationTokenSource.Cancel();
					}
					Console.WriteLine("Decrypting: " + e.ProgressPercentage + "%\n");
				};
			var rawFile = Path.Combine(TestContext.CurrentContext.TestDirectory, "Testfiles", "MyAwesomeChipmunkKiller.jpg");
			var outputDirectory = Path.Combine(TestContext.CurrentContext.TestDirectory, "Testfiles", "decrypted");
			const string privateKey = "31d9040b00a170532929b37db0afcb989e4175f96e5f9667ee8cbf5706679a71";
			const string publicKey = "6d0deec730700f9f60687a4e6e8755157ca22ea2f3815b9bf14b1fe9ae6a0b4d";
			var keyPair = new KeyPair(Utilities.HexToBinary(publicKey), Utilities.HexToBinary(privateKey));
			Console.Write("Encrypting testfile . . .\n");
			var encryptedFile = Cryptor.EncryptFileWithStream(keyPair.PrivateKey, keyPair.PublicKey,
				Utilities.HexToBinary(publicKey), rawFile, outputDirectory, ".test", true);
			Console.Write("Decrypting testfile . . .\n");
			Assert.ThrowsAsync<TaskCanceledException>(async () => await
				Cryptor.DecryptFileWithStreamAsync(keyPair.PrivateKey, Path.Combine(outputDirectory, encryptedFile),
					outputDirectory, progressDecrypt, cancellationToken: cancellationTokenSource.Token));
		}
Exemple #22
0
        private static void WriteProgress(Progress callback, string message, params string[] args)
        {
            if (callback == null)
                return;

            callback(string.Format(CultureInfo.InvariantCulture, message, args));
        }
Exemple #23
0
        private async void getInfo()
        {
            StorageFile myDB;
            try
            {
                string address = @"http://artmordent.ru/cheataxi/multiplylines.cr";
                StorageFile tempFile2 = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync("info", CreationCollisionOption.ReplaceExisting);
                BackgroundDownloader manager2 = new BackgroundDownloader();
                var operation = manager2.CreateDownload(new Uri(address), tempFile2);
                IProgress<DownloadOperation> progressH = new Progress<DownloadOperation>((p) => { });
                await operation.StartAsync().AsTask(progressH);                
                myDB = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync("info");
                
                // Read the data
                var alldata = await Windows.Storage.FileIO.ReadLinesAsync(myDB);
                string[] datalines = new string[alldata.Count];
                Int32 ko = 0;
                foreach (var line in alldata)
                {
                    datalines[ko] = line.ToString();
                    ko++;
                    infoBlockMain.Text += line.ToString() + "\r\n";
                }
                
                await myDB.DeleteAsync();


            }
            catch (Exception ex)
            {
                MessageDialog dialog = new MessageDialog("Ошибка загрузки информации. Проверьте ваше соединение или попробуйте позже.", "Ошибка загрузки");
            }
        }
        public override async void receive_file(String devicename, String add, int not)
        {
            try
            {
                _httpurl = new Uri(add);
                _httpprogress = new Progress<HttpProgress>(ProgressHandler);

                HttpRequestMessage request = new HttpRequestMessage(new HttpMethod("GET"), _httpurl);
                                
                HttpBaseProtocolFilter filter = new HttpBaseProtocolFilter();
                filter.CacheControl.ReadBehavior = HttpCacheReadBehavior.MostRecent;
                filter.CacheControl.WriteBehavior = HttpCacheWriteBehavior.NoCache;

                _httpclient = new HttpClient(filter);

                _cancel_token_source = new CancellationTokenSource();
                _cancel_token = _cancel_token_source.Token;

                scan_network_speed();
                _stopwatch.Start();

                _httpresponse = await _httpclient.SendRequestAsync(request).AsTask(_cancel_token, _httpprogress);

                StorageFolder folder = KnownFolders.PicturesLibrary;
                StorageFile file = await folder.CreateFileAsync(this.filepath, CreationCollisionOption.ReplaceExisting);
                IRandomAccessStream filestream = await file.OpenAsync(FileAccessMode.ReadWrite);
                IOutputStream filewriter = filestream.GetOutputStreamAt(0);
                _datawriter = new DataWriter(filewriter);

                _timer.Cancel();

                _transferspeed /= 1024;
                _message = format_message(_stopwatch.Elapsed, "Transferspeed", _transferspeed.ToString(), " kB/s");
                this.callback.on_transfer_speed_change(_message, this.results);
                this.main_view.text_to_logs(_message.Replace("\t", " "));

                _stopwatch.Stop();

                _buffer = await _httpresponse.Content.ReadAsBufferAsync();

                _datawriter.WriteBuffer(_buffer);
                await _datawriter.StoreAsync();

                _datawriter.Dispose();
                filewriter.Dispose();
                filestream.Dispose();

                _httpresponse.Content.Dispose();
                _httpresponse.Dispose();
                _httpclient.Dispose();

                _message = format_message(_stopwatch.Elapsed, "File Transfer", "OK", this.filepath);
                this.callback.on_file_received(_message, this.results);
                this.main_view.text_to_logs(_message.Replace("\t", " "));
            }
            catch (Exception e)
            {
                append_error_tolog(e, _stopwatch.Elapsed, "");
            }            
        }
 public async Task Upload()
 {
     if (State == CANCELED)
         return;
     State = UPLOADING;
     CTS = new CancellationTokenSource();
     await Task.Delay(5000);
     Progress = new Progress<HttpProgress>(HandleProgress);
     var base64Image = await GetBase64(file);
     var response = await Images.UploadImage(base64Image, CTS.Token, Progress, Title, Description);
     if (response.IsError)
     {
         if (response.Error is TaskCanceledException)
         {
             State = CANCELED;
             Message = "Upload was canceled";
         }
         else
         {
             State = ERROR;
             Message = string.IsNullOrEmpty(response.Message) ? response?.Error?.Message : response.Message;
         }
     }
     else
     {
         State = SUCCESSFUL;
         Response = new GalleryItem(response.Content);
         Message = "Tap here to edit";
     }
 }
 private async void BeforePrint()
 {
     try
     {
         Progress<PrintProgressValue> progress = new Progress<PrintProgressValue>();
         progress.ProgressChanged += (sender, args) =>
           {
               this.progress.Maximum = args.MaxValue;
               this.progress.Value = args.CurrentValue;
               this.lbl_Info.Content = string.Format("当前正发送第 {0} 个数据,共 {1} 个数据"
                   , args.CurrentValue, args.MaxValue);
           };
         await TaskEx.Delay(2);//等待2秒,显示UI
         await TaskEx.Run(() =>
         {
             //标识打印状态
             printState = PrintState.开始打印;
             BeginPrint(progress);
         });
         btn_QuitOrChanel.Content = "关         闭";
         lbl_Info.Content = isCancel ? "打印已取消" : "打印已完成";
         if (isCancel) this.Close();//如果是点击的取消则退出界面,如果是打印正常完成则停留在此界面
     }
     catch (Exception ex)
     {
         ModernDialog.ShowMessage(ex.Message, "消息", MessageBoxButton.OK);
     }
 }
 public static ProgressDialog Open(Progress<ProgressDialogState> reporter, Stopwatch stopwatch = null)
 {
     var box = new ProgressDialog();
     var vm = new ProgressDialogViewModel(box, reporter, stopwatch);
     box.DataContext = vm;
     return box;
 }
 private static async Task DownloadToCacheFileAsync(Uri uri, string fileName, IProgress<int> progress)
 {
     try
     {
         using (var client = new HttpClient())
         {
             var request = new HttpRequestMessage(HttpMethod.Get, uri);
             var response = await client.SendAsync(request);
             response.EnsureSuccessStatusCode();
             long length = response.Content.Headers.ContentLength ?? 0;
             using (var responseStream = await response.Content.ReadAsStreamAsync())
             using (var fileStream = await CreateTempFileStreamAsync(fileName))
             {
                 IProgress<long> absoluteProgress = null;
                 if (progress != null)
                 {
                     absoluteProgress =
                         new Progress<long>(bytesCopied =>
                         {
                             if (length > 0)
                                 progress.Report((int) (100*bytesCopied/length));
                             else
                                 progress.Report(-1);
                         });
                 }
                 await responseStream.CopyToAsync(fileStream, absoluteProgress);
             }
         }
     }
     catch
     {
         await DeleteTempFileAsync(fileName);
         throw;
     }
 }
Exemple #29
0
        private async void NewSearch()
        {
            shouldStop = true;
            await currentTask;

            string folder = Model.Folder;
            Func<string, bool> predicate = s => Path.GetFileName(s).Contains(Model.Keyword);
            var progress = new Progress<string>();

            progress.ProgressChanged += (sender, e) => Model.Result.Add(e);

            Model.Result.Clear();

            shouldStop = false;

            Model.State = "Searching…";

            currentTask = Task.Run(() =>
            {
                Dfs(folder, predicate, progress);
            });

            await currentTask;
            Model.State = "Done.";
        }
		public SyncingPrintersPage()
			: base("Close")
		{
			TextWidget syncingText = new TextWidget("Syncing Profiles...".Localize(),textColor: ActiveTheme.Instance.PrimaryTextColor);
			syncingDetails = new TextWidget("Retrieving sync information...".Localize(), textColor: ActiveTheme.Instance.PrimaryTextColor, pointSize:10);
			syncingDetails.AutoExpandBoundsToText = true;
			contentRow.AddChild(syncingText);
			contentRow.AddChild(syncingDetails);
			Progress<SyncReportType> progress = new Progress<SyncReportType>(ReportProgress);

			ApplicationController.SyncPrinterProfiles("SyncingPrintersPage.ctor()", progress).ContinueWith((task) =>
			{
				if (!ProfileManager.Instance.ActiveProfiles.Any())
				{
					// Switch to setup wizard if no profiles exist
					WizardWindow.ChangeToSetupPrinterForm();
				}
				else if (ProfileManager.Instance.ActiveProfiles.Count() == 1)
				{
					//Set as active printer
					ActiveSliceSettings.SwitchToProfile(ProfileManager.Instance.ActiveProfiles.First().ID);
					// only close the window if we are not switching to the setup printer form
					UiThread.RunOnIdle(WizardWindow.Close);
				}
				else // multiple printers - close the window
				{
					UiThread.RunOnIdle(WizardWindow.Close);
				}
			});
			footerRow.AddChild(new HorizontalSpacer());
			footerRow.AddChild(cancelButton);
		}
        protected Task <string> BuildTask(string filePath)
        {
            var progress = new FileCopyProgress(ReportProgress);

            return(FileCopier.CopyFileAsync(filePath, PathService.Destination, progress, CancellationTokenSource.Token));
        }