public override void ProcessRequest(HttpContext context, Match match)
    {
        context.Response.Cache.SetCacheability(HttpCacheability.NoCache);

        try
        {
            PccConfig.LoadConfig("pcc.config");
            string searchTermsId = GetStringFromUrl(context, match, "SearchTermsId");
            // make sure target directory exists
            String targetDir = System.IO.Path.GetDirectoryName(PccConfig.SearchTermsPath);
            if (!System.IO.Directory.Exists(targetDir))
            {
                context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                context.Response.Write("SearchTermsPath does not exist or is not configured correctly in pcc.config");
                context.Response.ContentType = "text/plain";
                return;
            }
            string searchTermsFileName = Path.Combine(targetDir, searchTermsId);
            using (FileStream searchStream = new FileStream(searchTermsFileName, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                searchStream.CopyTo(context.Response.OutputStream);
            }

            context.Response.ContentType = "application/json;charset=utf-8";
            context.Response.StatusCode = (int)HttpStatusCode.OK;
        }
        catch(Exception e)
        {
            context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
            context.Response.Write(e.Message);
            context.Response.ContentType = "text/plain";
            return;
        }
    }
예제 #2
0
        private static void ProcessAssembly(string asmFile)
        {
            var sw        = new Stopwatch();
            var asmLoadSw = new Stopwatch();
            var saveSw    = new Stopwatch();
            var processSw = new Stopwatch();

            basePath = new FileInfo(asmFile).Directory.FullName;

            Environment.CurrentDirectory = basePath;

            AppDomain.CurrentDomain.AssemblyResolve += (s, e) =>
            {
                var asmName = new AssemblyName(e.Name);
                var asmPath = Path.Combine(Environment.CurrentDirectory, asmName.Name + ".dll");

                using (var fs = new FileStream(asmPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                {
                    using (var ms = new MemoryStream())
                    {
                        fs.CopyTo(ms);
                        return(Assembly.Load(ms.ToArray()));
                    }
                }
            };

            var fileName     = asmFile;
            var fileInfo     = new FileInfo(fileName);
            var directory    = fileInfo.Directory;
            var targetFolder = fileName.Contains("/obj/") ? "obj" : "bin";

            while (!directory.Name.Equals(targetFolder, StringComparison.OrdinalIgnoreCase))
            {
                directory = directory.Parent;
            }

            directory = directory.Parent;
            var noAspectFile = Path.Combine(directory.FullName, "no.aspects");

            if (File.Exists(noAspectFile) || string.Equals(Environment.GetEnvironmentVariable("DISABLE_POSTASPECT"), "true", StringComparison.OrdinalIgnoreCase))
            {
                return;
            }

            Console.WriteLine("Started post-aspect Post-Processing for {0}", asmFile);

            var pdbFile    = new FileInfo(Path.Combine(basePath, Path.GetFileNameWithoutExtension(asmFile) + ".pdb"));
            var useSymbols = pdbFile.Exists || asmFile.IndexOf("/debug/", StringComparison.OrdinalIgnoreCase) >= 0;

            sw.Start();

            asmLoadSw.Start();
            var definition = ModuleDefinition.ReadModule(asmFile, new ReaderParameters {
                ReadSymbols = useSymbols
            });

            asmLoadSw.Stop();

            Console.WriteLine("post-aspect Assembly Load in {0} ms", asmLoadSw.ElapsedMilliseconds);

            var moduleWeaver = new ModuleWeaver
            {
                ModuleDefinition = definition
            };

            processSw.Start();
            moduleWeaver.Execute();
            processSw.Stop();

            Console.WriteLine("post-aspect Assembly Rewrite in {0} ms", processSw.ElapsedMilliseconds);

            saveSw.Start();
            //Write to disk
            definition.Write(asmFile, new WriterParameters {
                WriteSymbols = useSymbols
            });
            saveSw.Stop();

            Console.WriteLine("Saved post-aspect Processed Assembly in {0} ms", saveSw.ElapsedMilliseconds);

            sw.Stop();
            Console.WriteLine("Completed post-aspect Post-Processing in {0} ms", sw.ElapsedMilliseconds);

            Environment.ExitCode = 0;
        }
예제 #3
0
        /// <summary>
        /// The get album cover.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="localizationFile">The localization file.</param>
        /// <param name="previewCropped">if set to <c>true</c> [preview cropped].</param>
        public void GetAlbumCover([NotNull] HttpContext context, string localizationFile, bool previewCropped)
        {
            var etag = $@"""{context.Request.QueryString.GetFirstOrDefault("cover")}{localizationFile.GetHashCode()}""";

            try
            {
                // CoverID
                var fileName = string.Empty;
                var data     = new MemoryStream();
                if (context.Request.QueryString.GetFirstOrDefault("cover") == "0")
                {
                    var album = this.GetRepository <UserAlbumImage>().List(context.Request.QueryString.GetFirstOrDefaultAs <int>("album"));

                    var random = new Random();

                    if (album != null && album.Any())
                    {
                        var image = this.GetRepository <UserAlbumImage>().GetImage(album[random.Next(album.Count)].ID);

                        var uploadFolder = BoardFolders.Current.Uploads;

                        var oldFileName = context.Server.MapPath(
                            $"{uploadFolder}/{image.Item2.UserID}.{image.Item1.AlbumID}.{image.Item1.FileName}");
                        var newFileName = context.Server.MapPath(
                            $"{uploadFolder}/{image.Item2.UserID}.{image.Item1.AlbumID}.{image.Item1.FileName}.yafalbum");

                        // use the new fileName (with extension) if it exists...
                        fileName = File.Exists(newFileName) ? newFileName : oldFileName;
                    }
                }
                else
                {
                    var image = this.GetRepository <UserAlbumImage>()
                                .GetImage(context.Request.QueryString.GetFirstOrDefaultAs <int>("cover"));

                    if (image != null)
                    {
                        var uploadFolder = BoardFolders.Current.Uploads;

                        var oldFileName = context.Server.MapPath(
                            $"{uploadFolder}/{image.Item2.UserID}.{image.Item1.AlbumID}.{image.Item1.FileName}");
                        var newFileName = context.Server.MapPath(
                            $"{uploadFolder}/{image.Item2.UserID}.{image.Item1.AlbumID}.{image.Item1.FileName}.yafalbum");

                        // use the new fileName (with extension) if it exists...
                        fileName = File.Exists(newFileName) ? newFileName : oldFileName;
                    }
                }

                using (var input = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    input.CopyTo(data);
                }

                context.Response.ContentType = "image/png";

                // output stream...
                context.Response.OutputStream.Write(data.ToArray(), 0, data.Length.ToType <int>());
                context.Response.Cache.SetCacheability(HttpCacheability.Public);
                context.Response.Cache.SetExpires(System.DateTime.UtcNow.AddHours(2));
                context.Response.Cache.SetLastModified(System.DateTime.UtcNow);
                context.Response.Cache.SetETag(etag);

                data.Dispose();
            }
            catch (Exception x)
            {
                this.Get <ILogger>().Log(
                    this.Get <IUserDisplayName>().GetName(BoardContext.Current.CurrentUser),
                    this,
                    x,
                    EventLogTypes.Information);
                context.Response.Write(
                    "Error: Resource has been moved or is unavailable. Please contact the forum admin.");
            }
        }
예제 #4
0
        protected override void SetupRender()
        {
            if (_scaledImage != null)
            {
                _scaledImage.Dispose();
            }
            if (!string.IsNullOrEmpty(FileName) && Source == PictureSource.File)
            {
                var filePath = Path.Combine(PictureDescriptor.ModulePath, FileName);
                if (File.Exists(filePath))
                {
                    using (var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                    {
                        var ms = new MemoryStream();
                        fs.CopyTo(ms);
                        ms.Position = 0;
                        if (_image != null)
                        {
                            _image.Dispose();
                        }
                        _image = Image.FromStream(ms);
                    }
                }
                else
                {
                    Logging.Error("File is missing or invalid path. {0}", filePath);
                    FileName = "";
                }
            }
            else
            {
                if (Source == PictureSource.Embedded)
                {
                    var fs =
                        typeof(Picture).Assembly.GetManifestResourceStream("VixenModules.Effect.Picture.PictureTiles." +
                                                                           TilePictures + ".png");
                    _image = Image.FromStream(fs);
                }
            }

            if (_image != null)
            {
                _dimension = new FrameDimension(_image.FrameDimensionsList[0]);
                // Number of frames
                _frameCount = _image.GetFrameCount(_dimension);
                _gifSpeed   = true;
                if (_frameCount > 1)
                {
                    _gifSpeed = false;
                }
                UpdateGifSpeedAttribute();
                if (Colors == null)                 //This will only be null for Picture effects that are already on the time line. This is due to the upgrade for the effect.
                {
                    Colors    = new ColorGradient(Color.DodgerBlue);
                    Direction = 0;
                    //		IncreaseBrightness = 10;
                    GifSpeed     = 1;
                    ColorEffect  = ColorEffect.None;
                    MovementRate = 4;
                }
            }
            _movementX = 0.0;
            _movementY = 0.0;
        }
예제 #5
0
        } = new ProfileInput();                                         /* input-action mapping */

        /// <summary>
        ///   Saves object state to the inbound file.
        /// </summary>
        public void Save()
        {
            /**
             * We first open up a binary writer for storing the configuration in the blam.sav binary. Data is all written in
             * one go to the binary on the filesystem.
             */

            using (var fs = new FileStream(Path, FileMode.Open, FileAccess.ReadWrite))
                using (var ms = new MemoryStream(8192))
                    using (var bw = new BinaryWriter(ms))
                    {
                        void WriteBoolean(Offset offset, bool data)
                        {
                            ms.Position = (int)offset;
                            bw.Write(data);
                        }

                        void WriteInteger(Offset offset, int data)
                        {
                            ms.Position = (int)offset;
                            bw.Write(data);
                        }

                        void WriteByte(Offset offset, byte data)
                        {
                            ms.Position = (int)offset;
                            bw.Write(data);
                        }

                        fs.Position = 0;
                        fs.CopyTo(ms);

                        /**
                         * The name is stored in UTF-16; hence, we rely on the Unicode class to encode the string to a byte array for
                         * writing the profile name in the binary.
                         */

                        ms.Position = (int)Offset.ProfileName;
                        bw.Write(Encoding.Unicode.GetBytes(Details.Name));

                        /**
                         * First, we'll take care of the enum options. Storing them is rather straightforward: we cast their values to
                         * integers, which can be then written to the binary.
                         */

                        WriteInteger(Offset.ProfileColour, (int)Details.Colour);
                        WriteInteger(Offset.VideoFrameRate, (int)Video.FrameRate);
                        WriteInteger(Offset.VideoQualityParticles, (int)Video.Particles);
                        WriteInteger(Offset.VideoQualityTextures, (int)Video.Quality);
                        WriteInteger(Offset.AudioQuality, (int)Audio.Quality);
                        WriteInteger(Offset.AudioVariety, (int)Audio.Variety);
                        WriteInteger(Offset.NetworkConnectionType, (int)Network.Connection);

                        /**
                         * The following values are values which can have any integer (within the limits of the data types, of course).
                         */

                        WriteInteger(Offset.VideoResolutionWidth, Video.Resolution.Width);
                        WriteInteger(Offset.VideoResolutionHeight, Video.Resolution.Height);
                        WriteInteger(Offset.NetworkPortServer, Network.Port.Server);
                        WriteInteger(Offset.NetworkPortClient, Network.Port.Client);

                        WriteByte(Offset.VideoRefreshRate, Video.RefreshRate);
                        WriteByte(Offset.VideoMiscellaneousGamma, Video.Gamma);
                        WriteByte(Offset.MouseSensitivityHorizontal, Mouse.Sensitivity.Horizontal);
                        WriteByte(Offset.MouseSensitivityVertical, Mouse.Sensitivity.Vertical);
                        WriteByte(Offset.AudioVolumeMaster, Audio.Volume.Master);
                        WriteByte(Offset.AudioVolumeEffects, Audio.Volume.Effects);
                        WriteByte(Offset.AudioVolumeMusic, Audio.Volume.Music);

                        /**
                         * As for the boolean values, we convert them behind the scene to their integer equivalents -- 1 and 0 for true
                         * and false, respectively.
                         */

                        WriteBoolean(Offset.MouseInvertVerticalAxis, Mouse.InvertVerticalAxis);
                        WriteBoolean(Offset.VideoEffectsSpecular, Video.Effects.Specular);
                        WriteBoolean(Offset.VideoEffectsShadows, Video.Effects.Shadows);
                        WriteBoolean(Offset.VideoEffectsDecals, Video.Effects.Decals);
                        WriteBoolean(Offset.AudioEAX, Audio.EAX);
                        WriteBoolean(Offset.AudioHWA, Audio.HWA);

                        /**
                         * Mapping is conducted by writing values at offsets, where values = actions and offsets = inputs.
                         */

                        foreach (var offset in Enum.GetValues(typeof(Button)))
                        {
                            Debug("Nulling input - " + offset);

                            ms.Position = (int)offset;
                            bw.Write(0x7F);
                        }

                        foreach (var offset in Enum.GetValues(typeof(OddOffsets)))
                        {
                            Debug("Nulling input - " + offset);

                            ms.Position = (int)offset;
                            bw.Write(0xFFFF);
                        }

                        foreach (var mapping in Input.Mapping)
                        {
                            var value  = (byte)mapping.Key;  /* action */
                            var offset = (int)mapping.Value; /* button */

                            Debug("Assigning input to action - " + mapping.Key + " -> " + mapping.Value);

                            ms.Position = offset;
                            bw.Write(value);
                        }

                        foreach (var bitbind in Input.BitBinding)
                        {
                            var value  = (byte)bitbind.Key;  /* button */
                            var offset = (int)bitbind.Value; /* action */

                            Debug("Assigning input to action - " + bitbind.Key + " -> " + bitbind.Value);

                            ms.Position = offset;
                            bw.Write(value);
                            bw.Write((byte)0x00);
                        }

                        /**
                         * The layout of the blam.sav is, in a nutshell:
                         *
                         * [0x0000 - 0x1005] [0x1FFC - 0x2000]
                         *         |                 |
                         *         |                 + - hash data (4 bytes)
                         *         + ------------------- main data (8188 bytes)
                         *
                         * By ...
                         *
                         * 1.   truncating the last four bytes (the hash) from the memory stream; then
                         * 2.   calculating the hash for the main data (i.e. remaining bytes); then
                         * 3.   appending it to the memory stream (i.e. replacing the old hash) ...
                         *
                         * ... we can write the contents to filesystem and expect HCE to accept both the data and the new hash.
                         */

                        Debug("Truncating CRC32 checksum from memory stream");

                        ms.SetLength(ms.Length - 4);

                        Debug("Calculating new CRC32 checksum");

                        var hash = GetHash(ms.ToArray());

                        Debug("New CRC32 hash - 0x" + BitConverter.ToString(hash).Replace("-", string.Empty));

                        ms.SetLength(ms.Length + 4);
                        ms.Position = (int)Offset.BinaryCrc32Hash;
                        bw.Write(hash);

                        Debug("Clearing contents of the profile filesystem binary");

                        fs.SetLength(0);

                        Debug("Copying profile data in memory to the binary file");

                        ms.Position = 0;
                        ms.CopyTo(fs);

                        Info("Saved profile data to the binary on the filesystem");

                        /**
                         * This method returns a forged CRC-32 hash which can be written to the end of the blam.sav binary. This allows
                         * the binary to be considered valid by HCE. By forged hash, we refer to the bitwise complement of a CRC-32 hash
                         * of the blam.sav data.
                         */

                        byte[] GetHash(byte[] data)
                        {
                            /**
                             * This look-up table has been generated from the standard 0xEDB88320 polynomial, which results in hashes that
                             * HCE deems valid. The aforementioned polynomial is the reversed equivalent of 0x04C11DB7, and is used, well,
                             * everywhere!
                             */

                            var crcTable = new uint[]
                            {
                                0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832,
                                0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2,
                                0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, 0x646BA8C0, 0xFD62F97A,
                                0x8A65C9EC, 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172,
                                0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3,
                                0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423,
                                0xCFBA9599, 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB,
                                0xB6662D3D, 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433,
                                0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, 0x6B6B51F4,
                                0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950,
                                0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074,
                                0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0,
                                0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525,
                                0x206F85B3, 0xB966D409, 0xCE61E49F, 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81,
                                0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615,
                                0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1,
                                0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, 0xFED41B76,
                                0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8, 0xA1D1937E,
                                0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6,
                                0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236,
                                0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7,
                                0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F,
                                0x72076785, 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7,
                                0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777,
                                0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278,
                                0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC,
                                0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, 0xBDBDF21C, 0xCABAC28A, 0x53B39330,
                                0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94,
                                0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D
                            };

                            /**
                             * With the available data, we conduct a basic cyclic redundancy check operation on it, using the
                             * aforementioned look-up table. This provides us with the CRC-32 for the main data in the blam.sav binary.
                             *
                             * However, possibly for obfuscation, HCE stores the complement (bitwise NOT) of the hash. This requires us to
                             * flip each bit in the entire hash. Once we've done that, we are left with the desired hash that can be
                             * stored in the blam.sav binary.
                             */

                            var hashData = BitConverter.GetBytes(~data.Aggregate(0xFFFFFFFF, (checksumRegister, currentByte) =>
                                                                                 crcTable[(checksumRegister & 0xFF) ^ Convert.ToByte(currentByte)] ^ (checksumRegister >> 8)));

                            for (var i = 0; i < hashData.Length; i++)
                            {
                                hashData[i] = (byte)~hashData[i];
                            }

                            return(hashData);
                        }
                    }
        }
예제 #6
0
        private static long DownloadMails(DataContext dc, PcapCapture pcap)
        {
            List <string> log      = new List <string>();
            List <string> logError = new List <string>()
            {
                "", ""
            };

            DateTime dtStart = DateTime.UtcNow;

            log.Add("");
            log.Add("LOGIN PARAMS");
            log.Add("Host name: " + dc.HostName + " (resolved ip = " + System.Net.Dns.GetHostEntry(dc.HostName).AddressList.FirstOrDefault() + ") ");
            log.Add("Port: " + dc.Port);
            log.Add("UseSSL: " + dc.UseSSL.ToString());
            log.Add("User name: " + dc.UserName);
            log.Add("User password (Base64): " + Convert.ToBase64String(Encoding.Default.GetBytes(dc.UserPassword)));
            log.Add("");

            if (dc.MergeFolders == false)
            {
                if (File.Exists(dc.DestinationFolder))
                {
                    try
                    {
                        File.Delete(dc.DestinationFolder);
                    }
                    catch (Exception)
                    {
                        File.Move(dc.DestinationFolder, dc.DestinationFolder + "_old");
                    }
                }
            }
            else
            {
            }


            long totalMessagesDownloaded = 0;

            // clone the list
            TotalMails = dc.EmailFolders.Where(o => o.Selected).Sum(o => o.Messages);

            string lastDirName = dc.DestinationFolder.Split('\\', '/').Where(o => !string.IsNullOrEmpty(o)).Last();
            string superDir    = dc.DestinationFolder.Substring(0, dc.DestinationFolder.Length - lastDirName.Length - 1);

            string logFileName = Path.Combine(superDir, lastDirName + ".log");

            if (!Directory.Exists(superDir))
            {
                Directory.CreateDirectory(superDir);
            }

            if (!dc.MergeFolders)
            {
                // Delete previous log file
                if (File.Exists(logFileName))
                {
                    File.Delete(logFileName);
                }
                // Delete previous pcap file
                if (File.Exists(pcap.OutputFile))
                {
                    try
                    {
                        File.Delete(pcap.OutputFile);
                    }
                    catch { }
                }
            }

            pcap.StartCapture();

            bool      downloadFail = false;
            Exception internalEx   = null;

            object writeEntryBlock = new object();

            using (FileStream zipToOpen = new FileStream(dc.DestinationFolder, FileMode.OpenOrCreate))
            {
                ZipArchiveMode openMode = ZipArchiveMode.Create;

                if (File.Exists(dc.DestinationFolder) && dc.MergeFolders)
                {
                    openMode = ZipArchiveMode.Update;
                }

                using (ZipArchive archive = new ZipArchive(zipToOpen, openMode))
                {
                    try
                    {
                        Parallel.ForEach(dc.EmailFolders, new ParallelOptions()
                        {
                            MaxDegreeOfParallelism = dc.ConcurrentThreads
                        }, (folder) =>
                        {
                            if (folder.Selected == false)
                            {
                                return;
                            }

                            // The default port for IMAP over SSL is 993.
                            using (ImapClient client = new ImapClient())
                            {
                                client.ServerCertificateValidationCallback = (s, c, h, ee) => true;

                                try
                                {
                                    client.Connect(dc.HostName, dc.Port, dc.UseSSL);
                                }
                                catch (ImapProtocolException)
                                {
                                    // try twice
                                    System.Threading.Thread.Sleep(100);
                                    client.Connect(dc.HostName, dc.Port, dc.UseSSL);
                                }

                                // wait 10 seconds if error is too many connection
                                var intWaitTime = 10 * 1000;

                                while (true)
                                {
                                    try
                                    {
                                        client.Authenticate(dc.UserName, dc.UserPassword);
                                        break;
                                    }
                                    catch (MailKit.Security.AuthenticationException ex)
                                    {
                                        System.Threading.Thread.Sleep(intWaitTime *= 2);
                                    }

                                    if (intWaitTime > 15 * 60 * 1000)
                                    {
                                        // is waiting time is greather than 15 min I assume the download fails
                                        throw new Exception("Multiple connetion to host fails");
                                    }
                                }

                                ImapFolder imapFodler = (ImapFolder)client.GetFolder(folder.Folder);

                                folder.IsDownloading = true;

                                folder.DownloadedItems = 0;

                                string destZipFolder = folder.Folder.Replace(imapFodler.DirectorySeparator, '\\');
                                // remove wrong chars

                                var illegalChars = Path.GetInvalidFileNameChars().ToList();
                                // remove folder separator
                                illegalChars.Remove('\\');

                                destZipFolder = string.Join("_", destZipFolder.Split(illegalChars.ToArray()));

                                string messageIdSafeName = "";

                                try
                                {
                                    imapFodler.Open(FolderAccess.ReadOnly);
                                }
                                catch (Exception)
                                {
                                    logError.Add("Error: can't select imap folder '" + folder.Folder + "'");
                                    return;
                                }

                                //IList<IMessageSummary> items = imapFodler.Fetch(0, -1, MessageSummaryItems.UniqueId | MessageSummaryItems.Size);
                                IList <IMessageSummary> items = imapFodler.Fetch(0, -1, MessageSummaryItems.UniqueId | MessageSummaryItems.Size | MessageSummaryItems.InternalDate | MessageSummaryItems.Flags);

                                DateTime dt   = DateTime.Now;
                                long fileSize = 0;
                                MimeMessage msg;

                                long folderSize = items.Sum(o => o.Size ?? 0);

                                List <string> AlreadyExistingEntries = new List <string>();
                                if (dc.MergeFolders)
                                {
                                    AlreadyExistingEntries = archive.Entries.Select(o => o.FullName).OrderBy(o => o).ToList();
                                }

                                foreach (var item in items)
                                {
                                    if (dc.MergeFolders)
                                    {
                                        // search entry before start downloading
                                        if (AlreadyExistingEntries.Any(o => o.StartsWith(destZipFolder + "\\" + item.UniqueId + "_")))
                                        {
                                            logError.Add("Log: message id " + item.UniqueId + " already downloaded from folder '" + folder.Folder + "'");
                                            totalMessagesDownloaded++;
                                            folder.DownloadedItems++;
                                            continue;
                                        }
                                        else
                                        {
                                        }
                                    }

                                    dt       = DateTime.Now;
                                    fileSize = 0;

                                    try
                                    {
                                        msg = imapFodler.GetMessage(item.UniqueId);
                                    }
                                    catch
                                    {
                                        // Second attempt
                                        try
                                        {
                                            msg = imapFodler.GetMessage(item.UniqueId);
                                        }
                                        catch (Exception ex)
                                        {
                                            // in the meanwhile a message has been deleted.. sometimes happens
                                            logError.Add("Error: can't download message id " + item.UniqueId + " from folder '" + folder.Folder + "'");
                                            continue;
                                        }
                                    }

                                    ProgressMails++;

                                    if (folder.Selected == false)
                                    {
                                        continue;
                                    }

                                    // msg not exsist
                                    if (msg.From == null)
                                    {
                                        log.Add("Error: can't save message id " + item.UniqueId + " from folder '" + folder.Folder + "' because has no From field");
                                        continue;
                                    }

                                    totalMessagesDownloaded++;
                                    folder.DownloadedItems++;

                                    messageIdSafeName = System.Text.RegularExpressions.Regex.Replace(msg.Headers["Message-ID"] + "", "[<>\\/:]", "");

                                    string msgPrefix = item.UniqueId + "";

                                    if (item.Flags != null && !item.Flags.Value.HasFlag(MessageFlags.Seen))
                                    {
                                        msgPrefix += "_N";
                                    }

                                    if (string.IsNullOrEmpty(messageIdSafeName))
                                    {
                                        messageIdSafeName = Guid.NewGuid().ToString();
                                    }

                                    var destFileName = destZipFolder + "\\" + msgPrefix + "_" + messageIdSafeName + ".eml";

                                    lock (writeEntryBlock)
                                    {
                                        var entry           = archive.CreateEntry(destFileName);
                                        entry.LastWriteTime = item.InternalDate.Value;
                                        using (Stream s = entry.Open())
                                        {
                                            msg.WriteTo(s);
                                            fileSize = s.Position;
                                            s.Close();
                                        }
                                    }

                                    DownloadSpeed.Add(new Tuple <DateTime, double, long>(dt, DateTime.Now.Subtract(dt).TotalMilliseconds, fileSize));

                                    if (totalMessagesDownloaded % 1024 == 0)
                                    {
                                        GCCollectUtils.CheckAndFreeMemory();
                                        zipToOpen.FlushAsync();
                                    }
                                }

                                folder.IsDownloading = false;

                                try
                                {
                                    imapFodler.Close();
                                }
                                catch (MailKit.ServiceNotConnectedException)
                                {
                                }

                                log.Add("Folder: " + folder.Folder + "\t\t" + folder.DownloadedItems + " emails");
                            }
                        });
                    }
                    catch (Exception ex)
                    {
                        // someting worong but the zip file is safe
                        internalEx   = ex;
                        downloadFail = true;
                    }

                    if (pcap != null && pcap.IsCapturing)
                    {
                        // Add pcap file to archive
                        pcap.StopCapture();
                        var pcapName = pcap.OutputFile.Split('\\').Last();
                        if (File.Exists(pcap.OutputFile))
                        {
                            using (FileStream fileStream = new FileStream(pcap.OutputFile, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
                            {
                                var entry = archive.CreateEntry(pcapName);
                                using (Stream s = entry.Open())
                                {
                                    fileStream.CopyTo(s);
                                    s.Close();
                                }
                            }
                        }

                        log.Add("Pcap: " + pcapName + "");
                    }
                    else
                    {
                        log.Add("No Pcap file.");
                    }
                }
            }

            if (downloadFail)
            {
                throw internalEx;
            }


            log.Add("");

            log.Add("Total emails: " + totalMessagesDownloaded);

            DateTime dtEnd = DateTime.UtcNow;

            log.Add("");
            log.Add("Startd at " + dtStart.ToUniversalTime() + " UTC");
            log.Add("End at " + dtEnd.ToUniversalTime() + " UTC");

            log.Add("");

            dc.PartialPercent = 100;

            log.Add("Export file : " + dc.DestinationFolder);

            dc.Speed30sec = "";
            dc.SpeedTotal = "Calculating hash..";

            string md5  = CalculateMD5(dc.DestinationFolder).Replace("-", "");
            string sha1 = CalculateSHA1(dc.DestinationFolder).Replace("-", "");

            log.Add("MD5 : " + md5);
            log.Add("SHA1 : " + sha1);

            if (File.Exists(logFileName))
            {
                File.Delete(logFileName);
            }

            File.WriteAllLines(logFileName, log.Union(logError));

            dc.PartialPercent = 100;

            dc.Speed30sec = "DONE! ";
            dc.SpeedTotal = string.Format(" It took {0} ", DateTime.UtcNow.Subtract(dtStart));

            return(totalMessagesDownloaded);
        }
예제 #7
0
        static void TestOracle2(string name, Stopwatch writeStopwatch, Stopwatch readStopwatch)
        {
            using (OracleConnection conn = new OracleConnection(oracleConnstr))
            {
                conn.Open();

                writeStopwatch.Start();
                using (FileStream fs = new FileStream($"C:\\Temp\\files\\{name}.rar", FileMode.Open, FileAccess.Read, FileShare.None, 64 * 1024 * 1024, FileOptions.SequentialScan))
                {
                    using (OracleTransaction tx = conn.BeginTransaction())
                    {
                        //using (OracleCommand cmd = new OracleCommand("DECLARE c int; BEGIN BEGIN SELECT id into c FROM b WHERE id = 1 FOR UPDATE; EXCEPTION WHEN no_data_found THEN INSERT INTO B (ID, D) VALUES (1, HEXTORAW('0')); END; BEGIN SELECT id into c FROM b WHERE id = 1 AND d IS NOT NULL FOR UPDATE; EXCEPTION WHEN no_data_found THEN UPDATE B SET D = HEXTORAW('0') WHERE id = 1; END; END;", conn))
                        //{
                        //	cmd.CommandTimeout = 0;
                        //	cmd.ExecuteNonQuery();
                        //}

                        //using (OracleCommand cmd = new OracleCommand("SELECT id, d FROM b WHERE id = :id", conn))
                        //{
                        //	cmd.CommandTimeout = 0;
                        //	OracleParameter idParam = new OracleParameter(":id", OracleDbType.Decimal);
                        //	idParam.Value = 1;
                        //	cmd.Parameters.Add(idParam);

                        //	using (OracleDataReader dr = cmd.ExecuteReader())
                        //	{
                        //		if (dr.Read())
                        //		{
                        //			OracleBlob blob = dr.GetOracleBlobForUpdate(1);
                        //			fs.CopyTo(blob, 4 * 1024 * 1024);
                        //		}
                        //	}
                        //}

                        using (OracleCommand cmd = new OracleCommand("BBS", conn))
                        {
                            cmd.Transaction = tx;
                            cmd.CommandType = CommandType.StoredProcedure;
                            cmd.FetchSize   = 4 * 1024 * 1024;
                            //OracleCommandBuilder.DeriveParameters(cmd);
                            OracleParameter idParam = new OracleParameter("p_ID", OracleDbType.Decimal);
                            idParam.Value = 1;
                            cmd.Parameters.Add(idParam);
                            OracleParameter cParam = new OracleParameter("p_c", OracleDbType.RefCursor);
                            cParam.Direction = ParameterDirection.Output;
                            cmd.Parameters.Add(cParam);

                            using (OracleDataReader dr = cmd.ExecuteReader())
                            {
                                if (dr.Read())
                                {
                                    OracleBlob blob = dr.GetOracleBlob(1);

                                    fs.CopyTo(blob, 4 * 1024 * 1024);
                                }
                            }
                        }
                        tx.Commit();
                    }
                }
                writeStopwatch.Stop();
            }

            using (OracleConnection conn = new OracleConnection(oracleConnstr))
            {
                conn.Open();

                readStopwatch.Start();
                using (FileStream fs = new FileStream($"C:\\Temp\\files\\{name}_2.rar", FileMode.Create, FileAccess.Write, FileShare.None, 64 * 1024 * 1024, FileOptions.WriteThrough))
                {
                    using (OracleCommand cmd = new OracleCommand("SELECT d FROM b WHERE id = :id", conn))
                    {
                        cmd.CommandTimeout = 0;
                        cmd.FetchSize      = 4 * 1024 * 1024;
                        OracleParameter idParam = new OracleParameter(":id", OracleDbType.Decimal);
                        idParam.Value = 1;
                        cmd.Parameters.Add(idParam);

                        using (OracleDataReader dr = cmd.ExecuteReader(CommandBehavior.SequentialAccess))
                        {
                            if (dr.Read())
                            {
                                dr.GetOracleBlob(0).CopyTo(fs, 4 * 1024 * 1024);
                            }
                        }
                    }
                }
                readStopwatch.Stop();
            }
        }
    public override void ProcessRequest(HttpContext context, Match match)
    {
        context.Response.Cache.SetCacheability(HttpCacheability.NoCache);

        try
        {
            string documentID = GetStringFromUrl(context, match, "DocumentID");
            string annotationID = GetStringFromUrl(context, match, "AnnotationID");
            // make sure target directory exists
            String targetDir = System.IO.Path.GetDirectoryName(PccConfig.MarkupFolder);
            if (!System.IO.Directory.Exists(targetDir))
            {
                System.IO.Directory.CreateDirectory(targetDir);
            }

            JavaScriptSerializer serializer = new JavaScriptSerializer();

            // Perform an HTTP GET request to retrieve properties about the viewing session from PCCIS.
            // The properties will include an identifier of the source document that will be used below
            // to construct the name of file where markups are stored.
            string uriString = PccConfig.ImagingService + "/ViewingSession/u" + HttpUtility.UrlEncode(documentID);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uriString);
            request.Method = "GET";
            request.Headers.Add("acs-api-key", PccConfig.ApiKey);

            // Send request to PCCIS and get response
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            string responseBody = null;
            using (StreamReader sr = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8))
            {
                responseBody = sr.ReadToEnd();
            }

            ViewingSessionProperties viewingSessionProperties = serializer.Deserialize<ViewingSessionProperties>(responseBody);

            string documentMarkupId = string.Empty;
            viewingSessionProperties.origin.TryGetValue("documentMarkupId", out documentMarkupId);
            string annotationFileName = PccConfig.MarkupFolder + documentMarkupId + "_" + viewingSessionProperties.attachmentIndex + "_" + annotationID + ".xml";

            if (context.Request.RequestType == "POST")
            {
                using (FileStream annotationFile = new FileStream(annotationFileName, FileMode.Create, FileAccess.Write))
                {
                    context.Request.InputStream.CopyTo(annotationFile);
                }
            }
            else
            {
                context.Response.ContentType = "application/xml";
                if (File.Exists(annotationFileName))
                {
                    using (FileStream annotationFile = new FileStream(annotationFileName, FileMode.Open, FileAccess.Read))
                    {
                        annotationFile.CopyTo(context.Response.OutputStream);
                    }
                }
            }
        }
        catch (Exception e)
        {
            context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
            context.Response.Write(e.Message);
            context.Response.ContentType = "text/plain";
            return;
        }

        context.Response.StatusCode = (int)HttpStatusCode.OK;
    }
예제 #9
0
 private void WriteBytesInStream(string fullFilePath, Stream outputStream)
 {
     using (var stream = new FileStream(fullFilePath, FileMode.Open, FileAccess.Read, FileShare.Read))
         stream.CopyTo(outputStream);
 }
예제 #10
0
        public HttpResponseMessage DownloadDocument(string file, string folderName, bool isImage)
        {
            string outfileName = Path.GetFileNameWithoutExtension(file) + "_Out.zip";
            string outPath;

            if (!isImage)
            {
                if (System.IO.File.Exists(Config.Configuration.WorkingDirectory + folderName + "/" + file))
                {
                    outPath = Config.Configuration.WorkingDirectory + folderName + "/" + file;
                }
                else
                {
                    outPath = Config.Configuration.OutputDirectory + folderName + "/" + file;
                }
            }
            else
            {
                outPath = Config.Configuration.OutputDirectory + outfileName;
            }

            using (FilePathLock.Use(outPath))
            {
                if (isImage)
                {
                    if (System.IO.File.Exists(outPath))
                    {
                        System.IO.File.Delete(outPath);
                    }

                    List <string> lst = GetDocumentPages(file, folderName, 1);

                    if (lst.Count > 1)
                    {
                        int tmpPageCount = int.Parse(lst[0]);
                        for (int i = 2; i <= tmpPageCount; i++)
                        {
                            GetDocumentPages(file, folderName, i);
                        }
                    }

                    ZipFile.CreateFromDirectory(Config.Configuration.OutputDirectory + folderName + "/", outPath);
                }


                if ((!System.IO.File.Exists(outPath)) || !Path.GetFullPath(outPath).StartsWith(Path.GetFullPath(System.Web.HttpContext.Current.Server.MapPath("~/Assets/"))))
                {
                    var exception = new HttpResponseException(HttpStatusCode.NotFound);

                    throw exception;
                }

                try
                {
                    using (var fileStream = new FileStream(outPath, FileMode.Open, FileAccess.Read))
                    {
                        using (var ms = new MemoryStream())
                        {
                            fileStream.CopyTo(ms);
                            var result = new HttpResponseMessage(HttpStatusCode.OK)
                            {
                                Content = new ByteArrayContent(ms.ToArray())
                            };
                            result.Content.Headers.ContentDisposition =
                                new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
                            {
                                FileName = (isImage ? outfileName : file)
                            };
                            result.Content.Headers.ContentType =
                                new MediaTypeHeaderValue("application/octet-stream");

                            return(result);
                        }
                    }
                }
                catch (Exception x)
                {
                    Console.WriteLine(x.Message);
                }
            }

            return(null);
        }
예제 #11
0
        /// <summary>
        /// Open email client with image embedded in the email and also attached.
        /// </summary>
        public static bool OpenEmailClientWithEmbeddedImage(string file, string subject, string attachmentName, string imageContentType)
        {
            if (string.IsNullOrWhiteSpace(file) || !File.Exists(file))
            {
                return(false);
            }

            try
            {
                using (MemoryStream ms = new MemoryStream())
                    using (MailMessage message = new MailMessage())
                    {
                        // copy the file to memory.
                        using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
                        {
                            fs.CopyTo(ms);
                            fs.Flush();
                            ms.Position = 0;
                        }

                        // create a new email message with embedded image and also attach the image as alternate.
                        message.From = new MailAddress("*****@*****.**");
                        message.To.Add(new MailAddress("*****@*****.**"));
                        message.Subject = subject;
                        message.Attachments.Add(new Attachment(ms, attachmentName, imageContentType));
                        message.IsBodyHtml = true;

                        // setup the linked image.
                        using (MemoryStream imageSource = new MemoryStream(ms.GetBuffer()))
                        {
                            LinkedResource resource = new LinkedResource(imageSource);
                            resource.ContentId   = "snipimage";
                            resource.ContentType = new System.Net.Mime.ContentType(imageContentType);

                            // Create a plain view for clients not supporting html.
                            var plainView = AlternateView.CreateAlternateViewFromString("Please find my snip attached with this email.", null, "text/plain");

                            // Create a html view for clients supporting html
                            const string format   = @"<body style='font-family:""Calibri""'><img src=cid:snipimage alt-text='Snip' style='border:none;outline:0;' border='0' /><br/></body>";
                            var          htmlView = AlternateView.CreateAlternateViewFromString(format, null, "text/html");
                            htmlView.LinkedResources.Add(resource);

                            // Add both the views to the mail message.
                            message.AlternateViews.Add(htmlView);
                            message.AlternateViews.Add(plainView);

                            // Get the temp file.
                            string tempFile = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N") + ".eml");
                            while (File.Exists(tempFile))
                            {
                                tempFile = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N") + ".eml");
                            }

                            // save the message to disk and open it.
                            if (SaveMessage(message, tempFile))
                            {
                                Process.Start(tempFile);
                                return(true);
                            }
                            else
                            {
                                if (File.Exists(tempFile))
                                {
                                    File.Delete(tempFile);
                                }
                                return(false);
                            }
                        }
                    }
            }
            catch (Exception ex)
            {
                Diagnostics.LogException(ex);
                return(false);
            }
        }
        public void Build()
        {
            if (SourceFile == null)
            {
                throw new Exception("No recovery WIM file found.");
            }
            if (OverwriteBootloader)
            {
                Directory.CreateDirectory(Path.Combine(Drive.Name, @"boot\resources"));
                Directory.CreateDirectory(Path.Combine(Drive.Name, @"boot\fonts"));
                File.Copy(Path.Combine(BootloaderSourceDirectory, @"resources\bootres.dll"), Path.Combine(Drive.Name, @"boot\resources\bootres.dll"), true);
                File.Copy(Path.Combine(BootloaderSourceDirectory, @"DVD\EFI\boot.sdi"), Path.Combine(Drive.Name, @"boot\boot.sdi"), true);
                foreach (string font in Directory.GetFiles(Path.Combine(BootloaderSourceDirectory, @"fonts")))
                {
                    File.Copy(font, Path.Combine(Drive.Name, @"boot\fonts", Path.GetFileName(font)), true);
                }
                File.Copy(Path.Combine(BootloaderSourceDirectory, @"PCAT\memtest.exe"), Path.Combine(Drive.Name, @"boot\memtest.exe"), true);
                if (EfiUsed)
                {
                    Directory.CreateDirectory(Path.Combine(Drive.Name, @"efi\microsoft\boot\resources"));
                    Directory.CreateDirectory(Path.Combine(Drive.Name, @"efi\microsoft\boot\fonts"));
                    File.Copy(Path.Combine(BootloaderSourceDirectory, @"resources\bootres.dll"), Path.Combine(Drive.Name, @"efi\microsoft\boot\resources\bootres.dll"), true);
                    foreach (string font in Directory.GetFiles(Path.Combine(BootloaderSourceDirectory, @"fonts")))
                    {
                        File.Copy(font, Path.Combine(Drive.Name, @"efi\microsoft\boot\fonts", Path.GetFileName(font)), true);
                    }
                    File.Copy(Path.Combine(BootloaderSourceDirectory, @"EFI\memtest.efi"), Path.Combine(Drive.Name, @"efi\microsoft\boot\memtest.efi"), true);
                    if (!UseDeeperLocation)
                    {
                        Directory.CreateDirectory(Path.Combine(Drive.Name, @"efi\boot"));
                    }
                    File.Copy(Path.Combine(BootloaderSourceDirectory, @"EFI\bootmgfw.efi"), Path.Combine(Drive.Name, UseDeeperLocation ? @"efi\microsoft\bootx64.efi" : @"efi\boot\bootx64.efi"), true);
                }
                File.Copy(Path.Combine(BootloaderSourceDirectory, @"PCAT\bootmgr"), Path.Combine(Drive.Name, UseDeeperLocation ? @"boot\bootmgr" : @"bootmgr"), true);
            }
            if (OverwriteBCD)
            {
                for (int bcdIndex = 0; bcdIndex < (EfiUsed ? 2 : 1); bcdIndex++)
                {
                    string storeName = Path.Combine(Drive.Name, bcdIndex == 0 ? @"boot\BCD" : @"efi\microsoft\boot\BCD");
                    File.Copy(Path.Combine(BootloaderSourceDirectory, bcdIndex == 0 ? @"DVD\PCAT\BCD" : @"DVD\EFI\BCD"), storeName, true);
                    string[] oldDisplayOrder;
                    using (ManagementObject entry = new ManagementObject(@"root\WMI", "BcdObject.Id=\"" + EFI_GUID_bootmgr + "\",StoreFilePath=\"" + storeName.Replace(@"\", @"\\") + "\"", null))
                    {
                        oldDisplayOrder = (string[])((ManagementBaseObject)(InvokeWMIMethod(entry, "GetElement", "Type", 0x24000001U).Properties["Element"].Value)).Properties["Ids"].Value;
                        InvokeWMIMethod(entry, "SetObjectListElement", "Type", 0x24000001U, "Ids", new string[] { EFI_GUID_memdiag });
                        InvokeWMIMethod(entry, "SetObjectElement", "Type", 0x23000003U, "Id", EFI_GUID_memdiag);
                    }
                    using (ManagementObject entry = new ManagementObject(@"root\WMI", "BcdObject.Id=\"" + EFI_GUID_memdiag + "\",StoreFilePath=\"" + storeName.Replace(@"\", @"\\") + "\"", null))
                    {
                        InvokeWMIMethod(entry, "SetStringElement", "Type", 0x12000002U, "String", bcdIndex == 0 ? @"\boot\memtest.exe" : @"\efi\microsoft\boot\memtest.efi");
                    }
                    using (ManagementObject store = new ManagementObject(@"root\WMI", "BcdStore.FilePath=\"" + storeName.Replace(@"\", @"\\") + "\"", null))
                    {
                        InvokeWMIMethod(store, "DeleteObject", "Id", oldDisplayOrder[0]);
                    }
                }
            }
            if (SourceFile != "(use existing file)")
            {
                if (SourceFile.StartsWith(@"\\?\GLOBALROOT"))
                {
                    SafeFileHandle fileHandle = new SafeFileHandle(CreateFile(SourceFile, FileAccess.Read, FileShare.Read, IntPtr.Zero, FileMode.Open, FileAttributes.Normal, IntPtr.Zero), true);
                    using (FileStream inStream = new FileStream(fileHandle, FileAccess.Read))
                        using (FileStream outStream = new FileStream(Path.Combine(Drive.Name, "boot", DestinationFileName), FileMode.Create, FileAccess.Write))
                        {
                            inStream.CopyTo(outStream);
                        }
                    fileHandle.Close();
                }
                else
                {
                    File.Copy(SourceFile, Path.Combine(Drive.Name, "boot", DestinationFileName), true);
                }
            }
            string newEntryGUID = "{" + Guid.NewGuid().ToString().ToLowerInvariant() + "}";

            for (int bcdIndex = 0; bcdIndex < (EfiUsed ? 2 : 1); bcdIndex++)
            {
                string storeName = Path.Combine(Drive.Name, bcdIndex == 0 ? @"boot\BCD" : @"efi\microsoft\boot\BCD");
                using (ManagementObject store = new ManagementObject(@"root\WMI", "BcdStore.FilePath=\"" + storeName.Replace(@"\", @"\\") + "\"", null))
                {
                    InvokeWMIMethod(store, "CreateObject", "Id", newEntryGUID, "Type", 0x10200003U);
                }
                using (ManagementObject entry = new ManagementObject(@"root\WMI", "BcdObject.Id=\"" + newEntryGUID + "\",StoreFilePath=\"" + storeName.Replace(@"\", @"\\") + "\"", null))
                {
                    InvokeWMIMethod(entry, "SetFileDeviceElement", "Type", 0x11000001U, "DeviceType", 4U, "AdditionalOptions", EFI_GUID_ramdiskoptions, "Path", @"\boot\" + DestinationFileName, "ParentDeviceType", 1U, "ParentAdditionalOptions", "", "ParentPath", "");
                    InvokeWMIMethod(entry, "SetFileDeviceElement", "Type", 0x21000001U, "DeviceType", 4U, "AdditionalOptions", EFI_GUID_ramdiskoptions, "Path", @"\boot\" + DestinationFileName, "ParentDeviceType", 1U, "ParentAdditionalOptions", "", "ParentPath", "");
                    InvokeWMIMethod(entry, "SetStringElement", "Type", 0x12000002U, "String", bcdIndex == 0 ? @"\windows\system32\boot\winload.exe" : @"\windows\system32\boot\winload.efi");
                    InvokeWMIMethod(entry, "SetStringElement", "Type", 0x12000004U, "String", BootMenuEntryName);
                    InvokeWMIMethod(entry, "SetStringElement", "Type", 0x12000005U, "String", @"en-US");
                    InvokeWMIMethod(entry, "SetObjectListElement", "Type", 0x14000006U, "Ids", new string[] { EFI_GUID_bootloadersettings });
                    InvokeWMIMethod(entry, "SetStringElement", "Type", 0x22000002U, "String", @"\windows");
                    InvokeWMIMethod(entry, "SetIntegerElement", "Type", 0x250000C2U, "Integer", 1UL);
                    InvokeWMIMethod(entry, "SetBooleanElement", "Type", 0x26000010U, "Boolean", true);
                    InvokeWMIMethod(entry, "SetBooleanElement", "Type", 0x26000022U, "Boolean", true);
                    InvokeWMIMethod(entry, "SetBooleanElement", "Type", 0x260000b0U, "Boolean", false);
                }
                using (ManagementObject entry = new ManagementObject(@"root\WMI", "BcdObject.Id=\"" + EFI_GUID_bootmgr + "\",StoreFilePath=\"" + storeName.Replace(@"\", @"\\") + "\"", null))
                {
                    string[] oldDisplayOrder = (string[])((ManagementBaseObject)(InvokeWMIMethod(entry, "GetElement", "Type", 0x24000001U).Properties["Element"].Value)).Properties["Ids"].Value;
                    string[] newDisplayOrder = new string[oldDisplayOrder.Length + 1];
                    Array.Copy(oldDisplayOrder, newDisplayOrder, oldDisplayOrder.Length);
                    newDisplayOrder[newDisplayOrder.Length - 1] = newEntryGUID;
                    InvokeWMIMethod(entry, "SetObjectListElement", "Type", 0x24000001U, "Ids", newDisplayOrder);
                }
                File.Delete(storeName + ".LOG");
                File.Delete(storeName + ".LOG1");
                File.Delete(storeName + ".LOG2");
            }
            Unload();
        }
예제 #13
0
        public static void ProcessFile(string file)
        {
            currentFile = file;
            var fileName = Path.GetFileName(file);

            Console.WriteLine($"Processing {fileName}...");

            if (!File.Exists(file))
            {
                WarningMessage("File does not exist. Skipping...");
                return;
            }

            var ext = Path.GetExtension(file).ToLower();

            if ((games.HasFlag(Games.BBCT) ||
                 games.HasFlag(Games.BBCSEX) ||
                 games.HasFlag(Games.BBCPEX)) && ext != ".pac")
            {
                InfoMessage("Specified game only obfuscates .pac files. Skipping...");
                return;
            }

            if (games.HasFlag(Games.BBTAG) && !BBTAGObfuscatedFiles.Contains(ext))
            {
                InfoMessage($"Specified game does not obfuscate {ext} files. Skipping...");
                return;
            }

            if (ext == ".pacgz" && !modes.HasFlag(Modes.SwitchDeflate) && !modes.HasFlag(Modes.SwitchInflate) &&
                !modes.HasFlag(Modes.Auto))
            {
                InfoMessage($"Specified game and mode does not obfuscate {ext} files. Skipping...");
                return;
            }

            if (string.IsNullOrWhiteSpace(ext) &&
                (modes.HasFlag(Modes.SwitchDeflate) || modes.HasFlag(Modes.SwitchInflate)))
            {
                InfoMessage("Specified game and mode does not obfuscate empty exetension files. Skipping...");
                return;
            }

            byte[] fileBytes     = null;
            var    fileDirectory = outputPath;

            var magicBytes = new byte[4];

            using (var fs =
                       new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                fs.Read(magicBytes, 0, 4);
                fs.Close();
            }

            var isPACMB = magicBytes.SequenceEqual(new byte[] { 0x46, 0x50, 0x41, 0x43 });
            var isHIPMB = magicBytes.SequenceEqual(new byte[] { 0x48, 0x49, 0x50, 0x00 });
            var isHPLMB = magicBytes.SequenceEqual(new byte[] { 0x48, 0x50, 0x41, 0x4C });

            var fileIsKnown = isPACMB || isHIPMB || isHPLMB;

            if (modes == Modes.Auto || (games == Games.BBCSEX || games == Games.BBCPEX) && modes == 0)
            {
                if (magicBytes.SequenceEqual(new byte[] { 0x44, 0x46, 0x41, 0x53 }))
                {
                    modes = Modes.Inflate;
                }
            }

            if (modes == Modes.Auto || games == Games.BBTAG && modes == 0)
            {
                if (magicBytes.Take(3).SequenceEqual(new byte[] { 0x1F, 0x8B, 0x08 }))
                {
                    modes = Modes.SwitchInflate;
                }
                else if (MD5Tools.IsMD5(fileName))
                {
                    modes = Modes.MD5Decrypt;
                }
                else if (fileName.Length > 32 && MD5Tools.IsMD5(fileName.Substring(0, 32)))
                {
                    modes = Modes.MD5Encrypt;
                }
            }

            if (modes == Modes.Auto || games != 0 && modes == 0)
            {
                switch (games)
                {
                case Games.BBCT:
                    modes = fileIsKnown ? Modes.Encrypt : Modes.Decrypt;
                    break;

                case Games.BBTAG:
                    modes = fileIsKnown ? Modes.MD5Encrypt : Modes.MD5Decrypt;
                    break;

                case Games.BBCSEX:
                case Games.BBCPEX:
                case 0:
                    modes = fileIsKnown ? Modes.Deflate | Modes.Encrypt : Modes.Inflate | Modes.Decrypt;
                    break;
                }
            }

            if (modes == Modes.Auto || fileIsKnown && (modes.HasFlag(Modes.Decrypt) ||
                                                       modes.HasFlag(Modes.MD5Decrypt) ||
                                                       modes.HasFlag(Modes.Inflate) ||
                                                       modes.HasFlag(Modes.SwitchInflate)))
            {
                var pacFile = new PACFileInfo(file);
                if (pacFile.IsValidPAC)
                {
                    fileBytes = pacFile.GetBytes();
                }
                else
                {
                    var hipFile = new HIPFileInfo(file);
                    if (hipFile.IsValidHIP)
                    {
                        fileBytes = pacFile.GetBytes();
                    }
                    else
                    {
                        var hplFile = new HPLFileInfo(file);
                        if (hplFile.IsValidHPL)
                        {
                            fileBytes = pacFile.GetBytes();
                        }
                    }
                }
            }

            if (fileBytes == null)
            {
                var changed   = false;
                var memStream = new MemoryStream();
                using (var fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                {
                    fs.CopyTo(memStream);
                }

                if (modes.HasFlag(Modes.Deflate))
                {
                    memStream.Position      = 0;
                    Console.ForegroundColor = ConsoleColor.Cyan;
                    Console.WriteLine($"Deflating {fileName}...");
                    var ms = BBObfuscatorTools.DFASFPACDeflateStream(memStream);
                    memStream.Close();
                    memStream.Dispose();
                    memStream = ms;
                    changed   = true;
                }
                else if (modes.HasFlag(Modes.Decrypt))
                {
                    memStream.Position      = 0;
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine($"Decrypting {fileName}...");
                    var ms = BBObfuscatorTools.FPACCryptStream(memStream, file, CryptMode.Decrypt);
                    memStream.Close();
                    memStream.Dispose();
                    memStream = ms;
                    changed   = true;
                }

                if (modes.HasFlag(Modes.Encrypt))
                {
                    memStream.Position      = 0;
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine($"Encrypting {fileName}...");
                    var ms = BBObfuscatorTools.FPACCryptStream(memStream, file, CryptMode.Encrypt);
                    memStream.Close();
                    memStream.Dispose();
                    memStream = ms;
                    changed   = true;
                }
                else if (modes.HasFlag(Modes.Inflate))
                {
                    memStream.Position      = 0;
                    Console.ForegroundColor = ConsoleColor.Cyan;
                    Console.WriteLine($"Inflating {fileName}...");
                    var ms = BBObfuscatorTools.DFASFPACInflateStream(memStream);
                    memStream.Close();
                    memStream.Dispose();
                    memStream = ms;
                    changed   = true;
                }
                else if (modes.HasFlag(Modes.MD5Encrypt))
                {
                    memStream.Position = 0;
                    if (fileName.Length > 32 && MD5Tools.IsMD5(fileName.Substring(0, 32)) ||
                        file.LastIndexOf("data") >= 0)
                    {
                        Console.ForegroundColor = ConsoleColor.Green;
                        Console.WriteLine($"MD5 Encrypting {fileName}...");
                        var ms = BBTAGMD5CryptTools.BBTAGMD5CryptStream(memStream, file, CryptMode.Encrypt);
                        memStream.Close();
                        memStream.Dispose();
                        memStream = ms;
                        if (fileName.Length > 32 && MD5Tools.IsMD5(fileName.Substring(0, 32)))
                        {
                            fileName = fileName.Substring(0, 32);
                        }
                        else if (!MD5Tools.IsMD5(fileName))
                        {
                            var lastIndex = file.LastIndexOf("data");
                            var datapath  = file.Substring(lastIndex, file.Length - lastIndex);
                            fileName = MD5Tools.CreateMD5(datapath.Replace("\\", "/"));
                            file     = fileName;
                        }

                        changed = true;
                    }
                    else
                    {
                        WarningMessage(
                            "File's name and/or directory does not follow the rules for MD5 Encryption. Ignoring...");
                    }
                }
                else if (modes.HasFlag(Modes.MD5Decrypt))
                {
                    memStream.Position      = 0;
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine($"MD5 Decrypting {fileName}...");
                    var ms = BBTAGMD5CryptTools.BBTAGMD5CryptStream(memStream, file, CryptMode.Decrypt);
                    memStream.Close();
                    memStream.Dispose();
                    memStream = ms;
                    if (MD5Tools.IsMD5(fileName))
                    {
                        if (!string.IsNullOrWhiteSpace(pathsFile))
                        {
                            var length = pathsArray.Length;
                            for (var i = 0; i < length; i++)
                            {
                                if (pathsArray[i].filepathMD5 == fileName)
                                {
                                    var filepath = pathsArray[i].filepath;
                                    fileName      = Path.GetFileName(filepath);
                                    fileDirectory = Path.Combine(outputPath, Path.GetDirectoryName(filepath));
                                }
                            }
                        }

                        if (MD5Tools.IsMD5(fileName))
                        {
                            fileName = fileName + "_" + StringToByteArray(fileName)[7] % 43;
                        }
                    }

                    changed = true;
                }
                else if (modes.HasFlag(Modes.SwitchDeflate))
                {
                    memStream.Position      = 0;
                    Console.ForegroundColor = ConsoleColor.Cyan;
                    Console.WriteLine($"Switch Deflating {fileName}...");
                    var output = new MemoryStream();
                    var data   = memStream.ToArray();
                    using (Stream input = new GZipStream(output,
                                                         CompressionLevel.Optimal, true))
                    {
                        input.Write(data, 0, data.Length);
                        input.Close();
                    }

                    memStream.Close();
                    memStream.Dispose();
                    memStream = output;
                    changed   = true;
                    if (ext == ".pac")
                    {
                        fileName = Path.GetFileNameWithoutExtension(fileName) + ".pacgz";
                    }
                }
                else if (modes.HasFlag(Modes.SwitchInflate))
                {
                    memStream.Position      = 0;
                    Console.ForegroundColor = ConsoleColor.Cyan;
                    Console.WriteLine($"Switch Inflating {fileName}...");
                    using (Stream input = new GZipStream(new MemoryStream(memStream.GetBuffer()),
                                                         CompressionMode.Decompress, true))
                    {
                        using (var output = new MemoryStream())
                        {
                            input.CopyTo(output);
                            input.Close();
                            memStream.Close();
                            memStream.Dispose();
                            memStream = new MemoryStream(output.ToArray());
                        }
                    }

                    changed = true;

                    if (ext == ".pacgz")
                    {
                        fileName = Path.GetFileNameWithoutExtension(fileName) + ".pac";
                    }
                }

                Console.ForegroundColor = ConsoleColor.White;
                if (changed)
                {
                    fileBytes = memStream.ToArray();
                }
                memStream.Close();
                memStream.Dispose();
            }

            if (fileBytes == null)
            {
                var automaticString = modes == Modes.Auto || games != 0 && modes == 0 ? " automatically" : string.Empty;
                WarningMessage($"Could not{automaticString} process {fileName}.");
                return;
            }

            var directory = initFilePath == file || file == fileName
                ? fileDirectory
                : Path.Combine(fileDirectory, Path.GetDirectoryName(file).Replace(initFilePath, string.Empty));

            Directory.CreateDirectory(directory);
            var filePath = Path.GetFullPath(Path.Combine(directory, fileName));

            if (File.Exists(filePath) && !options.HasFlag(Options.Replace))
            {
                var backupPath = filePath + ".bak";
                if (File.Exists(backupPath))
                {
                    File.Delete(backupPath);
                }
                File.Move(filePath, backupPath);
            }

            File.WriteAllBytes(filePath, fileBytes);

            Console.Write("Finished processing ");
            var resultFileConsoleColor = ConsoleColor.White;

            if ((modes.HasFlag(Modes.Encrypt) || modes.HasFlag(Modes.MD5Encrypt)) && modes.HasFlag(Modes.Deflate))
            {
                resultFileConsoleColor = ConsoleColor.Magenta;
            }
            else if (modes.HasFlag(Modes.Deflate))
            {
                resultFileConsoleColor = ConsoleColor.Cyan;
            }
            else if (modes.HasFlag(Modes.Encrypt) || modes.HasFlag(Modes.MD5Encrypt))
            {
                resultFileConsoleColor = ConsoleColor.Green;
            }
            Console.ForegroundColor = resultFileConsoleColor;
            Console.Write($"{fileName}");
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine(".");
        }
예제 #14
0
        /// <summary>
        /// Load image from file
        /// </summary>
        /// <param name="path">Full path  of image file</param>
        /// <param name="width">Width value of scalable image format</param>
        /// <param name="height">Height value of scalable image format</param>
        /// <returns></returns>
        public static Bitmap Load(string path, int @width = 0, int @height = 0)
        {
            var ext = Path.GetExtension(path).ToLower();

            Bitmap bmp = null;

            switch (ext)
            {
            case ".gif":
                using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
                {
                    var ms = new MemoryStream();
                    fs.CopyTo(ms);
                    ms.Position = 0;

                    bmp = new Bitmap(ms, true);
                }
                break;

            case ".ico":
                bmp = ReadIconFile(path);
                break;

            default:
                try
                {
                    GetBitmapFromFile();

                    if (bmp == null)
                    {
                        GetBitmapFromWic();
                    }
                }
                catch (Exception)
                {
                    GetBitmapFromWic();
                }
                break;
            }

            void GetBitmapFromFile()
            {
                var settings = new MagickReadSettings();

                if (ext.CompareTo(".svg") == 0)
                {
                    settings.BackgroundColor = MagickColors.Transparent;
                }

                if (width > 0 && height > 0)
                {
                    settings.Width  = width;
                    settings.Height = height;
                }


                using (var magicImg = new MagickImage(path, settings))
                {
                    //Get Exif information
                    var profile = magicImg.GetExifProfile();
                    if (profile != null)
                    {
                        //Get Orieantation Flag
                        var exifTag = profile.GetValue(ExifTag.Orientation);

                        if (exifTag != null)
                        {
                            int orientationFlag = int.Parse(profile.GetValue(ExifTag.Orientation).Value.ToString());

                            var orientationDegree = GetOrientationDegree(orientationFlag);
                            if (orientationDegree != 0)
                            {
                                //Rotate image accordingly
                                magicImg.Rotate(orientationDegree);
                            }
                        }
                    }

                    //corect the image color
                    magicImg.AddProfile(ColorProfile.SRGB);

                    bmp = magicImg.ToBitmap();
                }
            }

            void GetBitmapFromWic()
            {
                var src = LoadImage(path);

                bmp = BitmapFromSource(src);
            }

            return(bmp);
        }
예제 #15
0
        /// <summary>
        /// Ensure that plugins are deployed to roaming user profile
        /// </summary>
        private static void InitializePluginsFolder()
        {
            if (!Directory.Exists(Paths.PluginsPath))
            {
                Directory.CreateDirectory(Paths.PluginsPath);
            }

            // Find archive that contains plugins to deploy
            var assembly = Assembly.GetExecutingAssembly();

            if (assembly.Location == null)
            {
                throw new NullReferenceException("Executing assembly is null!");
            }

            var currentDirectory = new FileInfo(assembly.Location).DirectoryName;

            if (currentDirectory == null)
            {
                throw new NullReferenceException("Current folder is null!");
            }

            // Check if previous installation contains a "Plugins" folder
            var currentPluginsPath = Path.Combine(currentDirectory, "Plugins");

            if (Directory.Exists(currentPluginsPath))
            {
                if (Path.GetFullPath(currentPluginsPath) != Path.GetFullPath(Paths.PluginsPath))
                {
                    foreach (FileInfo fi in new DirectoryInfo(currentPluginsPath).GetFiles())
                    {
                        using (FileStream sourceStream = new FileStream(fi.FullName, FileMode.Open))
                        {
                            using (
                                FileStream destStream = new FileStream(Path.Combine(Paths.PluginsPath, fi.Name),
                                                                       FileMode.Create))
                            {
                                destStream.Lock(0, sourceStream.Length);
                                sourceStream.CopyTo(destStream);
                                destStream.Unlock(0, sourceStream.Length);
                            }
                        }
                    }

                    Directory.Delete(currentPluginsPath, true);
                }
            }

            // Then updates plugins with latest version of plugins (zipped)
            var pluginsZipFilePath = Path.Combine(currentDirectory, "Plugins.zip");

            if (!File.Exists(pluginsZipFilePath))
            {
                return;
            }

            // Extract content of plugins archive to a temporary folder
            var tempPath = string.Format("{0}_Temp", Paths.PluginsPath);

            if (Directory.Exists(tempPath))
            {
                Directory.Delete(tempPath, true);
            }

            ZipFile.ExtractToDirectory(pluginsZipFilePath, tempPath);

            // Moves all plugins to appropriate folder if version is greater
            // to the version in place
            foreach (var fi in new DirectoryInfo(tempPath).GetFiles())
            {
                var targetFile = Path.Combine(Paths.PluginsPath, fi.Name);

                if (File.Exists(targetFile))
                {
                    if (fi.Extension.ToLower() != ".dll")
                    {
                        File.Copy(fi.FullName, targetFile, true);
                        continue;
                    }

                    var fiSourceVersion = new Version(FileVersionInfo.GetVersionInfo(fi.FullName).FileVersion);
                    var fiTargetVersion = new Version(FileVersionInfo.GetVersionInfo(targetFile).FileVersion);

                    if (fiSourceVersion > fiTargetVersion)
                    {
                        // If version to deploy is newer than current version
                        // Delete current version and copy the new one
                        File.Copy(fi.FullName, targetFile, true);
                    }
                }
                else
                {
                    File.Move(fi.FullName, targetFile);
                }
            }

            // Delete temporary folder
            Directory.Delete(tempPath, true);

            // Delete zip file
            File.Delete(pluginsZipFilePath);
        }
예제 #16
0
            public static PropertyItem[] GetExifProperties(string fileName)
            {
                MemoryStream ms = new MemoryStream();

                using (FileStream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
                {
                    stream.CopyTo(ms);
                }

                System.Drawing.Image image = System.Drawing.Image.FromStream(ms,
                                 /* useEmbeddedColorManagement = */ true,
                                 /* validateImageData = */ false);

                return image.PropertyItems;
            }
예제 #17
0
        internal static ZipArchiveEntry DoCreateEntryFromFile(ZipArchive destination,
                                                              string sourceFileName, string entryName, CompressionLevel? compressionLevel)
        {
            if (destination == null)
                throw new ArgumentNullException(nameof(destination));

            if (sourceFileName == null)
                throw new ArgumentNullException(nameof(sourceFileName));

            if (entryName == null)
                throw new ArgumentNullException(nameof(entryName));

            // Checking of compressionLevel is passed down to DeflateStream and the IDeflater implementation
            // as it is a pluggable component that completely encapsulates the meaning of compressionLevel.

            // Argument checking gets passed down to FileStream's ctor and CreateEntry
            Contract.Ensures(Contract.Result<ZipArchiveEntry>() != null);
            Contract.EndContractBlock();

            using (Stream fs = new FileStream(sourceFileName, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 0x1000, useAsync: false))
            {
                ZipArchiveEntry entry = compressionLevel.HasValue
                                                ? destination.CreateEntry(entryName, compressionLevel.Value)
                                                : destination.CreateEntry(entryName);

                DateTime lastWrite = File.GetLastWriteTime(sourceFileName);

                // If file to be archived has an invalid last modified time, use the first datetime representable in the Zip timestamp format
                // (midnight on January 1, 1980):
                if (lastWrite.Year < 1980 || lastWrite.Year > 2107)
                    lastWrite = new DateTime(1980, 1, 1, 0, 0, 0);

                entry.LastWriteTime = lastWrite;

                using (Stream es = entry.Open())
                    fs.CopyTo(es);

                return entry;
            }
        }
예제 #18
0
        /// <summary>
        /// Main Function
        /// </summary>
        /// <param name="args">[PATH] [Charset-String] [MIN LENGHT] [MAX LENGTH] {output}</param>
        static void Main(string[] args)
        {
            if (args.Length < 4 || args.Length > 5) //4 Arguments are needed, 'output' is optional
            {
                Console.WriteLine("Wrong use of arguments!");
                Console.WriteLine("[PATH] [Charset-String] [MIN LENGTH] [MAX LENGTH] {output}");
                Console.WriteLine("Adding 'output' to the end of the command will print all tries to the console. This will slow down the program!");
                Console.WriteLine("Example: C:\\bruh.zip ABCDEFGHIJKLMNOPQRSTUVWXYZ 5 8");
                return;
            }

            //Check if the Zip-File actually exists
            ZipPath = args[0];
            System.Diagnostics.Debug.WriteLine("Zip-Path: " + ZipPath);
            if (!File.Exists(ZipPath))
            {
                Console.WriteLine("[PATH] must exist!");
                return;
            }

            //Add the Provided Characters to the List
            System.Diagnostics.Debug.WriteLine("Charset: " + args[1]);

            try
            {
                MinLength = Convert.ToInt32(args[2]);
                System.Diagnostics.Debug.WriteLine("Min Length: " + MinLength.ToString());
                if (MinLength < 0) //Password has to be at least 0 characters long
                {
                    Console.WriteLine("[MIN LENGTH] must be 0 or greater!");
                    return;
                }
            }
            catch
            {
                Console.WriteLine("[MIN LENGTH] is not a valid number!");
                return;
            }

            try
            {
                MaxLength = Convert.ToInt32(args[3]);
                System.Diagnostics.Debug.WriteLine("Max Length: " + MaxLength.ToString());
                if (MaxLength < 0) //Password has to be at least 0 characters long
                {
                    Console.WriteLine("[MAX LENGTH] must be 0 or greater!");
                    return;
                }
                if (MaxLength < MinLength) //The maximum length of the password has to be >= the minimum length
                {
                    Console.WriteLine("[MAX LENGTH] must be [MIN LENGTH] or greater!");
                    return;
                }
            }
            catch
            {
                Console.WriteLine("[MAX LENGTH] is not a valid number!");
                return;
            }
            try
            {
                //Has the argument 'output' been provided?
                if (args[4].Trim().ToLower() == "output")
                {
                    PasswordTries = new ConcurrentQueue <String>(); //Create Output Queue
                    new Thread(() => OutputTries()).Start();        //Start Output Thread
                }
            }
            catch { }


            new Thread(() => GeneratorThread(MinLength, MaxLength, args[1])).Start(); //Start Password Generator Thread

            using (MemoryStream zipcontents = new MemoryStream())
            {
                using (FileStream fs = new FileStream(ZipPath, FileMode.Open))
                {
                    fs.CopyTo(zipcontents);
                }

                for (int i = 0; i < ThreadCount; i++)
                {
                    zipcontents.Position = 0;
                    try
                    {
                        MemoryStream currentZipContents = new MemoryStream();
                        zipcontents.CopyTo(currentZipContents);
                        currentZipContents.Position = 0;
                        new Thread(() => PasswordThread(currentZipContents)).Start(); //Start Password Try Thread
                    }
                    catch
                    {
                        Console.WriteLine("Could not write into Temporary Folder: " + TempPath);
                        return;
                    }
                }
            }



            Console.WriteLine("Press key to abort!");
            Console.ReadKey();

            //User wanted to abort. Clear queues, cancel threads and exit.
            PasswordTries?.Clear();
            Passwords.Clear();
            CancellationToken.Cancel();
            Environment.Exit(0);
        }
예제 #19
0
        static void TestMssql3(string name, Stopwatch writeStopwatch, Stopwatch readStopwatch)
        {
            using (SqlConnection conn = new SqlConnection(mssqlConnstr))
            {
                conn.Open();

                writeStopwatch.Start();
                using (FileStream fs = new FileStream($"C:\\Temp\\files\\{name}.rar", FileMode.Open, FileAccess.Read, FileShare.None, 64 * 1024 * 1024, FileOptions.SequentialScan))
                {
                    using (SqlTransaction tx = conn.BeginTransaction())
                    {
                        string pathName  = null;
                        byte[] txContext = null;
                        using (SqlCommand cmd = new SqlCommand("SELECT d.PathName(), GET_FILESTREAM_TRANSACTION_CONTEXT() FROM b2 WHERE id = @id", conn, tx))
                        {
                            SqlParameter idParam = new SqlParameter("@id", SqlDbType.Int);
                            idParam.Value = 1;
                            cmd.Parameters.Add(idParam);

                            using (SqlDataReader dr = cmd.ExecuteReader())
                            {
                                if (dr.Read())
                                {
                                    pathName  = dr.GetString(0);
                                    txContext = dr.GetSqlBytes(1).Buffer;
                                }
                            }
                        }

                        using (SqlFileStream sfs = new SqlFileStream(pathName, txContext, FileAccess.Write, FileOptions.SequentialScan, 0))
                        {
                            fs.CopyTo(sfs);
                        }

                        tx.Commit();
                    }
                }
                writeStopwatch.Stop();

                using (SqlCommand cmd = new SqlCommand("CHECKPOINT", conn))
                {
                    cmd.ExecuteNonQuery();
                }

                using (SqlCommand cmd = new SqlCommand("DBCC DROPCLEANBUFFERS", conn))
                {
                    cmd.ExecuteNonQuery();
                }
            }

            Thread.Sleep(1000);

            using (SqlConnection conn = new SqlConnection(mssqlConnstr))
            {
                conn.Open();

                readStopwatch.Start();
                using (FileStream fs = new FileStream($"C:\\Temp\\files\\{name}_3.rar", FileMode.Create, FileAccess.Write, FileShare.None, 64 * 1024 * 1024, FileOptions.WriteThrough))
                {
                    using (SqlTransaction tx = conn.BeginTransaction())
                    {
                        string pathName  = null;
                        byte[] txContext = null;
                        using (SqlCommand cmd = new SqlCommand("SELECT d.PathName(), GET_FILESTREAM_TRANSACTION_CONTEXT() FROM b2 WHERE id = @id", conn, tx))
                        {
                            SqlParameter idParam = new SqlParameter("@id", SqlDbType.Int);
                            idParam.Value = 1;
                            cmd.Parameters.Add(idParam);

                            using (SqlDataReader dr = cmd.ExecuteReader())
                            {
                                if (dr.Read())
                                {
                                    pathName  = dr.GetString(0);
                                    txContext = dr.GetSqlBytes(1).Buffer;
                                }
                            }
                        }

                        using (SqlFileStream sfs = new SqlFileStream(pathName, txContext, FileAccess.Read, FileOptions.SequentialScan, 0))
                        {
                            sfs.CopyTo(fs);
                        }

                        tx.Commit();
                    }
                }
                readStopwatch.Stop();
            }
        }
예제 #20
0
        /// <summary>
        /// Request certificate from Let's Encrypt
        /// </summary>
        /// <param name="binding"></param>
        /// <returns></returns>
        public CertificateInfo RequestCertificate(Target binding)
        {
            // What are we going to get?
            var identifiers  = binding.GetHosts(false);
            var friendlyName = FriendlyName(binding);
            var pfxPassword  = Properties.Settings.Default.PFXPassword;
            var pfxFileInfo  = new FileInfo(PfxFilePath(binding));

            // Try using cached certificate first to avoid rate limiting during
            // (initial?) deployment troubleshooting. Real certificate requests
            // will only be done once per day maximum.
            if (pfxFileInfo.Exists && pfxFileInfo.LastWriteTime > DateTime.Now.AddDays(-1))
            {
                try
                {
                    var cached = new CertificateInfo()
                    {
                        Certificate = ReadForUse(pfxFileInfo, pfxPassword),
                        PfxFile     = pfxFileInfo
                    };
                    var idn = new IdnMapping();
                    if (cached.SubjectName == identifiers.First() &&
                        cached.HostNames.Count == identifiers.Count &&
                        cached.HostNames.All(h => identifiers.Contains(idn.GetAscii(h))))
                    {
                        if (_options.ForceRenewal)
                        {
                            _log.Warning("Cached certificate available but not used with --forcerenewal. Use 'Renew specific' or 'Renew all' in the main menu to run unscheduled renewals without hitting rate limits.");
                        }
                        else
                        {
                            _log.Warning("Using cached certificate for {friendlyName}. To force issue of a new certificate within 24 hours, delete the .pfx file from the CertificatePath or run with the --forcerenewal switch. Be ware that you might run into rate limits doing so.", friendlyName);
                            return(cached);
                        }
                    }
                }
                catch
                {
                    // File corrupt or invalid password?
                    _log.Warning("Unable to read from certificate cache");
                }
            }

            using (var cp = CertificateProvider.GetProvider("BouncyCastle"))
            {
                // Generate the private key and CSR
                var    rsaPkp  = GetRsaKeyParameters();
                var    rsaKeys = cp.GeneratePrivateKey(rsaPkp);
                var    csr     = GetCsr(cp, identifiers, rsaKeys);
                byte[] derRaw;
                using (var bs = new MemoryStream())
                {
                    cp.ExportCsr(csr, EncodingFormat.DER, bs);
                    derRaw = bs.ToArray();
                }
                var derB64U = JwsHelper.Base64UrlEncode(derRaw);

                // Save request parameters to disk
                using (var fs = new FileStream(GetPath(binding, "-gen-key.json"), FileMode.Create))
                    cp.SavePrivateKey(rsaKeys, fs);

                using (var fs = new FileStream(GetPath(binding, "-key.pem"), FileMode.Create))
                    cp.ExportPrivateKey(rsaKeys, EncodingFormat.PEM, fs);

                using (var fs = new FileStream(GetPath(binding, "-gen-csr.json"), FileMode.Create))
                    cp.SaveCsr(csr, fs);

                using (var fs = new FileStream(GetPath(binding, "-csr.pem"), FileMode.Create))
                    cp.ExportCsr(csr, EncodingFormat.PEM, fs);

                // Request the certificate from Let's Encrypt
                _log.Information("Requesting certificate {friendlyName}", friendlyName);
                var certificateRequest = _client.Acme.RequestCertificate(derB64U);
                if (certificateRequest.StatusCode != HttpStatusCode.Created)
                {
                    throw new Exception($"Request status {certificateRequest.StatusCode}");
                }

                // Main certicate and issuer certificate
                Crt certificate;
                Crt issuerCertificate;

                // Certificate request was successful, save the certificate itself
                var crtDerFile = GetPath(binding, $"-crt.der");
                _log.Information("Saving certificate to {crtDerFile}", _certificatePath);
                using (var file = File.Create(crtDerFile))
                    certificateRequest.SaveCertificate(file);

                // Save certificate in PEM format too
                var crtPemFile = GetPath(binding, $"-crt.pem");
                using (FileStream source = new FileStream(crtDerFile, FileMode.Open),
                       target = new FileStream(crtPemFile, FileMode.Create))
                {
                    certificate = cp.ImportCertificate(EncodingFormat.DER, source);
                    cp.ExportCertificate(certificate, EncodingFormat.PEM, target);
                }

                // Get issuer certificate and save in DER and PEM formats
                issuerCertificate = GetIssuerCertificate(certificateRequest, cp);
                using (var target = new FileStream(GetPath(binding, "-crt.der", "ca-"), FileMode.Create))
                    cp.ExportCertificate(issuerCertificate, EncodingFormat.DER, target);

                var issuerPemFile = GetPath(binding, "-crt.pem", "ca-");
                using (var target = new FileStream(issuerPemFile, FileMode.Create))
                    cp.ExportCertificate(issuerCertificate, EncodingFormat.PEM, target);

                // Save chain in PEM format
                using (FileStream intermediate = new FileStream(issuerPemFile, FileMode.Open),
                       certificateStrean = new FileStream(crtPemFile, FileMode.Open),
                       chain = new FileStream(GetPath(binding, "-chain.pem"), FileMode.Create))
                {
                    certificateStrean.CopyTo(chain);
                    intermediate.CopyTo(chain);
                }

                // All raw data has been saved, now generate the PFX file
                using (FileStream target = new FileStream(pfxFileInfo.FullName, FileMode.Create))
                {
                    try
                    {
                        cp.ExportArchive(rsaKeys,
                                         new[] { certificate, issuerCertificate },
                                         ArchiveFormat.PKCS12,
                                         target,
                                         pfxPassword);
                    }
                    catch (Exception ex)
                    {
                        _log.Error("Error exporting archive {@ex}", ex);
                    }
                }

                // Flags used for the internally cached certificate
                X509KeyStorageFlags internalFlags =
                    X509KeyStorageFlags.MachineKeySet |
                    X509KeyStorageFlags.PersistKeySet |
                    X509KeyStorageFlags.Exportable;

                // See http://paulstovell.com/blog/x509certificate2
                try
                {
                    // Convert Private Key to different CryptoProvider
                    _log.Verbose("Converting private key...");
                    var res        = new X509Certificate2(pfxFileInfo.FullName, pfxPassword, internalFlags);
                    var privateKey = (RSACryptoServiceProvider)res.PrivateKey;
                    res.PrivateKey   = Convert(privateKey);
                    res.FriendlyName = friendlyName;
                    File.WriteAllBytes(pfxFileInfo.FullName, res.Export(X509ContentType.Pfx, pfxPassword));
                    pfxFileInfo.Refresh();
                }
                catch (Exception ex)
                {
                    // If we couldn't convert the private key that
                    // means we're left with a pfx generated with the
                    // 'wrong' Crypto provider therefor delete it to
                    // make sure it's retried on the next run.
                    _log.Warning("Error converting private key to Microsoft RSA SChannel Cryptographic Provider, which means it might not be usable for Exchange.");
                    _log.Verbose("{ex}", ex);
                }

                // Recreate X509Certificate2 with correct flags for Store/Install
                return(new CertificateInfo()
                {
                    Certificate = ReadForUse(pfxFileInfo, pfxPassword),
                    PfxFile = pfxFileInfo
                });
            }
        }
예제 #21
0
        public static MemoryStream GetTemplate(int id, string path, out string code, string _userID)
        {
            double Totalcost    = 0;
            var    memoryStream = new MemoryStream();


            ContractPrintModel item = ContractService.GetInstance().GetNegotiationPrintModel(id, _userID);

            code = item.NegotiationCode;
            QuoteRelation relation = ProposalService.GetInstance().getQuoteRelation(item.QuoteID);

            item.AuditCode   = relation.AuditCode;
            item.AuditTime   = relation.AuditTime;
            item.BidPlanCode = relation.BidPlanCode;
            item.BidPlanTime = relation.BidPlanTime;

            item.NegotiationCode = relation.NegotiationCode;
            item.NegotiationTime = relation.NegotiationTime;

            using (var fileStream = new FileStream(path, FileMode.Open, FileAccess.Read))
                fileStream.CopyTo(memoryStream);
            //  code = item.ProposalCode;
            using (var document = WordprocessingDocument.Open(memoryStream, true))
            {
                document.ChangeDocumentType(WordprocessingDocumentType.Document); // change from template to document
                DateTime date        = DateTime.Now;
                string   currentDate = " Ngày " + date.ToString("dd/MM/yyyy");
                var      body        = document.MainDocumentPart.Document.Body;
                var      paras       = body.Elements <Paragraph>();

                List <string>         headers = new List <string>();
                List <List <string> > items   = new List <List <string> >();
                headers.Add("STT");
                headers.Add("Tên gói thầu");
                headers.Add("Giá gói thầu");
                headers.Add("Nguồn vốn");
                headers.Add("Hình thức phương thức lựa chọn nhà thầu");
                headers.Add("Thời gian tổ chức lựa chọn nhà thầu");
                headers.Add("Loại hợp đồng");
                headers.Add("Thời gian thực hiện hợp đồng");

                foreach (ItemInfo record in item.Items)
                {
                    Totalcost += record.ItemPrice * record.Amount;
                }
                if (item.IsVAT)
                {
                    Totalcost = Totalcost * (item.VATNumber + 100) / 100;
                }

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


                Table tableData = CreateTable(item, Totalcost);


                string dateInStr     = "";
                string negoationtime = "";
                string desiciontime  = "";
                dateInStr = item.DateIn.Hour + " giờ ";
                if (item.DateIn.Minute != 0)
                {
                    dateInStr += item.DateIn.Minute + " phút ";
                }
                dateInStr += ", ngày" + item.DateIn.Day + " tháng " + item.DateIn.Month + " năm " + item.DateIn.Year;

                desiciontime += " ngày" + item.DecisionTime.Day + "/" + item.DecisionTime.Month + "/" + item.DecisionTime.Year;

                negoationtime += " ngày" + item.NegotiationTime.Day + "/" + item.NegotiationTime.Month + "/" + item.NegotiationTime.Year;

                foreach (var text in body.Descendants <Text>())
                {
                    text.Text = text.Text.Replace("#", "");
                    text.Text = text.Text.Replace("contractcode", WordUtils.checkNull(item.ContractCode));
                    text.Text = text.Text.Replace("contracttime", WordUtils.checkNull(dateInStr));
                    text.Text = text.Text.Replace("vatnumber", WordUtils.checkNull(item.VATNumber.ToString()));
                    text.Text = text.Text.Replace("desicioncode", WordUtils.checkNull(item.ContractCode));
                    text.Text = text.Text.Replace("desiciontime", WordUtils.checkNull(desiciontime));
                    text.Text = text.Text.Replace("negoationcode", WordUtils.checkNull(item.ContractCode));
                    text.Text = text.Text.Replace("negoationtime", WordUtils.checkNull(negoationtime));

                    text.Text = text.Text.Replace("inputcode", WordUtils.checkNull(item.Code));
                    //A side
                    text.Text = text.Text.Replace("aaddress", WordUtils.checkNull(HardData.location[Int32.Parse(item.ALocation) - 1]));
                    text.Text = text.Text.Replace("aside", WordUtils.checkNull(item.ASide));
                    text.Text = text.Text.Replace("aphone", WordUtils.checkNull(item.APhone));
                    text.Text = text.Text.Replace("arepresent", WordUtils.checkNull(item.ARepresent));
                    text.Text = text.Text.Replace("afax", WordUtils.checkNull(item.AFax));
                    text.Text = text.Text.Replace("aposition", WordUtils.checkNull(item.APosition));
                    text.Text = text.Text.Replace("atax", WordUtils.checkNull(item.ATaxCode));
                    text.Text = text.Text.Replace("abankidlabel", WordUtils.checkNull(HardData.NegotiationBankIDArr[Int32.Parse(item.ABankID) - 1]));
                    //B side
                    text.Text = text.Text.Replace("baddress", WordUtils.checkNull(item.BLocation));
                    text.Text = text.Text.Replace("bside", WordUtils.checkNull(item.BSide));
                    text.Text = text.Text.Replace("bphone", WordUtils.checkNull(item.BPhone));
                    text.Text = text.Text.Replace("brepresent", WordUtils.checkNull(item.BRepresent));
                    text.Text = text.Text.Replace("bfax", WordUtils.checkNull(item.BFax));
                    text.Text = text.Text.Replace("bposition", WordUtils.checkNull(item.BPosition));
                    text.Text = text.Text.Replace("btax", WordUtils.checkNull(item.BTaxCode));
                    text.Text = text.Text.Replace("bbankidlabel", WordUtils.checkNull(item.BBankID));

                    text.Text = text.Text.Replace("term", WordUtils.checkNull(item.Term.ToString()));
                    text.Text = text.Text.Replace("costnumber", string.Format("{0:0,0}", Totalcost).Replace(",", "."));
                    text.Text = text.Text.Replace("coststring", WordUtils.checkNull(Utils.NumberToTextVN((decimal)Totalcost)));


                    text.Text = text.Text.Replace("bidtype", item.BidType);
                    text.Text = text.Text.Replace("bidtime", item.BidExpirated + " " + item.BidExpiratedUnit);
                    if (text.Text == "table")
                    {
                        DocumentFormat.OpenXml.OpenXmlElement textP1 = text.Parent;
                        DocumentFormat.OpenXml.OpenXmlElement textP2 = textP1.Parent;
                        body.InsertAfter(tableData, textP2);
                        textP1.Remove();
                    }
                }

                document.Save();
                document.Close();
            }
            return(memoryStream);
        }
예제 #22
0
        public void LoadMedia(string path)
        {
            Console.WriteLine($"{Name} Loading media {path}!");

            // Don't attempt to load the same media that is already loaded, but put the media back to the start.
            if (path == CurrentMedia)
            {
                if (vlcControl != null)
                {
                    vlcControl.Position = 0f;
                }
                return;
            }

            FileType fileType = Utilities.GetFileType(path);

            if (fileType == FileType.Image)
            {
                errorMessageTextBox.Hide();
                vlcPlayerTableLayoutPanel.Hide();

                try
                {
                    Image img;

                    using (var fs = new FileStream(path, FileMode.Open))
                    {
                        var ms = new MemoryStream();
                        fs.CopyTo(ms);
                        ms.Position = 0;                               // <=== here
                        if (pictureBox.Image != null)
                        {
                            pictureBox.Image.Dispose();
                        }
                        img = Image.FromStream(ms);
                        pictureBox.Image = img;

                        pictureBox.Show();
                        pictureBox.Enabled = true;
                    }
                }
                catch (Exception e)
                {
                    ShowErrorMessageBox(e);
                    if (pictureBox.Image != null)
                    {
                        pictureBox.Image.Dispose();
                    }
                }
            }
            else if (fileType == FileType.Video)
            {
                pictureBox.Hide();
                errorMessageTextBox.Hide();

                try
                {
                    if (vlcControl != null)
                    {
                        FileInfo fi = new FileInfo(path);

                        ThreadPool.QueueUserWorkItem(_ =>
                        {
                            vlcControl.SetMedia(fi, (repeat) ? "input-repeat=4000" : "input-repeat=0");
                            vlcControl.Play();
                            vlcControl.Audio.Volume = (int)volumeTrackbar.Value;
                        });

                        vlcPlayerTableLayoutPanel.Show();
                    }
                    else
                    {
                        ShowErrorMessageBox("VLC must be located by this program in order to support video playback. This can be configured in the settings.");
                    }
                }
                catch (Exception e)
                {
                    ShowErrorMessageBox(e);
                }
            }
            else
            {
                ShowErrorMessageBox($"File format '{Path.GetExtension(path).ToLower()}' not supported.");
            }

            CurrentMedia = path;
            //Invoke((MethodInvoker)delegate { NotifyPropertyChanged(nameof(EnableButtons)); });
            NotifyPropertyChanged(nameof(EnableButtons));
        }
 public async Task Load(MemoryStream memoryStream, string wayToFile)
 {
     using (FileStream file = new FileStream(wayToFile, FileMode.Open, FileAccess.Read))
         file.CopyTo(memoryStream);
 }
        private void PerformPUT()
        {
            string fullPath = rootDir + WebUtility.UrlDecode(request.Url.AbsolutePath);

            var mode = FileMode.Create;

            if (request.Headers["X-Copy-To"] != null)
            {
                mode = FileMode.Open;
            }
            FileStream newFile = null;
            FileStream copy    = null;
            bool       created = false;

            try
            {
                int lastSeparatorForward  = fullPath.LastIndexOf('/');
                int lastSeparatorBackward = fullPath.LastIndexOf('\\');
                int lastSeparator         = Math.Max(lastSeparatorForward, lastSeparatorBackward);
                Directory.CreateDirectory(fullPath.Substring(0, lastSeparator));
                created = true;
                newFile = File.Open(fullPath, mode, FileAccess.ReadWrite, FileShare.Read);

                if (request.Headers["X-Copy-To"] != null)
                {
                    string target = rootDir + WebUtility.UrlDecode(request.Headers["X-Copy-To"]);

                    lastSeparatorForward  = target.LastIndexOf('/');
                    lastSeparatorBackward = target.LastIndexOf('\\');
                    lastSeparator         = Math.Max(lastSeparatorForward, lastSeparatorBackward);
                    Directory.CreateDirectory(target.Substring(0, lastSeparator));

                    copy = File.Open(target, FileMode.Create, FileAccess.Write, FileShare.Read);
                    newFile.CopyTo(copy);
                    newFile.Close();
                    copy.Close();
                    PrepareResponseHeaders(200, "OK");
                    response.ContentType = "text/html;charset=UTF-8";
                    response.Close(StatusResponse("File has been copied"), true);
                    return;
                }

                if (request.HasEntityBody)
                {
                    request.InputStream.CopyTo(newFile);
                    PrepareResponseHeaders(201, "Created");
                    response.ContentType = "text/html;charset=UTF-8";
                    response.Close(StatusResponse("File has been created"), true);
                }
                else
                {
                    PrepareResponseHeaders(201, "Created");
                    response.ContentType = "text/html;charset=UTF-8";
                    response.Close(StatusResponse("An empty file has been created"), true);
                }
                newFile.Close();
            }
            catch (UnauthorizedAccessException)
            {
                PrepareResponseHeaders(403, "Forbidden");
                response.ContentType = "text/html;charset=UTF-8";
                response.Close(StatusResponse("You have no rights for accessing this file/directory"), true);
            }
            catch (ArgumentException)
            {
                PrepareResponseHeaders(400, "Bad request");
                response.ContentType = "text/html;charset=UTF-8";
                response.Close(StatusResponse("Invalid path provided"), true);
            }
            catch (PathTooLongException)
            {
                PrepareResponseHeaders(414, "Path too long");
                response.ContentType = "text/html;charset=UTF-8";
                response.Close(StatusResponse("Path too long"), true);
            }
            catch (NotSupportedException)
            {
                PrepareResponseHeaders(400, "Bad request");
                response.ContentType = "text/html;charset=UTF-8";
                response.Close(StatusResponse("Ivalid path format"), true);
            }
            catch (FileNotFoundException)
            {
                PrepareResponseHeaders(404, "Not found");
                response.ContentType = "text/html;charset=UTF-8";
                response.Close(StatusResponse("File/directory was not found"), true);
            }
            catch (DirectoryNotFoundException)
            {
                PrepareResponseHeaders(400, "Bad request");
                response.ContentType = "text/html;charset=UTF-8";
                response.Close(StatusResponse("Provided path is invalid"), true);
            }
            catch (IOException)
            {
                if (!created)
                {
                    PrepareResponseHeaders(400, "Bad request");
                    response.ContentType = "text/html;charset=UTF-8";
                    response.Close(StatusResponse("Specified path is a file"), true);
                }
                else
                {
                    PrepareResponseHeaders(500, "Internal server error");
                    response.ContentType = "text/html;charset=UTF-8";
                    response.Close(StatusResponse("File cannot be created/written to due to unspecified internal error"), true);
                }
            }
            finally
            {
                newFile?.Close();
                copy?.Close();
            }
        }
예제 #25
0
파일: Zip.cs 프로젝트: sasiit23/smah1
        /// <summary>
        /// Compress and Decompress file with Zip format
        /// </summary>
        /// <param name="signature">Signature in begin file (can be null)</param>
        /// <param name="filenameIn">Input file</param>
        /// <param name="filenameOut">Output file</param>
        /// <param name="compress">True: compress, False: decompress</param>
        /// <param name="message">If raise error,return related message</param>
        /// <returns>True: success, False: fail</returns>
        public static bool CompressDecompressZip(
            byte[] signature,
            string filenameIn, string filenameOut,
            bool compress, out string message)
        {
            if (!File.Exists(filenameIn))
            {
                message = "Source file not found!";
                return(false);
            }

            FileStream infile    = null;
            FileStream outfile   = null;
            GZipStream zipStream = null;
            bool       ret       = false;

            message = "";
            try
            {
                infile = new FileStream(filenameIn, FileMode.Open, FileAccess.Read, FileShare.Read);

                //int count = infile.Read(buffer, 0, buffer.Length);
                if (File.Exists(filenameOut))
                {
                    File.Delete(filenameOut);  //If not delete,may be overwrite first bytes and stay last bytes!
                }
                outfile = new FileStream(filenameOut, FileMode.OpenOrCreate, FileAccess.Write);

                if (compress)
                {
                    if (signature != null && signature.Length > 0)
                    {
                        outfile.Write(signature, 0, signature.Length);
                    }
                    zipStream = new GZipStream(outfile, CompressionMode.Compress, true);
                    infile.CopyTo(zipStream);
                    ret = true;
                }
                else
                {
                    bool notError = true;
                    if (signature != null && signature.Length > 0)
                    {
                        byte[] signature2 = new byte[signature.Length];
                        infile.Read(signature2, 0, signature.Length);
                        for (int i = 0; i < signature.Length; i++)
                        {
                            if (signature[i] != signature2[i])
                            {
                                notError = false;
                                break;
                            }
                        }
                    }
                    if (notError)
                    {
                        zipStream = new GZipStream(infile, CompressionMode.Decompress);
                        zipStream.CopyTo(outfile);
                        ret = true;
                    }
                    else
                    {
                        message = "Error: Invalid file signature.";
                    }
                }
            }
            catch (InvalidDataException exc)
            {
                message = "Error: The file being read contains invalid data." + Environment.NewLine + exc.Message;
            }
            catch (FileNotFoundException exc)
            {
                message = "Error:The file specified was not found." + Environment.NewLine + exc.Message;
            }
            catch (ArgumentException exc)
            {
                message = "Error: path is a zero-length string, contains only white space, or contains one or more invalid characters" + Environment.NewLine + exc.Message;
            }
            catch (PathTooLongException exc)
            {
                message = "Error: The specified path, file name, or both exceed the system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters." + Environment.NewLine + exc.Message;
            }
            catch (DirectoryNotFoundException exc)
            {
                message = "Error: The specified path is invalid, such as being on an unmapped drive." + Environment.NewLine + exc.Message;
            }
            catch (IOException exc)
            {
                message = "Error: An I/O error occurred while opening the file." + Environment.NewLine + exc.Message;
            }
            catch (UnauthorizedAccessException exc)
            {
                message = "Error: path specified a file that is read-only, the path is a directory, or caller does not have the required permissions." + Environment.NewLine + exc.Message;
            }
            catch (IndexOutOfRangeException exc)
            {
                message = "Error: You must provide parameters for MyGZIP." + Environment.NewLine + exc.Message;
            }
            catch (Exception exc)
            {
                message = "Unknow Error : " + exc.Message + Environment.NewLine + exc.StackTrace;
            }
            finally
            {
                if (zipStream != null)
                {
                    zipStream.Close();
                }
                if (outfile != null)
                {
                    outfile.Close();
                }
                if (infile != null)
                {
                    infile.Close();
                }
            }
            return(ret);
        }
예제 #26
0
        public static string GetCertificate(Target binding)
        {
            List <string> identifiers = new List <string>();

            if (!Options.San)
            {
                identifiers.Add(binding.Host);
            }
            identifiers.AddRange(binding.AlternativeNames);
            identifiers = identifiers.Where(x => !string.IsNullOrWhiteSpace(x)).Distinct().ToList();
            if (identifiers.Count() == 0)
            {
                Log.Error("No DNS identifiers found.");
                throw new Exception("No DNS identifiers found.");
            }

            var identifier = identifiers.First();

            var cp     = CertificateProvider.GetProvider();
            var rsaPkp = new RsaPrivateKeyParams();

            try
            {
                if (Properties.Settings.Default.RSAKeyBits >= 1024)
                {
                    rsaPkp.NumBits = Properties.Settings.Default.RSAKeyBits;
                    Log.Debug("RSAKeyBits: {RSAKeyBits}", Properties.Settings.Default.RSAKeyBits);
                }
                else
                {
                    Log.Warning(
                        "RSA Key Bits less than 1024 is not secure. Letting ACMESharp default key bits. http://openssl.org/docs/manmaster/crypto/RSA_generate_key_ex.html");
                }
            }
            catch (Exception ex)
            {
                Log.Warning("Unable to set RSA Key Bits, Letting ACMESharp default key bits, Error: {@ex}", ex);
            }

            var rsaKeys    = cp.GeneratePrivateKey(rsaPkp);
            var csrDetails = new CsrDetails()
            {
                CommonName       = identifiers.FirstOrDefault(),
                AlternativeNames = identifiers
            };

            var csrParams = new CsrParams
            {
                Details = csrDetails
            };
            var csr = cp.GenerateCsr(csrParams, rsaKeys, Crt.MessageDigest.SHA256);

            byte[] derRaw;
            using (var bs = new MemoryStream())
            {
                cp.ExportCsr(csr, EncodingFormat.DER, bs);
                derRaw = bs.ToArray();
            }
            var derB64U = JwsHelper.Base64UrlEncode(derRaw);

            Log.Information($"Requesting certificate: {identifier}");
            var certRequ = _client.RequestCertificate(derB64U);

            Log.Debug("certRequ {@certRequ}", certRequ);
            Log.Debug("Request Status: {statusCode}", certRequ.StatusCode);

            if (certRequ.StatusCode == System.Net.HttpStatusCode.Created)
            {
                var    keyGenFile   = Path.Combine(_certificatePath, $"{identifier}-gen-key.json");
                var    keyPemFile   = Path.Combine(_certificatePath, $"{identifier}-key.pem");
                var    csrGenFile   = Path.Combine(_certificatePath, $"{identifier}-gen-csr.json");
                var    csrPemFile   = Path.Combine(_certificatePath, $"{identifier}-csr.pem");
                var    crtDerFile   = Path.Combine(_certificatePath, $"{identifier}-crt.der");
                var    crtPemFile   = Path.Combine(_certificatePath, $"{identifier}-crt.pem");
                var    chainPemFile = Path.Combine(_certificatePath, $"{identifier}-chain.pem");
                string crtPfxFile   = null;
                if (!Options.CentralSsl)
                {
                    crtPfxFile = Path.Combine(_certificatePath, $"{identifier}-all.pfx");
                }
                else
                {
                    crtPfxFile = Path.Combine(Options.CentralSslStore, $"{identifier}.pfx");
                }

                using (var fs = new FileStream(keyGenFile, FileMode.Create))
                    cp.SavePrivateKey(rsaKeys, fs);
                using (var fs = new FileStream(keyPemFile, FileMode.Create))
                    cp.ExportPrivateKey(rsaKeys, EncodingFormat.PEM, fs);
                using (var fs = new FileStream(csrGenFile, FileMode.Create))
                    cp.SaveCsr(csr, fs);
                using (var fs = new FileStream(csrPemFile, FileMode.Create))
                    cp.ExportCsr(csr, EncodingFormat.PEM, fs);

                Log.Information("Saving certificate to {crtDerFile}", crtDerFile);
                using (var file = File.Create(crtDerFile))
                    certRequ.SaveCertificate(file);

                Crt crt;
                using (FileStream source = new FileStream(crtDerFile, FileMode.Open),
                       target = new FileStream(crtPemFile, FileMode.Create))
                {
                    crt = cp.ImportCertificate(EncodingFormat.DER, source);
                    cp.ExportCertificate(crt, EncodingFormat.PEM, target);
                }

                // To generate a PKCS#12 (.PFX) file, we need the issuer's public certificate
                var isuPemFile = GetIssuerCertificate(certRequ, cp);

                using (FileStream intermediate = new FileStream(isuPemFile, FileMode.Open),
                       certificate = new FileStream(crtPemFile, FileMode.Open),
                       chain = new FileStream(chainPemFile, FileMode.Create))
                {
                    certificate.CopyTo(chain);
                    intermediate.CopyTo(chain);
                }

                Log.Debug($"CentralSsl {Options.CentralSsl} - San {Options.San}");

                if (Options.CentralSsl && Options.San)
                {
                    foreach (var host in identifiers)
                    {
                        Log.Debug($"Host: {host}");
                        crtPfxFile = Path.Combine(Options.CentralSslStore, $"{host}.pfx");

                        Log.Information("Saving certificate to {crtPfxFile}", crtPfxFile);
                        using (FileStream source = new FileStream(isuPemFile, FileMode.Open),
                               target = new FileStream(crtPfxFile, FileMode.Create))
                        {
                            try
                            {
                                var isuCrt = cp.ImportCertificate(EncodingFormat.PEM, source);
                                cp.ExportArchive(rsaKeys, new[] { crt, isuCrt }, ArchiveFormat.PKCS12, target,
                                                 Properties.Settings.Default.PFXPassword);
                            }
                            catch (Exception ex)
                            {
                                Log.Error("Error exporting archive {@ex}", ex);
                            }
                        }
                    }
                }
                else //Central SSL and San need to save the cert for each hostname
                {
                    Log.Information("Saving certificate to {crtPfxFile}", crtPfxFile);
                    using (FileStream source = new FileStream(isuPemFile, FileMode.Open),
                           target = new FileStream(crtPfxFile, FileMode.Create))
                    {
                        try
                        {
                            var isuCrt = cp.ImportCertificate(EncodingFormat.PEM, source);
                            cp.ExportArchive(rsaKeys, new[] { crt, isuCrt }, ArchiveFormat.PKCS12, target,
                                             Properties.Settings.Default.PFXPassword);
                        }
                        catch (Exception ex)
                        {
                            Log.Error("Error exporting archive {@ex}", ex);
                        }
                    }
                }

                cp.Dispose();

                return(crtPfxFile);
            }
            Log.Error("Request status = {StatusCode}", certRequ.StatusCode);
            throw new Exception($"Request status = {certRequ.StatusCode}");
        }
예제 #27
0
        static void Decrypt()
        {
            Console.WriteLine("begin to decrypt...");
            var aes = new AesManaged();

            aes.BlockSize = 128;
            aes.KeySize   = 128;
            aes.Mode      = CipherMode.CBC;
            aes.Key       = Encoding.UTF8.GetBytes(secretKey);
            aes.Padding   = PaddingMode.PKCS7;
            aes.IV        = Encoding.UTF8.GetBytes(secretKey);

            Console.WriteLine("begin to decrypt 1M file...");
            Stopwatch sw = new Stopwatch();

            sw.Start();
            using (FileStream fout = new FileStream("test1_de.dat", FileMode.Create, FileAccess.Write))
            {
                using (CryptoStream cryptostream = new CryptoStream(fout, aes.CreateDecryptor(aes.Key, aes.IV), CryptoStreamMode.Write))
                {
                    using (FileStream fin = new FileStream("test1_en.dat", FileMode.Open, FileAccess.Read))
                    {
                        fin.CopyTo(cryptostream);
                    }
                }
            }
            sw.Stop();
            Console.WriteLine("file decrypt complete, time elapsed:{0} ms", sw.ElapsedMilliseconds);

            Console.WriteLine("begin to decrypt 100M file...");
            sw = new Stopwatch();
            sw.Start();
            using (FileStream fout = new FileStream("test2_de.dat", FileMode.Create, FileAccess.Write))
            {
                using (CryptoStream cryptostream = new CryptoStream(fout, aes.CreateDecryptor(aes.Key, aes.IV), CryptoStreamMode.Write))
                {
                    using (FileStream fin = new FileStream("test2_en.dat", FileMode.Open, FileAccess.Read))
                    {
                        fin.CopyTo(cryptostream);
                    }
                }
            }
            sw.Stop();
            Console.WriteLine("file decrypt complete, time elapsed:{0} ms", sw.ElapsedMilliseconds);

            Console.WriteLine("begin to decrypt 1G file...");
            sw = new Stopwatch();
            sw.Start();
            using (FileStream fout = new FileStream("test3_de.dat", FileMode.Create, FileAccess.Write))
            {
                using (CryptoStream cryptostream = new CryptoStream(fout, aes.CreateDecryptor(aes.Key, aes.IV), CryptoStreamMode.Write))
                {
                    using (FileStream fin = new FileStream("test3_en.dat", FileMode.Open, FileAccess.Read))
                    {
                        fin.CopyTo(cryptostream);
                    }
                }
            }
            sw.Stop();
            Console.WriteLine("file decrypt complete, time elapsed:{0} ms", sw.ElapsedMilliseconds);
        }
예제 #28
0
        private void loadImage(string image, bool reloadDirectory = false)
        {
            try {
                // save the memory.
                if (pictureBox.Image != null)
                {
                    pictureBox.Image.Dispose();
                }

                currentFile = Path.GetFileName(image);

                // get all images from current image's directory.
                var directory = Path.GetDirectoryName(image);

                if (currentDirectory != directory || reloadDirectory)
                {
                    currentDirectory = directory;

                    var di = new DirectoryInfo(currentDirectory);
                    images = new List <string>();

                    foreach (var file in di.GetFiles())
                    {
                        if (isImageExtension(file.Extension))
                        {
                            images.Add(file.Name);
                        }
                    }

                    images.Sort(new NaturalComparer());

                    currentFileIndex = images.IndexOf(currentFile);
                }

                if (!File.Exists(image) && images.Count == 0)
                {
                    // show message.
                    labelErrorMessage.Visible   = false;
                    labelNoImageMessage.Visible = true;
                    toolPhotoshop.Visible       = false;
                    contextPhotoshop.Visible    = false;

                    disableControls();

                    Text = appTitle;

                    return;
                }

                // set form title.
                Text = currentFile + " - " + appTitle;

                // try to load image.
                using (var stream = new FileStream(image, FileMode.Open, FileAccess.Read)) {
                    var memStream = new MemoryStream();

                    stream.CopyTo(memStream);
                    memStream.Position = 0;

                    pictureBox.Image = Image.FromStream(memStream);
                }

                // show picture.
                labelErrorMessage.Visible   = false;
                labelNoImageMessage.Visible = false;

                enableControl();

                // recalculate zoom levels.
                recalculateZoomLevels();

                // resize and repostion picture box.
                zoomImage(settings.OpenFitToWindow ? Zoom.FitToWin : Zoom.ActualSize);

                // check if has photoshop file with same name.
                if (File.Exists(Path.Combine(currentDirectory, Path.GetFileNameWithoutExtension(currentFile) + ".psd")))
                {
                    toolPhotoshop.Visible    = true;
                    contextPhotoshop.Visible = true;
                }
            } catch (Exception) {
                // show message.
                labelErrorMessage.Visible   = true;
                labelNoImageMessage.Visible = false;
                toolPhotoshop.Visible       = false;
                contextPhotoshop.Visible    = false;

                disableControls();
            }
        }
예제 #29
0
        /// <summary>
        /// Load image from file
        /// </summary>
        /// <param name="filename">Full path of image file</param>
        /// <param name="size">A custom size of image</param>
        /// <param name="colorProfileName">Name or Full path of color profile</param>
        /// <param name="isApplyColorProfileForAll">If FALSE, only the images with embedded profile will be applied</param>
        /// <param name="quality">Image quality</param>
        /// <param name="channel">MagickImage.Channel value</param>
        /// <param name="useEmbeddedThumbnails">Return the embedded thumbnail if required size was not found.</param>
        /// <returns>Bitmap</returns>
        public static Bitmap Load(
            string filename,
            Size size = new Size(),
            string colorProfileName        = "sRGB",
            bool isApplyColorProfileForAll = false,
            int quality = 100,
            int channel = -1,
            bool useEmbeddedThumbnails = false
            )
        {
            Bitmap bitmap   = null;
            var    ext      = Path.GetExtension(filename).ToUpperInvariant();
            var    settings = new MagickReadSettings();

            #region Settings
            if (ext == ".SVG")
            {
                settings.BackgroundColor = MagickColors.Transparent;
            }

            if (size.Width > 0 && size.Height > 0)
            {
                settings.Width  = size.Width;
                settings.Height = size.Height;
            }
            #endregion


            #region Read image data
            switch (ext)
            {
            case ".GIF":
                // Note: Using FileStream is much faster than using MagickImageCollection
                using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read))
                {
                    var ms = new MemoryStream();
                    fs.CopyTo(ms);
                    ms.Position = 0;

                    bitmap = new Bitmap(ms, true);
                }
                break;

            case ".ICO":
            case ".TIF":
            case ".WEBP":
                try
                {
                    using (var imgColl = new MagickImageCollection(filename, settings))
                    {
                        bitmap = imgColl.ToBitmap();
                    }
                }
                catch
                {
                    // Issue #637: MagickImageCollection falls over with certain images, fallback to MagickImage
                    ReadWithMagickImage();
                }
                break;

            default:
                ReadWithMagickImage();

                break;
            }
            #endregion


            #region Internal Functions

            // Preprocess magick image
            void PreprocesMagickImage(MagickImage imgM, bool checkRotation = true)
            {
                imgM.Quality = quality;


                // Get Exif information
                var profile = imgM.GetExifProfile();

                // Use embedded thumbnails if specified
                if (profile != null && useEmbeddedThumbnails)
                {
                    // Fetch the embedded thumbnail
                    var thumbM = profile.CreateThumbnail();
                    if (thumbM != null)
                    {
                        bitmap = thumbM.ToBitmap();
                    }
                }


                // Revert to source image if an embedded thumbnail with required size was not found.
                if (bitmap == null)
                {
                    if (profile != null && checkRotation)
                    {
                        // Get Orientation Flag
                        var exifRotationTag = profile.GetValue(ExifTag.Orientation);

                        if (exifRotationTag != null)
                        {
                            if (int.TryParse(exifRotationTag.Value.ToString(), out var orientationFlag))
                            {
                                var orientationDegree = Helpers.GetOrientationDegree(orientationFlag);
                                if (orientationDegree != 0)
                                {
                                    //Rotate image accordingly
                                    imgM.Rotate(orientationDegree);
                                }
                            }
                        }
                    }


                    // get the color profile of image
                    var imgColorProfile = imgM.GetColorProfile();


                    // if always apply color profile
                    // or only apply color profile if there is an embedded profile
                    if (isApplyColorProfileForAll || imgColorProfile != null)
                    {
                        if (imgColorProfile != null)
                        {
                            // correct the image color space
                            imgM.ColorSpace = imgColorProfile.ColorSpace;
                        }
                        else
                        {
                            // set default color profile and color space
                            imgM.AddProfile(ColorProfile.SRGB);
                            imgM.ColorSpace = ColorProfile.SRGB.ColorSpace;
                        }

                        var colorProfile = Helpers.GetColorProfile(colorProfileName);
                        if (colorProfile != null)
                        {
                            imgM.AddProfile(colorProfile);
                            imgM.ColorSpace = colorProfile.ColorSpace;
                        }
                    }
                }
            }

            // Separate color channel
            MagickImage ApplyColorChannel(MagickImage imgM)
            {
                // separate color channel
                if (channel != -1)
                {
                    var magickChannel = (Channels)channel;
                    var channelImgM   = (MagickImage)imgM.Separate(magickChannel).First();

                    if (imgM.HasAlpha && magickChannel != Channels.Alpha)
                    {
                        using (var alpha = imgM.Separate(Channels.Alpha).First())
                        {
                            channelImgM.Composite(alpha, CompositeOperator.CopyAlpha);
                        }
                    }


                    return(channelImgM);
                }

                return(imgM);
            }

            void ReadWithMagickImage()
            {
                // Issue #530: ImageMagick falls over if the file path is longer than the (old)
                // windows limit of 260 characters. Workaround is to read the file bytes, but
                // that requires using the "long path name" prefix to succeed.

                //filename = Helpers.PrefixLongPath(filename);
                //var allBytes = File.ReadAllBytes(filename);

                // TODO: there is a bug of using bytes[]:
                // https://github.com/dlemstra/Magick.NET/issues/538
                using (var imgM = new MagickImage(filename, settings))
                {
                    var checkRotation = ext != ".HEIC";
                    PreprocesMagickImage(imgM, checkRotation);

                    using (var channelImgM = ApplyColorChannel(imgM))
                    {
                        bitmap = channelImgM.ToBitmap();
                    }
                }
            }

            #endregion


            return(bitmap);
        }
예제 #30
0
        // create image libraries
        private void CreateLibraries()
        {
            // fore each image library
            foreach (var i in imagesList)
            {
                if (i.BoundCheckBox == null || !i.BoundCheckBox.Checked)
                {
                    continue;
                }

                // create a blob container
                var container = new CloudBlobContainer(i.ContainerName.ToLower(), cbc);
                try
                {
                    // set metadata
                    container.CreateIfNotExist();
                    container.SetPermissions(
                        new BlobContainerPermissions()
                    {
                        PublicAccess = BlobContainerPublicAccessType.Blob
                    });
                    container.Metadata["ImageLibraryDescription"] = "Image tile library for PhotoMosaics";
                    container.SetMetadata();
                    this.Invoke((Action)(() => lbStatus.Items.Add(String.Format("Container '{0}' created (or already existed)", i.ContainerName))));

                    // loop through photos in collection
                    foreach (var p in i.PhotoEnumerator().Take(IMAGES_MAXPERLIBRARY))
                    {
                        // convert to URI (could be local path or URI)
                        var uri = new Uri(p.Path);

                        try
                        {
                            // get a memory stream
                            using (var memStream = new MemoryStream())
                            {
                                // get file contents as memory stream
                                if (uri.IsFile)
                                {
                                    var fs = new FileStream(p.Path, FileMode.Open, FileAccess.Read);
                                    fs.CopyTo(memStream);
                                }
                                else
                                {
                                    var request  = WebRequest.Create(p.Path);
                                    var response = request.GetResponse();
                                    response.GetResponseStream().CopyTo(memStream);
                                }

                                // upload to blob
                                var blobRef = new CloudBlob(String.Format("{0}/{1}", i.ContainerName.ToLower(), p.Id), cbc);
                                blobRef.Properties.ContentType  = "image/jpeg";
                                blobRef.Metadata["ImageSource"] = p.Path;
                                blobRef.UploadByteArray(memStream.GetBuffer());
                            }
                            this.Invoke((Action)(() => lbStatus.Items.Add(String.Format("  Added photo '{0}'", p.Path))));
                        }
                        catch (Exception e)
                        {
                            this.Invoke((Action)(() => lbStatus.Items.Add(e.Message)));
                        }
                    }
                }
                catch (StorageClientException sce)
                {
                    this.Invoke((Action)(() => lbStatus.Items.Add(String.Format("{0} [container: {1}]", sce.Message, i.ContainerName))));
                }
                catch (Exception e)
                {
                    this.Invoke((Action)(() => lbStatus.Items.Add(String.Concat("  ", e.Message))));
                }
            }

            this.Invoke((Action)(() => lbStatus.Items.Add("**** CREATE LIBRARY COMPLETED ****")));
        }
예제 #31
0
        private MediaData CreateNewFile(InRiverImportResource inriverResource)
        {
            ResourceMetaField resourceFileId = inriverResource.MetaFields.FirstOrDefault(m => m.Id == "ResourceFileId");

            if (String.IsNullOrEmpty(resourceFileId?.Values.FirstOrDefault()?.Data))
            {
                _logger.Debug("ResourceFileId is null, won't do stuff.");
                return(null);
            }

            _logger.Debug($"Attempting to create and import file from path: {inriverResource.Path}");

            var fileInfo = new FileInfo(inriverResource.Path);

            IEnumerable <Type> mediaTypes = _contentMediaResolver.ListAllMatching(fileInfo.Extension).ToList();

            _logger.Debug($"Found {mediaTypes.Count()} matching media types for extension {fileInfo.Extension}.");

            Type contentTypeType = mediaTypes.FirstOrDefault(x => x.GetInterfaces().Contains(typeof(IInRiverResource))) ??
                                   _contentMediaResolver.GetFirstMatching(fileInfo.Extension);

            if (contentTypeType == null)
            {
                _logger.Warning($"Can't find suitable content type when trying to import {inriverResource.Path}");
            }

            else
            {
                _logger.Debug($"Chosen content type-type is {contentTypeType.Name}.");
            }

            ContentType contentType = _contentTypeRepository.Load(contentTypeType);

            var newFile = _contentRepository.GetDefault <MediaData>(GetFolder(fileInfo, contentType), contentType.ID);

            newFile.Name        = fileInfo.Name;
            newFile.ContentGuid = EpiserverEntryIdentifier.EntityIdToGuid(inriverResource.ResourceId);

            // ReSharper disable once SuspiciousTypeConversion.Global
            if (newFile is IInRiverResource resource)
            {
                resource.ResourceFileId = Int32.Parse(resourceFileId.Values.First().Data);
                resource.EntityId       = inriverResource.ResourceId;

                try
                {
                    resource.HandleMetaData(inriverResource.MetaFields);
                }
                catch (Exception exception)
                {
                    _logger.Error($"Error when running HandleMetaData for resource {inriverResource.ResourceId} with contentType {contentType.Name}: {exception.Message}");
                }
            }

            Blob blob = _blobFactory.CreateBlob(newFile.BinaryDataContainer, fileInfo.Extension);

            using (Stream stream = blob.OpenWrite())
            {
                FileStream fileStream = File.OpenRead(fileInfo.FullName);
                fileStream.CopyTo(stream);
                fileStream.Dispose();
            }

            newFile.BinaryData = blob;

            _logger.Debug($"New mediadata is ready to be saved: {newFile.Name}, from path {inriverResource.Path}");

            ContentReference contentReference = _contentRepository.Save(newFile, SaveAction.Publish, AccessLevel.NoAccess);
            var mediaData = _contentRepository.Get <MediaData>(contentReference);

            _logger.Debug($"Saved file {fileInfo.Name} with Content ID {contentReference?.ID}.");

            return(mediaData);
        }
예제 #32
0
        public override void handleGETRequest(HttpProcessor p)
        {
            string pageLower = p.requestedPage.ToLower();

            if (p.requestedPage == "randomdata")
            {
                p.writeSuccess("application/x-binary");
                p.outputStream.Flush();

                int testSec = p.GetIntParam("testsec", 5);
                testSec = BPMath.Clamp(testSec, 1, 30);

                long   endTime    = sw.ElapsedMilliseconds + (long)TimeSpan.FromSeconds(testSec).TotalMilliseconds;
                byte[] randomData = StaticRandom.NextBytes(p.tcpClient.SendBufferSize);
                while (sw.ElapsedMilliseconds < endTime)
                {
                    p.tcpStream.Write(randomData, 0, randomData.Length);
                }
            }
            else if (p.requestedPage == "nstws")
            {
                wss.AcceptIncomingConnection(p.tcpClient);
            }
            else if (p.requestedPage == "HEADERS")
            {
                p.writeSuccess("text/plain");
                p.outputStream.Write(string.Join(Environment.NewLine, p.httpHeadersRaw.Select(h => h.Key + ": " + h.Value)));
            }
            else if (p.requestedPage == "IP")
            {
                p.writeSuccess("text/plain");
                p.outputStream.Write(p.RemoteIPAddressStr);
            }
            else
            {
                if (p.requestedPage == "")
                {
                    p.requestedPage = "default.html";
                }

                string wwwPath = Globals.ApplicationDirectoryBase + "www/";
#if DEBUG
                if (System.Diagnostics.Debugger.IsAttached)
                {
                    wwwPath = Globals.ApplicationDirectoryBase + "../../www/";
                }
#endif
                DirectoryInfo WWWDirectory     = new DirectoryInfo(wwwPath);
                string        wwwDirectoryBase = WWWDirectory.FullName.Replace('\\', '/').TrimEnd('/') + '/';
                FileInfo      fi             = new FileInfo(wwwDirectoryBase + p.requestedPage);
                string        targetFilePath = fi.FullName.Replace('\\', '/');
                if (!targetFilePath.StartsWith(wwwDirectoryBase) || targetFilePath.Contains("../"))
                {
                    p.writeFailure("400 Bad Request");
                    return;
                }
                if (!fi.Exists)
                {
                    return;
                }
                if ((fi.Extension == ".html" || fi.Extension == ".htm") && fi.Length < 256000)
                {
                    string html = File.ReadAllText(fi.FullName);
                    html = html.Replace("%%VERSION%%", System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString());
                    html = html.Replace("%%RND%%", rnd.ToString());

                    byte[] data = Encoding.UTF8.GetBytes(html);
                    p.writeSuccess(Mime.GetMimeType(fi.Extension), data.Length);
                    p.outputStream.Flush();
                    p.tcpStream.Write(data, 0, data.Length);
                    p.tcpStream.Flush();
                }
                else
                {
                    string mime = Mime.GetMimeType(fi.Extension);
                    if (pageLower.StartsWith(".well-known/acme-challenge/"))
                    {
                        mime = "text/plain";
                    }
                    if (fi.LastWriteTimeUtc.ToString("R") == p.GetHeaderValue("if-modified-since"))
                    {
                        p.writeSuccess(mime, -1, "304 Not Modified");
                        return;
                    }
                    p.writeSuccess(mime, fi.Length, additionalHeaders: GetCacheLastModifiedHeaders(TimeSpan.FromHours(1), fi.LastWriteTimeUtc));
                    p.outputStream.Flush();
                    using (FileStream fs = fi.OpenRead())
                    {
                        fs.CopyTo(p.tcpStream);
                    }
                    p.tcpStream.Flush();
                }
            }
        }
예제 #33
0
        private static void SystemDBSync(HttpListenerContext context)
        {
            try
            {
                if (!Config.AllowSystemDBSync)
                {
                    SEnvir.Log($"Trying sync but not enabled");
                    context.Response.StatusCode = 401;
                    return;
                }

                if (context.Request.HttpMethod != "POST" || !context.Request.HasEntityBody)
                {
                    SEnvir.Log($"Trying sync but method is not post or not have body");
                    context.Response.StatusCode = 401;
                    return;
                }

                if (context.Request.ContentLength64 > 1024 * 1024 * 10)
                {
                    SEnvir.Log($"Trying sync but exceeded SystemDB size");
                    context.Response.StatusCode = 400;
                    return;
                }

                var masterPassword = context.Request.QueryString["Key"];
                if (string.IsNullOrEmpty(masterPassword) || !masterPassword.Equals(Config.SyncKey))
                {
                    SEnvir.Log($"Trying sync but key received is not valid");
                    context.Response.StatusCode = 400;
                    return;
                }

                SEnvir.Log($"Starting remote syncronization...");

                var buffer     = new byte[context.Request.ContentLength64];
                var offset     = 0;
                var length     = 0;
                var bufferSize = 1024 * 16;

                while ((length = context.Request.InputStream.Read(buffer, offset, offset + bufferSize > buffer.Length ? buffer.Length - offset : bufferSize)) > 0)
                {
                    offset += length;
                }

                if (SEnvir.Session.BackUp && !Directory.Exists(SEnvir.Session.SystemBackupPath))
                {
                    Directory.CreateDirectory(SEnvir.Session.SystemBackupPath);
                }

                if (File.Exists(SEnvir.Session.SystemPath))
                {
                    if (SEnvir.Session.BackUp)
                    {
                        using (FileStream sourceStream = File.OpenRead(SEnvir.Session.SystemPath))
                            using (FileStream destStream = File.Create(SEnvir.Session.SystemBackupPath + "System " + SEnvir.Session.ToBackUpFileName(DateTime.UtcNow) + Session.Extension + Session.CompressExtension))
                                using (GZipStream compress = new GZipStream(destStream, CompressionMode.Compress))
                                    sourceStream.CopyTo(compress);
                    }

                    File.Delete(SEnvir.Session.SystemPath);
                }

                File.WriteAllBytes(SEnvir.Session.SystemPath, buffer);

                context.Response.StatusCode = 200;

                SEnvir.Log($"Syncronization completed...");
            }
            catch (Exception ex)
            {
                context.Response.StatusCode  = 500;
                context.Response.ContentType = "text/plain";
                var message = Encoding.UTF8.GetBytes(ex.ToString());
                context.Response.OutputStream.Write(message, 0, message.Length);
                SEnvir.Log("Syncronization exception: " + ex.ToString());
            }
            finally
            {
                context.Response.Close();
            }
        }
예제 #34
0
        /// <summary>
        /// original name + ".part_N.X" (N = file part number, X = total files)
        /// Objective = enumerate files in folder, look for all matching parts of split file. If found, merge and return true.
        /// </summary>
        /// <param name="FileName"></param>
        /// <returns></returns>
        public bool MergeFile(string FileName)
        {
            bool rslt = false;
            // parse out the different tokens from the filename according to the convention
            string partToken      = ".part_";
            string baseFileName   = FileName.Substring(0, FileName.IndexOf(partToken));
            string trailingTokens = FileName.Substring(FileName.IndexOf(partToken) + partToken.Length);
            int    FileIndex      = 0;
            int    FileCount      = 0;

            int.TryParse(trailingTokens.Substring(0, trailingTokens.IndexOf(".")), out FileIndex);
            int.TryParse(trailingTokens.Substring(trailingTokens.IndexOf(".") + 1), out FileCount);
            // get a list of all file parts in the temp folder
            string Searchpattern = Path.GetFileName(baseFileName) + partToken + "*";

            string[] FilesList = Directory.GetFiles(Path.GetDirectoryName(FileName), Searchpattern);
            //  merge .. improvement would be to confirm individual parts are there / correctly in sequence, a security check would also be important
            // only proceed if we have received all the file chunks
            if (FilesList.Count() == FileCount)
            {
                // use a singleton to stop overlapping processes
                if (!MergeFileManager.Instance.InUse(baseFileName))
                {
                    MergeFileManager.Instance.AddFile(baseFileName);
                    if (File.Exists(baseFileName))
                    {
                        File.Delete(baseFileName);
                    }
                    // add each file located to a list so we can get them into
                    // the correct order for rebuilding the file
                    List <SortedFile> MergeList = new List <SortedFile>();
                    foreach (string File in FilesList)
                    {
                        SortedFile sFile = new SortedFile();
                        sFile.FileName = File;
                        baseFileName   = File.Substring(0, File.IndexOf(partToken));
                        trailingTokens = File.Substring(File.IndexOf(partToken) + partToken.Length);
                        int.TryParse(trailingTokens.Substring(0, trailingTokens.IndexOf(".")), out FileIndex);
                        sFile.FileOrder = FileIndex;
                        MergeList.Add(sFile);
                    }
                    // sort by the file-part number to ensure we merge back in the correct order
                    var MergeOrder = MergeList.OrderBy(s => s.FileOrder).ToList();
                    using (FileStream FS = new FileStream(baseFileName, FileMode.Create))
                    {
                        // merge each file chunk back into one contiguous file stream
                        foreach (var chunk in MergeOrder)
                        {
                            try
                            {
                                using (FileStream fileChunk = new FileStream(chunk.FileName, FileMode.Open))
                                {
                                    fileChunk.CopyTo(FS);
                                }
                            }
                            catch (IOException ex)
                            {
                                // handle
                            }
                        }
                    }
                    rslt = true;
                    // unlock the file from singleton
                    MergeFileManager.Instance.RemoveFile(baseFileName);
                }
            }
            return(rslt);
        }
예제 #35
0
 public static void Write(ulong PhysicalAddress,string Filename)
 {
     using (FileStream stream = new FileStream(Filename,FileMode.Open))
     using (ASMMap_MapMem mapper = new ASMMap_MapMem(PhysicalAddress,(uint)stream.Length)) {
         Console.WriteLine("[+] Writing block of memory...");
         stream.CopyTo(mapper.PhysicalMemoryBlock);
     }
 }
예제 #36
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            if (Request.Form["ExportType"] != null && Request.Form["filename"] != null)
            {
                string tSvg = string.Empty;
                string tType = Request.Form["ExportType"].ToString();
                string tFileName = Request.Form["filename"].ToString();
                string TempPath = HttpContext.Current.Request.PhysicalApplicationPath + Constants.FolderName.TempCYV;

                tFileName = Global.GetValidFileName(tFileName);

                MemoryStream tStream = new MemoryStream();
                string tTmp = new Random().Next().ToString();

                string tExt = string.Empty;
                string tTypeString = string.Empty;
                string dbNid = string.Empty;
                string langCode = string.Empty;
                float height = 0, width = 0;
                bool includeLegend = false;
                string ThemeId = string.Empty;

                switch (tType)
                {
                    case "image":
                        if (Request.Form["extension"] != null)
                        {
                            tExt = Request.Form["extension"].ToString();
                        }
                        else
                        {
                            tExt = "png";
                        }

                        switch (tExt)
                        {
                            case "png":
                                tTypeString = "-m image/png";
                                break;
                            case "gif":
                                tTypeString = "-m image/gif";
                                break;
                            case "jpg":
                                tTypeString = "-m image/jpeg";
                                break;
                            case "bmp":
                                tTypeString = "-m image/x-ms-bmp";
                                break;
                            default:
                                tTypeString = "-m image/png";
                                tExt = "png";
                                break;
                        }

                        break;
                    case "kmz":
                        tTypeString = "application/vnd.google-earth.kmz kmz";
                        tExt = "kmz";
                        break;
                    case "excel":
                        tTypeString = "application/vnd.xls";
                        tExt = "xls";
                        break;
                    case "legendinfo":
                        tTypeString = "text/xml";
                        tExt = "xml";
                        break;
                }

                if (tTypeString != "")
                {
                    string tWidth = string.Empty;
                    Svg.SvgDocument tSvgObj = null;
                    tSvgObj = new SvgDocument();

                    switch (tExt)
                    {
                        case "png":
                        case "jpg":
                        case "bmp":
                        case "gif":
                            if (Request.Form["height"] != null)
                            {
                                height = float.Parse(Request.Form["height"]);
                            }

                            if (Request.Form["width"] != null)
                            {
                                width = float.Parse(Request.Form["width"].ToString());
                            }

                            if (Request.Form["includelegend"] != null)
                            {
                                includeLegend = Convert.ToBoolean(Request.Form["includelegend"].ToString());
                            }
                            else
                            { includeLegend = true; }
                            if (Request.Form["themeId"] != null)
                            {
                                tStream = this.ExportZippedPngMaps(tExt, includeLegend, height, width);
                                if (tFileName.Contains("("))
                                {
                                    tFileName = tFileName.Remove(tFileName.LastIndexOf("("));
                                }
                                tExt = "zip";
                            }
                            else
                            {
                               this.ExportPngMap(tStream, tExt, includeLegend, height, width);
                            }
                            break;
                        case "kmz":
                            if (Request.Form["includelegend"] != null)
                            {
                                includeLegend = Convert.ToBoolean(Request.Form["includelegend"].ToString());
                            }
                            else
                            { includeLegend = true; }

                            this.ExportKMZMap(tStream, includeLegend);
                            break;
                        case "xls":
                            if (Request.Form["dbnid"] != null)
                            {
                                dbNid = Request.Form["dbnid"].ToString();
                            }
                            else
                            {
                                dbNid = Global.GetDefaultDbNId();
                            }
                            if (Request.Form["langCode"] != null)
                            {
                                langCode = Request.Form["langCode"].ToString();
                            }
                            else
                            {
                                langCode = Global.GetDefaultLanguageCode();
                            }

                            MemoryStream excelStream = new MemoryStream();
                            if (Request.Form["themeId"] != null)
                            {
                                if (tFileName.Contains("("))
                                {
                                    tFileName = tFileName.Remove(tFileName.LastIndexOf("("));
                                }
                            }
                            this.ExportExcelMap(excelStream);
                            tStream = Global.GetZipFileStream(excelStream, tFileName + "." + tExt + "");
                            //tStream = Global.GetZipFileStream(excelStream, tFileName + "." + tExt + "", TempPath);
                            tExt = "zip";
                            excelStream.Dispose();
                            break;
                        case "xml":
                            if (tType == "legendinfo")
                            {
                                if (Request.Form["themeId"] != null)
                                {
                                    ThemeId = Request.Form["themeId"].ToString();
                                }

                                if (!string.IsNullOrEmpty(ThemeId))
                                {
                                    FileStream fs = new FileStream(this.DownloadLegends(ThemeId, tFileName), FileMode.Open);
                                    fs.CopyTo(tStream);
                                }
                            }
                            break;
                    }

                    //tFileName = Global.GetValidFileNameURLSupport(tFileName, "_");

                    Response.ClearContent();
                    Response.ClearHeaders();
                    Response.ContentType = tTypeString;
                    Response.AppendHeader("Content-Disposition", "attachment; filename=\"" + tFileName + "." + tExt + "\"");
                    Response.BinaryWrite(tStream.ToArray());
                    Response.End();

                }
            }
        }
    }