Пример #1
0
        public async Task DecomcryptAsync(Letter letter)
        {
            var decryptFailed = false;

            if (letter.LetterMetadata.Encrypted && (_hashKey?.Length > 0))
            {
                try
                {
                    letter.Body = AesEncrypt.Decrypt(letter.Body, _hashKey);
                    letter.LetterMetadata.Encrypted = false;
                }
                catch { decryptFailed = true; }
            }

            if (!decryptFailed && letter.LetterMetadata.Compressed)
            {
                try
                {
                    letter.Body = await Gzip.DecompressAsync(letter.Body).ConfigureAwait(false);

                    letter.LetterMetadata.Compressed = false;
                }
                catch { }
            }
        }
Пример #2
0
        private async Task ProcessDeliveriesAsync(ChannelReader <Letter> channelReader)
        {
            while (await channelReader.WaitToReadAsync().ConfigureAwait(false))
            {
                while (channelReader.TryRead(out var letter))
                {
                    if (letter == null)
                    {
                        continue;
                    }

                    if (Compress)
                    {
                        letter.Body = await Gzip.CompressAsync(letter.Body).ConfigureAwait(false);

                        letter.LetterMetadata.Compressed = Compress;
                    }

                    if (Encrypt && (_hashKey != null || _hashKey.Length == 0))
                    {
                        letter.Body = AesEncrypt.Encrypt(letter.Body, _hashKey);
                        letter.LetterMetadata.Encrypted = Encrypt;
                    }

                    _logger.LogDebug(LogMessages.AutoPublisher.LetterPublished, letter.LetterId, letter.LetterMetadata?.Id);

                    await Publisher
                    .PublishAsync(letter, CreatePublishReceipts, _withHeaders)
                    .ConfigureAwait(false);
                }
            }
        }
 private void UpdateCompressionSettings()
 {
     if (base.Fields.IsModified("GzipLevel"))
     {
         string metabasePath = this.DataObject.MetabasePath;
         Gzip.SetIisGzipLevel(IisUtility.WebSiteFromMetabasePath(metabasePath), GzipLevel.High);
         Gzip.SetVirtualDirectoryGzipLevel(metabasePath, this.DataObject.GzipLevel);
         if (Environment.OSVersion.Platform == PlatformID.Win32NT && Environment.OSVersion.Version.Major >= 6)
         {
             try
             {
                 Gzip.SetIisGzipMimeTypes();
             }
             catch (Exception ex)
             {
                 TaskLogger.Trace("Exception occurred in SetIisGzipMimeTypes(): {0}", new object[]
                 {
                     ex.Message
                 });
                 this.WriteWarning(Strings.SetIISGzipMimeTypesFailure);
                 throw;
             }
         }
     }
 }
Пример #4
0
        public static string Process(DownloadItem downloadItem, string cachePath)
        {
            var regexMatch = Regex.Match(downloadItem.Url, MatchRegex);

            var    internalType = regexMatch.Groups["internalType"].Value;
            var    idType       = regexMatch.Groups["idType"].Value;
            var    id           = regexMatch.Groups["id"].Value;
            string output       = string.Empty;

            switch (internalType)
            {
            case "movieMeterHandler":
                output = Tools.ThirdParty.MovieMeterApiHandler.GenerateMovieMeterXml(downloadItem, idType, id);
                break;
            }

            if (!string.IsNullOrEmpty(output))
            {
                File.WriteAllText(cachePath + ".txt.tmp", output, Encoding.UTF8);
                Gzip.Compress(cachePath + ".txt.tmp", cachePath + ".txt.gz");
                File.Delete(cachePath + ".txt.tmp");
            }

            return(output);
        }
Пример #5
0
        /// <summary>
        /// Handles the DoWork event of the SavingTVDB control.
        /// </summary>
        /// <param name="sender">
        /// The source of the event.
        /// </param>
        /// <param name="e">
        /// The <see cref="System.ComponentModel.DoWorkEventArgs"/> instance containing the event data.
        /// </param>
        private static void SavingTVDB_DoWork(object sender, DoWorkEventArgs e)
        {
            var    series = e.Argument as Series;
            string path   = Get.FileSystemPaths.PathDatabases + OutputName.TvDb + Path.DirectorySeparatorChar;
            string title  = FileNaming.RemoveIllegalChars(series.SeriesName);

            string writePath = path + title + ".Series";
            string json      = JsonConvert.SerializeObject(series);

            Gzip.CompressString(json, writePath + ".gz");

            if (series.SmallBanner != null)
            {
                var smallBanner = new Bitmap(series.SmallBanner);
                smallBanner.Save(path + title + ".banner.jpg");
            }

            if (series.SmallFanart != null)
            {
                var smallFanart = new Bitmap(series.SmallFanart);
                smallFanart.Save(path + title + ".fanner.jpg");
            }

            if (series.SmallPoster != null)
            {
                var smallPoster = new Bitmap(series.SmallPoster);
                smallPoster.Save(path + title + ".poster.jpg");
            }
        }
Пример #6
0
 public void OnRiotMessagingServiceReceived(object sender, MessageEventArgs message)
 {
     if (!HasEnabledRmsGzip)
     {
         var data = JsonConvert.DeserializeObject <RiotMessageService>(Encoding.Default.GetString(message.RawData));
         if (data.Subject == "rms:session")
         {
             RiotMessagingService.Send(Encoding.UTF8.GetBytes("{\r\n    " +
                                                              $"\"id\": \"{Guid.NewGuid():D}\",\r\n    " +
                                                              "\"payload\": " +
                                                              "{\r\n        " +
                                                              "\"enable\": \"true\"\r\n    " +
                                                              "},\r\n    " +
                                                              "\"subject\": \"rms:gzip\",\r\n    " +
                                                              "\"type\": \"request\"\r\n}"));
         }
         else if (data.Subject == "rms:gzip" && data.Payload.Enabled == "true")
         {
             HasEnabledRmsGzip = true;
         }
         Debugger.Log(0, "", Encoding.Default.GetString(message.RawData) + "\n");
     }
     else
     {
         var data = Encoding.UTF8.GetString(Gzip.Decompress(message.RawData));
         Debugger.Log(0, "", data);
     }
 }
Пример #7
0
        /// <summary>
        /// Sends a POST request to an API function using a <paramref name="token"/>, and returns
        /// the response as a JSON string.
        /// </summary>
        /// <param name="function">
        /// The name of the function.
        /// </param>
        /// <param name="args">
        /// A set of parameters to pass along with the request.
        /// </param>
        /// <param name="token">
        /// The auth token.
        /// </param>
        /// <returns>
        /// Upon success, the JSON string; otherwise, <c>null</c>.
        /// </returns>
        public async Task <string> PostToJsonAsync(string function, RequestParameters args, string token)
        {
            Contract.Requires <ArgumentNullException>(function != null);
            Contract.Requires <ArgumentNullException>(token != null);

            var response = await PostAsync(function, args, token);

            if (!response.IsSuccessStatusCode)
            {
                return(null);
            }

            // Obtain the JSON data (and decompress it if it is gzipped).
            string jsonData;

            if (response.Content.Headers.ContentEncoding.Contains(HttpContentCodingHeaderValue.Parse("gzip")))
            {
                var compressedData = (await response.Content.ReadAsBufferAsync()).ToArray();
                jsonData = await Gzip.DecompressAsync(compressedData, Encoding.UTF8);
            }
            else
            {
                jsonData = await response.Content.ReadAsStringAsync();
            }
            Debug.WriteLine("[EndpointManager] Received JSON data: {0}", jsonData);

            // Return the JSON data.
            return(jsonData);
        }
Пример #8
0
        private void UpdateCompressionSettings()
        {
            if (this.GzipLevel == GzipLevel.Error)
            {
                base.WriteError(new TaskException(Strings.GzipCannotBeSetToError), ErrorCategory.NotSpecified, null);
                return;
            }
            if (this.GzipLevel == GzipLevel.Low)
            {
                this.WriteWarning(Strings.GzipLowDoesNotUseDynamicCompression);
            }
            string metabasePath = this.DataObject.MetabasePath;

            Gzip.SetIisGzipLevel(IisUtility.WebSiteFromMetabasePath(metabasePath), GzipLevel.High);
            Gzip.SetVirtualDirectoryGzipLevel(metabasePath, this.DataObject.GzipLevel);
            if (Environment.OSVersion.Platform == PlatformID.Win32NT && Environment.OSVersion.Version.Major >= 6)
            {
                try
                {
                    Gzip.SetIisGzipMimeTypes();
                }
                catch (Exception ex)
                {
                    TaskLogger.Trace("Exception occurred in SetIisGzipMimeTypes(): {0}", new object[]
                    {
                        ex.Message
                    });
                    this.WriteWarning(Strings.SetIISGzipMimeTypesFailure);
                    throw;
                }
            }
        }
        public void BasicByteArrayTest(string value)
        {
            var compressed   = Gzip.Compress(value);
            var uncompressed = Gzip.DecompressToString(compressed);

            Assert.Equal(value, uncompressed);
        }
Пример #10
0
        private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
        {
            var messageData = JsonConvert.DeserializeObject <PartyPhaseMessage>(
                Encoding.UTF8.GetString(Gzip.Decompress(Convert.FromBase64String("H4sIAAAAAAAA/+VYTU/jMBC98yuinKkU5zt7a0vFVgttRXtDCDnJQCMcuxs7sBXiv6+dNiH9wOwiUFbaXtJ6ZjzPL/bMq59PDMNMWEkFFOY3wz9Vv1dLzGGCc5Aj5vB7/3I2nk5u56OL0XBhVh4/SyhhnEq761jVSLLE+SpjdA4EEjEXWKjoZ2mSRgE4r7xN5N3ZXhxHPdv2cM/F4PVCP3B6gR/FyAl8cANUpdhGDZdYXDH2gWhextU6VNygP7mdjYc/ahtORAVVXGRcSIfrathonsYW+Oazda8goNM9AyuGQMgRm1ivqtytvFtLTVUVZO2aWL4iIEBZ7jDh0BhfTt/F5mmweR1jizTYoo6xBRpsQcfYHA02p2Nslgab9RFsoft54FwNOLdj4nwNNr9jbKEGW9gxNluDzf5SbNtvN9XzZttFkrIogIp+3UzGNIVfr7OaCRSQM5oBH6wPnJ5fGi9CeNMq1boIySBdyObX6kx7pDQNdbfnJMePHy9ziQOKuqXjOGVGxo0cJ9m9edR1U5gjy7FcPzpK4CxLHsZSNlBxSOTbHGPOs3sK6YzxTDGi4Eymk9EeipVcCNos0D202EdOMX/Itvne3VHvkYe05PWfgLMcRmm61lDn+shFked2Sd2bzO1z+nnU2VrqVkzKQoZspNtzge9Zdoj+M+IcLXHnxjlLjUBHWxhECHnOP0mbjb6KNldL21mB7xm9yOgDijTc+YEbRnLTdVrm0Fvkvb/l6uZUO5pAIV//YQOxjxPraYnVkPkX7/SN1H53qYPuUofdpY4+IfWOQKqlDWEJJjOC13DwJ7kWTwvZEsgiy+Eyk7JH6aDIkp89J2m/ghxnNKP3jWPgO35QXxUUOAU1eF2LM6mi2NN0JWTEtBTTuwGmKrqWdm2vuTxTm2uLzUkVRbljPytXJEuwAFUL+N4MBRSMkN37jjrwqrIdZG2ieLOohsyauhgLQWDAGBfH5x68OhzMHqtRHBNQKxuqy512gWrPrWTpI25J3sYJbywthd1rSpRZUvlqHyCdV9WozXsloytIPbSzoLpYDoAmy4MlxWp0RBXmQyivdXaT6aTecdXcZslhTB/lNmHFeobF0rZQ2Cj4l9/w94A44RIAAA=="))));

            UserInterfaceCore.ChangeMainPageView <ChampionSelectPage>(messageData);
        }
Пример #11
0
        public void UploadMorpherCache(List <KeyValuePair <string, MorpherCacheObject> > cache)
        {
            List <KeyValuePair <string, MorpherCacheObject> > pairs =
                cache.Select(
                    pair => new KeyValuePair <string, MorpherCacheObject>(pair.Key, (MorpherCacheObject)pair.Value)).ToList();

            string serializedCache = Gzip.Zip(JsonConvert.SerializeObject(pairs));

            using (CompressedCacheDataContext context = new CompressedCacheDataContext())
            {
                var result =
                    context.CompressedCaches.FirstOrDefault(
                        compressedCache => compressedCache.Date == DateTime.Now.Date);

                if (result != null)
                {
                    result.GZipCache = serializedCache;
                }
                else
                {
                    context.CompressedCaches.InsertOnSubmit(new CompressedCache()
                    {
                        Date      = DateTime.Now.Date,
                        GZipCache = serializedCache
                    });
                }

                context.SubmitChanges();
            }
        }
        public void ToStringTest(string value)
        {
            var compressed   = Gzip.CompressToString(value);
            var uncompressed = Gzip.DecompressToString(compressed);

            Assert.Equal(value, uncompressed);
        }
Пример #13
0
        private async Task ProcessEvent(string eventName, string message)
        {
            message = Gzip.Decompress(message);

            if (_subsManager.HasSubscriptionsForEvent(eventName))
            {
                using (var scope = _autofac.BeginLifetimeScope(AUTOFAC_SCOPE_NAME))
                {
                    var subscriptions = _subsManager.GetHandlersForEvent(eventName);

                    foreach (var subscription in subscriptions)
                    {
                        if (subscription.IsDynamic)
                        {
                            var     handler   = scope.ResolveOptional(subscription.HandlerType) as IDynamicEventHandler;
                            dynamic eventData = JObject.Parse(message);
                            await handler.Handle(eventData);
                        }
                        else
                        {
                            var eventType        = _subsManager.GetEventTypeByName(eventName);
                            var integrationEvent = JsonConvert.DeserializeObject(message, eventType);
                            var handler          = scope.ResolveOptional(subscription.HandlerType);
                            var concreteType     = typeof(IEventHandler <>).MakeGenericType(eventType);

                            await(Task) concreteType.GetMethod("Handle").Invoke(
                                handler,
                                new object[] { integrationEvent });
                        }
                    }
                }
            }
        }
Пример #14
0
        // Returns Success
        public async Task <bool> DecompressAsync(Letter letter)
        {
            if (letter.LetterMetadata.Encrypted)
            {
                return(false);
            }                 // Don't decompress before decryption.

            if (letter.LetterMetadata.Compressed)
            {
                try
                {
                    letter.Body = await Gzip.DecompressAsync(letter.Body).ConfigureAwait(false);

                    letter.LetterMetadata.Compressed = false;

                    if (letter.LetterMetadata.CustomFields.ContainsKey(Constants.HeaderForCompressed))
                    {
                        letter.LetterMetadata.CustomFields.Remove(Constants.HeaderForCompressed);
                    }

                    if (letter.LetterMetadata.CustomFields.ContainsKey(Constants.HeaderForCompression))
                    {
                        letter.LetterMetadata.CustomFields.Remove(Constants.HeaderForCompression);
                    }
                }
                catch { return(false); }
            }

            return(true);
        }
Пример #15
0
        /// <summary>
        /// Loads the movie DB.
        /// </summary>
        private static void LoadMovieDB()
        {
            string path = Get.FileSystemPaths.PathDatabases + OutputName.MovieDb + Path.DirectorySeparatorChar;

            Directory.CreateDirectory(path);
            FileData[] files = FastDirectoryEnumerator.GetFiles(path, "*.movie.gz", SearchOption.TopDirectoryOnly);

            MovieDBFactory.MovieDatabase.Clear();

            foreach (FileData file in files)
            {
                string json = Gzip.Decompress(file.Path);

                var movieModel = JsonConvert.DeserializeObject(json, typeof(MovieModel)) as MovieModel;

                MovieDBFactory.MovieDatabase.Add(movieModel);

                string title = FileNaming.RemoveIllegalChars(movieModel.Title);

                string poster = path + title + ".poster.jpg";
                string fanart = path + title + ".fanart.jpg";

                if (File.Exists(poster))
                {
                    movieModel.SmallPoster = ImageHandler.LoadImage(poster);
                }

                if (File.Exists(fanart))
                {
                    movieModel.SmallFanart = ImageHandler.LoadImage(fanart);
                }
            }
        }
Пример #16
0
        public async Task ComcryptDecomcryptTest()
        {
            var message = new Message {
                StringMessage = $"Sensitive ReceivedLetter 0", MessageId = 0
            };
            var data = JsonSerializer.SerializeToUtf8Bytes(message);

            var hashKey = await ArgonHash
                          .GetHashKeyAsync(Passphrase, Salt, HouseofCat.Encryption.Constants.Aes256.KeySize)
                          .ConfigureAwait(false);

            _output.WriteLine(Encoding.UTF8.GetString(hashKey));
            _output.WriteLine($"HashKey: {Encoding.UTF8.GetString(hashKey)}");

            // Comcrypt
            var payload = await Gzip.CompressAsync(data);

            var encryptedPayload = AesEncrypt.Aes256Encrypt(payload, hashKey);

            // Decomcrypt
            var decryptedData = AesEncrypt.Aes256Decrypt(encryptedPayload, hashKey);

            Assert.NotNull(decryptedData);

            var decompressed = await Gzip.DecompressAsync(decryptedData);

            JsonSerializer.SerializeToUtf8Bytes(decompressed);
            _output.WriteLine($"Data: {Encoding.UTF8.GetString(data)}");
            _output.WriteLine($"Decrypted: {Encoding.UTF8.GetString(decryptedData)}");

            Assert.Equal(data, decompressed);
        }
Пример #17
0
        private async Task ProcessDeliveriesAsync(ChannelReader <Letter> channelReader)
        {
            while (await channelReader.WaitToReadAsync().ConfigureAwait(false))
            {
                while (channelReader.TryRead(out var letter))
                {
                    if (letter == null)
                    {
                        continue;
                    }

                    if (_compress)
                    {
                        letter.Body = await Gzip.CompressAsync(letter.Body).ConfigureAwait(false);

                        letter.LetterMetadata.Compressed = _compress;
                        letter.LetterMetadata.CustomFields[Utils.Constants.HeaderForEncrypt] = Utils.Constants.HeaderValueForGzipCompress;
                    }

                    if (_encrypt)
                    {
                        letter.Body = AesEncrypt.Encrypt(letter.Body, _hashKey);
                        letter.LetterMetadata.Encrypted = _encrypt;
                        letter.LetterMetadata.CustomFields[Utils.Constants.HeaderForEncrypt] = Utils.Constants.HeaderValueForArgonAesEncrypt;
                    }

                    _logger.LogDebug(LogMessages.AutoPublisher.LetterPublished, letter.LetterId, letter.LetterMetadata?.Id);

                    await PublishAsync(letter, _createPublishReceipts, _withHeaders)
                    .ConfigureAwait(false);
                }
            }
        }
        protected override void StampChangesOn(IConfigurable dataObject)
        {
            ADWebServicesVirtualDirectory adwebServicesVirtualDirectory = dataObject as ADWebServicesVirtualDirectory;

            adwebServicesVirtualDirectory.GzipLevel = Gzip.GetGzipLevel(adwebServicesVirtualDirectory.MetabasePath);
            dataObject.ResetChangeTracking();
            base.StampChangesOn(dataObject);
        }
Пример #19
0
        private static void SaveTvDB()
        {
            SavingCount++;

            var path = Get.FileSystemPaths.PathDatabases + OutputName.TvDb + Path.DirectorySeparatorChar;

            Directory.CreateDirectory(path);
            Folders.DeleteFilesInFolder(path);

            string writePath = path + "hidden.hiddenSeries";
            string json      = JsonConvert.SerializeObject(TvDBFactory.HiddenTvDatabase);

            Gzip.CompressString(json, writePath + ".gz");

            var parallelOptions = new ParallelOptions {
                MaxDegreeOfParallelism = 6
            };

            SavingTVDBMax   = TvDBFactory.TvDatabase.Count;
            SavingTVDBValue = 0;

            Parallel.ForEach(
                TvDBFactory.TvDatabase,
                parallelOptions,
                series =>
            {
                var title      = FileNaming.RemoveIllegalChars(series.Value.SeriesName);
                var seriesPath = string.Concat(Get.FileSystemPaths.PathDatabases, OutputName.TvDb, Path.DirectorySeparatorChar, title, ".Series.gz");

                json = JsonConvert.SerializeObject(series.Value);
                Gzip.CompressString(json, seriesPath);

                if (series.Value.SmallBanner != null)
                {
                    var smallBanner = new Bitmap(series.Value.SmallBanner);
                    smallBanner.Save(path + title + ".banner.jpg");
                }

                if (series.Value.SmallFanart != null)
                {
                    var smallFanart = new Bitmap(series.Value.SmallFanart);
                    smallFanart.Save(path + title + ".fanner.jpg");
                }

                if (series.Value.SmallPoster != null)
                {
                    var smallPoster = new Bitmap(series.Value.SmallPoster);
                    smallPoster.Save(path + title + ".poster.jpg");
                }

                SavingTVDBValue++;

                Application.DoEvents();
            });

            SavingCount--;
            frmSavingDB.TvDBFinished();
        }
 internal static void UpdateMetabase(ExchangeWebAppVirtualDirectory webAppVirtualDirectory, string metabasePath, bool enableAnonymous)
 {
     try
     {
         DirectoryEntry directoryEntry2;
         DirectoryEntry directoryEntry = directoryEntry2 = IisUtility.CreateIISDirectoryEntry(webAppVirtualDirectory.MetabasePath);
         try
         {
             ArrayList arrayList = new ArrayList();
             if (webAppVirtualDirectory.DefaultDomain.Length > 0)
             {
                 arrayList.Add(new MetabaseProperty("DefaultLogonDomain", webAppVirtualDirectory.DefaultDomain, true));
             }
             else if (webAppVirtualDirectory.DefaultDomain == "")
             {
                 directoryEntry.Properties["DefaultLogonDomain"].Clear();
             }
             IisUtility.SetProperties(directoryEntry, arrayList);
             directoryEntry.CommitChanges();
             IisUtility.SetAuthenticationMethod(directoryEntry, AuthenticationMethodFlags.None, true);
             IisUtility.SetAuthenticationMethod(directoryEntry, AuthenticationMethodFlags.Basic, webAppVirtualDirectory.BasicAuthentication);
             IisUtility.SetAuthenticationMethod(directoryEntry, AuthenticationMethodFlags.Digest, webAppVirtualDirectory.DigestAuthentication);
             IisUtility.SetAuthenticationMethod(directoryEntry, AuthenticationMethodFlags.WindowsIntegrated, webAppVirtualDirectory.WindowsAuthentication);
             IisUtility.SetAuthenticationMethod(directoryEntry, AuthenticationMethodFlags.LiveIdFba, webAppVirtualDirectory.LiveIdAuthentication);
             if (webAppVirtualDirectory.FormsAuthentication)
             {
                 OwaIsapiFilter.EnableFba(directoryEntry);
             }
             else
             {
                 OwaIsapiFilter.DisableFba(directoryEntry);
             }
             IisUtility.SetAuthenticationMethod(directoryEntry, MetabasePropertyTypes.AuthFlags.Anonymous, enableAnonymous);
             directoryEntry.CommitChanges();
         }
         finally
         {
             if (directoryEntry2 != null)
             {
                 ((IDisposable)directoryEntry2).Dispose();
             }
         }
         GzipLevel gzipLevel = webAppVirtualDirectory.GzipLevel;
         string    site      = IisUtility.WebSiteFromMetabasePath(webAppVirtualDirectory.MetabasePath);
         Gzip.SetIisGzipLevel(site, GzipLevel.High);
         Gzip.SetVirtualDirectoryGzipLevel(webAppVirtualDirectory.MetabasePath, gzipLevel);
     }
     catch (IISGeneralCOMException ex)
     {
         if (ex.Code == -2147023174)
         {
             throw new IISNotReachableException(IisUtility.GetHostName(webAppVirtualDirectory.MetabasePath), ex.Message);
         }
         throw;
     }
 }
Пример #21
0
 public static async Task <byte[]> DecompressAsync(ReadOnlyMemory <byte> data, CompressionMethod method)
 {
     return(method switch
     {
         CompressionMethod.LZ4 => await LZ4.DecompressAsync(data).ConfigureAwait(false),
         CompressionMethod.Deflate => await Deflate.DecompressAsync(data).ConfigureAwait(false),
         CompressionMethod.Brotli => await Brotli.DecompressAsync(data).ConfigureAwait(false),
         CompressionMethod.Gzip => await Gzip.DecompressAsync(data).ConfigureAwait(false),
         _ => await Gzip.DecompressAsync(data).ConfigureAwait(false)
     });
Пример #22
0
        private static void Main(string[] args)
        {
            try
            {
                bool isCompress = true;

                if (args.Length < 3)
                {
                    throw new Exception("Вы не ввели команду программы,имя исходного и результирующего файла");
                }

                if (args[0] != "compress")
                {
                    isCompress = false;
                    if (args[0] != "decompress")
                    {
                        throw new Exception($"Команда \"{args[0]}\" не существует");
                    }
                }

                if (args.Length < 2)
                {
                    throw new Exception("Вы не ввели имя исходного и результирующего файла");
                }

                if (args.Length < 3)
                {
                    throw new Exception("Вы не ввели имя результирующего файла");
                }

                var readingFile = args[1];
                var writingFile = args[2];

                var gzip = new Gzip();

                if (isCompress)
                {
                    gzip.Compress(readingFile, writingFile);
                }
                else
                {
                    gzip.Decompress(readingFile, writingFile);
                }

                Console.WriteLine("0");
                Console.ReadKey();
            }

            catch (Exception e)
            {
                Console.WriteLine($"Error message: {e.Message}");
                Console.WriteLine("1");
                Console.ReadKey();
            }
        }
        protected override void ProcessMetabaseProperties(ExchangeVirtualDirectory dataObject)
        {
            TaskLogger.LogEnter();
            base.ProcessMetabaseProperties(dataObject);
            ADWebServicesVirtualDirectory adwebServicesVirtualDirectory = (ADWebServicesVirtualDirectory)dataObject;

            adwebServicesVirtualDirectory.GzipLevel = Gzip.GetGzipLevel(adwebServicesVirtualDirectory.MetabasePath);
            adwebServicesVirtualDirectory.CertificateAuthentication     = base.GetCertificateAuthentication(dataObject, "Management");
            adwebServicesVirtualDirectory.LiveIdNegotiateAuthentication = base.GetLiveIdNegotiateAuthentication(dataObject, "Nego2");
            TaskLogger.LogExit();
        }
Пример #24
0
        /// <summary>
        /// Handles the DoWork event of the bgwSaveScanSeriesPick control.
        /// </summary>
        /// <param name="sender">
        /// The source of the event.
        /// </param>
        /// <param name="e">
        /// The <see cref="System.ComponentModel.DoWorkEventArgs"/> instance containing the event data.
        /// </param>
        private static void bgwSaveScanSeriesPick_DoWork(object sender, DoWorkEventArgs e)
        {
            string path = Get.FileSystemPaths.PathDatabases + OutputName.ScanSeriesPick + Path.DirectorySeparatorChar;

            Directory.CreateDirectory(path);

            const string WritePath = "SeriesPick";
            string       json      = JsonConvert.SerializeObject(ImportTvFactory.ScanSeriesPicks);

            Gzip.CompressString(json, path + WritePath + "SeriesPick.gz");
        }
Пример #25
0
        /// <summary>
        /// Handles the DoWork event of the bgwSaveMovieSets control.
        /// </summary>
        /// <param name="sender">
        /// The source of the event.
        /// </param>
        /// <param name="e">
        /// The <see cref="System.ComponentModel.DoWorkEventArgs"/> instance containing the event data.
        /// </param>
        private static void bgwSaveMovieSets_DoWork(object sender, DoWorkEventArgs e)
        {
            string path = Get.FileSystemPaths.PathDatabases + OutputName.MovieSets + Path.DirectorySeparatorChar;

            Directory.CreateDirectory(path);

            foreach (MovieSetModel set in MovieSetManager.CurrentDatabase)
            {
                string json = JsonConvert.SerializeObject(set);
                Gzip.CompressString(json, path + FileNaming.RemoveIllegalChars(set.SetName) + ".MovieSet.gz");
            }
        }
Пример #26
0
        public void GzippingWorks()
        {
            var input        = "{'IsPrimitive':true,'IsArray':true,'IsNumeric':false,'Type':'Array','Value':[{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'65'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'80'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'71'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'33'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'48'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'81'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'94'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'67'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'26'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'55'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'29'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'68'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'53'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'53'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'30'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'84'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'15'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'25'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'76'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'45'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'49'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'96'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'4'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'40'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'84'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'39'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'73'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'1'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'18'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'6'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'14'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'57'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'71'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'33'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'23'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'32'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'50'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'14'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'74'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'24'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'45'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'52'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'90'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'40'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'33'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'66'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'38'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'28'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'10'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'98'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'81'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'45'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'76'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'79'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'91'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'69'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'76'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'32'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'49'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'9'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'8'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'94'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'49'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'21'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'42'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'72'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'97'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'21'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'31'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'98'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'34'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'2'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'50'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'52'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'1'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'96'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'6'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'63'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'7'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'18'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'2'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'46'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'90'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'19'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'24'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'68'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'80'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'91'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'41'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'54'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'55'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'19'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'64'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'66'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'16'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'50'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'4'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'70'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'98'},{'IsPrimitive':true,'IsArray':false,'IsNumeric':true,'Type':'Int32','Value':'60'}]}";
            var gzipped      = Gzip.Compress(input);
            var decompressed = Gzip.Decompress(gzipped);

            Assert.AreEqual(decompressed, input);

            double inputByteCount   = Encoding.UTF8.GetBytes(input).Length;
            double gzippedByteCount = Convert.FromBase64String(gzipped).Length;

            Assert.IsTrue(gzippedByteCount < (inputByteCount * 5));
        }
        // Save and send to API
        public void OnBtnSaveRecording()
        {
            string exerciseRecordingCompressed = Convert.ToBase64String(Gzip.Compress(JsonConvert.SerializeObject(homeRevalSession.CurrentRecording.ExerciseRecording)));

            JObject exerciseJson = new JObject(
                new JProperty("name", homeRevalSession.CurrentRecording.Name),
                new JProperty("description", homeRevalSession.CurrentRecording.Description),
                new JProperty("recording", exerciseRecordingCompressed));


            /*string exercisePlanning = "{\"startDate\":\""+ homeRevalSession.CurrentRecording.StartDate.ToLongDateString() + "\", " +
             *  "\"endDate\":\"" + homeRevalSession.CurrentRecording.EndDate.ToLongDateString() + "\"" +
             *  "\"description\":\"Geen idee hebben we nog niet.\"" +
             *  "\"amount\":" + homeRevalSession.CurrentRecording.Amount + "}";*/

            Debug.Log("request begint nu!");
            StartCoroutine(requestService.Post("/exercise", exerciseJson.ToString(),
                                               success => {
                Debug.Log(success);
                JObject response = JObject.Parse(success);
                //Debug.Log(response.ToString());

                JObject exercisePlanningJson = new JObject(
                    new JProperty("startDate", homeRevalSession.CurrentRecording.StartDate.ToLongDateString()),
                    new JProperty("endDate", homeRevalSession.CurrentRecording.EndDate.ToLongDateString()),
                    new JProperty("amount", homeRevalSession.CurrentRecording.Amount),
                    new JProperty("description", "Planning description die we nog niet kunnen invullen in unity dus deze is voor nu leeg."),
                    new JProperty("userExercise", new JObject(
                                      new JProperty("user_ID", homeRevalSession.UserID.ToString()),
                                      new JProperty("exercise_ID", response.GetValue("id").ToString())
                                      ))
                    );

                Debug.Log("JSON EXERCISE PLANNING DIE IK VERZEND: " + exercisePlanningJson.ToString());

                // Save planning
                StartCoroutine(requestService.Post("/exerciseplanning", exercisePlanningJson.ToString(),
                                                   successPlanning => {
                    Debug.Log(successPlanning);
                    SceneManager.LoadScene(0);
                },
                                                   errorPlanning => {
                    Debug.Log(errorPlanning);
                }
                                                   ));
            },
                                               error => {
                Debug.Log(error);
            }
                                               ));
        }
Пример #28
0
        private async void ReadRtmpResp(object sender, MessageReceivedEventArgs eventArgs)
        {
            if (eventArgs.Body is LcdsServiceProxyResponse proxy)
            {
                if (proxy.MessageId == null && proxy.MethodName == "tbdGameDtoV1" && proxy.ServiceName == "teambuilder-draft")
                {
                    var messageData = JsonConvert.DeserializeObject <PartyPhaseMessage>(
                        Encoding.UTF8.GetString(Gzip.Decompress(Convert.FromBase64String(proxy.Payload))));

                    if (messageData.PhaseName == "MATCHMAKING")
                    {
                        await Dispatcher.BeginInvoke(DispatcherPriority.Render, (Action)(() => StartGameButton.Content = "Matchmaking"));
                    }
                    else if (messageData.PhaseName == "AFK_CHECK")
                    {
                        if (_autoAccept)
                        {
                            var acceptData =
                                await StaticVars.ActiveClient.RiotProxyCalls.DoLcdsProxyCallWithResponse(
                                    "teambuilder-draft", "indicateAfkReadinessV1", "{\"afkReady\":true}");

                            await Dispatcher.BeginInvoke(DispatcherPriority.Render, (Action)(() =>
                            {
                                if (acceptData.Status != "ACK")
                                {
                                    UserInterfaceCore.HolderPage.ShowNotification(
                                        UserInterfaceCore.ShortNameToString("UnknownResult"));
                                }

                                UserInterfaceCore.Flash?.Invoke();
                                UserInterfaceCore.HolderPage.ShowNotification(
                                    UserInterfaceCore.ShortNameToString("AcceptedGame"));
                            }));
                        }
                        else
                        {
                            //U piece of shit. No. just no
                        }
                    }
                    else if (messageData.PhaseName == "CHAMPION_SELECT")
                    {
                        await Dispatcher.BeginInvoke(DispatcherPriority.Render, (Action)(() =>
                        {
                            //Really bad method. Don't think that this can play more than one game at a time. Will fix
                            UserInterfaceCore.ChangeMainPageView <ChampionSelectPage>(messageData);
                        }));
                    }
                }
            }
        }
Пример #29
0
        /// <summary>
        /// Loads the movie DB.
        /// </summary>
        private static void LoadMovieDB()
        {
            string path = Get.FileSystemPaths.PathDatabases + OutputName.MovieDb + Path.DirectorySeparatorChar;

            Directory.CreateDirectory(path);
            var files = FileHelper.GetFilesRecursive(path, "*.movie.gz").ToArray();

            MovieDBFactory.MovieDatabase.Clear();

            foreach (var file in files)
            {
                string json = Gzip.Decompress(file);

                var movieModel = JsonConvert.DeserializeObject(json, typeof(MovieModel)) as MovieModel;

                if (json.Contains(@"ChangedText"":false"))
                {
                    movieModel.ChangedText = false;
                }

                if (json.Contains(@"ChangedPoster"":false"))
                {
                    movieModel.ChangedPoster = false;
                }

                if (json.Contains(@"ChangedFanart"":false"))
                {
                    movieModel.ChangedFanart = false;
                }

                movieModel.DatabaseSaved = true;

                MovieDBFactory.MovieDatabase.Add(movieModel);

                string title = FileNaming.RemoveIllegalChars(movieModel.Title);

                string poster = path + title + ".poster.jpg";
                string fanart = path + title + ".fanart.jpg";

                if (File.Exists(poster))
                {
                    movieModel.SmallPoster = ImageHandler.LoadImage(poster);
                }

                if (File.Exists(fanart))
                {
                    movieModel.SmallFanart = ImageHandler.LoadImage(fanart);
                }
            }
        }
Пример #30
0
        /// <summary>
        /// Loads the scan series pick db
        /// </summary>
        private static void LoadScanSeriesPick()
        {
            string path = Get.FileSystemPaths.PathDatabases + OutputName.ScanSeriesPick + Path.DirectorySeparatorChar;

            Directory.CreateDirectory(path);

            if (File.Exists(path + "SeriesPickSeriesPick.gz"))
            {
                string json = Gzip.Decompress(path + "SeriesPickSeriesPick.gz");

                ImportTvFactory.ScanSeriesPicks =
                    JsonConvert.DeserializeObject(json, typeof(BindingList <ScanSeriesPick>)) as
                    BindingList <ScanSeriesPick>;
            }
        }