Example #1
0
        public async Task ExtractInstallFiles(Action<int> progressCallback)
        {
            if (_casc == null)
                return;

            IProgress<int> progress = new Progress<int>(progressCallback);

            await Task.Run(() =>
            {
                var installFiles = _casc.Install.GetEntries("Windows");
                var build = _casc.Config.BuildName;

                int numFiles = installFiles.Count();
                int numDone = 0;

                foreach (var file in installFiles)
                {
                    EncodingEntry enc;

                    if (_casc.Encoding.GetEntry(file.MD5, out enc))
                        _casc.SaveFileTo(enc.Key, Path.Combine("data", build, "install_files"), file.Name);

                    progress.Report((int)(++numDone / (float)numFiles * 100));
                }
            });
        }
        /// <summary>
        /// This is a javascript application.
        /// </summary>
        /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
        public Application(IApp page)
        {
            //  Task.Factory.StartNewWithProgress(
            // X:\jsc.svn\core\ScriptCoreLib.Async\ScriptCoreLib.Async\Extensions\TaskAsyncExtensions.cs

            Native.css.style.transition = "background-color 300ms linear";

            // future jsc will allow a background thread to directly talk to the DOM, while creating a callsite in the background
            IProgress<string> set_backgroundColor = new Progress<string>(yield);

            var g = new
            {
                yield,
                colors = new
                {
                    white = "white",
                    yellow = "yellow",
                    cyan = "cyan"
                }
            };

            //var colors = new { yellow = "yellow", cyan = "cyan" };

            new IHTMLButton { "invoke" }.AttachToDocument().onclick +=
                async e =>
                {
                    await Task.Run(async delegate
                    {
                        // we could also support direct delegates?

                        set_backgroundColor.Report(g.colors.yellow);

                        // the .css thing is under our control is it not. could be the first to get special support
                        //Native.css.style.backgroundColor = "red";

                        await Task.Delay(1000);

                        set_backgroundColor.Report(g.colors.cyan);
                    });
                    await Task.Delay(1000);
                    set_backgroundColor.Report(g.colors.white);
                };
        }
Example #3
0
        public async Task ExtractInstallFiles(Action<int> progressCallback)
        {
            if (_casc == null)
                return;

            IProgress<int> progress = new Progress<int>(progressCallback);

            await Task.Run(() =>
            {
                var installFiles = _casc.Install.GetEntries("Windows");
                var build = _casc.Config.BuildName;

                int numFiles = installFiles.Count();
                int numDone = 0;

                foreach (var file in installFiles)
                {
                    _casc.ExtractFile(_casc.Encoding.GetEntry(file.MD5).Key, "data\\" + build + "\\install_files", file.Name);

                    progress.Report((int)(++numDone / (float)numFiles * 100.0f));
                }
            });
        }
        // out parameters can't be used in anonymous methods, so a separate pointer to backgroundWorker is required for return to the caller
        private async Task<bool> TryBeginFolderLoadAsync(FolderLoad folderLoad)
        {
            List<FileInfo> filesToAdd = folderLoad.GetFiles();
            if (filesToAdd.Count == 0)
            {
                // no images were found in folder; see if user wants to try again
                MessageBox messageBox = new MessageBox("Select a folder containing images or videos?", this, MessageBoxButton.YesNo);
                messageBox.Message.Problem = "There aren't any images or videos in the folder '" + this.FolderPath + "' so your image set is currentl empty.";
                messageBox.Message.Reason = "\u2022 This folder has no images in it (files ending in .jpg)." + Environment.NewLine;
                messageBox.Message.Reason += "\u2022 This folder has no videos in it (files ending in .avi or .mp4).";
                messageBox.Message.Solution = "Choose Yes and select a folder containing images and/or videos or choose No and add files later via the File menu.";
                messageBox.Message.Hint = "\u2022 The files may be in a subfolder of this folder." + Environment.NewLine;
                messageBox.Message.Hint += "\u2022 If you need to set the image set's time zone before adding files choose No." + Environment.NewLine;
                messageBox.Message.StatusImage = MessageBoxImage.Question;
                if (messageBox.ShowDialog() == false)
                {
                    return false;
                }

                IEnumerable<string> folderPaths;
                if (this.ShowFolderSelectionDialog(out folderPaths))
                {
                    folderLoad.FolderPaths.Clear();
                    folderLoad.FolderPaths.AddRange(folderPaths);
                    return await this.TryBeginFolderLoadAsync(folderLoad);
                }

                // exit if user changed their mind about trying again
                return false;
            }

            // update UI for import (visibility is inverse of RunWorkerCompleted)
            this.FeedbackControl.Visibility = Visibility.Visible;
            this.FileNavigatorSlider.Visibility = Visibility.Collapsed;
            IProgress<FolderLoadProgress> folderLoadStatus = new Progress<FolderLoadProgress>(this.UpdateFolderLoadProgress);
            FolderLoadProgress folderLoadProgress = new FolderLoadProgress(filesToAdd.Count, this.MarkableCanvas.Width > 0 ? (int)this.MarkableCanvas.Width : (int)this.Width);
            folderLoadStatus.Report(folderLoadProgress);
            if (this.state.SkipDarkImagesCheck)
            {
                this.statusBar.SetMessage("Loading folders...");
            }
            else
            {
                this.statusBar.SetMessage("Loading folders (if this is slower than you like and dark image detection isn't needed you can select Skip dark check in the Options menu right now)...");
            }
            this.FileViewPane.IsActive = true;

            // Load all files found
            // First pass: Examine files to extract their basic properties and build a list of files not already in the database
            //
            // With dark calculations enabled:
            // Profiling of a 1000 image load on quad core, single 80+MB/s capable SSD shows the following:
            // - one thread:   100% normalized execution time, 35% CPU, 16MB/s disk (100% normalized time = 1 minute 58 seconds)
            // - two threads:   55% normalized execution time, 50% CPU, 17MB/s disk (6.3% normalized time with dark checking skipped)
            // - three threads: 46% normalized execution time, 70% CPU, 20MB/s disk
            // This suggests memory bound operation due to image quality calculation.  The overhead of displaying preview images is fairly low; 
            // normalized time is about 5% with both dark checking and previewing skipped.
            //
            // For now, try to get at least two threads as that captures most of the benefit from parallel operation.  Video loading may be more CPU bound 
            // due to initial frame rendering and benefit from additional threads.  This requires further investigation.  It may also be desirable to reduce 
            // the pixel stride in image quality calculation, which would increase CPU load.
            //
            // With dark calculations disabled:
            // The bottleneck's the SQL insert though using more than four threads (or possibly more threads than the number of physical processors as the 
            // test machine was quad core) results in slow progress on the first 20 files or so, making the optimum number of loading threads complex as it
            // depends on amortizing startup lag across faster progress on the remaining import.  As this is comparatively minor relative to SQL (at least
            // for O(10,000) files for now just default to four threads in the disabled case.
            //
            // Note: the UI thread is free during loading.  So if loading's going slow the user can switch off dark checking asynchronously to speed up 
            // loading.
            //
            // A sequential partitioner is used as this keeps the preview images displayed to the user in pretty much the same order as they're named,
            // which is less confusing than TPL's default partitioning where the displayed image jumps back and forth through the image set.  Pulling files
            // nearly sequentially may also offer some minor disk performance benefit.
            List<ImageRow> filesToInsert = new List<ImageRow>();
            TimeZoneInfo imageSetTimeZone = this.dataHandler.FileDatabase.ImageSet.GetTimeZone();
            await Task.Run(() => Parallel.ForEach(
                new SequentialPartitioner<FileInfo>(filesToAdd),
                Utilities.GetParallelOptions(this.state.SkipDarkImagesCheck ? Environment.ProcessorCount : 2), 
                (FileInfo fileInfo) =>
                {
                    ImageRow file;
                    if (this.dataHandler.FileDatabase.GetOrCreateFile(fileInfo, imageSetTimeZone, out file))
                    {
                        // the database already has an entry for this file so skip it
                        // if needed, a separate list of files to update could be generated
                        return;
                    }

                    BitmapSource bitmapSource = null;
                    try
                    {
                        if (this.state.SkipDarkImagesCheck)
                        {
                            file.ImageQuality = FileSelection.Ok;
                        }
                        else
                        {
                            // load bitmap and determine its quality
                            // Parallel doesn't await async bodies so awaiting the load results in Parallel prematurely concluding the body task completed and
                            // dispatching another, resulting in system overload.  The simplest solution is to block this worker thread, which is OK as there
                            // are many workers and they're decoupled from the UI thread.
                            bitmapSource = file.LoadBitmapAsync(this.FolderPath, folderLoadProgress.RenderWidthBestEstimate).GetAwaiter().GetResult();
                            if (bitmapSource == Constant.Images.CorruptFile.Value)
                            {
                                file.ImageQuality = FileSelection.Corrupt;
                            }
                            else
                            {
                                file.ImageQuality = bitmapSource.AsWriteable().IsDark(this.state.DarkPixelThreshold, this.state.DarkPixelRatioThreshold);
                            }
                        }

                        // see if the datetime can be updated from the metadata
                        file.TryReadDateTimeOriginalFromMetadata(this.FolderPath, imageSetTimeZone);
                    }
                    catch (Exception exception)
                    {
                        Debug.Fail(String.Format("Load of {0} failed as it's likely corrupted.", file.FileName), exception.ToString());
                        bitmapSource = Constant.Images.CorruptFile.Value;
                        file.ImageQuality = FileSelection.Corrupt;
                    }

                    lock (filesToInsert)
                    {
                        filesToInsert.Add(file);
                    }

                    DateTime utcNow = DateTime.UtcNow;
                    if (utcNow - folderLoadProgress.MostRecentStatusDispatch > this.state.Throttles.DesiredIntervalBetweenRenders)
                    {
                        lock (folderLoadProgress)
                        {
                            if (utcNow - folderLoadProgress.MostRecentStatusDispatch > this.state.Throttles.DesiredIntervalBetweenRenders)
                            {
                                // if file was already loaded for dark checking use the resulting bitmap
                                // otherwise, load the file for display
                                if (bitmapSource != null)
                                {
                                    folderLoadProgress.BitmapSource = bitmapSource;
                                }
                                else
                                {
                                    folderLoadProgress.BitmapSource = null;
                                }
                                folderLoadProgress.CurrentFile = file;
                                folderLoadProgress.CurrentFileIndex = filesToInsert.Count;
                                folderLoadProgress.DisplayBitmap = true;
                                folderLoadProgress.MostRecentStatusDispatch = utcNow;
                                folderLoadStatus.Report(folderLoadProgress);
                            }
                        }
                    }
                }));

            // Second pass: Update database
            // Parallel execution above produces out of order results.  Put them back in order so the user sees images in file name order when
            // reviewing the image set.
            folderLoadProgress.DatabaseInsert = true;
            await Task.Run(() =>
                {
                    filesToInsert = filesToInsert.OrderBy(file => Path.Combine(file.RelativePath, file.FileName)).ToList();
                    this.dataHandler.FileDatabase.AddFiles(filesToInsert, (ImageRow file, int fileIndex) =>
                    {
                        // skip reloading images to display as the user's already seen them import
                        folderLoadProgress.BitmapSource = null;
                        folderLoadProgress.CurrentFile = file;
                        folderLoadProgress.CurrentFileIndex = fileIndex;
                        folderLoadProgress.DisplayBitmap = false;
                        folderLoadStatus.Report(folderLoadProgress);
                    });
                });

            // hide the feedback bar, show the file slider
            this.FeedbackControl.Visibility = Visibility.Collapsed;
            this.FileNavigatorSlider.Visibility = Visibility.Visible;

            await this.OnFolderLoadingCompleteAsync(true);

            // tell the user how many files were loaded
            this.MaybeShowFileCountsDialog(true);
            return true;
        }
        private async void StartDoneButton_Click(object sender, RoutedEventArgs e)
        {
            // This list will hold key / value pairs that will be bound to the datagrid feedback, 
            // which is the way to make those pairs appear in the data grid during background worker progress updates
            ObservableCollection<DateTimeRereadFeedbackTuple> feedbackRows = new ObservableCollection<DateTimeRereadFeedbackTuple>();
            this.FeedbackGrid.ItemsSource = feedbackRows;
            this.CancelButton.IsEnabled = false;
            this.StartDoneButton.Content = "_Done";
            this.StartDoneButton.Click -= this.StartDoneButton_Click;
            this.StartDoneButton.Click += this.DoneButton_Click;
            this.StartDoneButton.IsEnabled = false;

            IProgress<DateTimeRereadFeedbackTuple> rereadStatus = new Progress<DateTimeRereadFeedbackTuple>(this.ReportProgress);
            DateTimeRereadFeedbackTuple rereadProgress = new DateTimeRereadFeedbackTuple("Pass 1: Examining images and videos...", "Checking if dates/time differ");
            rereadStatus.Report(rereadProgress);
            await Task.Run(() =>
            {
                // check to see what date/times need updating
                List<ImageRow> filesToAdjust = new List<ImageRow>();
                int count = this.database.CurrentlySelectedFileCount;
                TimeZoneInfo imageSetTimeZone = this.database.ImageSet.GetTimeZone();
                for (int fileIndex = 0; fileIndex < count; ++fileIndex)
                {
                    ImageRow file = this.database.Files[fileIndex];
                    DateTimeOffset originalDateTime = file.GetDateTime();
                    string feedbackMessage = String.Empty;
                    try
                    {
                        DateTimeAdjustment dateTimeAdjustment = file.TryReadDateTimeOriginalFromMetadata(this.database.FolderPath, imageSetTimeZone);
                        if (dateTimeAdjustment == DateTimeAdjustment.None)
                        {
                            // couldn't read metadata, so get a candidate date/time from the file
                            file.SetDateTimeOffsetFromFileInfo(this.database.FolderPath, imageSetTimeZone);
                            feedbackMessage = "Using file date/time: ";
                        }
                        else if ((dateTimeAdjustment & DateTimeAdjustment.PreviousMetadata) == DateTimeAdjustment.PreviousMetadata)
                        {
                            feedbackMessage = "Using previous metadata date/time: ";
                        }
                        else
                        {
                            feedbackMessage = "Using metadata date/time: ";
                        }

                        DateTimeOffset rescannedDateTime = file.GetDateTime();
                        bool updateNeeded = false;
                        if (rescannedDateTime.Date == originalDateTime.Date)
                        {
                            feedbackMessage += "same date, ";
                        }
                        else
                        {
                            updateNeeded = true;
                            feedbackMessage += "different date, ";
                        }

                        if (rescannedDateTime.TimeOfDay == originalDateTime.TimeOfDay)
                        {
                            feedbackMessage += "same time, ";
                        }
                        else
                        {
                            updateNeeded = true;
                            feedbackMessage += "different time, ";
                        }

                        if (rescannedDateTime.Offset == originalDateTime.Offset)
                        {
                            feedbackMessage += "same UTC offset";
                        }
                        else
                        {
                            updateNeeded = true;
                            feedbackMessage += "different UTC offset";
                        }

                        if (updateNeeded)
                        {
                            filesToAdjust.Add(file);
                        }
                    }
                    catch (Exception exception)
                    {
                        Debug.Fail(String.Format("Unexpected exception processing '{0}'.", file.FileName), exception.ToString());
                        feedbackMessage += String.Format(" , skipping due to {0}: {1}.", exception.GetType().FullName, exception.Message);
                    }

                    if (fileIndex % Constant.ThrottleValues.SleepForImageRenderInterval == 0)
                    {
                        rereadProgress.FileName = file.FileName;
                        rereadProgress.Message = feedbackMessage;
                        rereadStatus.Report(new DateTimeRereadFeedbackTuple(file.FileName, feedbackMessage));
                        Thread.Sleep(Constant.ThrottleValues.RenderingBackoffTime); // Put in a delay every now and then, as otherwise the UI won't update.
                    }
                }

                // Pass 2. Update each date as needed 
                rereadProgress.FileName = String.Empty;
                rereadProgress.Message = String.Empty;
                rereadStatus.Report(rereadProgress);  // A blank separator
                rereadProgress.FileName = "Pass 2: Updating date/times";
                rereadProgress.Message = String.Format("Updating {0} images and videos...", filesToAdjust.Count);
                rereadStatus.Report(rereadProgress);

                List<ColumnTuplesWithWhere> imagesToUpdate = new List<ColumnTuplesWithWhere>();
                foreach (ImageRow image in filesToAdjust)
                {
                    imagesToUpdate.Add(image.GetDateTimeColumnTuples());
                }
                database.UpdateFiles(imagesToUpdate);  // Write the updates to the database
                rereadProgress.FileName = String.Empty;
                rereadProgress.Message = "Done";
                rereadStatus.Report(rereadProgress);
            });

            this.StartDoneButton.IsEnabled = true;
        }
        static Application()
        {
            // inside worker?
            if (Native.document == null)
                return;



            // http://dejanglozic.com/tag/shadow-dom/

            Native.document.registerElement("x-work",
                async (IHTMLElement e) =>
                {
                    var s = e.createShadowRoot();


                    new IHTMLPre { "working... " + new { Thread.CurrentThread.ManagedThreadId } }.AttachTo(s);


                    new IHTMLElement(IHTMLElement.HTMLElementEnum.hr).AttachTo(s);

                    // first insertion point
                    new IHTMLContent { }.AttachTo(s);


                    new IHTMLElement(IHTMLElement.HTMLElementEnum.hr).AttachTo(s);



                    IProgress<string> worker_new_IHTMLPre = new Progress<string>(value => new IHTMLPre { value }.AttachTo(s));

                    var z = await Task.Run(
                        async delegate
                    {
                        // inside a worker thread now.

                        // can a worker talk to a shadow dom? :)
                        // perhaps if we expend our scope sharing?
                        // yet
                        // how would it look like to create a node in a worker?


                        //new IHTMLPre { "working... " + new { Thread.CurrentThread.ManagedThreadId } }.AttachTo(s);

                        for (int i = 0; i < 10; i++)
                        {
                            // look we are scope sharing
                            worker_new_IHTMLPre.Report(
                               "working... " + new { i, Thread.CurrentThread.ManagedThreadId }
                          );


                            await Task.Delay(500);
                            // did we resync scope fields?
                            // we got new data from attributes?
                        }




                        return 42;
                    }
                    );



                    new IHTMLPre { "working... done " + new { z } }.AttachTo(s);

                }
            );
        }
Example #7
0
        private async void LoadEmployees()
        {
            CancellationTokenSource = new CancellationTokenSource();
            IProgress<double> progress = new Progress<double>(x => CurrentProgress = x);
            try {
                CurrentStatus = "Loading employees";

                Items.Clear();
                var result = await _dataProvider.LoadEmployeesAsync(CancellationTokenSource.Token, progress);

                if (result.Result != null) {
                    foreach (var item in result.Result) {
                        Items.Add(item);
                    }
                }
                if (result.Exception != null) {
                    throw result.Exception;
                }

                CurrentStatus = "Operation completed";
            }
            catch (OperationCanceledException) {
                CurrentStatus = "Operation cancelled";
            }
            catch (Exception ex) {
                CurrentStatus = "Operation failed - " + ex.Message;
            }
            finally {
                CancellationTokenSource.Dispose();
                CancellationTokenSource = null;
                progress.Report(0);
            }
        }
Example #8
0
        public async void TimerRun()
        {
            try 
	        {
                bool bRunning = false;
                await Task.Run(async () =>
                {
                    while (mbIsRunning == true)
                    {
                        bRunning = false; //Reset
                        await Task.Delay(1000);
                        foreach (Appliance appl in Appliances)
                        {
                            if (appl.IsRunning == true)
                            {
                                appl.Time = appl.Time.Add(new TimeSpan(0, 0, -1));

                                IProgress<object> progress = new Progress<object>(_ => ApplyTime(appl));
                                progress.Report(null);
                                bRunning = true;
                                progress = null;
                            }
                        }

                        //All timers have completed.  Why waste the cycles if we don't need to.... That's just rude.
                        if (bRunning == false) { mbIsRunning = false; }
                    }
                });
	        }
	        catch (Exception ex)
	        {
		        logException(ex);
	        }
        }
Example #9
0
        private async void concatenateButton_Click(object sender, EventArgs e)
        {
            concatenateButton.Enabled = false;

            IProgress<string> progress_str = new Progress<string>(status =>
            {
                listBox1.Items.Add(status);
				listBox1.TopIndex = listBox1.Items.Count - 1;
            });

            try
            {
                IProgress<int> progress = new Progress<int>(percent =>
                {
                    progressBar1.Value = percent;
                });

                listBox1.Items.Clear();

                List<string> inFiles = new List<string>();
                inFiles.Add(openFileDialog1.FileName);
                inFiles.Add(openFileDialog2.FileName);
                if (inFile3CheckBox.Checked) inFiles.Add(openFileDialog3.FileName);
                if (inFile4CheckBox.Checked) inFiles.Add(openFileDialog4.FileName);

                await DoAsync(inFiles, saveFileDialog1.FileName, progress, progress_str);
            }
            catch
            {
                progress_str.Report("Exception caught processing files!");
            }
            finally
            {
                GC.Collect();
                GC.WaitForPendingFinalizers();

                concatenateButton.Enabled = true;
            }
        }
Example #10
0
 private void tPhone_KeyPress(object sender, KeyPressEventArgs e)
 {
     if (e.KeyChar == (char)Keys.Return)
     {
         IProgress<Customer> customerProgess = new Progress<Customer>(
             c =>
             {
                 this.c = c;
                 ceView.tName.Text = c.Name;
                 ceView.tCompany.Text = c.Company;
                 ceView.tAddress.Text = c.Address;
                 ceView.tCity.Text = c.City;
                 ceView.tCountry.Text = c.Country;
                 ceView.tPostalCode.Text = c.PostalCode;
                 ceView.tPhone.Text = c.Phone;
                 ceView.tDoB.Value = c.DoB;
                 ceView.tID.Text = c.ID.ToString();
                 ceView.tEmail.Text = c.Email;
                 bPay.Click -= bPay_NoCustomer;
                 bPay.Click += bPay_Click;
             });
         new Loading("Loading customer",
             () =>
             {
                 var phone = tPhone.Text;
                 var phone2 = string.Format("1-{0}-{1}-{2}", phone.Substring(0, 3), phone.Substring(3, 3), phone.Substring(6));
     #if DEBUG
                 Console.WriteLine(phone2);
     #endif
                 uint cid = 0;
                 if (uint.TryParse("" + DB.Instance.SelectSingleValue("select id from customer where phone = '" + phone2 + "'"), out cid))
                 {
                     customerProgess.Report(new Customer(cid));
                 }
                 else
                 {
                     if (MessageBox.Show("No Customer Found!\nWould you like to rigister?", "Customer", MessageBoxButtons.YesNo) == DialogResult.Yes)
                     {
                         CustomerEdit ce = new CustomerEdit();
                         ce.tPhone.Text = phone2;
                         if ((new EditWindow(ce).ShowDialog()) == DialogResult.OK)
                         {
                             cid = (uint)DB.Instance.SelectSingleValue("select id from customer where phone = '" + phone2 + "'");
                             customerProgess.Report(new Customer(cid));
                         }
                     }
                 }
             });
     }
 }
Example #11
0
        public async Task AnalyzeUnknownFiles(Action<int> progressCallback)
        {
            if (_casc == null)
                return;

            IProgress<int> progress = new Progress<int>(progressCallback);

            await Task.Run(() =>
            {
                FileScanner scanner = new FileScanner(_casc, _root);

                Dictionary<int, string> idToName = new Dictionary<int, string>();

                if (_casc.Config.GameType == CASCGameType.WoW)
                {
                    if (_casc.FileExists("DBFilesClient\\SoundEntries.db2"))
                    {
                        using (Stream stream = _casc.OpenFile("DBFilesClient\\SoundEntries.db2"))
                        {
                            DB2Reader se = new DB2Reader(stream);

                            foreach (var row in se)
                            {
                                string name = row.Value.GetField<string>(2);

                                int type = row.Value.GetField<int>(1);

                                bool many = row.Value.GetField<int>(4) > 0;

                                for (int i = 3; i < 23; i++)
                                    idToName[row.Value.GetField<int>(i)] = "unknown\\sound\\" + name + (many ? "_" + (i - 2).ToString("D2") : "") + (type == 28 ? ".mp3" : ".ogg");
                            }
                        }
                    }

                    if (_casc.FileExists("DBFilesClient\\SoundKit.db2") && _casc.FileExists("DBFilesClient\\SoundKitEntry.db2"))
                    {
                        using (Stream skStream = _casc.OpenFile("DBFilesClient\\SoundKit.db2"))
                        using (Stream skeStream = _casc.OpenFile("DBFilesClient\\SoundKitEntry.db2"))
                        {
                            DB5Reader sk = new DB5Reader(skStream);
                            DB5Reader ske = new DB5Reader(skeStream);

                            Dictionary<int, List<int>> lookup = new Dictionary<int, List<int>>();

                            foreach (var row in ske)
                            {
                                int soundKitId = row.Value.GetField<int>(3);

                                if (!lookup.ContainsKey(soundKitId))
                                    lookup[soundKitId] = new List<int>();

                                lookup[soundKitId].Add(row.Value.GetField<int>(0));
                            }

                            foreach (var row in sk)
                            {
                                string name = row.Value.GetField<string>(0).Replace(':', '_');

                                int type = row.Value.GetField<byte>(12);

                                List<int> ske_entries;

                                if (!lookup.TryGetValue(row.Key, out ske_entries))
                                    continue;

                                bool many = ske_entries.Count > 1;

                                int i = 0;

                                foreach (var fid in ske_entries)
                                {
                                    idToName[fid] = "unknown\\sound\\" + name + (many ? "_" + (i + 1).ToString("D2") : "") + (type == 28 ? ".mp3" : ".ogg");
                                    i++;
                                }
                            }
                        }
                    }
                }

                CASCFolder unknownFolder = _root.GetEntry("unknown") as CASCFolder;

                if (unknownFolder == null)
                    return;

                IEnumerable<CASCFile> files = CASCFolder.GetFiles(unknownFolder.Entries.Select(kv => kv.Value), null, true);
                int numTotal = files.Count();
                int numDone = 0;

                WowRootHandler wowRoot = _casc.Root as WowRootHandler;

                foreach (var unknownEntry in files)
                {
                    CASCFile unknownFile = unknownEntry as CASCFile;

                    string name;
                    if (idToName.TryGetValue(wowRoot.GetFileDataIdByHash(unknownFile.Hash), out name))
                        unknownFile.FullName = name;
                    else
                    {
                        string ext = scanner.GetFileExtension(unknownFile);
                        unknownFile.FullName += ext;

                        if (ext == ".m2")
                        {
                            using (var m2file = _casc.OpenFile(unknownFile.Hash))
                            using (var br = new BinaryReader(m2file))
                            {
                                m2file.Position = 0x138;
                                string m2name = br.ReadCString();

                                unknownFile.FullName = "unknown\\" + m2name + ".m2";
                            }
                        }
                    }

                    progress.Report((int)(++numDone / (float)numTotal * 100));
                }

                _casc.Root.Dump();
            });
        }
Example #12
0
        private void Play()
        {
            currentlyPlayingMusic = true;
            PlayIcon = new SymbolIcon(Symbol.Pause);
            MediaElement.Play();

            ProgressMaximumDisplay = ConvertToMinuteFormat(MediaElement.NaturalDuration.TimeSpan.TotalSeconds);
            ProgressMaximum = MediaElement.NaturalDuration.TimeSpan.TotalSeconds;

            IProgress<object> progress = new Progress<object>(_ => UpdateTicker());
            Task.Run(async () =>
            {
                while (true)
                {
                    await Task.Delay(200);
                    progress.Report(null);
                }
            });
        }
        static void Main(string[] args)
        {
            //Get credentials
            Console.Write("Enter your username:"******"Enter your password:"******"my-service");
            service.setUserCredentials(user, password);
            ListFeed listFeed = null;
            SpreadsheetFeed feed = null;
            IProgress<string> p = new Progress<string>(Console.WriteLine);

            //Get list of spreadsheets
            var getSheets = Task.Run(() =>
                {
                    p.Report("Getting all your Google spreadsheets...");
                    var query = new SpreadsheetQuery();
                    feed = service.Query(query);
                });

            getSheets.Wait();

            //Show list of spreadsheets...
            foreach (SpreadsheetEntry entry in feed.Entries.OrderBy(x => x.Title.Text))
            {
                Console.WriteLine(entry.Title.Text);
            }

            Console.WriteLine("Which spreadsheet would you like to see the contents of?");
            var title = Console.ReadLine();

            //Get list of spreadsheets
            var getInfo = Task.Run(() =>
            {
                p.Report("Reading rows from spreadsheet");
                var query = new SpreadsheetQuery();
                query.Title = title;
                feed = service.Query(query);

                var spreadsheet = feed.Entries.FirstOrDefault() as SpreadsheetEntry;
                var wsFeed = spreadsheet.Worksheets;
                var worksheet = wsFeed.Entries.FirstOrDefault() as WorksheetEntry;

                //Define the URL to request the list feed of the worksheet
                var listFeedLink = worksheet.Links.FindService(GDataSpreadsheetsNameTable.ListRel, null);
                p.Report(string.Format("Spreadsheet table link: {0}", listFeedLink.HRef));

                //Rows in spreadsheet
                var listQuery = new ListQuery(listFeedLink.HRef.ToString());
                listFeed = service.Query(listQuery);

            });

            getInfo.Wait();

            //Iterate through the rows...
            foreach (ListEntry row in listFeed.Entries)
            {
                foreach (ListEntry.Custom element in row.Elements)
                {
                    Console.WriteLine(element.Value);
                }
            }

            //NOTE: google docs always treats the first row as the header row... 
            Console.WriteLine("Type a new value for the first cell in the first column:");
            var newValue = Console.ReadLine();

            Console.WriteLine("Updating row data...");
            var updateRow = (ListEntry)listFeed.Entries[0];
            ListEntry.Custom updateMe = updateRow.Elements[0];
            updateMe.Value = newValue;
            updateRow.Update();

            Console.Read();
        }
        static void Main(string[] args)
        {
            var localHtmlDocname = "docContents.htm";

            //Get credentials
            Console.Write("Enter your username:"******"Enter your password:"******"my-service");
            service.setUserCredentials(user, password);
            DocumentsFeed listFeed = null;
            AtomFeed feed = null;
            DocumentsListQuery query = null;
            IProgress<string> p = new Progress<string>(Console.WriteLine);

            //Get list of documents
            var getList = Task.Run(() =>
            {
                p.Report("Reading list of documents");
                query = new DocumentsListQuery();
                feed = service.Query(query);
            });

            getList.Wait();

            foreach (DocumentEntry entry in feed.Entries.OrderBy(x => x.Title.Text))
            {
                if (entry.IsDocument)
                    Console.WriteLine(entry.Title.Text);
            }

            Console.WriteLine("Type the name of the document you would like to open:");
            var openDocTitle = Console.ReadLine();
            string contents = string.Empty;

            //Get list of documents
            var openDoc = Task.Run(() =>
            {
                p.Report("Reading document contents");
                query.Title = openDocTitle;
                feed = service.Query(query);

                var openMe = feed.Entries[0] as DocumentEntry;
                var stream = service.Query(new Uri(openMe.Content.Src.ToString()));
                var reader = new StreamReader(stream);
                contents = reader.ReadToEnd();

                using (var fs = File.Create(localHtmlDocname))
                {
                    using (var writer = new StreamWriter(fs))
                    {
                        contents += Environment.UserName + " was here - " + DateTime.Now.ToString() + "<br/>";
                        writer.Write(contents);
                        writer.Flush();
                        writer.Close();
                    }

                    fs.Close();
                }

                //OPTIONAL: Uncomment to save changes BACK to the google doc
                /*
                openMe.MediaSource = new MediaFileSource(localHtmlDocname, "text/html");
                var uploader = new ResumableUploader();

                //Get an authenticator
                var authenticator = new ClientLoginAuthenticator("document-access-test", ServiceNames.Documents, service.Credentials);

                //Perform the upload...
                Console.WriteLine("Saving to Google Drive...");
                uploader.Update(authenticator, openMe);
                */
            });

            openDoc.Wait();
            Console.WriteLine("Opening contents of Google doc file...");
            System.Diagnostics.Process.Start(localHtmlDocname);
        }
        /// <summary>
        /// Redo image quality calculations with current thresholds for all images selected.  Updates the database.
        /// </summary>
        private async Task BeginUpdateImageQualityForAllSelectedImagesAsync()
        {
            List<ImageRow> selectedFiles = this.database.Files.ToList();
            this.ApplyDoneButton.Content = "_Done";
            this.ApplyDoneButton.IsEnabled = false;
            this.DarkPixelRatioThumb.IsEnabled = false;
            this.DarkThreshold.IsEnabled = false;
            this.PreviousFile.IsEnabled = false;
            this.NextFile.IsEnabled = false;
            this.ScrollImages.IsEnabled = false;
            this.ResetButton.IsEnabled = false;

            IProgress<ImageQuality> updateStatus = new Progress<ImageQuality>(this.ReportProgress);
            await Task.Run(() =>
            {
                TimeSpan desiredRenderInterval = TimeSpan.FromSeconds(1.0 / Constant.ThrottleValues.DesiredMaximumImageRendersPerSecondDefault);
                DateTime mostRecentStatusDispatch = DateTime.UtcNow - desiredRenderInterval;
                object renderLock = new object();

                int fileIndex = 0;
                List<ColumnTuplesWithWhere> filesToUpdate = new List<ColumnTuplesWithWhere>();
                Parallel.ForEach(
                    new SequentialPartitioner<ImageRow>(selectedFiles),
                    Utilities.GetParallelOptions(Environment.ProcessorCount), 
                    (ImageRow file, ParallelLoopState loopState) =>
                    {
                        if (this.stop)
                        {
                            loopState.Break();
                        }

                        // if it's not a valid image, say so and go onto the next one.
                        int currentFileIndex = Interlocked.Increment(ref fileIndex);
                        ImageQuality imageQuality = new ImageQuality(file);
                        if ((imageQuality.OldImageQuality != FileSelection.Ok) && (imageQuality.OldImageQuality != FileSelection.Dark))
                        {
                            imageQuality.FileIndex = currentFileIndex;
                            imageQuality.NewImageQuality = null;
                            updateStatus.Report(imageQuality);
                            return;
                        }

                        try
                        {
                            // find the new image quality and add file to the update list
                            // See remarks in CarnassialWindow.xaml.cs about synchronous loading.
                            imageQuality.Bitmap = file.LoadBitmapAsync(this.database.FolderPath).GetAwaiter().GetResult().AsWriteable();
                            imageQuality.FileIndex = currentFileIndex;
                            imageQuality.NewImageQuality = imageQuality.Bitmap.IsDark(this.darkPixelThreshold, this.darkPixelRatio, out this.darkPixelRatioFound, out this.isColor);
                            imageQuality.IsColor = this.isColor;
                            imageQuality.DarkPixelRatioFound = this.darkPixelRatioFound;
                            if (imageQuality.OldImageQuality != imageQuality.NewImageQuality.Value)
                            {
                                filesToUpdate.Add(new ColumnTuplesWithWhere(new List<ColumnTuple> { new ColumnTuple(Constant.DatabaseColumn.ImageQuality, imageQuality.NewImageQuality.Value.ToString()) }, file.ID));
                            }
                        }
                        catch (Exception exception)
                        {
                            // file isn't there?
                            Debug.Fail("Exception while assessing image quality.", exception.ToString());
                        }

                        DateTime utcNow = DateTime.UtcNow;
                        if (utcNow - mostRecentStatusDispatch > desiredRenderInterval)
                        {
                            lock (renderLock)
                            {
                                if (utcNow - mostRecentStatusDispatch > desiredRenderInterval)
                                {
                                    mostRecentStatusDispatch = utcNow;
                                    updateStatus.Report(imageQuality);
                                }
                            }
                        }
                    });

                    this.database.UpdateFiles(filesToUpdate);
                });

            await this.DisplayImageAndDetailsAsync();
            this.ApplyDoneButton.IsEnabled = true;
            this.CancelStopButton.IsEnabled = false;
        }
        /// <summary>
        /// This is a javascript application.
        /// </summary>
        /// <param name="page">HTML document rendered by the web server which can now be enhanced.</param>
        public Application(IApp page)
        {
            // X:\jsc.svn\examples\javascript\async\test\TestScopeWithDelegate\TestScopeWithDelegate\Application.cs

            // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2014/201406/20140629
            // can we get support for any level1 scope progress elements?
            // after that we may want to allow Tasks being sent back to the worker.
            // what about sharing static bools too. we already share strings..
            // what about synchronizing scope objects once worker is running?
            // a Thread Signal or Task Yield may request the sync to take place.
            // this would allow data sharing during computation?
            // then we may also want to get delegate sharing..


            //0:6113ms Task scope { MemberName = progress, IsString = false, IsNumber = false, TypeIndex = type$Iuc7fw31uTShD4lFrT9xIg }
            //0:6161ms Task scope { MemberName = CS___9__CachedAnonymousMethodDelegate6, IsString = false, IsNumber = false, TypeIndex = type$P_aMwuiDRzTKOqkDQd7BGAw }

            // X:\jsc.svn\core\ScriptCoreLib\JavaScript\BCLImplementation\System\Threading\Tasks\Task\Task.ctor.cs
            IProgress<string> progress = new Progress<string>(
                x =>
                {
                    new IHTMLPre {
                        new { x, Thread.CurrentThread.ManagedThreadId }
                    }.AttachToDocument();
                }
            );

            // http://www.w3schools.com/tags/tag_progress.asp
            //new IHTMLInput(ScriptCoreLib.Shared.HTMLInputTypeEnum.pro
            var p = new IHTMLElement("progress").AttachToDocument();

            p.setAttribute("value", 20);
            p.setAttribute("max", 100);

            IProgress<int> set_progress = new Progress<int>(
                x =>
                    {
                        p.setAttribute("value", x);
                    }
            );


            Native.css.style.transition = "background-color 300ms linear";

            // future jsc will allow a background thread to directly talk to the DOM, while creating a callsite in the background
            IProgress<string> set_backgroundColor = new Progress<string>(
                x =>
                {
                    Native.css.style.backgroundColor = x;
                }
            );


            var foo = "foo";

            new IHTMLButton { "invoke" }.AttachToDocument().onclick +=
                async e =>
                {
                    progress.Report("UI " + new { foo, Thread.CurrentThread.ManagedThreadId });

                    await Task.Run(async delegate
                    {
                        Console.WriteLine("inside worker " + new { foo, Thread.CurrentThread.ManagedThreadId });

                        // we could also support direct delegates?
                        progress.Report("inside worker " + new { foo, Thread.CurrentThread.ManagedThreadId });

                        set_backgroundColor.Report("yellow");

                        // this will confuse task to be Task<?> ?
                        for (int i = 20; i <= 100; i += 2)
                        {
                            set_progress.Report(i);
                            await Task.Delay(100);
                        }

                        set_backgroundColor.Report("cyan");

                        Console.WriteLine("exit worker " + new { foo, Thread.CurrentThread.ManagedThreadId });

                        // we could also support direct delegates?
                        progress.Report("exit worker " + new { foo, Thread.CurrentThread.ManagedThreadId });
                    });
                };

        }
		private void ApplicationControl_Load(object sender, System.EventArgs e)
		{
			Console.WriteLine("enter ApplicationControl_Load " + new { Thread.CurrentThread.ManagedThreadId });

			this.SpecialEvent += value =>
			{
				Console.WriteLine("SpecialEvent " + new { value, Thread.CurrentThread.ManagedThreadId });
			};

			IProgress<string> progress = new Progress<string>(
				handler: value =>
				{
					Console.WriteLine("Progress " + new { value, Thread.CurrentThread.ManagedThreadId });

				}
			);


			progress.Report("hello from UI");

			var loc1 = new AsyncLocal<string>(
				// would we be able to send the delegate over to worker?

				// called by ExecutionContext

				//>	TestAsyncLocal.exe!TestAsyncLocal.ApplicationControl.ApplicationControl_Load.AnonymousMethod__1_1(System.Threading.AsyncLocalValueChangedArgs<string> value) Line 40	C#
				// 	mscorlib.dll!System.Threading.AsyncLocal<T>.System.Threading.IAsyncLocal.OnValueChanged(object previousValueObj, object currentValueObj, bool contextChanged)	Unknown
				// 	mscorlib.dll!System.Threading.ExecutionContext.OnAsyncLocalContextChanged(System.Threading.ExecutionContext previous, System.Threading.ExecutionContext current)	Unknown
				// 	mscorlib.dll!System.Threading.ExecutionContext.SetExecutionContext(System.Threading.ExecutionContext executionContext, bool preserveSyncCtx)	Unknown
				// 	mscorlib.dll!System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx)	Unknown
				// 	mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx)	Unknown
				// 	mscorlib.dll!System.Threading.Tasks.Task.ExecuteWithThreadLocal(System.Threading.Tasks.Task currentTaskSlot)	Unknown
				// 	mscorlib.dll!System.Threading.Tasks.Task.ExecuteEntry(bool bPreventDoubleExecution)	Unknown
				// 	mscorlib.dll!System.Threading.Tasks.Task.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()	Unknown
				// 	mscorlib.dll!System.Threading.ThreadPoolWorkQueue.Dispatch()	Unknown
				// 	mscorlib.dll!System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()	Unknown


				valueChangedHandler: value =>
				{
					Console.WriteLine("AsyncLocal " + new { value.ThreadContextChanged, value.CurrentValue, value.PreviousValue, Thread.CurrentThread.ManagedThreadId });
				}
			);

			loc1.Value = "hello from UI";

			var s = new SemaphoreSlim(1);

			this.SpecialEvent("hello from UI");

			Task.Run(
				delegate
				{
					Console.WriteLine("enter worker " + new { loc1, progress, Thread.CurrentThread.ManagedThreadId });

					//this.InvokeRequired
					this.SpecialEvent("hello from UI " + new { this.InvokeRequired });

					progress.Report("hello from worker");

					s.Release();

					loc1.Value = "hello from worker / " + new { loc1.Value };

				}
			);

			//enter ApplicationControl_Load { ManagedThreadId = 3 }
			//AsyncLocal { ThreadContextChanged = False, CurrentValue = hello from UI, PreviousValue = , ManagedThreadId = 3 }
			//SpecialEvent { value = hello from UI, ManagedThreadId = 3 }
			//ApplicationForm.Load
			//AsyncLocal { ThreadContextChanged = True, CurrentValue = hello from UI, PreviousValue = , ManagedThreadId = 5 }
			//AsyncLocal { ThreadContextChanged = True, CurrentValue = hello from UI, PreviousValue = , ManagedThreadId = 4 }
			//SemaphoreSlim WaitAsync { CurrentCount = 0, ManagedThreadId = 5 }
			//AsyncLocal { ThreadContextChanged = True, CurrentValue = , PreviousValue = hello from UI, ManagedThreadId = 5 }
			//enter worker { loc1 = System.Threading.AsyncLocal`1[System.String], progress = System.Progress`1[System.String], ManagedThreadId = 4 }
			//SpecialEvent { value = hello from UI { InvokeRequired = True }, ManagedThreadId = 4 }
			//AsyncLocal { ThreadContextChanged = False, CurrentValue = hello from worker / { Value = hello from UI }, PreviousValue = hello from UI, ManagedThreadId = 4 }
			//AsyncLocal { ThreadContextChanged = True, CurrentValue = , PreviousValue = hello from worker / { Value = hello from UI }, ManagedThreadId = 4 }
			//AsyncLocal { ThreadContextChanged = True, CurrentValue = , PreviousValue = hello from UI, ManagedThreadId = 3 }
			//Progress { value = hello from UI, ManagedThreadId = 3 }
			//AsyncLocal { ThreadContextChanged = True, CurrentValue = hello from UI, PreviousValue = , ManagedThreadId = 3 }
			//Progress { value = hello from worker, ManagedThreadId = 3 }

			s.WaitAsync().ContinueWith(
				t =>
				{
					Console.WriteLine("SemaphoreSlim WaitAsync " + new { s.CurrentCount, Thread.CurrentThread.ManagedThreadId });

				}
			);




		}
        public void AsyncTicker()
        {
            var ts = new CancellationTokenSource();
            taskSource = ts;
            CancellationToken ct = taskSource.Token;

            IProgress<object> progress = new Progress<object>(_ => LoadCurrentItems());
            Task.Run(async () =>
            {
                while (true)
                {
                    await Task.Delay(1000);
                    progress.Report(null);
                }
            }, ct);
        }