Exemplo n.º 1
0
        }         // End Sub CreateHugeGzipFile

        private static void CreateHugeBullshitGzipFile()
        {
            if (System.IO.File.Exists(fileName))
            {
                return;
            }

            byte[] buffer = new byte[ONE_MEGABYTE]; // 1MB

            using (System.IO.FileStream gzipTargetAsStream = System.IO.File.OpenWrite(fileName))
            {
                using (System.IO.Compression.GZipStream gzipStream =
                           new System.IO.Compression.GZipStream(gzipTargetAsStream, System.IO.Compression.CompressionLevel.Optimal))
                {
                    try
                    {
                        for (int i = 0; i < REPEAT_COUNT; ++i)
                        {
                            gzipStream.Write(buffer, 0, ONE_MEGABYTE);
                            gzipStream.Flush();
                            gzipTargetAsStream.Flush();
                        } // Next i
                    }
                    catch (System.Exception ex)
                    {
                        System.Console.WriteLine(ex.Message);
                    }
                } // End Using GZipStream
            }     // End Using gzipTargetAsStream
        }         // End Sub CreateHugeBullshitGzipFile
Exemplo n.º 2
0
        private void backupFile()
        {
            var bkp1 = Path.Combine(config.SpiderDataDirectory.FullName, "results.old.gz");
            var bkp2 = Path.Combine(config.SpiderDataDirectory.FullName, "results.older.gz");
            var tmp  = Path.GetTempFileName();

            using (var fs = new FileStream(tmp, FileMode.Create, FileAccess.Write))
            {
                using var gz         = new System.IO.Compression.GZipStream(fs, System.IO.Compression.CompressionMode.Compress);
                using var fileToSave = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                fileToSave.CopyTo(gz);
                gz.Flush();
                fs.Flush();
            }

            if (File.Exists(bkp1))
            {
                // netstandard2.1 File.Move don't have OverrideFile parameter
                if (File.Exists(bkp2))
                {
                    File.Delete(bkp2);
                }
                File.Move(bkp1, bkp2);
            }

            File.Move(tmp, bkp1);
        }
        }     // End Sub Main

        public static void CompressFile(string FileToCompress, string CompressedFile)
        {
            //byte[] buffer = new byte[1024 * 1024 * 64];
            byte[] buffer = new byte[1024 * 1024];     // 1MB

            using (System.IO.FileStream sourceFile = System.IO.File.OpenRead(FileToCompress))
            {
                using (System.IO.FileStream destinationFile = System.IO.File.Create(CompressedFile))
                {
                    using (System.IO.Compression.GZipStream output = new System.IO.Compression.GZipStream(destinationFile,
                                                                                                          System.IO.Compression.CompressionMode.Compress))
                    {
                        int bytesRead = 0;
                        while (bytesRead < sourceFile.Length)
                        {
                            int ReadLength = sourceFile.Read(buffer, 0, buffer.Length);
                            output.Write(buffer, 0, ReadLength);
                            output.Flush();
                            bytesRead += ReadLength;
                        }     // Whend

                        destinationFile.Flush();
                    }     // End Using System.IO.Compression.GZipStream output

                    destinationFile.Close();
                }     // End Using System.IO.FileStream destinationFile

                // Close the files.
                sourceFile.Close();
            } // End Using System.IO.FileStream sourceFile
        }     // End Sub CompressFile
Exemplo n.º 4
0
        /// <summary>
        /// Saves the dataset encrypted in specified file
        /// </summary>
        /// <param name="dataset">Dataset to save</param>
        /// <param name="username">Username for encryption</param>
        /// <param name="password">Password for encryption</param>
        /// <param name="fileName">File name where to save</param>
        /// <param name="compress">Should the file be compressed</param>
        internal static void EncryptDataSet(System.Data.DataSet dataset, string username, string password, string fileName, bool compress)
        {
            // Check the parameters
            if (dataset == null ||
                string.IsNullOrEmpty(username) ||
                string.IsNullOrEmpty(password) ||
                string.IsNullOrEmpty(fileName))
            {
                throw new System.ArgumentNullException("All arguments must be supplied.");
            }

            // Save the dataset as encrypted
            using (System.Security.Cryptography.Aes aes = Cryptography.InitAes(username, password)) {
                using (System.IO.FileStream fileStream = new System.IO.FileStream(fileName, System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite, System.IO.FileShare.None)) {
                    using (System.Security.Cryptography.CryptoStream cryptoStream = new System.Security.Cryptography.CryptoStream(fileStream, aes.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write)) {
                        if (compress)
                        {
                            // when compression is requested, use GZip
                            using (System.IO.Compression.GZipStream zipStream = new System.IO.Compression.GZipStream(cryptoStream, System.IO.Compression.CompressionMode.Compress)) {
                                dataset.WriteXml(zipStream, System.Data.XmlWriteMode.WriteSchema);
                                zipStream.Flush();
                            }
                        }
                        else
                        {
                            dataset.WriteXml(cryptoStream, System.Data.XmlWriteMode.WriteSchema);
                            cryptoStream.FlushFinalBlock();
                        }
                    }
                }
            }
        }
Exemplo n.º 5
0
        /// <summary>
        /// Compress with Stream
        /// </summary>
        public static void Compress(Stream input)
        {
            System.IO.Compression.GZipStream stream =
                new System.IO.Compression.GZipStream(
                    input, System.IO.Compression.CompressionMode.Compress, true);

            stream.Flush();
        }
 private static async Task CompressOriginalContentStream(IHttpContent originalContent, System.IO.MemoryStream ms)
 {
     using (var compressingStream = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Compress, true))
     {
         using (var originalContentStream = await originalContent.ReadAsInputStreamAsync().AsTask().ConfigureAwait(false))
         {
             originalContentStream.AsStreamForRead().CopyTo(compressingStream);
         }
         compressingStream.Flush();
     }
 }
Exemplo n.º 7
0
 static public byte[] CompressGzip(byte[] original)
 {
     using (var compressedStream = new System.IO.MemoryStream())
     {
         using (var compressStream = new System.IO.Compression.GZipStream(
                    compressedStream, System.IO.Compression.CompressionMode.Compress))
         {
             compressStream.Write(original);
             compressStream.Flush();
             return(compressedStream.ToArray());
         }
     }
 }
Exemplo n.º 8
0
        /// <summary>
        /// 保存到流中。
        /// </summary>
        /// <param name="stream">流。</param>
        /// <returns>返回是否成功。</returns>
        public bool Save(System.IO.Stream stream)
        {
            if (stream == null || !stream.CanWrite)
            {
                return(false);
            }

            using (System.IO.Stream compresStream = new System.IO.Compression.GZipStream(stream, System.IO.Compression.CompressionMode.Compress, true)) {
                System.Collections.Generic.Dictionary <string, object> root = new System.Collections.Generic.Dictionary <string, object>();
                root.Add("version", _version);
                System.Collections.Generic.Dictionary <string, object> items = new System.Collections.Generic.Dictionary <string, object>();
                root.Add("items", items);
                bool has = _list != null && _list.Count > 0;
                if (has)
                {
                    for (int i = 0; i < _list.Count; i++)
                    {
                        Resource item = _list[i];
                        items.Add(item.Name, new object[] {
                            item.Offset,
                            item.Length
                        });
                    }
                }
                {
                    string json   = Symbol.Serialization.Json.ToString(root);
                    byte[] buffer = BitConverter.GetBytes((ushort)json.Length);
                    compresStream.Write(buffer, 0, buffer.Length);

                    buffer = System.Text.Encoding.UTF8.GetBytes(json);
                    compresStream.Write(buffer, 0, buffer.Length);
                }
                if (has)
                {
                    for (int i = 0; i < _list.Count; i++)
                    {
                        Resource item = _list[i];
                        compresStream.Write(item.Data, 0, item.Length);
                    }
                }
                compresStream.Flush();
                stream.Flush();
            }
            return(true);
        }
Exemplo n.º 9
0
        }     // End Sub CompressFile

        // http://www.dotnetperls.com/compress
        /// <summary>
        /// Compresses byte array to new byte array.
        /// </summary>
        public static byte[] Compress(byte[] raw)
        {
            byte[] baRetVal;

            using (System.IO.MemoryStream memstrm = new System.IO.MemoryStream())
            {
                using (System.IO.Compression.GZipStream gzip = new System.IO.Compression.GZipStream(memstrm, System.IO.Compression.CompressionMode.Compress, true))
                {
                    gzip.Write(raw, 0, raw.Length);
                    gzip.Flush();
                } // End Using System.IO.Compression.GZipStream gzip

                memstrm.Flush();
                baRetVal = memstrm.ToArray();
                memstrm.Close();
            } // End Using System.IO.MemoryStream memory

            return(baRetVal);
        } // End Function Compress
Exemplo n.º 10
0
        public void Compress()
        {
            string content = _contentWriter.ToString();

            _contentWriter = new StringWriter();
            MemoryStream ms = new MemoryStream();

            System.IO.Compression.GZipStream d = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Compress);

            byte[] data = System.Text.Encoding.Default.GetBytes(content);

            d.Write(data, 0, data.Length);
            d.Flush();
            d.Close();

            data = ms.ToArray();

            _contentWriter.Write(System.Text.Encoding.Default.GetString(data));

            SetValue <string[]>("Filter", new string[] { "FlateDecode" });
        }
Exemplo n.º 11
0
        /// <summary>
        /// Encodes an image in Base64 format.
        /// </summary>
        /// <param name="im">the image to be encoded.</param>
        /// <returns>the string with the encoded image.</returns>
        public static string ImageToBase64(SySal.Imaging.Image im)
        {
            if (im.Info.PixelFormat != PixelFormatType.GrayScale8)
            {
                throw new Exception("Unsupported format. The only supported format is " + PixelFormatType.GrayScale8 + ".");
            }
            int bitsperpixel = (im.Info.BitsPerPixel / 8);

            byte[] b = new byte[bitsperpixel * im.Info.Width * im.Info.Height];
            int    i;

            for (i = 0; i < b.Length; i++)
            {
                b[i] = im.Pixels[(uint)i];
            }
            System.IO.MemoryStream           ms = new System.IO.MemoryStream();
            System.IO.Compression.GZipStream gz = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Compress);
            gz.Write(b, 0, b.Length);
            gz.Flush();
            gz.Close();
            return(Base64String + im.Info.Width + "," + im.Info.Height + "," + im.Info.BitsPerPixel + "\r\n" + System.Convert.ToBase64String(ms.ToArray(), Base64FormattingOptions.InsertLineBreaks));
        }
Exemplo n.º 12
0
        }     // End Sub CompressFile

        public static void CompressFile_AllInOne(string FileToCompress, string CompressedFile)
        {
            using (System.IO.FileStream sourceFile = System.IO.File.OpenRead(FileToCompress))
            {
                using (System.IO.FileStream destinationFile = System.IO.File.Create(CompressedFile))
                {
                    byte[] buffer = new byte[sourceFile.Length];
                    sourceFile.Read(buffer, 0, buffer.Length);

                    using (System.IO.Compression.GZipStream output = new System.IO.Compression.GZipStream(destinationFile,
                                                                                                          System.IO.Compression.CompressionMode.Compress))
                    {
                        output.Write(buffer, 0, buffer.Length);
                        output.Flush();
                        destinationFile.Flush();
                    }     // End Using System.IO.Compression.GZipStream output

                    // Close the files.
                    destinationFile.Close();
                }     // End Using System.IO.FileStream destinationFile

                sourceFile.Close();
            } // End Using System.IO.FileStream sourceFile
        }     // End Sub CompressFile
Exemplo n.º 13
0
            public async Task SendJsonMessage(string messageBody)
            {
                if (ShouldRenewAuthHeader())
                {
                    SetAuthHeader();
                }

                using (var ms = new System.IO.MemoryStream())
                {
                    var bytes = System.Text.UTF8Encoding.UTF8.GetBytes(messageBody);

                    if (_UseCompression)
                    {
                        using (var cs = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Compress, true))
                        {
                            cs.Write(bytes, 0, bytes.Length);
                            cs.Flush();
                        }
                    }
                    else
                    {
                        ms.Write(bytes, 0, bytes.Length);
                    }

                    int retries = 0, maxRetries = 5;
                    while (retries < maxRetries)
                    {
                        ms.Seek(0, System.IO.SeekOrigin.Begin);

                        using (var content = new StreamContent(ms))
                        {
                            if (_UseCompression)
                            {
                                content.Headers.ContentEncoding.Add("gzip");
                            }

                            var result = await _HttpClient.PostAsync(_ConnectionString.EventHubUrl + "/" + _ConnectionString.EventHubPath + "/messages", content).ConfigureAwait(false);

                            if (((int)result.StatusCode >= 500 && (int)result.StatusCode < 600) || (int)result.StatusCode == 429)
                            {
                                retries++;
                                if (retries < maxRetries)
                                {
#if SUPPORTS_TASKEX
                                    await TaskEx.Delay(250 *(retries + 1)).ConfigureAwait(false);
#else
                                    await Task.Delay(250 *(retries + 1)).ConfigureAwait(false);
#endif
                                    continue;
                                }
                            }

                            try
                            {
                                result.EnsureSuccessStatusCode();
                                break;
                            }
                            catch (HttpRequestException hrex)
                            {
                                hrex.Data.Add("StatusCode", result.StatusCode);
                                throw;
                            }
                        }
                    }
                }
            }
Exemplo n.º 14
0
        public void Save(string path)
        {
            if (!System.IO.Directory.Exists(path))
                System.IO.Directory.CreateDirectory(path);

            System.IO.FileStream fs = new System.IO.FileStream(GetFilePath(path, this.CategoryName), System.IO.FileMode.Create);
            System.IO.Compression.GZipStream gz = new System.IO.Compression.GZipStream(fs, System.IO.Compression.CompressionMode.Compress);

            ProtoBuf.Serializer.PrepareSerializer<CompositionCategory>();

            ProtoBuf.Serializer.Serialize(gz, this);

            gz.Flush();

            gz.Close();

            fs.Close();
        }
Exemplo n.º 15
0
        public async void RemoteManageLoop(HttpListenerContext context)
        {
            try {
                LineLog.Debug("serving: " + context.Request.RawUrl);
                var req  = context.Request;
                var resp = context.Response;

                var msg = getResponse(req);
                resp.StatusCode = (int)msg.StatusCode;
                LineLog.Debug("returning: " + resp.StatusCode);
                foreach (var h in msg.Headers)
                {
                    foreach (var v in h.Value)
                    {
                        resp.Headers.Add(h.Key, v);
                    }
                }

                if (resp.StatusCode != 303)
                {
                    using (var output = resp.OutputStream) {
                        byte[] outBytes = Encoding.UTF8.GetBytes("Critical Failure");
                        bool   expires  = false;
                        if (msg.Content is StringContent)
                        {
                            var    qw = msg.Content as StringContent;
                            string qq = await qw.ReadAsStringAsync();

                            resp.ContentType = mimeTypes.Where(t => req.Url.AbsolutePath.EndsWith(t.Key)).FirstOrDefault().Value;
                            if (resp.ContentType == null)
                            {
                                resp.ContentType = "text/html";                                                 // Default to HTML
                            }
                            outBytes = Encoding.UTF8.GetBytes(qq);
                        }
                        else if (msg.Content is FileContent)
                        {
                            var qw = msg.Content as FileContent;
                            resp.ContentType = qw.Type;
                            if (resp.ContentType == null)
                            {
                                resp.ContentType = "application/octet-stream";                                  // Should always be set, but bin just incase
                            }
                            //resp.Headers.Add("Content-Disposition", $"attachment; filename=\"{qw.FileName}\"");
                            outBytes = await qw.ReadAsByteArrayAsync();
                        }
                        else if (msg.Content is ByteArrayContent)
                        {
                            var qw = msg.Content as ByteArrayContent;
                            resp.ContentType = mimeTypes.Where(t => req.Url.AbsolutePath.EndsWith(t.Key)).FirstOrDefault().Value;
                            if (resp.ContentType == null)
                            {
                                resp.ContentType = "application/octet-stream";                                  // Default to binary
                            }
                            outBytes = await qw.ReadAsByteArrayAsync();
                        }
                        else if (msg.Content is StreamContent)
                        {
                            var qw = msg.Content as StreamContent;
                            using (var ms = new MemoryStream()) {
                                var stream = await qw.ReadAsStreamAsync();

                                stream.CopyTo(ms);
                                //resp.ContentType = "application/octet-stream"
                                outBytes = ms.ToArray();
                            }
                        }
                        //resp.Headers.Add("Content-language", "en-au");
                        resp.Headers.Add("Access-Control-Allow-Origin: *");
                        resp.Headers.Add("Access-Control-Allow-Methods: *");

                        if (expires)
                        {
                            resp.Headers.Add("Cache-Control", "no-cache, no-store, must-revalidate");
                            resp.Headers.Add("Pragma", "no-cache");
                            resp.Headers.Add("Expires", "Wed, 16 Jul 1969 13:32:00 UTC");
                        }

                        if ((outBytes.Length > 0) && (resp.ContentType != "image/png"))                             // Don't compress empty responses or compressed file types
                        {
                            var enc = req.Headers.GetValues("Accept-Encoding");

                            if (enc?.Contains("gzip") ?? false)
                            {
                                using (MemoryStream ms = new MemoryStream())
                                    using (System.IO.Compression.GZipStream gs = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Compress)) {
                                        gs.Write(outBytes, 0, outBytes.Length);
                                        gs.Flush();
                                        gs.Close();                                     // https://stackoverflow.com/questions/3722192/how-do-i-use-gzipstream-with-system-io-memorystream#comment3929538_3722263
                                        ms.Flush();
                                        outBytes = ms.ToArray();
                                    }
                                resp.Headers.Add("Content-Encoding", "gzip");
                            }
                            else if (enc?.Any(a => a.ToLowerInvariant() == "deflate") ?? false)
                            {
                                using (MemoryStream ms = new MemoryStream()) {
                                    using (System.IO.Compression.DeflateStream ds = new System.IO.Compression.DeflateStream(ms, System.IO.Compression.CompressionMode.Compress)) {
                                        ds.Write(outBytes, 0, outBytes.Length);
                                        ds.Flush();
                                    }
                                    ms.Flush();
                                    outBytes = ms.ToArray();
                                }
                                resp.Headers.Add("Content-Encoding", "deflate");
                            }
                        }

                        resp.ContentLength64 = outBytes.Length;
                        try {
                            output.Write(outBytes, 0, outBytes.Length);
                        }
                        catch (Exception ex) {
                            Program.LineLog.Error("Failed to write " + ex.GetType().ToString() + " " + ex.Message);
                        }
                    }
                }
                else
                {
                    resp.OutputStream.Close();
                }
            }
            catch (Exception e) {
                LineLog.Error("Something went wrong.", e);
                var resp = context.Response;
                resp.StatusCode = 500;
                using (var output = resp.OutputStream) {
                    byte[] outBytes = Encoding.UTF8.GetBytes(e.GetType() + ": " + e.Message);
                    resp.ContentLength64 = outBytes.Length;
                    try {
                        output.Write(outBytes, 0, outBytes.Length);
                    }
                    catch (Exception ex) {
                        Program.LineLog.Error("Failed to write " + ex.GetType().ToString() + " " + ex.Message);
                    }
                }
            }
        }
Exemplo n.º 16
0
        public static string UnGZIP(ref byte[] input)
        {
            System.IO.MemoryStream oMemoryStream = null;
            System.IO.Compression.GZipStream oGZipStream = null;
            int iLength = 0;
            byte[] byteArray = new byte[100001];
            System.Text.StringBuilder oStringBuilder = new System.Text.StringBuilder();

            oMemoryStream = new System.IO.MemoryStream(input);
            oGZipStream = new System.IO.Compression.GZipStream(oMemoryStream, System.IO.Compression.CompressionMode.Decompress);
            oMemoryStream.Flush();
            oGZipStream.Flush();
            do
            {
                iLength = oGZipStream.Read(byteArray, 0, byteArray.Length);
                if (iLength < 1)
                    break; // TODO: might not be correct. Was : Exit Do
                oStringBuilder.Append(System.Text.Encoding.UTF8.GetString(byteArray, 0, iLength));
            } while (true);
            oGZipStream.Close();
            oMemoryStream.Close();
            oGZipStream.Dispose();
            oMemoryStream.Dispose();
            return oStringBuilder.ToString();
        }
Exemplo n.º 17
0
        public void SaveStuff()
        {
            if (loading)
            {
                return;
            }

            var allMonStr = JsonConvert.SerializeObject(allMons);

            using (MemoryStream ms = new MemoryStream())
            {
                using (System.IO.Compression.GZipStream gz = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Compress))
                {
                    var bytes = Encoding.ASCII.GetBytes(allMonStr);
                    gz.Write(bytes, 0, bytes.Length);
                    gz.Flush();
                }
                ms.Flush();
                File.WriteAllBytes(PluginDataDirectory + "\\allMons.gz", ms.ToArray());
            }

            File.WriteAllText(PluginDataDirectory + "\\matchCount.json", JsonConvert.SerializeObject(matchCount));

            FileInfo     excelFile = new FileInfo(PluginDataDirectory + @"\riftstats.xlsx");
            ExcelPackage excelPack = null;

            excelPack = new ExcelPackage(excelFile);
            Dictionary <string, int> mcount = new Dictionary <string, int>();

            foreach (var montype in allMons)
            {
                int row = 1;
                int col = 1;

                var page = excelPack.Workbook.Worksheets.FirstOrDefault(p => p.Name == montype.Key);
                if (page == null)
                {
                    page = excelPack.Workbook.Worksheets.Add(montype.Key);
                }

                List <string> colHead = new List <string>();

                foreach (var th in "Raid,Grade,Points,Pos,Lead, ,HP,ATK,DEF,SPD,CR,CD,RES,ACC,Set1,Set2,Set3,EHP,EHPDB,DPS,MxD,AvD".Split(','))
                {
                    colHead.Add(th);
                    page.Cells[row, col].Value = th; col++;
                }
                row++;

                foreach (var kvm in montype.Value.OrderByDescending(mv => mv.Value.Key.ClearDamage))
                {
                    if (!mcount.ContainsKey(montype.Key))
                    {
                        mcount[montype.Key] = 1;
                    }
                    else
                    {
                        mcount[montype.Key]++;
                    }

                    var mon   = kvm.Value.Value;
                    var stats = mon.GetStats();
                    for (col = 1; col <= colHead.Count; col++)
                    {
                        switch (colHead[col - 1])
                        {
                        case "Raid":
                            page.Cells[row, col].Value = kvm.Value.Key.RiftDungeonId;
                            break;

                        case "Grade":
                            page.Cells[row, col].Value = kvm.Value.Key.ClearRating;
                            break;

                        case "Points":
                            page.Cells[row, col].Value = kvm.Value.Key.ClearDamage;
                            break;

                        case "Pos":
                            page.Cells[row, col].Value = kvm.Value.Key.Monsters.FirstOrDefault(l => l.MonsterId == (long)mon.Id)?.Position;
                            break;

                        case "Lead":
                            var rifty = kvm.Value.Key.Monsters.FirstOrDefault(l => l.MonsterId == (long)mon.Id);
                            page.Cells[row, col].Value = (rifty?.Position == kvm.Value.Key.LeaderIndex);
                            break;

                        case "HP":
                            page.Cells[row, col].Value = stats.Health;
                            break;

                        case "ATK":
                            page.Cells[row, col].Value = stats.Attack;
                            break;

                        case "DEF":
                            page.Cells[row, col].Value = stats.Defense;
                            break;

                        case "SPD":
                            page.Cells[row, col].Value = stats.Speed;
                            break;

                        case "CR":
                            page.Cells[row, col].Value = stats.CritRate;
                            break;

                        case "CD":
                            page.Cells[row, col].Value = stats.CritDamage;
                            break;

                        case "RES":
                            page.Cells[row, col].Value = stats.Resistance;
                            break;

                        case "ACC":
                            page.Cells[row, col].Value = stats.Accuracy;
                            break;

                        case "Set1":
                            if (Rune.SetRequired(mon.Current.Sets[1]) == 4)
                            {
                                page.Cells[row, col].Value = mon.Current.Sets[1];
                            }
                            else
                            {
                                page.Cells[row, col].Value = mon.Current.Sets[0];
                            }
                            break;

                        case "Set2":
                            if (Rune.SetRequired(mon.Current.Sets[1]) == 4)
                            {
                                page.Cells[row, col].Value = mon.Current.Sets[0];
                            }
                            else
                            {
                                page.Cells[row, col].Value = mon.Current.Sets[1];
                            }
                            break;

                        case "Set3":
                            page.Cells[row, col].Value = mon.Current.Sets[2];
                            break;

                        case "EHP":
                            page.Cells[row, col].Value = stats.ExtraValue(Attr.EffectiveHP);
                            break;

                        case "EHPDB":
                            page.Cells[row, col].Value = stats.ExtraValue(Attr.EffectiveHPDefenseBreak);
                            break;

                        case "DPS":
                            page.Cells[row, col].Value = stats.ExtraValue(Attr.DamagePerSpeed);
                            break;

                        case "MxD":
                            page.Cells[row, col].Value = stats.ExtraValue(Attr.MaxDamage);
                            break;

                        case "AvD":
                            page.Cells[row, col].Value = stats.ExtraValue(Attr.AverageDamage);
                            break;
                        }
                    }
                    row++;
                }
            }

            var sheets = excelPack.Workbook.Worksheets;

            foreach (var cc in mcount.OrderBy(v => v.Value))
            {
                var thissheet = sheets[cc.Key];
                try
                {
                    var tables = thissheet.Tables;
                    int row    = 1;
                    while (!string.IsNullOrWhiteSpace(thissheet.Cells[row, 1].Value?.ToString()))
                    {
                        row++;
                    }
                    int headsize = 1;
                    while (headsize < 10 || !string.IsNullOrWhiteSpace(thissheet.Cells[1, headsize].Value?.ToString()))
                    {
                        headsize++;
                    }

                    var range = thissheet.Cells[1, 1, row - 1, headsize - 1];
                    if (tables.FirstOrDefault(t => t.Name == cc.Key.Replace(" ", "_")) == null)
                    {
                        tables.Add(range, cc.Key.Replace(" ", "_"));
                    }
                    else
                    {
                        var newRange = new ExcelAddress(1, 1, row - 1, headsize - 1).ToString();

                        var tableElement = tables.FirstOrDefault(t => t.Name == cc.Key.Replace(" ", "_")).TableXml.DocumentElement;
                        tableElement.Attributes["ref"].Value = newRange;
                        tableElement["autoFilter"].Attributes["ref"].Value = newRange;
                    }
                }
                catch { }
                excelPack.Workbook.Worksheets.MoveToStart(cc.Key);
            }

            foreach (var rd in matchCount)
            {
                var page = excelPack.Workbook.Worksheets.FirstOrDefault(p => p.Name == rd.Key.ToString());
                if (page == null)
                {
                    page = excelPack.Workbook.Worksheets.Add(rd.Key.ToString());
                }

                var rmons = allMons.SelectMany(q => q.Value.Select(r => r.Value)).Where(d => d.Key.RiftDungeonId == rd.Key);
                var monm  = rmons.Select(d => d.Value);
                //var mp = rmons.Select(d => d.Value._monsterTypeId.ToString().Substring(0,3)).Select(i => monm.FirstOrDefault(m => m._monsterTypeId.ToString().Substring(0,3) == i));

                int row = 2;
                int col = 2;

                var monsX = rd.Value.OrderByDescending(q => q.Value.Sum(v => v.Value)).Select(q => q.Key).ToArray();

                //var monsY = rd.Value.OrderByDescending(q => q.Value.Sum(v => v.Value)).SelectMany(q => q.Value.Select(w => w.Key)).Distinct().ToArray();
                var monsdY = new Dictionary <string, int>();
                foreach (var mq in rd.Value)
                {
                    foreach (var mw in mq.Value)
                    {
                        if (!monsdY.ContainsKey(mw.Key))
                        {
                            monsdY.Add(mw.Key, 0);
                        }
                        monsdY[mw.Key]++;
                    }
                }
                var monsY = monsdY.OrderByDescending(v => v.Value).Select(v => v.Key).ToArray();


                foreach (var mx in monsX)
                {
                    page.Cells[1, col].Value = mx; col++;
                }
                foreach (var my in monsY)
                {
                    page.Cells[row, 1].Value = my; row++;
                }

                row = 2;
                col = 2;

                foreach (var mx in monsX)
                {
                    row = 2;
                    foreach (var my in monsY)
                    {
                        if (rd.Value.ContainsKey(monsX[col - 2]) && rd.Value[mx].ContainsKey(monsY[row - 2]))
                        {
                            var c = rd.Value[mx][my];
                            c = rd.Value[monsX[col - 2]][monsY[row - 2]];
                            //var c = rds.Count(r => r.Monsters.Any(p => p.unit_master_id == mx._monsterTypeId) && r.Monsters.Any(p => p.unit_master_id == my._monsterTypeId)); ;
                            page.Cells[row, col].Value = c;
                        }
                        else
                        {
                            page.Cells[row, col].Value = "";
                        }


                        row++;
                    }
                    col++;
                }
                excelPack.Workbook.Worksheets.MoveToStart(rd.Key.ToString());
            }
            try {
                if (excelPack.Workbook.Worksheets.Count > 0)
                {
                    excelPack.Save();
                }
                Console.WriteLine("Saved riftstats");
            }
            catch (Exception e) {
                Console.WriteLine("Failed saving riftstats because " + e.GetType() + ": " + e.Message);
            }
        }