Ejemplo n.º 1
0
        public void CompareUntyped(double value, double valueToCompareWith, int expectedResult)
        {
            var valueSize = new ByteSize(value);
            object otherSize = new ByteSize(valueToCompareWith);
            var result = valueSize.CompareTo(otherSize);

            Assert.Equal(expectedResult, result);
        }
Ejemplo n.º 2
0
        public void HumanizesRates(long inputBytes, double perSeconds, string expectedValue)
        {
            var size = new ByteSize(inputBytes);
            var interval = TimeSpan.FromSeconds(perSeconds);

            var rate = size.Per(interval).Humanize();

            Assert.Equal(expectedValue, rate);
        }
Ejemplo n.º 3
0
        public void Constructor()
        {
            var result = new ByteSize(1099511627776);

            Assert.Equal(8.796093022208e12, result.Bits);
            Assert.Equal(1099511627776, result.Bytes);
            Assert.Equal(1073741824, result.Kilobytes);
            Assert.Equal(1048576, result.Megabytes);
            Assert.Equal(1024, result.Gigabytes);
            Assert.Equal(1, result.Terabytes);
        }
Ejemplo n.º 4
0
        public void Constructor2()
        {
            var bs = new ByteSize(10);
            Assert.AreEqual(10, bs.ByteCount);

            bs = new ByteSize(1000);
            Assert.AreEqual(1000, bs.ByteCount);

            bs = new ByteSize(1024);
            Assert.AreEqual(1024, bs.ByteCount);
        }
        async private Task<IFileStorage> RandomlySelectStorageWithEnoughSpaceAsync(ByteSize requiredSize)
        {
            var storages = new List<IFileStorage>();

            foreach (var stg in _storages.Values)
            {
                var cap = await stg.GetCapacityAsync();

                if (requiredSize == null || cap.Available > requiredSize)
                    storages.Add(stg);
            }

            return storages.Any() ? storages.RandomElement() : _storages.Values.RandomElement();
        }
        public Task<IFileStorage> GetFileStorageAsync(ByteSize requiredSize)
        {
            switch (_mode)
            {
                case SelectionMode.RandomlySelectStorageWithEnoughSpace:
                    return RandomlySelectStorageWithEnoughSpaceAsync(requiredSize);

                case SelectionMode.SelectStorageWithTheMostFreeSpace:
                    return SelectStorageWithTheMostFreeSpaceAsync();

                default:
                    throw new ArgumentOutOfRangeException();
            }
        }
Ejemplo n.º 7
0
        public void Constructor()
        {
            // Arrange
            double byteSize = 1099511627776;

            // Act
            var result = new ByteSize(byteSize);

            // Assert
            Assert.Equal(8.796093022208e12, result.Bits);
            Assert.Equal(1099511627776, result.Bytes);
            Assert.Equal(1073741824, result.KiloBytes);
            Assert.Equal(1048576, result.MegaBytes);
            Assert.Equal(1024, result.GigaBytes);
            Assert.Equal(1, result.TeraBytes);
        }
        public void Constructor()
        {
            // Arrange
            double byteSize = 1125899906842624;

            // Act
            var result = new ByteSize(byteSize);

            // Assert
            Assert.Equal(byteSize * 8, result.Bits);
            Assert.Equal(byteSize, result.Bytes);
            Assert.Equal(byteSize / 1024, result.KiloBytes);
            Assert.Equal(byteSize / 1024 / 1024, result.MegaBytes);
            Assert.Equal(byteSize / 1024 / 1024 / 1024, result.GigaBytes);
            Assert.Equal(byteSize / 1024 / 1024 / 1024 / 1024, result.TeraBytes);
            Assert.Equal(1, result.PetaBytes);
        }
Ejemplo n.º 9
0
        public void Constructor3Binary()
        {
            var bs = new ByteSize(1024, ByteSizeUnit.Bytes);
            Assert.AreEqual(1024, bs.ByteCount);

            bs = new ByteSize(0, ByteSizeUnit.KibiByte);
            Assert.AreEqual(0, bs.ByteCount);

            bs = new ByteSize(1, ByteSizeUnit.KibiByte);
            Assert.AreEqual(1024, bs.ByteCount);

            bs = new ByteSize(2, ByteSizeUnit.KibiByte);
            Assert.AreEqual(1024 * 2, bs.ByteCount);

            bs = new ByteSize(3, ByteSizeUnit.KibiByte);
            Assert.AreEqual(1024 * 3, bs.ByteCount);

            bs = new ByteSize(0, ByteSizeUnit.MibiByte);
            Assert.AreEqual(0, bs.ByteCount);

            bs = new ByteSize(1, ByteSizeUnit.MibiByte);
            Assert.AreEqual(1024 * 1024, bs.ByteCount);

            bs = new ByteSize(2, ByteSizeUnit.MibiByte);
            Assert.AreEqual(1024 * 1024 * 2, bs.ByteCount);

            bs = new ByteSize(3, ByteSizeUnit.MibiByte);
            Assert.AreEqual(1024 * 1024 * 3, bs.ByteCount);

            bs = new ByteSize(0, ByteSizeUnit.GibiByte);
            Assert.AreEqual(0, bs.ByteCount);

            bs = new ByteSize(1, ByteSizeUnit.GibiByte);
            Assert.AreEqual(1024 * 1024 * 1024, bs.ByteCount);

            bs = new ByteSize(2, ByteSizeUnit.GibiByte);
            Assert.AreEqual(1024L * 1024L * 1024L * 2L, bs.ByteCount);

            bs = new ByteSize(3, ByteSizeUnit.GibiByte);
            Assert.AreEqual(1024L * 1024L * 1024L * 3L, bs.ByteCount);
        }
Ejemplo n.º 10
0
        public void Constructor3Decimal()
        {
            var bs = new ByteSize(1024, ByteSizeUnit.Bytes);
            Assert.AreEqual(1024, bs.ByteCount);

            bs = new ByteSize(0, ByteSizeUnit.KiloByte);
            Assert.AreEqual(0, bs.ByteCount);

            bs = new ByteSize(1, ByteSizeUnit.KiloByte);
            Assert.AreEqual(1000, bs.ByteCount);

            bs = new ByteSize(2, ByteSizeUnit.KiloByte);
            Assert.AreEqual(1000 * 2, bs.ByteCount);

            bs = new ByteSize(3, ByteSizeUnit.KiloByte);
            Assert.AreEqual(1000 * 3, bs.ByteCount);

            bs = new ByteSize(0, ByteSizeUnit.MegaByte);
            Assert.AreEqual(0, bs.ByteCount);

            bs = new ByteSize(1, ByteSizeUnit.MegaByte);
            Assert.AreEqual(1000 * 1000, bs.ByteCount);

            bs = new ByteSize(2, ByteSizeUnit.MegaByte);
            Assert.AreEqual(1000 * 1000 * 2, bs.ByteCount);

            bs = new ByteSize(3, ByteSizeUnit.MegaByte);
            Assert.AreEqual(1000 * 1000 * 3, bs.ByteCount);

            bs = new ByteSize(0, ByteSizeUnit.GigaByte);
            Assert.AreEqual(0, bs.ByteCount);

            bs = new ByteSize(1, ByteSizeUnit.GigaByte);
            Assert.AreEqual(1000 * 1000 * 1000, bs.ByteCount);

            bs = new ByteSize(2, ByteSizeUnit.GigaByte);
            Assert.AreEqual(1000 * 1000 * 1000 * 2, bs.ByteCount);

            bs = new ByteSize(3, ByteSizeUnit.GigaByte);
            Assert.AreEqual(1000L * 1000L * 1000L * 3L, bs.ByteCount);
        }
Ejemplo n.º 11
0
 // Token: 0x0600001D RID: 29 RVA: 0x0000214B File Offset: 0x0000034B
 public static ByteSize Megabytes(this uint input)
 {
     return(ByteSize.FromMegabytes(input));
 }
Ejemplo n.º 12
0
 // Token: 0x06000026 RID: 38 RVA: 0x0000219D File Offset: 0x0000039D
 public static ByteSize Gigabytes(this double input)
 {
     return(ByteSize.FromGigabytes(input));
 }
Ejemplo n.º 13
0
        private static void HandleUpload(string[] args)
        {
            var region = RegionEndpoint.EnumerableAllRegions.SingleOrDefault(reg => reg.SystemName == args[2]);

            if (args.Length < 6 || region == null)
            {
                Console.WriteLine($"args should be aws_key aws_secret region vault_name description filename");
                return;
            }
            var aws_key     = args[0];
            var aws_secret  = args[1];
            var vault_name  = args[3];
            var description = args[4];
            var filename    = args[5];
            var creds       = new BasicAWSCredentials(aws_key, aws_secret);
            var config      = new AmazonGlacierConfig
            {
                RegionEndpoint = region,
                Timeout        = TimeSpan.FromDays(10)
            };
            var client    = new AmazonGlacierClient(creds, config);
            var initReq   = new InitiateMultipartUploadRequest(vault_name, description, PartSize);
            var ts        = new CancellationTokenSource();
            var completed = 0;
            var started   = 0;

            try
            {
                var res      = client.InitiateMultipartUploadAsync(initReq, ts.Token).Result;
                var promises = new List <Task <UploadMultipartPartResponse> >();
                Task <UploadMultipartPartResponse> lastPart = null;
                var  sem        = new SemaphoreSlim(ConcurrencyLimit);
                long totalSize  = 0;
                int  totalParts = 0;
                using (var fs = new FileStream(filename, FileMode.Open))
                {
                    totalSize = fs.Length;
                    Console.WriteLine($"Preparing to upload {ByteSize.FromBytes(totalSize)}");
                    totalParts = (int)(fs.Length / PartSize) + 1;
                    bool noErrors = true;
                    while (noErrors)
                    {
                        sem.Wait();
                        var arr     = new byte[PartSize];
                        var start   = fs.Position;
                        var read    = fs.Read(arr, 0, (int)PartSize);
                        var check   = TreeHasher.ComputeArrayHashString(arr, read);
                        var partReq = new UploadMultipartPartRequest(vault_name,
                                                                     res.UploadId,
                                                                     check,
                                                                     $"bytes {start}-{start + read - 1}/*",
                                                                     new MemoryStream(arr, 0, read));
                        var promise = client.UploadMultipartPartAsync(partReq, ts.Token);
                        Interlocked.Increment(ref started);
                        Console.WriteLine($"Started {started} out of {totalParts}");
                        promise.ContinueWith(tsk =>
                        {
                            if (tsk.IsFaulted)
                            {
                                Console.WriteLine($"Exception encountered: {tsk.Exception.ToString()}");
                                noErrors = false;
                                throw tsk.Exception;
                            }
                            Interlocked.Increment(ref completed);
                            Console.WriteLine($"{completed} out of {totalParts} completed.");
                            sem.Release();
                        });
                        promises.Add(promise);
                        if (read < PartSize || fs.Position >= fs.Length - 1)
                        {
                            lastPart = promise;
                            break;
                        }
                    }
                }

                Task.WaitAll(promises.ToArray());
                using (var fs = new FileStream(filename, FileMode.Open))
                {
                    var check    = TreeHasher.ComputeHashString(fs);
                    var finisher = new CompleteMultipartUploadRequest(vault_name, res.UploadId, totalSize.ToString(), check);
                    Console.WriteLine("Finishing up");
                    Console.WriteLine($"Computed checksum {check}");
                    var result = client.CompleteMultipartUploadAsync(finisher, ts.Token).Result;
                    Console.WriteLine($"Completed: {result.Checksum}");
                    Console.WriteLine($"Calculated: {check}");
                    var match = string.Equals(result.Checksum, check, StringComparison.InvariantCultureIgnoreCase) ? "" : "not ";
                    Console.WriteLine($"Checksums do {match}match.");
                    Console.WriteLine($"Archive ID: {result.ArchiveId} Location: {result.Location}");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Exception thrown: {ex.GetType().Name} - {ex.Message}");
                Console.WriteLine($"Full exception: {ex.ToString()}");
            }
        }
Ejemplo n.º 14
0
 // Token: 0x06000017 RID: 23 RVA: 0x00002115 File Offset: 0x00000315
 public static ByteSize Kilobytes(this long input)
 {
     return(ByteSize.FromKilobytes((double)input));
 }
Ejemplo n.º 15
0
 /// <summary>
 /// Create a ByteRate with given quantity of bytes across an interval
 /// </summary>
 /// <param name="size"></param>
 /// <param name="interval"></param>
 public ByteRate(ByteSize size, TimeSpan interval)
 {
     this.Size = size;
     this.Interval = interval;
 }
Ejemplo n.º 16
0
 private static string MonoWorkaround(long byteCount, bool useBinaryPrefix)
 {
     // TODO: Test for equal output
     var bs = new ByteSize(byteCount);
     return bs.ToString(useBinaryPrefix ? PrefixType.Binary : PrefixType.Decimal);
 }
Ejemplo n.º 17
0
        private void BeginImportingMods()
        {
            var modsToExtract        = CompressedMods.Where(x => x.SelectedForImport).ToList();
            NamedBackgroundWorker bw = new NamedBackgroundWorker(@"ModExtractor");

            bw.DoWork             += ExtractModsBackgroundThread;
            bw.RunWorkerCompleted += (a, b) =>
            {
                TaskRunning = false;
                if (b.Result is List <Mod> modList)
                {
                    OnClosing(new DataEventArgs(modList));
                    return;
                }


                long            requiredSpace = 0;
                ModImportResult result        = ModImportResult.None;
                if (b.Result is (long spaceRequired, ModImportResult res))
                {
                    result        = res;
                    requiredSpace = spaceRequired;
                }

                if (b.Result is ModImportResult res2)
                {
                    result = res2;
                }

                switch (result)
                {
                case ModImportResult.USER_ABORTED_IMPORT:
                {
                    ProgressValue         = 0;
                    ProgressMaximum       = 100;
                    ProgressIndeterminate = false;
                    ActionText            = M3L.GetString(M3L.string_selectModsToImportOrInstall);
                    return;         //Don't do anything.
                }

                case ModImportResult.ERROR_COULD_NOT_DELETE_EXISTING_DIR:
                {
                    ProgressValue         = 0;
                    ProgressMaximum       = 100;
                    ProgressIndeterminate = false;
                    ActionText            = M3L.GetString(M3L.string_errorUnableToDeleteExistingModDirectory);
                    return;         //Don't do anything.
                }

                case ModImportResult.ERROR_INSUFFICIENT_DISK_SPACE:
                {
                    ProgressValue         = 0;
                    ProgressMaximum       = 100;
                    ProgressIndeterminate = false;
                    ActionText            = M3L.GetString(M3L.string_insufficientDiskSpaceToExtractSelectedMods); //localize me
                    Utilities.DriveFreeBytes(Utilities.GetModsDirectory(), out var freeSpace);
                    M3L.ShowDialog(window, M3L.GetString(M3L.string_interp_dialogNotEnoughFreeSpaceToExtract, ByteSize.FromBytes(requiredSpace).ToString(), ByteSize.FromBytes(freeSpace).ToString()), M3L.GetString(M3L.string_insufficientDiskSpace), MessageBoxButton.OK, MessageBoxImage.Error);
                    return;         //Don't do anything.
                }
                }
                //Close.
                OnClosing(DataEventArgs.Empty);
            };
            TaskRunning = true;
            bw.RunWorkerAsync(modsToExtract);
        }
Ejemplo n.º 18
0
 private void UpdateDownloadProgress(string fileName, ByteSize current, ByteSize total)
 {
     Console.WriteLine(string.Format(ProgressFormat, current, total));
 }
Ejemplo n.º 19
0
 double BytesToMegabytes(long bytes) => Math.Round(ByteSize.FromBytes(bytes).Megabytes, 2);
Ejemplo n.º 20
0
 public string GetBytesReadable(long size)
 {
     return(ByteSize.FromKiloBytes(size).ToString());
 }
Ejemplo n.º 21
0
        static void Main(string[] args)
        {
            Console.CancelKeyPress += (sender, cancelArgs) =>
            {
                Log.Verbose("Cancelling execution...");
                cts.Cancel();
            };

            var app = new CommandLineApplication
            {
                Name             = "redis-benchmark",
                FullName         = "Minimal redis-benchmark clone using StackExchange.Redis",
                ExtendedHelpText = $@"
The version of StackExchange.Redis can be changed by specifying
the environment variable StackExchangeRedisVersion and providing a
value that is a valid version of the NuGet package.

If no value is specified it will default to {HighestTestedVersion}.

Note that the version must be compatible with the APIs used in the 
tool. The lowest version tested was {LowestTestedVersion} and the highest was {HighestTestedVersion}."
            };

            app.HelpOption("-?|--help");

            var hostOption                 = app.Option("-h|--host", "Server hostname (default 127.0.0.1)", CommandOptionType.SingleValue, false);
            var portOption                 = app.Option("-p|--port", "Server port (default 6379)", CommandOptionType.SingleValue, false);
            var socketOption               = app.Option("-s|--socket", "Server socket (overrides host and port)", CommandOptionType.SingleValue, false);
            var passwordOption             = app.Option("-a|--auth-password", "Password for Redis Auth", CommandOptionType.SingleValue, false);
            var clientsOption              = app.Option("-c|--clients", "Number of parallel connections (default 50)", CommandOptionType.SingleValue, false);
            var requestsOption             = app.Option("-n|--num-requests", "Total number of requests (default 100000)", CommandOptionType.SingleValue, false);
            var sizeOption                 = app.Option("-d|--data-size", "Data size of SET/GET value, specified  (default 2B)", CommandOptionType.SingleValue, false);
            var dbNumOption                = app.Option("--dbnum", "SELECT the specified db number (default 0)", CommandOptionType.SingleValue, false);
            var keyspaceLenOption          = app.Option("-r|--keyspace-length", @"Use random keys for SET/GET/INCR, random values for SADD
  Using this option the benchmark will expand the string __rand_int__
  inside an argument with a 12 digits number in the specified range
  from 0 to keyspacelen - 1.The substitution changes every time a command
  is executed.Default tests use this to hit random keys in the
  specified range.", CommandOptionType.SingleValue, false);
            var quietOption                = app.Option("-q|--quiet", "Quiet. Just show query/sec values", CommandOptionType.NoValue, false);
            var loopOption                 = app.Option("-l|--loop", "Loop. Run the tests forever", CommandOptionType.NoValue, false);
            var testsOption                = app.Option("-t|--tests", "Only run the comma separated list of tests. The test names are the same as the ones produced as output", CommandOptionType.SingleValue, false);
            var longLivedConnectionsOption = app.Option("-L|--long-lived-connections", "Use long lived connections for all test runs", CommandOptionType.NoValue, false);

            app.OnExecute(async() =>
            {
                var config = new BenchmarkConfiguration();

                if (socketOption.HasValue())
                {
                    var values      = socketOption.Value().Split(":");
                    config.Endpoint = new IPEndPoint(IPAddress.Parse(values[0]), int.Parse(values[1]));
                }
                else if (hostOption.HasValue() || portOption.HasValue())
                {
                    var host        = IPAddress.Parse(hostOption.HasValue() ? hostOption.Value() : "127.0.0.1");
                    var port        = int.Parse(portOption.HasValue() ? portOption.Value() : "6379");
                    config.Endpoint = new IPEndPoint(host, port);
                }

                if (testsOption.HasValue())
                {
                    var tests             = testsOption.Value().ToLower().Split(",");
                    config.BenchmarkTests = new HashSet <string>(tests);
                }

                if (passwordOption.HasValue())
                {
                    config.Password = passwordOption.Value();
                }
                if (clientsOption.HasValue())
                {
                    config.ClientCount = int.Parse(clientsOption.Value());
                }
                if (requestsOption.HasValue())
                {
                    config.RequestCount = int.Parse(requestsOption.Value());
                }
                if (sizeOption.HasValue())
                {
                    config.ValueSize = ByteSize.Parse(sizeOption.Value());
                }
                if (dbNumOption.HasValue())
                {
                    config.DatabaseNumber = int.Parse(dbNumOption.Value());
                }
                if (keyspaceLenOption.HasValue())
                {
                    config.KeyspaceLength = int.Parse(keyspaceLenOption.Value());
                }
                if (quietOption.HasValue())
                {
                    config.QuietOutput = true;
                }
                if (loopOption.HasValue())
                {
                    config.LoopIndefinitely = true;
                }
                if (longLivedConnectionsOption.HasValue())
                {
                    config.LongLivedConnections = true;
                }

                Log.Logger = new LoggerConfiguration()
                             .MinimumLevel.Is(config.QuietOutput ? LogEventLevel.Information : LogEventLevel.Verbose)
                             .WriteTo.Console()
                             .CreateLogger();

                if (!config.LoopIndefinitely)
                {
                    await ExecuteBenchmarks(config);
                }
                else
                {
                    while (true)
                    {
                        await ExecuteBenchmarks(config);
                    }
                }

                // Clean up all connections if long lived connections are configured
                if (config.LongLivedConnections && StaticClients != null)
                {
                    foreach (var client in StaticClients)
                    {
                        client.Dispose();
                    }
                    StaticClients = null;
                }

                return(0);
            });

            app.Execute(args);
        }
Ejemplo n.º 22
0
        public async override void GetSpecialProperties()
        {
            if (Item.IsShortcutItem)
            {
                ViewModel.ItemSizeVisibility = Visibility.Visible;
                ViewModel.ItemSize           = ByteSize.FromBytes(Item.FileSizeBytes).ToBinaryString().ConvertSizeAbbreviation()
                                               + " (" + ByteSize.FromBytes(Item.FileSizeBytes).Bytes.ToString("#,##0") + " " + "ItemSizeBytes".GetLocalized() + ")";
                ViewModel.ItemCreatedTimestamp  = Item.ItemDateCreated;
                ViewModel.ItemAccessedTimestamp = Item.ItemDateAccessed;
                if (Item.IsLinkItem || string.IsNullOrWhiteSpace(((ShortcutItem)Item).TargetPath))
                {
                    // Can't show any other property
                    return;
                }
            }

            var parentDirectory = AppInstance.FilesystemViewModel.CurrentFolder;

            StorageFolder storageFolder = null;

            try
            {
                var isItemSelected = await CoreApplication.MainView.ExecuteOnUIThreadAsync(() => AppInstance?.ContentPage?.IsItemSelected ?? true);

                if (isItemSelected)
                {
                    storageFolder = await AppInstance.FilesystemViewModel.GetFolderFromPathAsync((Item as ShortcutItem)?.TargetPath ?? Item.ItemPath);
                }
                else if (!parentDirectory.ItemPath.StartsWith(App.AppSettings.RecycleBinPath))
                {
                    storageFolder = await AppInstance.FilesystemViewModel.GetFolderFromPathAsync(parentDirectory.ItemPath);
                }
            }
            catch (Exception ex)
            {
                NLog.LogManager.GetCurrentClassLogger().Error(ex, ex.Message);
                // Could not access folder, can't show any other property
                return;
            }

            if (storageFolder != null)
            {
                ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings;
                string returnformat = Enum.Parse <TimeStyle>(localSettings.Values[LocalSettings.DateTimeFormat].ToString()) == TimeStyle.Application ? "D" : "g";
                ViewModel.ItemCreatedTimestamp = ListedItem.GetFriendlyDateFromFormat(storageFolder.DateCreated, returnformat);
                LoadFolderIcon(storageFolder);
                GetOtherProperties(storageFolder.Properties);
                GetFolderSize(storageFolder, TokenSource.Token);
            }
            else if (parentDirectory.ItemPath.StartsWith(App.AppSettings.RecycleBinPath))
            {
                // GetFolderFromPathAsync cannot access recyclebin folder
                if (AppInstance.FilesystemViewModel.Connection != null)
                {
                    var value = new ValueSet();
                    value.Add("Arguments", "RecycleBin");
                    value.Add("action", "Query");
                    // Send request to fulltrust process to get recyclebin properties
                    var response = await AppInstance.FilesystemViewModel.Connection.SendMessageAsync(value);

                    if (response.Status == Windows.ApplicationModel.AppService.AppServiceResponseStatus.Success)
                    {
                        if (response.Message.TryGetValue("BinSize", out var binSize))
                        {
                            ViewModel.ItemSizeBytes      = (long)binSize;
                            ViewModel.ItemSize           = ByteSize.FromBytes((long)binSize).ToString();
                            ViewModel.ItemSizeVisibility = Visibility.Visible;
                        }
                        else
                        {
                            ViewModel.ItemSizeVisibility = Visibility.Collapsed;
                        }
                        if (response.Message.TryGetValue("NumItems", out var numItems))
                        {
                            ViewModel.FilesCount = (int)(long)numItems;
                            SetItemsCountString();
                            ViewModel.FilesAndFoldersCountVisibility = Visibility.Visible;
                        }
                        else
                        {
                            ViewModel.FilesAndFoldersCountVisibility = Visibility.Collapsed;
                        }
                        ViewModel.ItemCreatedTimestampVisibiity   = Visibility.Collapsed;
                        ViewModel.ItemAccessedTimestampVisibility = Visibility.Collapsed;
                        ViewModel.ItemModifiedTimestampVisibility = Visibility.Collapsed;
                        ViewModel.ItemFileOwnerVisibility         = Visibility.Collapsed;
                        ViewModel.LastSeparatorVisibility         = Visibility.Collapsed;
                    }
                }
            }
        }
Ejemplo n.º 23
0
        public void OperatorSubtract()
        {
            var bs1 = new ByteSize();
            var bs2 = new ByteSize();
            var expected = new ByteSize();
            var actual = bs1 - bs2;

            Assert.AreEqual(expected.ToString(), actual.ToString());

            bs1 = new ByteSize(2);
            bs2 = new ByteSize(1);
            expected = new ByteSize(1);
            actual = bs1 - bs2;
            Assert.AreEqual(expected.ToString(), actual.ToString());

            bs1 = new ByteSize(1024);
            bs2 = new ByteSize(2);
            expected = new ByteSize(1022);
            actual = bs1 - bs2;
            Assert.AreEqual(expected.ToString(), actual.ToString());

            bs1 = new ByteSize(1, ByteSizeUnit.KibiByte);
            bs2 = new ByteSize(2);
            expected = new ByteSize(1022);
            actual = bs1 - bs2;
            Assert.AreEqual(expected.ToString(), actual.ToString());
        }
Ejemplo n.º 24
0
 // Token: 0x0600002C RID: 44 RVA: 0x000021D2 File Offset: 0x000003D2
 public static ByteSize Terabytes(this int input)
 {
     return(ByteSize.FromTerabytes((double)input));
 }
Ejemplo n.º 25
0
        private void ExtractModsBackgroundThread(object sender, DoWorkEventArgs e)
        {
            List <Mod> mods          = (List <Mod>)e.Argument;
            List <Mod> extractedMods = new List <Mod>();

            void TextUpdateCallback(string x)
            {
                ActionText = x;
            }

            //get total size requirement
            long requiredDiskSpace = mods.Sum(x => x.GetRequiredSpaceForExtraction(ArchiveFilePath));

            if (Utilities.DriveFreeBytes(Utilities.GetModsDirectory(), out var freespaceBytes))
            {
                requiredDiskSpace = (long)(requiredDiskSpace * 1.05); //5% buffer
                Log.Information($@"Selected mods require: {ByteSize.FromBytes(requiredDiskSpace)}");
                if ((long)freespaceBytes < requiredDiskSpace)
                {
                    Log.Error(@"There is not enough free space on the disk to extract these mods.");
                    Log.Error($@"Selected mods require: {ByteSize.FromBytes(requiredDiskSpace)} | Disk space available in library partition: {ByteSize.FromBytes(freespaceBytes)}");
                    e.Result = (requiredDiskSpace, ModImportResult.ERROR_INSUFFICIENT_DISK_SPACE);
                    return;
                }
            }
            else
            {
                Log.Error(@"Unable to get amount of free space for mod library directory disk! We will continue anyways. Path: " + Utilities.GetModsDirectory());
            }



            foreach (var mod in mods)
            {
                //Todo: Extract files
                Log.Information(@"Extracting mod: " + mod.ModName);
                ActionText            = M3L.GetString(M3L.string_interp_extractingX, mod.ModName);
                ProgressValue         = 0;
                ProgressMaximum       = 100;
                ProgressIndeterminate = true;
                //Ensure directory
                var modDirectory  = Utilities.GetModDirectoryForGame(mod.Game);
                var sanitizedPath = Path.Combine(modDirectory, Utilities.SanitizePath(mod.ModName));


                if (Directory.Exists(sanitizedPath))
                {
                    //Will delete on import
                    bool abort = false;
                    Application.Current.Dispatcher.Invoke(delegate
                    {
                        var result = M3L.ShowDialog(Window.GetWindow(this), M3L.GetString(M3L.string_interp_dialogImportingModWillDeleteExistingMod, sanitizedPath), M3L.GetString(M3L.string_modAlreadyExists), MessageBoxButton.YesNo, MessageBoxImage.Warning, MessageBoxResult.No);
                        if (result == MessageBoxResult.No)
                        {
                            e.Result = ModImportResult.USER_ABORTED_IMPORT;
                            abort    = true;
                            return;
                        }

                        try
                        {
                            if (!Utilities.DeleteFilesAndFoldersRecursively(sanitizedPath))
                            {
                                Log.Error(@"Could not delete existing mod directory.");
                                e.Result = ModImportResult.ERROR_COULD_NOT_DELETE_EXISTING_DIR;
                                M3L.ShowDialog(Window.GetWindow(this), M3L.GetString(M3L.string_dialogErrorOccuredDeletingExistingMod), M3L.GetString(M3L.string_errorDeletingExistingMod), MessageBoxButton.OK, MessageBoxImage.Error);
                                abort = true;
                                return;
                            }
                        }
                        catch (Exception ex)
                        {
                            //I don't think this can be triggered but will leave as failsafe anyways.
                            Log.Error(@"Error while deleting existing output directory: " + App.FlattenException(ex));
                            M3L.ShowDialog(Window.GetWindow(this), M3L.GetString(M3L.string_interp_errorOccuredDeletingExistingModX, ex.Message), M3L.GetString(M3L.string_errorDeletingExistingMod), MessageBoxButton.OK, MessageBoxImage.Error);
                            e.Result = ModImportResult.ERROR_COULD_NOT_DELETE_EXISTING_DIR;
                            abort    = true;
                        }
                    });
                    if (abort)
                    {
                        Log.Warning(@"Aborting mod import.");
                        return;
                    }
                }

                Directory.CreateDirectory(sanitizedPath);

                //Check if RCW mod
                if (mod.InstallationJobs.Count == 1 && mod.InstallationJobs[0].Header == ModJob.JobHeader.ME2_RCWMOD)
                {
                    Log.Information(@"Generating M3 wrapper moddesc.ini for " + mod.ModName);
                    mod.ExtractRCWModToM3LibraryMod(sanitizedPath);
                    extractedMods.Add(mod);
                }
                else
                {
                    mod.ExtractFromArchive(ArchiveFilePath, sanitizedPath, CompressPackages, TextUpdateCallback, ExtractionProgressCallback, CompressedPackageCallback);
                    extractedMods.Add(mod);
                }
            }
            e.Result = extractedMods;
        }
Ejemplo n.º 26
0
        /// <summary> 
        /// Load the message definition list from a text file.
        /// </summary>
        public void Load(string fName)
        {
            // Quit if file doesn't exist.
            FileInfo fi = new FileInfo(fName);
            if(fi.Exists == false)
                return;

                // Open text definitions file in read-only mode.
            FileStream   fs = new FileStream(fName, FileMode.Open, FileAccess.Read);
            StreamReader sr = new StreamReader(fs);

            // Set file pointer to beginning of file.
            sr.BaseStream.Seek(0, SeekOrigin.Begin);

            string line = "";
            string data = "";
            while((line = sr.ReadLine()) != null)
            {
                data = line.Substring(line.IndexOf(":")+1);
                if(line.StartsWith("<Port Name>"))
                    this.portName = data;
                if(line.StartsWith("<Baud Rate>"))
                    this.baudRate = (LineSpeed) int.Parse(data);
                if(line.StartsWith("<CTS Flow>"))
                    this.txFlowCTS = bool.Parse(data);
                if(line.StartsWith("<DSR Flow>"))
                    this.txFlowDSR = bool.Parse(data);
                if(line.StartsWith("<DTR Ctrl>"))
                    this.dtrControl = (PinState) byte.Parse(data);
                if(line.StartsWith("<DSR Sense>"))
                    this.rxDSRsense = bool.Parse(data);
                if(line.StartsWith("<TX Continue>"))
                    this.txContinue = bool.Parse(data);
                if(line.StartsWith("<TX Xoff Flow>"))
                    this.txFlowXoff = bool.Parse(data);
                if(line.StartsWith("<RX Xoff Flow>"))
                    this.rxFlowXoff = bool.Parse(data);
                if(line.StartsWith("<Error Replace>"))
                    this.errReplace = bool.Parse(data);
                if(line.StartsWith("<Null Discard>"))
                    this.nulDiscard = bool.Parse(data);
                if(line.StartsWith("<RTS Control>"))
                    this.rtsControl = (PinState) byte.Parse(data);
                if(line.StartsWith("<Abort On Error>"))
                    this.abortOnErr = bool.Parse(data);
                if(line.StartsWith("<Xon Limit>"))
                    this.xonLimit = short.Parse(data);
                if(line.StartsWith("<Xoff Limit>"))
                    this.xoffLimit = short.Parse(data);
                if(line.StartsWith("<Bits/Byte>"))
                    this.dataBits = (ByteSize) byte.Parse(data);
                if(line.StartsWith("<Parity>"))
                    this.parity = (Parity) byte.Parse(data);
                if(line.StartsWith("<Stop Bits>"))
                    this.stopBits = (StopBits) byte.Parse(data);
                if(line.StartsWith("<Xon Char>"))
                    this.xonChar = byte.Parse(data);
                if(line.StartsWith("<Xoff Char>"))
                    this.xoffChar = byte.Parse(data);
                if(line.StartsWith("<Error Char>"))
                    this.errChar = byte.Parse(data);
                if(line.StartsWith("<EOF Char>"))
                    this.eofChar = byte.Parse(data);
                if(line.StartsWith("<Event Char>"))
                    this.evtChar = byte.Parse(data);
                if(line.StartsWith("<Handshaking>"))
                    this.handshake = (Handshake) byte.Parse(data);
                if(line.StartsWith("<RX Q Length>"))
                    this.rxQueLen = int.Parse(data);
                if(line.StartsWith("<TX Q Length>"))
                    this.txQueLen = int.Parse(data);
                if(line.StartsWith("<TX Timeout(M)>"))
                    this.txTmoMulti = uint.Parse(data);
                if(line.StartsWith("<TX Timeout(C)>"))
                    this.txTmoConst = uint.Parse(data);
                if(line.StartsWith("<Receive Mode>"))
                    this.receiveMode = bool.Parse(data);
            }

            // FClose.
            fs.Close();
            return;
        }
Ejemplo n.º 27
0
        public override async void GetSpecialProperties()
        {
            ViewModel.ItemSizeVisibility = Visibility.Visible;
            ViewModel.ItemSize           = ByteSize.FromBytes(Item.FileSizeBytes).ToBinaryString().ConvertSizeAbbreviation()
                                           + " (" + ByteSize.FromBytes(Item.FileSizeBytes).Bytes.ToString("#,##0") + " " + ResourceController.GetTranslation("ItemSizeBytes") + ")";

            if (Item.IsShortcutItem)
            {
                ViewModel.ItemCreatedTimestamp  = Item.ItemDateCreated;
                ViewModel.ItemAccessedTimestamp = Item.ItemDateAccessed;
                ViewModel.LoadLinkIcon          = Item.IsLinkItem;
                if (Item.IsLinkItem || string.IsNullOrWhiteSpace(((ShortcutItem)Item).TargetPath))
                {
                    // Can't show any other property
                    return;
                }
            }

            StorageFile file = null;

            try
            {
                file = await ItemViewModel.GetFileFromPathAsync((Item as ShortcutItem)?.TargetPath ?? Item.ItemPath);
            }
            catch (Exception ex)
            {
                NLog.LogManager.GetCurrentClassLogger().Error(ex, ex.Message);
                // Could not access file, can't show any other property
                return;
            }

            using (var Thumbnail = await file.GetThumbnailAsync(ThumbnailMode.SingleItem, 80, ThumbnailOptions.UseCurrentScale))
            {
                BitmapImage icon = new BitmapImage();
                if (Thumbnail != null)
                {
                    ViewModel.FileIconSource = icon;
                    await icon.SetSourceAsync(Thumbnail);

                    ViewModel.LoadUnknownTypeGlyph = false;
                    ViewModel.LoadFileIcon         = true;
                }
            }

            if (Item.IsShortcutItem)
            {
                // Can't show any other property
                return;
            }

            ViewModel.ItemCreatedTimestamp = ListedItem.GetFriendlyDate(file.DateCreated);
            GetOtherProperties(file.Properties);

            // Get file MD5 hash
            var hashAlgTypeName = HashAlgorithmNames.Md5;

            ViewModel.ItemMD5HashProgressVisibility = Visibility.Visible;
            ViewModel.ItemMD5HashVisibility         = Visibility.Visible;
            try
            {
                ViewModel.ItemMD5Hash = await App.CurrentInstance.InteractionOperations
                                        .GetHashForFile(Item, hashAlgTypeName, TokenSource.Token, ProgressBar);
            }
            catch (Exception ex)
            {
                NLog.LogManager.GetCurrentClassLogger().Error(ex, ex.Message);
                ViewModel.ItemMD5HashCalcError = true;
            }
        }
Ejemplo n.º 28
0
 //Private methods
 private void LoadMembers(XmlTextReader xtr)
 {
     if (xtr.NodeType == XmlNodeType.Element)
     {
         switch (xtr.Name)
         {
             case "PortIndex":
                 xtr.Read();
                 if (xtr.NodeType == XmlNodeType.Text)
                     this.portIndex = int.Parse(xtr.Value);
                 break;
             case "BaudRate":
                 xtr.Read();
                 if (xtr.NodeType == XmlNodeType.Text)
                     this.baudRate = (BaudRate)int.Parse(xtr.Value);
                 break;
             case "Parity":
                 xtr.Read();
                 if (xtr.NodeType == XmlNodeType.Text)
                     this.parity = (Parity)byte.Parse(xtr.Value);
                 break;
             case "DataBits":
                 xtr.Read();
                 if (xtr.NodeType == XmlNodeType.Text)
                     this.dataBits = (ByteSize)byte.Parse(xtr.Value);
                 break;
             case "StopBits":
                 xtr.Read();
                 if (xtr.NodeType == XmlNodeType.Text)
                     this.stopBits = (StopBits)byte.Parse(xtr.Value);
                 break;
             case "ReadIntervalTimeout":
                 xtr.Read();
                 if (xtr.NodeType == XmlNodeType.Text)
                     this.ReadIntervalTimeout = UInt32.Parse(xtr.Value);
                 break;
             case "ReadTotalTimeoutMultiplier":
                 xtr.Read();
                 if (xtr.NodeType == XmlNodeType.Text)
                     this.ReadTotalTimeoutMultiplier = UInt32.Parse(xtr.Value);
                 break;
             case "ReadTotalTimeoutConstant":
                 xtr.Read();
                 if (xtr.NodeType == XmlNodeType.Text)
                     this.ReadTotalTimeoutConstant = UInt32.Parse(xtr.Value);
                 break;
             case "WriteTotalTimeoutMultiplier":
                 xtr.Read();
                 if (xtr.NodeType == XmlNodeType.Text)
                     this.WriteTotalTimeoutMultiplier = UInt32.Parse(xtr.Value);
                 break;
             case "WriteTotalTimeoutConstant":
                 xtr.Read();
                 if (xtr.NodeType == XmlNodeType.Text)
                     this.WriteTotalTimeoutConstant = UInt32.Parse(xtr.Value);
                 break;
             case "Tag":
                 xtr.Read();
                 if (xtr.NodeType == XmlNodeType.Text)
                     this.tag = xtr.Value;
                 break;
         }
     }
 }
Ejemplo n.º 29
0
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            this.Invoke((MethodInvoker) delegate()
            {
                string text = metroComboBox1.Text;
                if (metroComboBox1.SelectedItem == "")
                {
                }
                else if (metroComboBox1.SelectedItem == "TITLE")
                {
                    metroProgressBar1.Increment(25);
                    path = metroTextBox1.Text;
                    cmd3 = "\" -c %TITLE% -d";
                    cmd1 = " \"";
                    if (metroCheckBox1.Checked)
                    {
                        arg = (cmd1 + path + cmd3 + " -r");
                    }
                    else
                    {
                        arg = (cmd1 + path + cmd3);
                    }
                    Process p               = new Process();
                    p.StartInfo.FileName    = "rename2.exe";
                    p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                    p.StartInfo.Arguments   = arg;
                    p.Start();
                    metroProgressBar1.Increment(25);
                    p.WaitForExit();
                    metroProgressBar1.Increment(25);
                }
                else if (metroComboBox1.SelectedItem == "CONTENT_ID")
                {
                    metroProgressBar1.Increment(25);
                    path = metroTextBox1.Text;
                    cmd3 = "\" -c %CONTENT_ID% -d";
                    cmd1 = " \"";
                    if (metroCheckBox1.Checked)
                    {
                        arg = (cmd1 + path + cmd3 + " -r");
                    }
                    else
                    {
                        arg = (cmd1 + path + cmd3);
                    }
                    Process p               = new Process();
                    p.StartInfo.FileName    = "rename1.exe";
                    p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                    p.StartInfo.Arguments   = arg;
                    p.Start();
                    metroProgressBar1.Increment(25);
                    p.WaitForExit();
                    metroProgressBar1.Increment(25);
                }
                else if (metroComboBox1.SelectedItem == "TITLE (TITLE_ID)")
                {
                    metroProgressBar1.Increment(25);
                    path = metroTextBox1.Text;
                    cmd3 = "\" -1 -d";
                    cmd1 = " \"";
                    if (metroCheckBox1.Checked)
                    {
                        arg = (cmd1 + path + cmd3 + " -r");
                    }
                    else
                    {
                        arg = (cmd1 + path + cmd3);
                    }
                    Process p               = new Process();
                    p.StartInfo.FileName    = "rename2.exe";
                    p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                    p.StartInfo.Arguments   = arg;
                    p.Start();
                    metroProgressBar1.Increment(25);
                    p.WaitForExit();
                    metroProgressBar1.Increment(25);
                }
                else if (metroComboBox1.SelectedItem == "TITLE (REGION)")
                {
                    metroProgressBar1.Increment(25);
                    path = metroTextBox1.Text;
                    cmd3 = "\" -2 -d";
                    cmd1 = " \"";
                    if (metroCheckBox1.Checked)
                    {
                        arg = (cmd1 + path + cmd3 + " -r");
                    }
                    else
                    {
                        arg = (cmd1 + path + cmd3);
                    }
                    Process p               = new Process();
                    p.StartInfo.FileName    = "rename2.exe";
                    p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                    p.StartInfo.Arguments   = arg;
                    p.Start();
                    metroProgressBar1.Increment(25);
                    p.WaitForExit();
                    metroProgressBar1.Increment(25);
                }
                else if (metroComboBox1.SelectedItem == "TITLE (TITLE_ID) [VERSION]")
                {
                    metroProgressBar1.Increment(25);
                    path = metroTextBox1.Text;
                    cmd3 = "\" -n -d";
                    cmd1 = " \"";
                    if (metroCheckBox1.Checked)
                    {
                        arg = (cmd1 + path + cmd3 + " -r");
                    }
                    else
                    {
                        arg = (cmd1 + path + cmd3);
                    }
                    Process p               = new Process();
                    p.StartInfo.FileName    = "rename1.exe";
                    p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                    p.StartInfo.Arguments   = arg;
                    p.Start();
                    metroProgressBar1.Increment(25);
                    p.WaitForExit();
                    metroProgressBar1.Increment(25);
                }

                dataGridView1.Rows.Clear();
                DirectoryInfo d = new DirectoryInfo(metroTextBox1.Text);
                foreach (var file in d.GetFiles("*.PKG"))
                {
                    length   = new System.IO.FileInfo(file.FullName).Length;
                    var temp = ByteSize.FromBytes(length);
                    var MB   = temp.MegaBytes;
                    dataGridView1.Rows.Add(file, MB.ToString("#####.##"));
                }
                metroProgressBar1.Increment(25);
                metroProgressBar1.Visible = false;
                metroProgressBar1.Value   = 0;
            });
        }
Ejemplo n.º 30
0
        public async override void GetSpecialProperties()
        {
            if (Item.IsShortcutItem)
            {
                ViewModel.ItemSizeVisibility = Visibility.Visible;
                ViewModel.ItemSize           = ByteSize.FromBytes(Item.FileSizeBytes).ToBinaryString().ConvertSizeAbbreviation()
                                               + " (" + ByteSize.FromBytes(Item.FileSizeBytes).Bytes.ToString("#,##0") + " " + ResourceController.GetTranslation("ItemSizeBytes") + ")";
                ViewModel.ItemCreatedTimestamp  = Item.ItemDateCreated;
                ViewModel.ItemAccessedTimestamp = Item.ItemDateAccessed;
                // Can't show any other property
                return;
            }

            StorageFolder storageFolder;

            if (App.CurrentInstance.ContentPage.IsItemSelected)
            {
                storageFolder = await ItemViewModel.GetFolderFromPathAsync(Item.ItemPath);

                ViewModel.ItemCreatedTimestamp = ListedItem.GetFriendlyDate(storageFolder.DateCreated);
                GetOtherProperties(storageFolder.Properties);
                GetFolderSize(storageFolder, TokenSource.Token);
            }
            else
            {
                var parentDirectory = App.CurrentInstance.FilesystemViewModel.CurrentFolder;
                if (parentDirectory.ItemPath.StartsWith(App.AppSettings.RecycleBinPath))
                {
                    // GetFolderFromPathAsync cannot access recyclebin folder
                    if (App.Connection != null)
                    {
                        var value = new ValueSet();
                        value.Add("Arguments", "RecycleBin");
                        value.Add("action", "Query");
                        // Send request to fulltrust process to get recyclebin properties
                        var response = await App.Connection.SendMessageAsync(value);

                        if (response.Status == Windows.ApplicationModel.AppService.AppServiceResponseStatus.Success)
                        {
                            if (response.Message.TryGetValue("BinSize", out var binSize))
                            {
                                ViewModel.ItemSizeBytes      = (long)binSize;
                                ViewModel.ItemSize           = ByteSize.FromBytes((long)binSize).ToString();
                                ViewModel.ItemSizeVisibility = Visibility.Visible;
                            }
                            else
                            {
                                ViewModel.ItemSizeVisibility = Visibility.Collapsed;
                            }
                            if (response.Message.TryGetValue("NumItems", out var numItems))
                            {
                                ViewModel.FilesCount = (int)(long)numItems;
                                SetItemsCountString();
                                ViewModel.FilesAndFoldersCountVisibility = Visibility.Visible;
                            }
                            else
                            {
                                ViewModel.FilesAndFoldersCountVisibility = Visibility.Collapsed;
                            }
                            ViewModel.ItemCreatedTimestampVisibiity   = Visibility.Collapsed;
                            ViewModel.ItemAccessedTimestampVisibility = Visibility.Collapsed;
                            ViewModel.ItemModifiedTimestampVisibility = Visibility.Collapsed;
                            ViewModel.ItemFileOwnerVisibility         = Visibility.Collapsed;
                            ViewModel.LastSeparatorVisibility         = Visibility.Collapsed;
                        }
                    }
                }
                else
                {
                    storageFolder = await ItemViewModel.GetFolderFromPathAsync(parentDirectory.ItemPath);

                    ViewModel.ItemCreatedTimestamp = ListedItem.GetFriendlyDate(storageFolder.DateCreated);
                    GetOtherProperties(storageFolder.Properties);
                    GetFolderSize(storageFolder, TokenSource.Token);
                }
            }
        }
Ejemplo n.º 31
0
        public new void ToString()
        {
            var bs = new ByteSize(1024, ByteSizeUnit.Bytes);
            Assert.AreEqual("1 KiB", bs.ToString());

            bs = new ByteSize(0, ByteSizeUnit.KibiByte);
            Assert.AreEqual("0 bytes", bs.ToString());

            bs = new ByteSize(1, ByteSizeUnit.KibiByte);
            Assert.AreEqual("1 KiB", bs.ToString());

            bs = new ByteSize(2, ByteSizeUnit.KibiByte);
            Assert.AreEqual("2 KiB", bs.ToString());

            bs = new ByteSize(3, ByteSizeUnit.KibiByte);
            Assert.AreEqual("3 KiB", bs.ToString());

            bs = new ByteSize(0, ByteSizeUnit.MibiByte);
            Assert.AreEqual("0 bytes", bs.ToString());

            bs = new ByteSize(1, ByteSizeUnit.MibiByte);
            Assert.AreEqual("1 MiB", bs.ToString());

            bs = new ByteSize(2, ByteSizeUnit.MibiByte);
            Assert.AreEqual("2 MiB", bs.ToString());

            bs = new ByteSize(3, ByteSizeUnit.MibiByte);
            Assert.AreEqual("3 MiB", bs.ToString());

            bs = new ByteSize(0, ByteSizeUnit.GibiByte);
            Assert.AreEqual("0 bytes", bs.ToString());

            bs = new ByteSize(1, ByteSizeUnit.GibiByte);
            Assert.AreEqual("1 GiB", bs.ToString());

            bs = new ByteSize(2, ByteSizeUnit.GibiByte);
            Assert.AreEqual("2 GiB", bs.ToString());

            bs = new ByteSize(3, ByteSizeUnit.GibiByte);
            Assert.AreEqual("3 GiB", bs.ToString());
        }
Ejemplo n.º 32
0
        public override async void GetSpecialProperties()
        {
            ViewModel.IsReadOnly = NativeFileOperationsHelper.HasFileAttribute(
                Item.ItemPath, System.IO.FileAttributes.ReadOnly);
            ViewModel.IsHidden = NativeFileOperationsHelper.HasFileAttribute(
                Item.ItemPath, System.IO.FileAttributes.Hidden);

            ViewModel.ItemSizeVisibility = Visibility.Visible;
            ViewModel.ItemSize           = ByteSize.FromBytes(Item.FileSizeBytes).ToBinaryString().ConvertSizeAbbreviation()
                                           + " (" + ByteSize.FromBytes(Item.FileSizeBytes).Bytes.ToString("#,##0") + " " + "ItemSizeBytes".GetLocalized() + ")";

            var fileIconInfo = await AppInstance.FilesystemViewModel.LoadIconOverlayAsync(Item.ItemPath, 80);

            if (fileIconInfo.Icon != null && !Item.IsLinkItem)
            {
                ViewModel.FileIconSource = fileIconInfo.Icon;
            }

            if (Item.IsShortcutItem)
            {
                ViewModel.ItemCreatedTimestamp  = Item.ItemDateCreated;
                ViewModel.ItemAccessedTimestamp = Item.ItemDateAccessed;
                ViewModel.LoadLinkIcon          = Item.IsLinkItem;
                if (Item.IsLinkItem || string.IsNullOrWhiteSpace(((ShortcutItem)Item).TargetPath))
                {
                    // Can't show any other property
                    return;
                }
            }

            StorageFile file = await AppInstance.FilesystemViewModel.GetFileFromPathAsync((Item as ShortcutItem)?.TargetPath ?? Item.ItemPath);

            if (file == null)
            {
                // Could not access file, can't show any other property
                return;
            }

            if (Item.IsShortcutItem)
            {
                // Can't show any other property
                return;
            }

            ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings;
            string returnformat = Enum.Parse <TimeStyle>(localSettings.Values[LocalSettings.DateTimeFormat].ToString()) == TimeStyle.Application ? "D" : "g";

            ViewModel.ItemCreatedTimestamp = ListedItem.GetFriendlyDateFromFormat(file.DateCreated, returnformat);
            GetOtherProperties(file.Properties);

            // Get file MD5 hash
            var hashAlgTypeName = HashAlgorithmNames.Md5;

            ViewModel.ItemMD5HashProgressVisibility = Visibility.Visible;
            ViewModel.ItemMD5HashVisibility         = Visibility.Visible;
            try
            {
                ViewModel.ItemMD5Hash = await AppInstance.InteractionOperations
                                        .GetHashForFileAsync(Item, hashAlgTypeName, TokenSource.Token, ProgressBar);
            }
            catch (Exception ex)
            {
                NLog.LogManager.GetCurrentClassLogger().Error(ex, ex.Message);
                ViewModel.ItemMD5HashCalcError = true;
            }
        }
Ejemplo n.º 33
0
        public static async Task <ListedItem> GetFile(
            WIN32_FIND_DATA findData,
            string pathRoot,
            string dateReturnFormat,
            NamedPipeAsAppServiceConnection connection,
            CancellationToken cancellationToken
            )
        {
            IUserSettingsService userSettingsService = Ioc.Default.GetService <IUserSettingsService>();

            var itemPath = Path.Combine(pathRoot, findData.cFileName);

            string itemName;

            if (userSettingsService.PreferencesSettingsService.ShowFileExtensions && !findData.cFileName.EndsWith(".lnk") && !findData.cFileName.EndsWith(".url"))
            {
                itemName = findData.cFileName; // never show extension for shortcuts
            }
            else
            {
                if (findData.cFileName.StartsWith("."))
                {
                    itemName = findData.cFileName; // Always show full name for dotfiles.
                }
                else
                {
                    itemName = Path.GetFileNameWithoutExtension(itemPath);
                }
            }

            DateTime itemModifiedDate, itemCreatedDate, itemLastAccessDate;

            try
            {
                FileTimeToSystemTime(ref findData.ftLastWriteTime, out SYSTEMTIME systemModifiedDateOutput);
                itemModifiedDate = new DateTime(
                    systemModifiedDateOutput.Year, systemModifiedDateOutput.Month, systemModifiedDateOutput.Day,
                    systemModifiedDateOutput.Hour, systemModifiedDateOutput.Minute, systemModifiedDateOutput.Second, systemModifiedDateOutput.Milliseconds,
                    DateTimeKind.Utc);

                FileTimeToSystemTime(ref findData.ftCreationTime, out SYSTEMTIME systemCreatedDateOutput);
                itemCreatedDate = new DateTime(
                    systemCreatedDateOutput.Year, systemCreatedDateOutput.Month, systemCreatedDateOutput.Day,
                    systemCreatedDateOutput.Hour, systemCreatedDateOutput.Minute, systemCreatedDateOutput.Second, systemCreatedDateOutput.Milliseconds,
                    DateTimeKind.Utc);

                FileTimeToSystemTime(ref findData.ftLastAccessTime, out SYSTEMTIME systemLastAccessOutput);
                itemLastAccessDate = new DateTime(
                    systemLastAccessOutput.Year, systemLastAccessOutput.Month, systemLastAccessOutput.Day,
                    systemLastAccessOutput.Hour, systemLastAccessOutput.Minute, systemLastAccessOutput.Second, systemLastAccessOutput.Milliseconds,
                    DateTimeKind.Utc);
            }
            catch (ArgumentException)
            {
                // Invalid date means invalid findData, do not add to list
                return(null);
            }

            long   itemSizeBytes     = findData.GetSize();
            var    itemSize          = ByteSize.FromBytes(itemSizeBytes).ToBinaryString().ConvertSizeAbbreviation();
            string itemType          = "ItemTypeFile".GetLocalized();
            string itemFileExtension = null;

            if (findData.cFileName.Contains('.'))
            {
                itemFileExtension = Path.GetExtension(itemPath);
                itemType          = itemFileExtension.Trim('.') + " " + itemType;
            }

            bool itemThumbnailImgVis = false;
            bool itemEmptyImgVis     = true;

            if (cancellationToken.IsCancellationRequested)
            {
                return(null);
            }

            if (findData.cFileName.EndsWith(".lnk") || findData.cFileName.EndsWith(".url"))
            {
                if (connection != null)
                {
                    var(status, response) = await connection.SendMessageForResponseAsync(new ValueSet()
                    {
                        { "Arguments", "FileOperation" },
                        { "fileop", "ParseLink" },
                        { "filepath", itemPath }
                    });

                    // If the request was canceled return now
                    if (cancellationToken.IsCancellationRequested)
                    {
                        return(null);
                    }
                    if (status == AppServiceResponseStatus.Success &&
                        response.ContainsKey("TargetPath"))
                    {
                        var    isUrl  = findData.cFileName.EndsWith(".url");
                        string target = (string)response["TargetPath"];

                        bool   isHidden = (((FileAttributes)findData.dwFileAttributes & FileAttributes.Hidden) == FileAttributes.Hidden);
                        double opacity  = 1;

                        if (isHidden)
                        {
                            opacity = Constants.UI.DimItemOpacity;
                        }

                        return(new ShortcutItem(null, dateReturnFormat)
                        {
                            PrimaryItemAttribute = (bool)response["IsFolder"] ? StorageItemTypes.Folder : StorageItemTypes.File,
                            FileExtension = itemFileExtension,
                            IsHiddenItem = isHidden,
                            Opacity = opacity,
                            FileImage = null,
                            LoadFileIcon = !(bool)response["IsFolder"] && itemThumbnailImgVis,
                            LoadWebShortcutGlyph = !(bool)response["IsFolder"] && isUrl && itemEmptyImgVis,
                            ItemName = itemName,
                            ItemDateModifiedReal = itemModifiedDate,
                            ItemDateAccessedReal = itemLastAccessDate,
                            ItemDateCreatedReal = itemCreatedDate,
                            ItemType = isUrl ? "ShortcutWebLinkFileType".GetLocalized() : "ShortcutFileType".GetLocalized(),
                            ItemPath = itemPath,
                            FileSize = itemSize,
                            FileSizeBytes = itemSizeBytes,
                            TargetPath = target,
                            Arguments = (string)response["Arguments"],
                            WorkingDirectory = (string)response["WorkingDirectory"],
                            RunAsAdmin = (bool)response["RunAsAdmin"],
                            IsUrl = isUrl,
                        });
                    }
                }
            }
            else if (App.LibraryManager.TryGetLibrary(itemPath, out LibraryLocationItem library))
            {
                return(new LibraryItem(library)
                {
                    ItemDateModifiedReal = itemModifiedDate,
                    ItemDateCreatedReal = itemCreatedDate,
                });
            }
            else
            {
                bool   isHidden = (((FileAttributes)findData.dwFileAttributes & FileAttributes.Hidden) == FileAttributes.Hidden);
                double opacity  = 1;

                if (isHidden)
                {
                    opacity = Constants.UI.DimItemOpacity;
                }

                if (".zip".Equals(itemFileExtension, StringComparison.OrdinalIgnoreCase) && await ZipStorageFolder.CheckDefaultZipApp(itemPath))
                {
                    return(new ZipItem(null, dateReturnFormat)
                    {
                        PrimaryItemAttribute = StorageItemTypes.Folder, // Treat zip files as folders
                        FileExtension = itemFileExtension,
                        FileImage = null,
                        LoadFileIcon = itemThumbnailImgVis,
                        ItemName = itemName,
                        IsHiddenItem = isHidden,
                        Opacity = opacity,
                        ItemDateModifiedReal = itemModifiedDate,
                        ItemDateAccessedReal = itemLastAccessDate,
                        ItemDateCreatedReal = itemCreatedDate,
                        ItemType = itemType,
                        ItemPath = itemPath,
                        FileSize = itemSize,
                        FileSizeBytes = itemSizeBytes
                    });
                }
                else
                {
                    return(new ListedItem(null, dateReturnFormat)
                    {
                        PrimaryItemAttribute = StorageItemTypes.File,
                        FileExtension = itemFileExtension,
                        FileImage = null,
                        LoadFileIcon = itemThumbnailImgVis,
                        ItemName = itemName,
                        IsHiddenItem = isHidden,
                        Opacity = opacity,
                        ItemDateModifiedReal = itemModifiedDate,
                        ItemDateAccessedReal = itemLastAccessDate,
                        ItemDateCreatedReal = itemCreatedDate,
                        ItemType = itemType,
                        ItemPath = itemPath,
                        FileSize = itemSize,
                        FileSizeBytes = itemSizeBytes
                    });
                }
            }
            return(null);
        }
Ejemplo n.º 34
0
        private static async Task <ListedItem> AddFileAsync(
            StorageFile file,
            StorageFolderWithPath currentStorageFolder,
            string dateReturnFormat,
            bool suppressThumbnailLoading,
            Type sourcePageType,
            CancellationToken cancellationToken
            )
        {
            var basicProperties = await file.GetBasicPropertiesAsync();

            var extraProperties = await basicProperties.RetrievePropertiesAsync(new[] { "System.DateCreated" });

            // Display name does not include extension
            var itemName = string.IsNullOrEmpty(file.DisplayName) || App.AppSettings.ShowFileExtensions ?
                           file.Name : file.DisplayName;
            var itemModifiedDate = basicProperties.DateModified;

            DateTimeOffset.TryParse(extraProperties["System.DateCreated"] as string, out var itemCreatedDate);
            var itemPath          = string.IsNullOrEmpty(file.Path) ? Path.Combine(currentStorageFolder.Path, file.Name) : file.Path;
            var itemSize          = ByteSize.FromBytes(basicProperties.Size).ToBinaryString().ConvertSizeAbbreviation();
            var itemSizeBytes     = basicProperties.Size;
            var itemType          = file.DisplayType;
            var itemFolderImgVis  = false;
            var itemFileExtension = file.FileType;

            BitmapImage icon = new BitmapImage();
            bool        itemThumbnailImgVis;
            bool        itemEmptyImgVis;

            if (sourcePageType != typeof(GridViewBrowser))
            {
                try
                {
                    var itemThumbnailImg = suppressThumbnailLoading ? null :
                                           await file.GetThumbnailAsync(ThumbnailMode.ListView, 40, ThumbnailOptions.UseCurrentScale);

                    if (itemThumbnailImg != null)
                    {
                        itemEmptyImgVis        = false;
                        itemThumbnailImgVis    = true;
                        icon.DecodePixelWidth  = 40;
                        icon.DecodePixelHeight = 40;
                        await icon.SetSourceAsync(itemThumbnailImg);
                    }
                    else
                    {
                        itemEmptyImgVis     = true;
                        itemThumbnailImgVis = false;
                    }
                }
                catch
                {
                    itemEmptyImgVis     = true;
                    itemThumbnailImgVis = false;
                    // Catch here to avoid crash
                }
            }
            else
            {
                try
                {
                    var itemThumbnailImg = suppressThumbnailLoading ? null :
                                           await file.GetThumbnailAsync(ThumbnailMode.ListView, 80, ThumbnailOptions.UseCurrentScale);

                    if (itemThumbnailImg != null)
                    {
                        itemEmptyImgVis        = false;
                        itemThumbnailImgVis    = true;
                        icon.DecodePixelWidth  = 80;
                        icon.DecodePixelHeight = 80;
                        await icon.SetSourceAsync(itemThumbnailImg);
                    }
                    else
                    {
                        itemEmptyImgVis     = true;
                        itemThumbnailImgVis = false;
                    }
                }
                catch
                {
                    itemEmptyImgVis     = true;
                    itemThumbnailImgVis = false;
                }
            }
            if (cancellationToken.IsCancellationRequested)
            {
                return(null);
            }

            if (file.Name.EndsWith(".lnk") || file.Name.EndsWith(".url"))
            {
                // This shouldn't happen, StorageFile api does not support shortcuts
                Debug.WriteLine("Something strange: StorageFile api returned a shortcut");
            }
            else
            {
                return(new ListedItem(file.FolderRelativeId, dateReturnFormat)
                {
                    PrimaryItemAttribute = StorageItemTypes.File,
                    FileExtension = itemFileExtension,
                    IsHiddenItem = false,
                    Opacity = 1,
                    LoadUnknownTypeGlyph = itemEmptyImgVis,
                    FileImage = icon,
                    LoadFileIcon = itemThumbnailImgVis,
                    LoadFolderGlyph = itemFolderImgVis,
                    ItemName = itemName,
                    ItemDateModifiedReal = itemModifiedDate,
                    ItemDateCreatedReal = itemCreatedDate,
                    ItemType = itemType,
                    ItemPath = itemPath,
                    FileSize = itemSize,
                    FileSizeBytes = (long)itemSizeBytes,
                });
            }
            return(null);
        }
Ejemplo n.º 35
0
        public async Task <long> CalculateFolderSizeAsync(string path, CancellationToken token)
        {
            if (string.IsNullOrEmpty(path))
            {
                // In MTP devices calculating folder size would be too slow
                // Also should use StorageFolder methods instead of FindFirstFileExFromApp
                return(0);
            }

            long size = 0;
            FINDEX_INFO_LEVELS findInfoLevel = FINDEX_INFO_LEVELS.FindExInfoBasic;
            int additionalFlags = FIND_FIRST_EX_LARGE_FETCH;

            IntPtr hFile = FindFirstFileExFromApp(path + "\\*.*", findInfoLevel, out WIN32_FIND_DATA findData, FINDEX_SEARCH_OPS.FindExSearchNameMatch, IntPtr.Zero,
                                                  additionalFlags);

            var count = 0;

            if (hFile.ToInt64() != -1)
            {
                do
                {
                    if (((FileAttributes)findData.dwFileAttributes & FileAttributes.Directory) != FileAttributes.Directory)
                    {
                        size += findData.GetSize();
                        ++count;
                        ViewModel.FilesCount++;
                    }
                    else if (((FileAttributes)findData.dwFileAttributes & FileAttributes.Directory) == FileAttributes.Directory)
                    {
                        if (findData.cFileName != "." && findData.cFileName != "..")
                        {
                            var itemPath = Path.Combine(path, findData.cFileName);

                            size += await CalculateFolderSizeAsync(itemPath, token);

                            ++count;
                            ViewModel.FoldersCount++;
                        }
                    }

                    if (size > ViewModel.ItemSizeBytes)
                    {
                        await Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                        {
                            ViewModel.ItemSizeBytes = size;
                            ViewModel.ItemSize      = ByteSize.FromBytes(size).ToBinaryString().ConvertSizeAbbreviation();
                            SetItemsCountString();
                        });
                    }

                    if (token.IsCancellationRequested)
                    {
                        break;
                    }
                } while (FindNextFile(hFile, out findData));
                FindClose(hFile);
                return(size);
            }
            else
            {
                return(0);
            }
        }
Ejemplo n.º 36
0
 // Token: 0x06000016 RID: 22 RVA: 0x0000210D File Offset: 0x0000030D
 public static ByteSize Kilobytes(this double input)
 {
     return(ByteSize.FromKilobytes(input));
 }
        public async Task <AddImagesViewModel> AddImagesAsync(List <IFormFile> files)
        {
            var UploadErrors = new List <string>();
            var AddedImages  = new List <Image>();
            var imagesFolder = Path.Combine(_hostingEnvironment.WebRootPath, "images");

            foreach (var formFile in files)
            {
                var _ext = Path.GetExtension(formFile.FileName).ToLower(); //file Extension

                if (formFile.Length > 0 && formFile.Length < 1000000)
                {
                    if (!(_ext == ".jpg" || _ext == ".png" || _ext == ".gif" || _ext == ".jpeg"))
                    {
                        UploadErrors.Add("The File \"" + formFile.FileName + "\" could Not be Uploaded because it has a bad extension --> \"" + _ext + "\"");
                        continue;
                    }

                    string NewFileName;
                    var    ExistingFilePath         = Path.Combine(imagesFolder, formFile.FileName);
                    var    FileNameWithoutExtension = Path.GetFileNameWithoutExtension(formFile.FileName);

                    for (var count = 1; File.Exists(ExistingFilePath) == true; count++)
                    {
                        FileNameWithoutExtension = FileNameWithoutExtension + " (" + count.ToString() + ")";

                        var UpdatedFileName = FileNameWithoutExtension + _ext;
                        var UpdatedFilePath = Path.Combine(imagesFolder, UpdatedFileName);
                        ExistingFilePath = UpdatedFilePath;
                    }

                    NewFileName = FileNameWithoutExtension + _ext;
                    var filePath = Path.Combine(imagesFolder, NewFileName);

                    using (var stream = new FileStream(filePath, FileMode.Create))
                    {
                        await formFile.CopyToAsync(stream);
                    }
                    var image = new Image
                    {
                        ID       = Guid.NewGuid().ToString(),
                        Name     = NewFileName,
                        Size     = ByteSize.FromBytes(formFile.Length).ToString(),
                        ImageUrl = "~/images/" + NewFileName,
                        FilePath = filePath
                    };
                    AddedImages.Add(image);
                }
                else
                {
                    UploadErrors.Add(formFile.FileName + " Size is not Valid. -->(" + ByteSize.FromBytes(formFile.Length).ToString() + ")... Upload a file less than 1MB");
                }
            }
            _context.Images.AddRange(AddedImages);
            _context.SaveChanges();


            var result = new AddImagesViewModel
            {
                AddedImages  = AddedImages,
                UploadErrors = UploadErrors
            };

            return(result);
        }
Ejemplo n.º 38
0
 // Token: 0x0600001B RID: 27 RVA: 0x00002139 File Offset: 0x00000339
 public static ByteSize Megabytes(this ushort input)
 {
     return(ByteSize.FromMegabytes((double)input));
 }
Ejemplo n.º 39
0
        public void Execute(Process process)
        {
            process.Mode = _mode;

            // Since we're in a Console app, and honor output format
            if (process.Output().Provider.In("internal", "console"))
            {
                process.Output().Provider = "console";
                process.Output().Format   = _format;
            }

            var logger = new NLogPipelineLogger(SlugifyTransform.Slugify(_cfg));

            if (!string.IsNullOrEmpty(process.MaxMemory))
            {
                var context = new PipelineContext(logger, process);

                var timer = new Stopwatch();
                timer.Start();
                GC.Collect();
                GC.WaitForPendingFinalizers();
                timer.Stop();
                context.Info($"Collected free memory. Time taken: {timer.Elapsed}.");

                var currentBytes = System.Diagnostics.Process.GetCurrentProcess().WorkingSet64.Bytes();
                var maxMemory    = ByteSize.Parse(process.MaxMemory);

                if (maxMemory.CompareTo(currentBytes) < 0)
                {
                    context.Error($"Process exceeded {maxMemory.Megabytes.ToString("#.0")} Mb. Current memory is {currentBytes.Megabytes.ToString("#.0")} Mb!");
                    Environment.Exit(1);
                }
                else
                {
                    context.Info($"The process is using {currentBytes.Megabytes.ToString("#.0")} Mb of it's max {maxMemory.Megabytes.ToString("#.0")} Mb allowed.");
                }
            }

            var builder = new ContainerBuilder();

            builder.RegisterInstance(logger).As <IPipelineLogger>().SingleInstance();
            builder.RegisterCallback(new RootModule(process.Shorthand).Configure);
            builder.RegisterCallback(new ContextModule(process).Configure);

            // providers
            builder.RegisterCallback(new AdoModule(process).Configure);
            builder.RegisterCallback(new LuceneModule(process).Configure);
            builder.RegisterCallback(new SolrModule(process).Configure);
            builder.RegisterCallback(new ElasticModule(process).Configure);
            builder.RegisterCallback(new InternalModule(process).Configure);
            builder.RegisterCallback(new FileModule(process).Configure);
            builder.RegisterCallback(new FolderModule(process).Configure);
            builder.RegisterCallback(new DirectoryModule(process).Configure);
            builder.RegisterCallback(new ExcelModule(process).Configure);
            builder.RegisterCallback(new WebModule(process).Configure);

            builder.RegisterCallback(new MapModule(process).Configure);
            builder.RegisterCallback(new TemplateModule(process).Configure);
            builder.RegisterCallback(new ActionModule(process).Configure);

            builder.RegisterCallback(new EntityPipelineModule(process).Configure);
            builder.RegisterCallback(new ProcessPipelineModule(process).Configure);
            builder.RegisterCallback(new ProcessControlModule(process).Configure);

            using (var scope = builder.Build().BeginLifetimeScope()) {
                try {
                    scope.Resolve <IProcessController>().Execute();
                } catch (Exception ex) {
                    scope.Resolve <IContext>().Error(ex.Message);
                }
            }
        }
Ejemplo n.º 40
0
 // Token: 0x06000003 RID: 3 RVA: 0x00002062 File Offset: 0x00000262
 public static ByteSize Bits(this short input)
 {
     return(ByteSize.FromBits((long)input));
 }
Ejemplo n.º 41
0
        public void DriversSelectionChanged(object x)
        {
            TreeOfFolders.Clear();
            try
            {
                foreach (DirectoryInfo dir in new DirectoryInfo(x.ToString()).GetDirectories().OrderBy(y => y.Name).ToArray())
                {
                    ShellObject  shellFolder = ShellObject.FromParsingName(dir.FullName.ToString());
                    BitmapSource shellThumb  = shellFolder.Thumbnail.SmallBitmapSource;

                    Folder folder = new Folder
                    {
                        Name     = dir.ToString(),
                        Icon     = shellThumb,
                        FullName = dir.FullName,
                    };
                    try
                    {
                        folder.CountOfFolders = new DirectoryInfo(dir.FullName).GetDirectories().Length.ToString();
                    }
                    catch (UnauthorizedAccessException ex)
                    {
                        folder.CountOfFolders = "Отказано в доступе";
                    }

                    try
                    {
                        folder.CountOfFiles = new DirectoryInfo(dir.FullName).GetFiles().Length.ToString();
                    }
                    catch (UnauthorizedAccessException ex)
                    {
                        folder.CountOfFiles = "Отказано в доступе";
                    }

                    try
                    {
                        folder.CreationTime = dir.CreationTime.ToString(CultureInfo.InvariantCulture);
                    }
                    catch (UnauthorizedAccessException ex)
                    {
                    }

                    folder.Children.Add(new Folder
                    {
                        Name     = "*",
                        Icon     = null,
                        FullName = dir.FullName
                    });

                    TreeOfFolders.Add(folder);
                }


                foreach (FileInfo file in new DirectoryInfo(x.ToString()).GetFiles().OrderBy(y => y.Name).ToArray())
                {
                    Icon icon =
                        (System.Drawing.Icon)System.Drawing.Icon.ExtractAssociatedIcon(file.FullName.ToString());


                    if (file.Extension.ToLower() == ".jpg" || file.Extension.ToLower() == ".jpeg" || file.Extension.ToLower() == ".bmp" || file.Extension.ToLower() == ".png")
                    {
                        TreeOfFolders.Add(
                            new CustomImage
                        {
                            Name         = file.ToString(),
                            Icon         = icon.ToImageSource(),
                            FullName     = file.FullName.ToString(),
                            Size         = ByteSize.FromBytes(file.Length).ToString(),
                            CreationTime = file.CreationTime.ToString(CultureInfo.InvariantCulture)
                        }
                            );
                    }
                    else
                    {
                        TreeOfFolders.Add(
                            new CustomFile
                        {
                            Name         = file.ToString(),
                            Icon         = icon.ToImageSource(),
                            FullName     = file.FullName.ToString(),
                            Size         = ByteSize.FromBytes(file.Length).ToString(),
                            CreationTime = file.CreationTime.ToString(CultureInfo.InvariantCulture)
                        }
                            );
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(@ex.Message);
            }
        }
Ejemplo n.º 42
0
 // Token: 0x06000027 RID: 39 RVA: 0x000021A5 File Offset: 0x000003A5
 public static ByteSize Gigabytes(this long input)
 {
     return(ByteSize.FromGigabytes((double)input));
 }
Ejemplo n.º 43
0
 public static async Task <bool> HasEnoughSpace(this IDevice device, ByteSize requiredSize)
 {
     return((await device.GetDeviceDisk()).HasEnoughSpace(requiredSize));
 }
Ejemplo n.º 44
0
 /// <summary>
 /// Initialize this instance with standard settings. 
 /// 9600:N:8:1, handshaking disabled.
 /// </summary>
 /// <param name="index">The port index - 1,2,...</param>
 public void Initialize(int index)
 {
     portName   = "COM" + index.ToString() + ":";
     baudRate   = LineSpeed.Baud_9600;
     txFlowCTS  = false;
     txFlowDSR  = false;
     dtrControl = PinState.Disable;
     rxDSRsense = false;
     txContinue = true;
     txFlowXoff = false;
     rxFlowXoff = false;
     errReplace = false;
     nulDiscard = false;
     rtsControl = PinState.Disable;
     abortOnErr = false;
     xonLimit   = 0;	// 0=OS managed
     xoffLimit  = 0; // 0=OS managed
     dataBits   = ByteSize.Eight;
     parity     = Parity.None;
     stopBits   = StopBits.One;
     xonChar    = (byte) CtrlChar.DC1;
     xoffChar   = (byte) CtrlChar.DC3;
     errChar    = (byte) '?';
     eofChar    = (byte) CtrlChar.SUB;
     evtChar    = (byte) CtrlChar.NULL;
     handshake  = Handshake.None;
     rxQueLen   = 0; // 0=OS managed
     txQueLen   = 0; // 0=OS managed
     txTmoMulti = 0;
     txTmoConst = 0;
     receiveMode = false;
     return;
 }
 public Task<IFileStorage> GetFileStorageAsync(ByteSize requiredSize)
 {
     return Task.FromResult(_storages.Values.RandomElement());
 }
Ejemplo n.º 46
0
        /* CONSTRUCTOR */
        public Com_SerialPort()
        {
            portIndex = 1;
            baudRate = BaudRate.Baud_9600;
            parity = Parity.None;
            dataBits = ByteSize.Eight;
            stopBits = StopBits.One;
            handle = IntPtr.Zero;
            ReadIntervalTimeout = Com_WinApi.MAXDWORD;

            _pcfg = new Hashtable();

            _pcfg.Add("PORT", this.portIndex);
            _pcfg.Add("RATE", (int)this.baudRate);
            _pcfg.Add("PARITY", (byte)this.parity);
            _pcfg.Add("DBITS", (byte)this.dataBits);
            _pcfg.Add("SBITS", (int)this.stopBits);
            _pcfg.Add("RT", this.ReadIntervalTimeout);
            _pcfg.Add("RM", this.ReadTotalTimeoutMultiplier);
            _pcfg.Add("RC", this.ReadTotalTimeoutConstant);
            _pcfg.Add("WM", this.WriteTotalTimeoutMultiplier);
            _pcfg.Add("WC", this.WriteTotalTimeoutConstant);
        }
Ejemplo n.º 47
0
        internal static async Task Moons(ICommandContext context)
        {
            var channel = context.Channel;

            var botid      = APIHelper.DiscordAPI.GetCurrentUser().Id;
            var memoryUsed = ByteSize.FromBytes(Process.GetCurrentProcess().WorkingSet64);
            var runTime    = DateTime.Now - Process.GetCurrentProcess().StartTime;
            var totalUsers = APIHelper.DiscordAPI.GetUsersCount();



            Dictionary <string, string> moons = new Dictionary <string, string>();
            List <string> output = new List <string>();

            try
            {
                var guildID = SettingsManager.Settings.Config.DiscordGuildId;

                foreach (var groupPair in SettingsManager.Settings.NotificationFeedModule.Groups)
                {
                    var group = groupPair.Value;
                    if (!group.CharacterID.Any() || group.CharacterID.All(a => a == 0))
                    {
                        await LogHelper.LogError($"[CONFIG] Notification group {groupPair.Key} has no characterID specified!");

                        continue;
                    }

                    if (group.DefaultDiscordChannelID == 0)
                    {
                        await LogHelper.LogError($"[CONFIG] Notification group {groupPair.Key} has no DefaultDiscordChannelID specified!");

                        continue;
                    }

                    //skip empty group
                    if (group.Filters.Values.All(a => a.Notifications.Count == 0))
                    {
                        continue;
                    }


                    foreach (var charId in group.CharacterID)
                    {
                        var rToken = await SQLHelper.GetRefreshTokenDefault(charId);

                        if (string.IsNullOrEmpty(rToken))
                        {
                            await LogHelper.LogWarning($"Failed to get notifications refresh token for character {charId}! User is not authenticated.");

                            continue;
                        }

                        var tq = await APIHelper.ESIAPI.RefreshToken(rToken, SettingsManager.Settings.WebServerModule.CcpAppClientId, SettingsManager.Settings.WebServerModule.CcpAppSecret);

                        var token = tq.Result;
                        if (tq.Data.IsNoConnection)
                        {
                            return;
                        }
                        if (string.IsNullOrEmpty(token))
                        {
                            if (tq.Data.IsNotValid)
                            {
                                await LogHelper.LogWarning($"Notifications token for character {charId} is outdated or no more valid!");
                            }
                            else
                            {
                                await LogHelper.LogWarning($"Unable to get notifications token for character {charId}. Current check cycle will be skipped. {tq.Data.ErrorCode}({tq.Data.Message})");
                            }
                            continue;
                        }
                        //await LogHelper.LogInfo($"Checking characterID:{charId}", Category, LogToConsole, false);
                        Console.WriteLine($"Checking characterID:{charId}");


                        var etag = _tags.GetOrNull(charId);

                        var result = await APIHelper.ESIAPI.GetCalendar("", charId, token, etag);

                        var results = result.Result;

                        foreach (var r in results)
                        {
                            if (r.title.StartsWith("Moon extraction for "))
                            {
                                string key = r.event_date + "..." + r.title;


                                if (!moons.ContainsKey(key))
                                {
                                    //sb.AppendLine(value);


                                    string   dteve = r.event_date.Replace("T", " ").Replace("Z", " ");
                                    DateTime dt    = DateTime.Parse(dteve);

                                    string value = dt.ToString() + " --- " + r.title + "...";
                                    moons.Add(key, value);
                                    output.Add(value);
                                }
                            }
                        }
                    }
                }
                output.Sort();

                StringBuilder sb = new StringBuilder();
                foreach (string o in output)
                {
                    sb.AppendLine(o);
                }


                await APIHelper.DiscordAPI.SendMessageAsync(channel, $"{context.User.Mention},{Environment.NewLine}{Environment.NewLine}```" +
                                                            sb.ToString() + "```").ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                //await LogHelper.LogEx(ex.Message, ex, Category);

                await APIHelper.DiscordAPI.SendMessageAsync(channel, $"{context.User.Mention},{Environment.NewLine}{Environment.NewLine}" +
                                                            "Errors reading the moons").ConfigureAwait(false);
            }
            finally
            {
                //_passNotifications.Clear();
            }



            await Task.CompletedTask;
        }
Ejemplo n.º 48
0
 //Constructor & destructor
 public ComPort()
 {
     portIndex = 1;
     baudRate = BaudRate.Baud_9600;
     parity = Parity.None;
     dataBits = ByteSize.Eight;
     stopBits = StopBits.One;
     handle = IntPtr.Zero;
     ReadIntervalTimeout = API.MAXDWORD;
 }
Ejemplo n.º 49
0
        public override async void GetSpecialProperties()
        {
            if (List.All(x => x.PrimaryItemAttribute == StorageItemTypes.File))
            {
                ViewModel.IsReadOnly = List.All(x => NativeFileOperationsHelper.HasFileAttribute(x.ItemPath, System.IO.FileAttributes.ReadOnly));
            }
            ViewModel.IsHidden = List.All(x => NativeFileOperationsHelper.HasFileAttribute(x.ItemPath, System.IO.FileAttributes.Hidden));

            ViewModel.LastSeparatorVisibility = Visibility.Collapsed;
            ViewModel.ItemSizeVisibility      = Visibility.Visible;

            ViewModel.FilesCount   += List.Where(x => x.PrimaryItemAttribute == StorageItemTypes.File).ToList().Count;
            ViewModel.FoldersCount += List.Where(x => x.PrimaryItemAttribute == StorageItemTypes.Folder).ToList().Count;

            long totalSize   = 0;
            long filesSize   = List.Where(x => x.PrimaryItemAttribute == StorageItemTypes.File).Sum(x => x.FileSizeBytes);
            long foldersSize = 0;

            ViewModel.ItemSizeProgressVisibility = Visibility.Visible;
            foreach (var item in List)
            {
                if (item.PrimaryItemAttribute == StorageItemTypes.Folder)
                {
                    var fileSizeTask = Task.Run(async() =>
                    {
                        var size = await CalculateFolderSizeAsync(item.ItemPath, TokenSource.Token);
                        return(size);
                    });
                    try
                    {
                        foldersSize += await fileSizeTask;
                    }
                    catch (Exception ex)
                    {
                        NLog.LogManager.GetCurrentClassLogger().Error(ex, ex.Message);
                    }
                }
            }
            ViewModel.ItemSizeProgressVisibility = Visibility.Collapsed;

            totalSize          = filesSize + foldersSize;
            ViewModel.ItemSize = $"{ByteSize.FromBytes(totalSize).ToBinaryString().ConvertSizeAbbreviation()} ({ByteSize.FromBytes(totalSize).Bytes:#,##0} {"ItemSizeBytes".GetLocalized()})";
            SetItemsCountString();
        }
Ejemplo n.º 50
0
 private void UpdateDownloadProgress(string fileName, ByteSize current, ByteSize total) {
     ProgressBar.Fraction = current.Bytes / total.Bytes;
     ProgressBar.Text = string.Format(ProgressFormat, fileName, current, total);
 }
Ejemplo n.º 51
0
 public void Constructor()
 {
     var bs = new ByteSize();
     Assert.AreEqual(0, bs.ByteCount);
 }
Ejemplo n.º 52
0
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            var sent = (uint)value;

            return(string.Format("{0} kbps", ByteSize.FromBits(sent).KiloBytes.ToString().Split('.')[0]));
        }
Ejemplo n.º 53
0
        private void DoValidation()
        {
            if (string.IsNullOrEmpty(ConfigPath))
            {
                ConfigErrors.Add(@"Config validation failed. There is no config file set.");
                Log.Error(@"Config validation failed. There is no config file set.");
                return;
            }

            Log.Debug("validating config file {0}", ConfigPath);

            // RULE: at least one data source must be specified
            if (!SnapShotSources.Any())
            {
                ConfigErrors.Add("At least one data source must be specified. Check the value for \"d1\" \r\n");
            }

            // RULE: the first parity location must not be empty
            if (string.IsNullOrEmpty(ParityFile1))
            {
                ConfigErrors.Add("The first parity location must not be empty. Check the value for \"parity\"");
            }

            // RULE: number of content files must be at least the (number of parity files + 1)
            if (ContentFiles.Count < ParityPaths.Count + 1)
            {
                ConfigErrors.Add($"The number of content files must be at least one greater than the number of parity files. There should be at least {ParityPaths.Count + 1} content files.");
            }

            // RULE: check that devices are not repeated
            if (!IsRulePassDevicesMustNotRepeat(DataParityPaths))
            {
                ConfigErrors.Add("Devices for data and parity must be unique. Check the values for data and parity");
            }

            // RULE: data paths must be accessible
            foreach (SnapShotSource source in DataParityPaths)
            {
                // test if path exists
                if (Directory.Exists(source.DirSource))
                {
                    continue;
                }

                ConfigErrors.Add($"Parity source is inaccessible: {source.DirSource}");
            }

            // RULE: parity devices should be greater or equal to data devices
            ByteSize largestDataDevice    = new ByteSize(StorageUtil.GetDriveSizes(DataParityPaths).Max());
            ByteSize smallestParityDevice = new ByteSize(StorageUtil.GetDriveSizes(DataParityPaths).Min());

            if (largestDataDevice > smallestParityDevice)
            {
                ConfigWarnings.Add($@"One or more data devices [{largestDataDevice}] are larger than the smallest parity device [{smallestParityDevice}]. All parity devices should be equal or greater in size than all data devices.");
            }

            // RULE: blockSize valid value
            if (BlockSizeKB < 1 || BlockSizeKB > 16384)
            {
                ConfigErrors.Add(@"The blockSize value is invalid and must be between 1 and 16384");
            }

            // RULE: autoSave valid value
            if (AutoSaveGB > Constants.MaxAutoSave)
            {
                ConfigErrors.Add($"The autoSave value is invalid and must be between {Constants.MinAutoSave} and {Constants.MaxAutoSave}");
            }

            if (!IsValid)
            {
                Log.Error(@"The configuration file is not valid. See errors below:");

                foreach (string error in ConfigErrors)
                {
                    Log.Error(@" - {0}", error);
                }
            }
        }