Beispiel #1
1
        public void CheckMail()
        {
            try
            {
                string processLoc = dataActionsObject.getProcessingFolderLocation();
                StreamWriter st = new StreamWriter("C:\\Test\\_testings.txt");
                string emailId = "*****@*****.**";// ConfigurationManager.AppSettings["UserName"].ToString();
                if (emailId != string.Empty)
                {
                    st.WriteLine(DateTime.Now + " " + emailId);
                    st.Close();
                    ExchangeService service = new ExchangeService();
                    service.Credentials = new WebCredentials(emailId, "Sea2013");
                    service.UseDefaultCredentials = false;
                    service.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");
                    Folder inbox = Folder.Bind(service, WellKnownFolderName.Inbox);
                    SearchFilter sf = new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false));
                    if (inbox.UnreadCount > 0)
                    {
                        ItemView view = new ItemView(inbox.UnreadCount);
                        FindItemsResults<Item> findResults = inbox.FindItems(sf, view);
                        PropertySet itempropertyset = new PropertySet(BasePropertySet.FirstClassProperties, EmailMessageSchema.From, EmailMessageSchema.ToRecipients);
                        itempropertyset.RequestedBodyType = BodyType.Text;
                        //inbox.UnreadCount
                        ServiceResponseCollection<GetItemResponse> items = service.BindToItems(findResults.Select(item => item.Id), itempropertyset);
                        MailItem[] msit = getMailItem(items, service);

                        foreach (MailItem item in msit)
                        {
                            item.message.IsRead = true;
                            item.message.Update(ConflictResolutionMode.AlwaysOverwrite);
                            foreach (Attachment attachment in item.attachment)
                            {
                                if (attachment is FileAttachment)
                                {
                                    string extName = attachment.Name.Substring(attachment.Name.LastIndexOf('.'));
                                    FileAttachment fileAttachment = attachment as FileAttachment;
                                    FileStream theStream = new FileStream(processLoc + fileAttachment.Name, FileMode.OpenOrCreate, FileAccess.ReadWrite);
                                    fileAttachment.Load(theStream);
                                    byte[] fileContents;
                                    MemoryStream memStream = new MemoryStream();
                                    theStream.CopyTo(memStream);
                                    fileContents = memStream.GetBuffer();
                                    theStream.Close();
                                    theStream.Dispose();
                                    Console.WriteLine("Attachment name: " + fileAttachment.Name + fileAttachment.Content + fileAttachment.ContentType + fileAttachment.Size);
                                }
                            }
                        }
                    }
                    DeleteMail(emailId);
                }
            }
            catch (Exception ex)
            {

            }
        }
Beispiel #2
0
        protected void FlushResponse(HttpListenerContext context, FileStream stream)
        {
            if (stream.Length > 1024
                && context.Request.Headers.AllKeys.Contains("Accept-Encoding")
                && context.Request.Headers["Accept-Encoding"].Contains("gzip"))
            {
                using (var ms = new MemoryStream())
                {
                    using (var zip = new GZipStream(ms, CompressionMode.Compress, true))
                    {
                        stream.CopyTo( zip );
                    }
                    ms.Position = 0;

                    context.Response.AddHeader("Content-Encoding", "gzip");
                    context.Response.ContentLength64 = ms.Length;
                    ms.WriteTo( context.Response.OutputStream );
                 }
            }
            else
            {
                context.Response.ContentLength64 = stream.Length;
                stream.CopyTo( context.Response.OutputStream );
            }

            context.Response.OutputStream.Close();
            context.Response.Close();
        }
Beispiel #3
0
        /// <summary>
        /// Saves the data source to the specified stream.
        /// </summary>
        /// <param name="stream">The stream.</param>
        protected override void SaveCore(Stream stream)
        {
            stream = Enforce.NotNull(stream, () => stream);

            // Copy the input stream to the output stream.
            try
            {
                string absolutepath = this.Mapping.Uri.AbsolutePath;

                string rootSign = "~";
                if (!absolutepath.StartsWith(rootSign))
                {
                    absolutepath = string.Concat(rootSign, absolutepath);
                }

                string mapped = HostingEnvironment.MapPath((absolutepath));

                var response = this.Container.Resolve<IRuntimeContext>().HttpResponse;

                using (FileStream inputStream =
                    new FileStream(mapped, FileMode.Open))
                {
                    response.AddHeader("content-length", inputStream.Length.ToString(CultureInfo.InvariantCulture));
                    inputStream.CopyTo(stream,
                        () => response.IsClientConnected,
                        () => this.OnDownloadFinished(new DownloadFinishedEventArgs { Mapping = this.Mapping, State = DownloadFinishedState.Succeeded }),
                        () => this.OnDownloadFinished(new DownloadFinishedEventArgs { Mapping = this.Mapping, State = DownloadFinishedState.Canceled }));
                }
            }
            catch (FileNotFoundException ex)
            {
                throw new SilkveilException(
                    String.Format(CultureInfo.CurrentCulture,
                        "The data source '{0}' could not be read.", this.Mapping.Uri), ex);
            }
            catch (DirectoryNotFoundException ex)
            {
                throw new SilkveilException(
                    String.Format(CultureInfo.CurrentCulture,
                        "The data source '{0}' could not be read.", this.Mapping.Uri), ex);
            }
            catch (PathTooLongException ex)
            {
                throw new SilkveilException(
                    String.Format(CultureInfo.CurrentCulture,
                        "The data source '{0}' could not be read.", this.Mapping.Uri), ex);
            }
            catch (IOException ex)
            {
                throw new SilkveilException(
                    String.Format(CultureInfo.CurrentCulture,
                        "The data source '{0}' could not be read.", this.Mapping.Uri), ex);
            }
            catch (SecurityException ex)
            {
                throw new SilkveilException(
                    String.Format(CultureInfo.CurrentCulture,
                        "The data source '{0}' could not be read.", this.Mapping.Uri), ex);
            }
        }
Beispiel #4
0
 public static void RenderExternalJavascript(Stream responseStream, IRootPathProvider rootPath)
 {
     using (var js = new FileStream(Path.Combine(rootPath.GetRootPath(), "content/external.js"), FileMode.Open))
     {
         js.CopyTo(responseStream);
     }
 }
Beispiel #5
0
        private void barButtonItem1_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                string reportruta = result + "save.repx";
                xrDesignDockManager1.XRDesignPanel.SaveReport(reportruta);

                Byte[] data;
                using (System.IO.FileStream FL = new System.IO.FileStream(reportruta, System.IO.FileMode.Open))
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        FL.CopyTo(ms);
                        data = ms.ToArray();
                    }
                }
                InfoDoc_x_Emp.File_Disenio_Reporte = data;
                String Mensajes = "";
                if (busDoc_x_Emp.GuardarDatos(InfoDoc_x_Emp, ref Mensajes))
                {
                    MessageBox.Show("Se Guardo Exitosamente el Diseño", "SISTEMA", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    MessageBox.Show(Mensajes, "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                Log_Error_bus.Log_Error(ex.ToString());
                MessageBox.Show(ex.Message, param.Nombre_sistema, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        public void DecryptFile(string sourceFilename, string destinationFilename, string password)
        {
            AesManaged aes = new AesManaged();
            aes.BlockSize = aes.LegalBlockSizes[0].MaxSize;
            aes.KeySize = aes.LegalKeySizes[0].MaxSize;
            // NB: Rfc2898DeriveBytes initialization and subsequent calls to   GetBytes   must be eactly the same, including order, on both the encryption and decryption sides.
            Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(password, salt, iterations);
            aes.Key = key.GetBytes(aes.KeySize / 8);
            aes.IV = key.GetBytes(aes.BlockSize / 8);
            aes.Mode = CipherMode.CBC;
            ICryptoTransform transform = aes.CreateDecryptor(aes.Key, aes.IV);

            using (FileStream destination = new FileStream(destinationFilename, FileMode.CreateNew, FileAccess.Write, FileShare.None))
            {
                using (CryptoStream cryptoStream = new CryptoStream(destination, transform, CryptoStreamMode.Write))
                {
                    try
                    {
                        using (FileStream source = new FileStream(sourceFilename, FileMode.Open, FileAccess.Read, FileShare.Read))
                        {
                            source.CopyTo(cryptoStream);
                        }
                    }
                    catch (CryptographicException exception)
                    {
                        if (exception.Message == "Padding is invalid and cannot be removed.")
                            throw new ApplicationException("Universal Microsoft Cryptographic Exception (Not to be believed!)", exception);
                        else
                            throw;
                    }
                }
            }
        }
Beispiel #7
0
 internal void Load(string filePath)
 {
     FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read);
     file.CopyTo(this.stream);
     file.Close();
     this.Seek(0, SeekOrigin.Begin); //Reset stream position to the beginning where the reading should start
 }
Beispiel #8
0
        private void MenuItem_Click(object sender, RoutedEventArgs e)
        {
            // 画像を開く
            var dialog = new OpenFileDialog();
            dialog.Filter = "画像|*.jpg;*.jpeg;*.png;*.bmp";
            if (dialog.ShowDialog() != true)
            {
                return;
            }

            // ファイルをメモリにコピー
            var ms = new MemoryStream();
            using (var s = new FileStream(dialog.FileName, FileMode.Open))
            {
                s.CopyTo(ms);
            }
            // ストリームの位置をリセット
            ms.Seek(0, SeekOrigin.Begin);
            // ストリームをもとにBitmapImageを作成
            var bmp = new BitmapImage();
            bmp.BeginInit();
            bmp.StreamSource = ms;
            bmp.EndInit();
            // BitmapImageをSourceに指定して画面に表示する
            this.image.Source = bmp;
        }
        public void ReadBlocksWithMemoryStream()
        {
            var resources = new Dictionary<string, Resource>();
            var path = Path.Combine(TestContext.CurrentContext.TestDirectory, "Files");
            var files = Directory.GetFiles(path, "*.*_c");

            if (files.Length == 0)
            {
                Assert.Fail("There are no files to test.");
            }

            foreach (var file in files)
            {
                var resource = new Resource();

                var fs = new FileStream(file, FileMode.Open, FileAccess.Read);
                var ms = new MemoryStream();
                fs.CopyTo(ms);
                ms.Seek(0, SeekOrigin.Begin);

                resource.Read(ms);

                resources.Add(Path.GetFileName(file), resource);
            }

            VerifyResources(resources);
        }
Beispiel #10
0
        static void Main(string[] args)
        {
            HttpWebRequest request = (HttpWebRequest) WebRequest.Create(Url);
            HttpWebResponse response = (HttpWebResponse) request.GetResponse();

            using (var stream = response.GetResponseStream())
            {
                var ms = new MemoryStream();
                stream.CopyTo(ms);
                var buff = ms.ToArray();
            //                var image = Image.FromStream(stream);
            //                image.Save("text.jpg");
            //                stream.Position = 0;
                string hash = GetHash(buff);
                File.WriteAllBytes("test.jpg",buff);

                using (var ms3 = new MemoryStream())
                {
                    using (var fs = new FileStream("test.jpg", FileMode.Open))
                    {
                        fs.CopyTo(ms3);
                        var buff2 = ms3.ToArray();
                        var hash2 = GetHash(buff2);
                    }
                }
                var h = GetHash(File.ReadAllBytes("test.jpg"));

                using (var sr = new StreamReader(stream))
                {
                    string text = sr.ReadToEnd();
                    Console.WriteLine(text);
                }
            }
            Console.ReadKey();
        }
        public bool Grabar(tb_Comprobante_tipo_Info Infocbte)
        {
            try
            {
                string reportruta = Ruta_Temporal + "saveComprobante.repx";
                xrDesignDockManager.XRDesignPanel.SaveReport(reportruta);
                Byte[] data;
                using (System.IO.FileStream FL = new System.IO.FileStream(reportruta, System.IO.FileMode.Open))
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        FL.CopyTo(ms);
                        data = ms.ToArray();
                    }
                }
                Infocbte.ReporteBy = data;

                Cbte_tipo_Info.IdEmpresa          = Infocbte.IdEmpresa;
                Cbte_tipo_Info.idComprobante_tipo = Infocbte.IdComprobante_tipo;
                Cbte_tipo_Info.File_disenio_rpt   = Infocbte.ReporteBy;

                if (Buscbte.ModificarDB(Cbte_tipo_Info, ref MensajeError))
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
        /// <summary>
        ///     Specifies the static image to use.
        /// </summary>
        /// <param name="imagePath">
        ///     The path to the image.
        /// </param>
        /// <exception cref="ArgumentNullException">
        ///     <paramref name="imagePath"/> is null <see cref="string.Empty"/>.
        /// </exception>
        /// <exception cref="SecurityException"></exception>
        /// <exception cref="FileNotFoundException"></exception>
        /// <exception cref="DirectoryNotFoundException"></exception>
        /// <exception cref="PathTooLongException"></exception>
        /// <exception cref="IOException"></exception>
        public StaticImageLoader WithImage(string imagePath)
        {
            if (string.IsNullOrWhiteSpace(imagePath))
            {
                throw new ArgumentNullException("imagePath");
            }

            using (var memoryStream = new MemoryStream())
            {
                using (var fileStream = new FileStream(imagePath, FileMode.Open))
                {
                    fileStream.CopyTo(memoryStream);
                }

                if (memoryStream.Length > 0)
                {
                    imageData = memoryStream.ToArray();
                }
                else
                {
                    throw new IOException(string.Format("The image file '{0}' is empty", imagePath));
                }
            }

            return this;
        }
Beispiel #13
0
        public virtual void Configure()
        {
            try {
                using (var MSM = new io.MemoryStream()) {
                    using (var stm = new io.FileStream(PTH, io.FileMode.Open)) {
                        stm.CopyTo(MSM);
                    }

                    MSM.Position = 0;

                    using (var rdr = new io.StreamReader(MSM)) {
                        LVAL.Clear();
                        while (!rdr.EndOfStream)
                        {
                            if (this.tryParse(rdr.ReadLine(), out input val))
                            {
                                LVAL.Add(val);
                            }
                        }
                    }
                }
            }
            catch (Exception ex) { throw new io.FileLoadException("Unable to read configuration file '" + PTH + "'", PTH, ex); }

            var enm = LVAL.GetEnumerator();

            while (enm.MoveNext())
            {
                var itm = enm.Current;
                this.setParameter(itm.Section, itm.Key, itm.Value);
            }
        }
Beispiel #14
0
        public static byte[] GetByteArrayFromFile(string logoFile)
        {
            var logoData = new byte[0];

            try
            {
                if (File.Exists(logoFile))
                {
                    using (var fileStream = new FileStream(logoFile, FileMode.Open))
                    {
                        using (var ms = new MemoryStream())
                        {
                            fileStream.CopyTo(ms);
                            logoData = ms.ToArray();
                        }
                    }
                }

            }
            catch (Exception)
            {
               //Log
            }

            return logoData;
        }
Beispiel #15
0
 public void WriteFile(string file)
 {
     using (var fileStream = new FileStream(file, FileMode.Open))
     {
         Write(stream => fileStream.CopyTo(stream, 64000));
     }
 }
Beispiel #16
0
        static void Main(string[] args)
        {
            const int minimumFileLength = 65*1024;

            string inputFileName = null;
            if (args.Length >= 1) inputFileName = args[0];
            else
            {
                Console.WriteLine(@"Укажите путь к входному файлу");
                inputFileName = Console.ReadLine();
            }

            string outputFilePath = Path.Combine(Path.GetDirectoryName(inputFileName), "1.otl");

            using (
                Stream inputStream = new FileStream(inputFileName, FileMode.Open),
                    outputStream = new FileStream(outputFilePath, FileMode.Create),
                    headerStream = new MemoryStream(Resources.header)
                )
            {
                headerStream.CopyTo(outputStream);
                inputStream.CopyTo(outputStream);
                while (outputStream.Length < minimumFileLength) outputStream.WriteByte(0xff);
            }
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Готово");
            Console.ResetColor();
            Console.ReadLine();
        }
Beispiel #17
0
 public override bool Execute()
 {
     // Originally taken from https://peteris.rocks/blog/creating-release-zip-archive-with-msbuild/
       // Then modified not to be inline anymore
       try
       {
     using (Stream zipStream = new FileStream(Path.GetFullPath(OutputFilename), FileMode.Create, FileAccess.Write))
     using (ZipArchive archive = new ZipArchive(zipStream, ZipArchiveMode.Create))
     {
       foreach (ITaskItem fileItem in Files)
       {
     string filename = fileItem.ItemSpec;
     using (Stream fileStream = new FileStream(filename, FileMode.Open, FileAccess.Read))
     using (Stream fileStreamInZip = archive.CreateEntry(new FileInfo(filename).Name).Open())
       fileStream.CopyTo(fileStreamInZip);
       }
     }
     return true;
       }
       catch (Exception ex)
       {
     Log.LogErrorFromException(ex);
     return false;
       }
 }
Beispiel #18
0
        private void buttonBrowse_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();

            openFileDialog1.Filter = "GIF Files|*.gif";
            openFileDialog1.Title  = "Select a GIF File";

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                textBoxPath.Text = openFileDialog1.FileName;

                using (var fs = new System.IO.FileStream(openFileDialog1.FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read))
                {
                    var ms = new System.IO.MemoryStream();
                    fs.CopyTo(ms);
                    ms.Position = 0;

                    if (pictureBoxSource.Image != null)
                    {
                        pictureBoxSource.Image.Dispose();
                    }

                    pictureBoxSource.Image = Image.FromStream(ms);
                }
            }
        }
Beispiel #19
0
        private void barButtonItem2_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                string reportruta = result + "save.repx";
                xrDesignDockManager1.XRDesignPanel.SaveReport(reportruta);

                Byte[] data;
                using (System.IO.FileStream FL = new System.IO.FileStream(reportruta, System.IO.FileMode.Open))
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        FL.CopyTo(ms);
                        data = ms.ToArray();
                    }
                }
                cuenta_i.Reporte = data;
                cuenta_b.ModificarDB(cuenta_i);
            }
            catch (Exception ex)
            {
                Log_Error_bus.Log_Error(ex.ToString());
                MessageBox.Show(ex.Message, param.Nombre_sistema, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
		public MemoryStream CompressVideo( string sourceFilePath, string destinationFilePath, bool deleteSourceFile )
		{
			
			try 
			{
				string downloadPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
				string fileName = Path.GetFileNameWithoutExtension( sourceFilePath ) + ".mp4";
				string downloadFilePath = Path.Combine(downloadPath, fileName );

				var asset = AVAsset.FromUrl( NSUrl.FromFilename( sourceFilePath ) );

				AVAssetExportSession export = new AVAssetExportSession (asset, AVAssetExportSession.PresetLowQuality );

				export.OutputUrl = NSUrl.FromFilename( downloadFilePath );
				export.OutputFileType = AVFileType.Mpeg4;
				export.ShouldOptimizeForNetworkUse = true;

				export.ExportTaskAsync().Wait();

				MemoryStream ms = new MemoryStream();    
				FileStream file = new FileStream(  downloadFilePath, FileMode.Open, FileAccess.Read);
				file.CopyTo ( ms );
				file.Close();
				return ms;

			} 
			catch (Exception ex) 
			{
				System.Diagnostics.Debug.WriteLine ( ex.Message );
				return null;
			}

		
		}
        public void EncryptionTest()
        {
            var key = Encoding.ASCII.GetBytes("20121109joyetechjoyetech20128850");

            byte[] actual;
            using (var decFileStream = new FileStream("Evic11.dec", FileMode.Open, FileAccess.Read))
            using (var firmware = new Firmware(key))
            {
                decFileStream.CopyTo(firmware.Stream);
                firmware.UpdateHeader();

                actual = new byte[firmware.BaseStream.Length];
                firmware.BaseStream.Seek(0, SeekOrigin.Begin);
                firmware.BaseStream.Read(actual, 0, actual.Length);
            }

            byte[] expected;
            using (var encFileStream = new FileStream("Evic11.enc", FileMode.Open, FileAccess.Read))
            {
                expected = new byte[actual.Length];
                encFileStream.Read(expected, 0, expected.Length);
            }

            CollectionAssert.AreEquivalent(expected, actual);
        }
Beispiel #22
0
        /// <summary>
        /// Gets the dimensions of an image.
        /// </summary>
        /// <param name="path">The path of the image to get the dimensions of.</param>
        /// <param name="logger">The logger.</param>
        /// <returns>The dimensions of the specified image.</returns>
        /// <exception cref="ArgumentException">The image was of an unrecognised format.</exception>
        public static Size GetDimensions(string path, ILogger logger)
        {
            try
            {
                using (var fs = File.OpenRead(path))
                {
                    using (var binaryReader = new BinaryReader(fs))
                    {
                        return GetDimensions(binaryReader);
                    }
                }
            }
            catch
            {
                logger.Info("Failed to read image header for {0}. Doing it the slow way.", path);
            }

            // Buffer to memory stream to avoid image locking file
            using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                using (var memoryStream = new MemoryStream())
                {
                    fs.CopyTo(memoryStream);

                    // Co it the old fashioned way
                    using (var b = Image.FromStream(memoryStream, true, false))
                    {
                        return b.Size;
                    }
                }
            }
        }
Beispiel #23
0
        private void buttonBrowse_Click(object sender, EventArgs e)
        {
            // Displays an OpenFileDialog so the user can select a Gif file
            OpenFileDialog openFileDialog = new OpenFileDialog();

            openFileDialog.Filter = "GIF Files|*.gif";
            openFileDialog.Title  = "Select a GIF File";

            // Show th Dialog.
            // If the user clicked OK in the dialogue and a .GIF file was selected, open it.

            if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                textBoxPath.Text = openFileDialog.FileName;
                // show the gif image in the picture box
                using (var fs = new System.IO.FileStream(openFileDialog.FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read))
                {
                    var ms = new System.IO.MemoryStream();
                    fs.CopyTo(ms);
                    ms.Position = 0;
                    if (pictureBoxSource.Image != null)
                    {
                        pictureBoxSource.Image.Dispose();
                    }
                    pictureBoxSource.Image = Image.FromStream(ms);
                }
            }
        }
Beispiel #24
0
        public Stream GetImage(String name)
        {
            String modulePath = String.Format(@"{0}\resource\server\image\{1}", solution.SolutionFolder, name);

            if (System.IO.File.Exists(modulePath))
            {
                switch (new System.IO.FileInfo(modulePath).Extension.ToLower())
                {
                case "jpg":
                case "jpeg":
                    WebOperationContext.Current.OutgoingResponse.ContentType = "image/jpeg";
                    break;

                case "png":
                    WebOperationContext.Current.OutgoingResponse.ContentType = "image/png";
                    break;
                }

                System.IO.MemoryStream ms = new MemoryStream();
                using (System.IO.FileStream f = System.IO.File.OpenRead(modulePath))
                {
                    f.CopyTo(ms);
                }
                ms.Position = 0;
                return(ms);
            }
            else
            {
                return(null);
            }
        }
Beispiel #25
0
 public override void WriteTo(HttpListenerResponse resp)
 {
     base.WriteTo(resp);
     FileStream fs = new FileStream(_file, FileMode.Open);
     fs.CopyTo(resp.OutputStream);
     fs.Close();
 }
Beispiel #26
0
        public override bool Execute()
        {
            if (!System.IO.File.Exists(File))
            {
                Log.LogError("The specified file does not exist");
                return false;
            }

            string outpath;
            try
            {
                outpath = Path.GetFullPath(Destination);
            }
            catch (ArgumentException) { Log.LogError("Destination path is not a valid path"); return false; }
            catch (PathTooLongException) { Log.LogError("Destination path is exceeds maximum length"); return false; }
            catch (System.Security.SecurityException) { Log.LogError("Access to the destination was denied"); return false; }

            Log.LogMessage("Deflating file \"{0}\"", File);
            using (var deflate = new DeflateStream(new FileStream(outpath, FileMode.Create), CompressionMode.Compress))
                using (var fs = new FileStream(File, FileMode.Open,FileAccess.Read,FileShare.Read))
                    fs.CopyTo(deflate);

            Log.LogMessage("Deflated file has been placed at \"{1}\" ",File, Destination);
            return true;
        }
        public byte[] GetFont(string faceName)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                string ttfFile;

                if (fontfaceTofontfileMap.TryGetValue(faceName, out int idx))
                {
                    ttfFile = s_SupportedFonts[idx];
                }
                else if (s_SupportedFonts.Length > 0)
                {
                    ttfFile = s_SupportedFonts[0];
                }
                else
                {
                    throw new System.Exception("No Font Files Found");
                }

                using (System.IO.FileStream ttf = System.IO.File.OpenRead(ttfFile))
                {
                    ttf.CopyTo(ms);
                    ms.Position = 0;
                    return(ms.ToArray());
                }
            }
        }
Beispiel #28
0
 /// <summary>
 /// DoWork непосредственно выполняющий считывание указанного в диалоге открытия файл.
 /// Также он отправляет файл в первый по очереди сокет
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void backgroundLoadFileWorker_DoWork(object sender, DoWorkEventArgs e)
 {
     try {
         fs = new FileStream(openFileDialog1.FileName, FileMode.Open);
         using (MemoryStream memoryStream = new MemoryStream())
         {
             fs.CopyTo(memoryStream);
             memoryStream.Position = 0;
             MyListener list = new MyListener();
             list.Sender(memoryStream, g_host, g_port);
         }
         //Thread.Sleep(1000); //чтобы успеть посмотреть
         //fs.Close();
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message, "File operation failed",
         MessageBoxButtons.OK,
         MessageBoxIcon.Error);
     }
     finally
     {
         fs.Close();
     }
 }
        static void Main(string[] args)
        {
            string filepath = @"weapon_mg42.bnk"; //music

            //string[] bnkfiles = Directory.GetFiles(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "*.bnk", SearchOption.TopDirectoryOnly);

            BNK soundbank;

            //foreach (string bnk in bnkfiles)
            //{
            using (FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.Read))
                {
                    MemoryStream ms = new MemoryStream();
                    fs.CopyTo(ms);
                    soundbank = new BNK();
                    soundbank.LoadBNK(ms);
                    ms.Close();
                }

                //generate the same bnk
            using (FileStream fs = new FileStream(filepath + "_gen", FileMode.Create, FileAccess.Write))
                {
                    MemoryStream ms = new MemoryStream();
                    soundbank.GenerateBNK(ms);
                    ms.WriteTo(fs);
                    ms.Close();
                }
            //}
        }
Beispiel #30
0
        public override void handleGETRequest(HttpProcessor p)
        {
            Stream fs;

            try
            {
                if (p.http_url == "/" || p.http_url == "")
                {
                    p.http_url = "/index.html";
                }
                if (!AllowParentDirectory && p.http_url.Contains("../"))
                {
                    p.writeFailure();
                    return;
                }

                using (fs = new System.IO.FileStream(this.Root + HttpUtility.UrlDecode(p.http_url), System.IO.FileMode.Open, System.IO.FileAccess.Read, FileShare.ReadWrite))
                {
                    //p.writeSuccess();
                    fs.CopyTo(p.outputStream.BaseStream);
                    p.outputStream.BaseStream.Flush();
                }
            }
            catch (Exception e)
            {
                p.writeFailure();
                Console.WriteLine("Error: " + e.Message);
                throw;
            }
        }
 static void Main(string[] args)
 {
     using (FileStream filestream1 = new FileStream("..\\..\\temple.png",FileMode.Open,FileAccess.Read),
                       filestream2 = new FileStream("..\\..\\temple_copy.png",FileMode.OpenOrCreate,FileAccess.Write))
     {
         filestream1.CopyTo(filestream2);
     }
 }
        static void Main(string[] args)
        {
            var image = new FileStream("image.png", FileMode.Open);
            var newImage = new FileStream("newImage.png", FileMode.Create);

            image.CopyTo(newImage);
            newImage.Flush();
        }
Beispiel #33
0
        static void Main(string[] args)
        {
            Console.WriteLine("------------------------");
            Console.WriteLine(" Filr logfile collector");
            Console.WriteLine(" v1.01 [email protected]");
            Console.WriteLine("------------------------");

            if (!Directory.Exists(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Novell\\Filr")))
            {
                Console.WriteLine("");
                Console.WriteLine("Could not find Filr logfile directory!");
                Console.WriteLine("");
                Console.WriteLine("Press any key to exit . . .");
                Console.ReadKey(true);
                return;
            }

            string desktopPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "FilrLog_" + DateTime.Now.ToString("yyyyMMdd_HHmmss") + ".zip");

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

            var logFiles = Directory.GetFiles(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Novell\\Filr"), "*.log*");

            Console.WriteLine("");
            Console.WriteLine("zipping logfiles to " + desktopPath + " . . .");
            Console.WriteLine("");

            try {
                using (ZipArchive zip = ZipFile.Open(desktopPath, ZipArchiveMode.Create))
                {
                    foreach (var logFile in logFiles)
                    {
                        using (var stream = new FileStream(logFile, FileMode.Open, FileAccess.Read, FileShare.Delete | FileShare.ReadWrite))
                        {
                            var zipArchiveEntry = zip.CreateEntry(Path.GetFileName(logFile), CompressionLevel.Optimal);
                            using (var destination = zipArchiveEntry.Open())
                            {
                                stream.CopyTo(destination);
                                Console.WriteLine(zipArchiveEntry.FullName + " added");
                            }
                        }
                    }
                }
            } catch (Exception er)
            {
                Console.WriteLine("Error: " + er.Message);
            }

            Console.WriteLine("");
            Console.WriteLine("Done!");
            Console.WriteLine("");
            Console.WriteLine("Press any key to exit . . .");
            Console.ReadKey(true);
            return;
        }
 public void Save(Stream stream)
 {
     var tempFileName = Path.GetTempFileName();
     Surface.WriteToPng(tempFileName);
     using (var tempFile = new FileStream(tempFileName, FileMode.Create))
     {
         tempFile.CopyTo(stream);
     }
 }
Beispiel #35
0
 protected void Page_Load(object sender, EventArgs e)
 {
     var upload = Request.HttpMethod == "POST";
     if (upload && !Request.GetUser().OperateFiles)
     {
         Response.StatusCode = 401;
         return;
     }
     var data = upload ? Request.Form : Request.QueryString;
     string id = data["resumableIdentifier"], path = FileHelper.Combine
                 (RouteData.GetRelativePath(), data["resumableRelativePath"].ToValidPath(false)),
            filePath = FileHelper.GetFilePath(path), dataPath = FileHelper.GetDataFilePath(path),
            state = FileHelper.GetState(dataPath);
     Directory.CreateDirectory(Path.GetDirectoryName(filePath));
     Directory.CreateDirectory(Path.GetDirectoryName(dataPath));
     if (state != TaskType.UploadTask || state == TaskType.UploadTask && new UploadTask(path).Identifier != id)
     {
         FileHelper.Delete(path);
         File.WriteAllBytes(filePath, new byte[0]);
         try
         {
             new UploadTask(path, id, int.Parse(data["resumableTotalChunks"]),
                            long.Parse(data["resumableTotalSize"])).Save();
         }
         catch (IOException) { } // another save in progress
     }
     var index = int.Parse(data["resumableChunkNumber"]) - 1;
     if (upload)
     {
         string basePath = FileHelper.GetDataPath(path), partSuffix = ".part" + index,
                partPath = basePath + ".incomplete" + partSuffix;
         try
         {
             using (var output = new FileStream(partPath, FileMode.Create, FileAccess.Write, FileShare.Read))
                 Request.Files[Request.Files.AllKeys.Single()].InputStream.CopyTo(output);
             File.Move(partPath, basePath + ".complete" + partSuffix);
         }
         catch
         {
             FileHelper.DeleteWithRetries(partPath); // delete imcomplete file
         }
         var task = new UploadTask(path);
         if (task.FinishedParts != task.TotalParts) return;
         using (var output = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.Read))
             for (var i = 0; i < task.TotalParts; ++i)
             {
                 using (var input = new FileStream(
                     partPath = FileHelper.GetDataPath(path + ".complete.part" + i),
                     FileMode.Open, FileAccess.Read, FileShare.Read)) input.CopyTo(output);
                 FileHelper.DeleteWithRetries(partPath);
             }
         task.Finish();
     }
     else Response.StatusCode = File.Exists(FileHelper.GetDataPath(path + ".complete.part" + index))
                                    ? 200 : 204;  // test
 }
Beispiel #36
0
 private static void Write(PxCell xcell, FileStream fs)
 {
     xcell.Root.Set(new object[] {99, new object[0]});
     xcell.Root.Field(1).SetRepeat(fs.Length);
     PxEntry zel = xcell.Root.Field(1).Element(0);
     fs.Position = 0L;
     xcell.BasicStream.Position = zel.offset;
     fs.CopyTo(xcell.BasicStream);
     xcell.BasicStream.Flush();
 }
        public void OldNewVersionTextStorageSizeThreshold()
        {
            //var mockContext = new Mock<ISourceLogContext>();

            //var logSubscription = new LogSubscription (() => mockContext.Object)
            //    {
            //        LogSubscriptionId = 1,
            //        Log = new TrulyObservableCollection<LogEntry>()
            //    };

            //var fakeLogSubscriptionDbSet = new FakeLogSubscriptionDbSet { logSubscription };
            //mockContext.Setup(m => m.LogSubscriptions).Returns(fakeLogSubscriptionDbSet);

            //var logEntriesDbSet = new FakeDbSet<LogEntry>();
            //mockContext.Setup(m => m.LogEntries).Returns(logEntriesDbSet);

            var changedFileDto = new ChangedFileDto();

            using (var reader = new FileStream("jquery.signalR.core.js.oldversion",FileMode.Open))
            {
                using (var memoryStream = new MemoryStream())
                {
                    reader.CopyTo(memoryStream);
                    changedFileDto.OldVersion = memoryStream.ToArray();
                }
            }

            using (var reader = new FileStream("jquery.signalR.core.js.newversion", FileMode.Open))
            {
                using (var memoryStream = new MemoryStream())
                {
                    reader.CopyTo(memoryStream);
                    changedFileDto.NewVersion = memoryStream.ToArray();
                }
            }

            var logEntryDto = new LogEntryDto
            {
                ChangedFiles = new List<ChangedFileDto> { changedFileDto }
            };

            //logSubscription.AddNewLogEntry(this, new NewLogEntryEventArgs { LogEntry = logEntryDto });

            var logEntry = new LogEntry(logEntryDto);

            logEntry.GenerateFlowDocuments();

            var changedFile = logEntry.ChangedFiles.First();

            Assert.IsTrue(changedFile.LeftFlowDocumentData.Length <= 5388,
                "changedFile.LeftFlowDocumentData.Length: " + changedFile.LeftFlowDocumentData.Length);

            Assert.IsTrue(changedFile.RightFlowDocumentData.Length <= 5383,
                "changedFile.RightFlowDocumentData.Length: " + changedFile.RightFlowDocumentData.Length);
        }
Beispiel #38
0
 public Stream Retrieve(string resourceID)
 {
     if (!Exists(resourceID)) throw new ResourceToRetrieveNotFoundException("Key not found: " + resourceID);
     var stream = new MemoryStream();
     using (var fileStream = new FileStream(CreatePath(resourceID), FileMode.Open))
     {
         fileStream.CopyTo(stream);
     }
     stream.Position = 0;
     return stream;
 }
        internal void HandleRequest()
        {
            var location = XmlRecordFile.Instance.CheckForCachedFile(Context.Request.RawUrl);
            if (location != null)
            {
                using (var outputStream = Context.Response.OutputStream)
                {
                    using (var fileStream = new FileStream(location, FileMode.Open, FileAccess.Read))
                    {
                        Context.Response.KeepAlive = Context.Request.KeepAlive;
                        Context.Response.ContentType = Context.Request.ContentType;
                        Context.Response.ContentEncoding = Context.Request.ContentEncoding;
                        Context.Response.StatusCode = 200;
                        Context.Response.ContentLength64 = fileStream.Length;
                        Context.Response.ProtocolVersion = Context.Request.ProtocolVersion;
                        fileStream.CopyTo(outputStream);
                    }
                }
                return;
            }
            var webRequest = (HttpWebRequest)WebRequest.Create(Context.Request.RawUrl);
            webRequest.KeepAlive = Context.Request.KeepAlive;
            webRequest.UserAgent = Context.Request.UserAgent;
            webRequest.ContentType = Context.Request.ContentType;
            webRequest.ContentLength = Context.Request.ContentLength64;
            webRequest.Method = Context.Request.HttpMethod;
            webRequest.Proxy = null;
            if (webRequest.Method == "POST")
            {
                HandlePost(ref webRequest);
            }
            var newStream = new MemoryStream();
            using (var responce = webRequest.GetResponse())
            {
                using (var responseStream = responce.GetResponseStream())
                {
                    responseStream?.CopyTo(newStream);
                    newStream.Position = 0;
                    using (var outputStream = Context.Response.OutputStream)
                    {
                        try
                        {
                            newStream.CopyTo(outputStream);
                        }
                        catch
                        {
                            // ignored
                        }
                    }
                }
            }
            new Task(() => new FileHandler().SaveCachedFile(newStream, webRequest)).Start();

        }
 public Task CopyToAsync(MemoryStream memStream)
 {
     if (YetaWFManager.IsSync())
     {
         Stream.CopyTo(memStream);
         return(Task.CompletedTask);
     }
     else
     {
         return(Stream.CopyToAsync(memStream));
     }
 }
Beispiel #41
0
    public static byte[] ConvertToBytes(string sourcePath)
    {
        byte[] bytes = null;

        using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) {
            using (System.IO.FileStream f = new System.IO.FileStream(sourcePath, System.IO.FileMode.Open, System.IO.FileAccess.Read)) {
                f.CopyTo(ms);
                bytes = ms.ToArray();
            }
        }

        return(bytes);
    }
Beispiel #42
0
        /// <summary>
        /// Name: Download
        /// Description: Method to download a file from storage
        /// </summary>
        /// <param name="containerName">ContainerName</param>
        /// <param name="fileId">FileId</param>
        /// <returns>Resource Stream</returns>
        public Stream Download(string containerName, string fileId)
        {
            Mutex.WaitOne();
            string path   = System.IO.Path.Combine(this.RootPath, containerName, fileId);
            Stream stream = new MemoryStream();

            using (System.IO.FileStream fileStream = new System.IO.FileStream(path, FileMode.Open))
            {
                fileStream.CopyTo(stream);
            }
            Mutex.ReleaseMutex();
            return(stream);
        }
Beispiel #43
0
 private void FileCopy(string s, string d)
 {
     using (System.IO.FileStream s_fs = System.IO.File.Open(s, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite))
     {
         using (System.IO.FileStream d_fs = System.IO.File.Open(d, System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.ReadWrite))
         {
             this.Dispatcher.Invoke((Action) delegate()
             {
                 clientState_SetStatusText("Copying File... " + Environment.NewLine + "Src: " + System.IO.Path.GetFileName(d) + Environment.NewLine + "Size: " + s_fs.Length.ToString() + " Bytes.");
             });
             s_fs.CopyTo(d_fs, (int)(s_fs.Length > MaxCopyBufferSize ? MaxCopyBufferSize : s_fs.Length));
         }
     }
 }
Beispiel #44
0
 public byte[] ConvertImageToByteArray()
 {
     if (string.IsNullOrEmpty(Path))
     {
         return(new byte[0]);
     }
     using (var stream = new System.IO.FileStream(Path, System.IO.FileMode.Open))
     {
         using (var memoryStream = new System.IO.MemoryStream())
         {
             stream.CopyTo(memoryStream);
             return(memoryStream.ToArray());
         }
     }
 }
Beispiel #45
0
        public void AddEntry(string entryName, DateTime dateTime, System.IO.FileStream stream)
        {
            string fileName  = Path.Combine(tempPath, entryName);
            string directory = Path.GetDirectoryName(fileName);

            if (!Directory.Exists(directory))
            {
                Directory.CreateDirectory(directory);
            }
            using (var destStream = File.Create(fileName))
            {
                stream.CopyTo(destStream);
            }

            File.SetLastWriteTime(fileName, dateTime);
        }
Beispiel #46
0
        public static void Execute <TContext, TResquest>(TContext context, NFinal.Action.ActionData <TContext, TResquest> actionData, NFinal.Owin.Request request)
        {
            var environment = context as IDictionary <string, object>;

            if (environment != null)
            {
                var headers = environment.GetResponseHeaders();
                headers.Add("Content-Type", new string[] { "image/x-icon" });
                headers.Add("Cache-Control", new string[] { "public" });
                environment.SetResponseStatusCode(200);
                Stream stream = environment.GetResponseBody();
                fs.Seek(0, SeekOrigin.Begin);
                fs.CopyTo(stream);
                fs.Flush();
            }
        }
Beispiel #47
0
        static void Main(string[] args)
        {
            byte[] data1 = new byte[4896 * 3264 * 3];
            byte[] data2 = new byte[4896 * 3264 * 3];
            Random r     = new Random();

            r.NextBytes(data1);
            r.NextBytes(data2);

            Stopwatch stopwatch = new Stopwatch();

            MutableByteImageFactory factory = new MutableByteImageFactory(null);
            Bitmap bitmap = new Bitmap(4896, 3264, PixelFormat.Format24bppRgb);

            var          fs           = new System.IO.FileStream("1.jpg", FileMode.Open);
            MemoryStream memoryStream = new MemoryStream();

            fs.CopyTo(memoryStream);
            bitmap.Save(memoryStream, ImageFormat.Jpeg);
            memoryStream.Seek(0, SeekOrigin.Begin);

            stopwatch.Start();
            JpegDecode(memoryStream);
            stopwatch.Stop();
            Console.WriteLine($"jpegdecode {stopwatch.ElapsedMilliseconds}");

            stopwatch.Reset();
            memoryStream.Seek(0, SeekOrigin.Begin);
            stopwatch.Start();
            SysdrawingDecode(memoryStream);
            stopwatch.Stop();
            Console.WriteLine($"sysdecode {stopwatch.ElapsedMilliseconds}");

            stopwatch.Reset();
            memoryStream.Seek(0, SeekOrigin.Begin);
            stopwatch.Start();
            SysdrawingDecode2(memoryStream);
            stopwatch.Stop();
            Console.WriteLine($"sysdecode2 {stopwatch.ElapsedMilliseconds}");

            stopwatch.Reset();
            memoryStream.Seek(0, SeekOrigin.Begin);
            stopwatch.Start();
            JpegDecode2(memoryStream);
            stopwatch.Stop();
            Console.WriteLine($"libjpg {stopwatch.ElapsedMilliseconds}");
        }
 static void Compress(FileInfo fileToCompress)
 {
     using (System.IO.FileStream originalFileStream = fileToCompress.OpenRead())
     {
         if ((File.GetAttributes(fileToCompress.FullName) & FileAttributes.Hidden) != FileAttributes.Hidden & fileToCompress.Extension != ".gz")
         {
             using (FileStream compressedFileStream = File.Create(fileToCompress.FullName + ".gz"))
             {
                 using (GZipStream compressionStream = new GZipStream(compressedFileStream, CompressionMode.Compress))
                 {
                     originalFileStream.CopyTo(compressionStream);
                     //Console.WriteLine("Compressed {0} from {1} to {2} bytes.", fileToCompress.Name, fileToCompress.Length.ToString(), compressedFileStream.Length.ToString())
                 }
             }
         }
     }
 }
        private Stream AddFile(string filename)
        {
            Stream writeStream = null;
            string guid        = Guid.NewGuid().ToString();

            lock (m_SyncRoot)
            {
                m_FileNamesMap.Add(filename, guid);
                writeStream = m_IsolatedStorageFile.CreateFile(guid);

                using (System.IO.FileStream readStream = new System.IO.FileStream(filename, System.IO.FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    GrowQuotaAsNeeded(readStream.Length);
                    readStream.CopyTo(writeStream);
                }
            }

            return(writeStream);
        }
Beispiel #50
0
        public Stream GetStyle(String name)
        {
            WebOperationContext.Current.OutgoingResponse.ContentType = "text/css";
            String modulePath = String.Format(@"{0}\resource\server\css\{1}", solution.SolutionFolder, name);

            if (System.IO.File.Exists(modulePath))
            {
                System.IO.MemoryStream ms = new MemoryStream();
                using (System.IO.FileStream f = System.IO.File.OpenRead(modulePath))
                {
                    f.CopyTo(ms);
                }
                ms.Position = 0;
                return(ms);
            }
            else
            {
                return(null);
            }
        }
Beispiel #51
0
        public override void Close()
        {
            if (!_closed)
            {
                tempStream.Close();
                _closed = true;
                if (!System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(DestinationPath)))
                {
                    System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(DestinationPath));
                }

                if (mode == FileMode.Create)
                {
                    // handle file creation mode
                    if (System.IO.File.Exists(TempFilePath))
                    {
                        if (System.IO.File.Exists(DestinationPath))
                        {
                            System.IO.File.Delete(DestinationPath);
                        }
                        System.IO.File.Move(TempFilePath, DestinationPath);
                    }
                }
                else if (mode == FileMode.Append)
                {
                    var fi = new System.IO.FileInfo(DestinationPath);
                    if (fi.Exists)
                    {
                        using (var appender = new System.IO.FileStream(DestinationPath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite | FileShare.Delete))
                            using (var wrapper = new System.IO.FileStream(TempFilePath, FileMode.Open, FileAccess.Read))
                            {
                                wrapper.CopyTo(appender);
                            }
                    }
                    else
                    {
                        System.IO.File.Move(TempFilePath, DestinationPath);
                    }
                }
            }
        }
        public IActionResult PreviewDocx()
        {
            var path = Path.Combine(Directory.GetCurrentDirectory(), "sample.Pdf");

            System.IO.FileStream   fs = new System.IO.FileStream(path, System.IO.FileMode.Open, System.IO.FileAccess.Read);
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            fs.CopyTo(ms);
            ms.Position = 0;
            var fileResult = new Response
            {
                ContentType = "application/pdf",
                FileName    = "This is the new name of the file.pdf",
                Document    = ms
            };
            var response = File(fileResult.Document, fileResult.ContentType);

            response.FileDownloadName = fileResult.FileName;
            Response.Headers.Add("FileDownloadName", response.FileDownloadName);
            Response.Headers.Add("Access-Control-Expose-Headers", "filedownloadname");
            return(response);
        }
 private Boolean Guardar()
 {
     try
     {
         Boolean resultado  = false;
         string  reportruta = result + "save_reporte_disenio.repx";
         xrDesignDockManager1.XRDesignPanel.SaveReport(reportruta);
         Byte[] data;
         using (System.IO.FileStream FL = new System.IO.FileStream(reportruta, System.IO.FileMode.Open))
         {
             using (MemoryStream ms = new MemoryStream())
             {
                 FL.CopyTo(ms);
                 data = ms.ToArray();
             }
         }
         InfoReporte.Disenio_reporte = data;
         resultado = BusReporte.ModificarDB_Disenio(InfoReporte);
         if (resultado == true)
         {
             data = null;
             MessageBox.Show(param.Get_Mensaje_sys(enum_Mensajes_sys.Se_modifico_corrrectamente) + " el Reporte: " + InfoReporte.Class_NomReporte, param.Nombre_sistema, MessageBoxButtons.OK, MessageBoxIcon.Information);
             return(resultado);
         }
         else
         {
             MessageBox.Show(param.Get_Mensaje_sys(enum_Mensajes_sys.No_se_modificaron_los_datos) + " del Reporte ", param.Nombre_sistema, MessageBoxButtons.OK, MessageBoxIcon.Information);
             return(resultado);
         }
     }
     catch (Exception ex)
     {
         string NameMetodo = System.Reflection.MethodBase.GetCurrentMethod().Name;
         NameMetodo = NameMetodo + " - " + ex.ToString();
         Log_Error_bus.Log_Error(NameMetodo + " - " + ex.ToString());
         MessageBox.Show(NameMetodo + " " + param.Get_Mensaje_sys(enum_Mensajes_sys.Error_comunicarse_con_sistemas)
                         , param.Nombre_sistema, MessageBoxButtons.OK, MessageBoxIcon.Error);
         return(false);
     }
 }
Beispiel #54
0
        public static void SaveExportExcel(eExportModule ExportModule, BatchExportConfigSet.ExportConfigSet exportConfig, string ExcelTemplateFileName, DataTable DataExport, int ExcelStartRow, string ExcelStartColumn, Action <SLDocument> styleExcel = null)
        {
            MemoryStream TemplateStream = new System.IO.MemoryStream();
            SLDocument   report         = null;

            try
            {
                string strDateTimeFileName = DateTime.Now.ToString("yyyyMMdd_HHmm");
                string strFileName         = string.Empty;
                string tmpPath             = string.Format("{0}\\Template\\Excel\\{1}", System.AppDomain.CurrentDomain.BaseDirectory, ExcelTemplateFileName);
                Console.WriteLine(string.Format("Read {0} template file", ExportModule));
                using (var TemplateBase = new System.IO.FileStream(tmpPath, System.IO.FileMode.Open))
                {
                    TemplateBase.CopyTo(TemplateStream);
                    TemplateBase.Close();
                    TemplateStream.Seek(0, SeekOrigin.Begin);
                }

                Console.WriteLine(string.Format("Prepare {0} data", ExportModule));

                int iAllExcelRow   = DataExport.Rows.Count;
                int iMaxRowPerFile = Convert.ToInt32(AppConstant.MaxExcelRowPerFile);
                int iNoOfExcelFile = Convert.ToInt32(Math.Ceiling(Convert.ToDouble(iAllExcelRow) / Convert.ToDouble(iMaxRowPerFile)));

                Console.WriteLine(string.Format("All Excel row(s) : {0}", iAllExcelRow));
                Console.WriteLine(string.Format("Max Row per file : {0}", iMaxRowPerFile));
                Console.WriteLine(string.Format("Number of Excel file : {0}", iNoOfExcelFile));

                for (int i = 0; i < iNoOfExcelFile; i++)
                {
                    if (iNoOfExcelFile == 1)
                    {
                        if (ExportModule == eExportModule.LeadsForTKS)
                        {
                            strFileName = string.Format("KK_INS_T1_{0}.xlsx", DateTime.Now.ToString("yyyyMMddHHmmss"));
                        }
                        else
                        {
                            strFileName = string.Format("{0}_{1}.xlsx", ExportModule, strDateTimeFileName);
                        }
                    }
                    else
                    {
                        if (ExportModule == eExportModule.LeadsForTKS)
                        {
                            strFileName = string.Format("KK_INS_T1_{0}_{1}.xlsx", DateTime.Now.ToString("yyyyMMddHHmmss"), i + 1);
                        }
                        else
                        {
                            strFileName = string.Format("{0}_{1}_{2}.xlsx", ExportModule, strDateTimeFileName, i + 1);
                        }
                    }

                    DataTable dt = DataExport.AsEnumerable().Select(x => x).Skip(i * iMaxRowPerFile).Take(iMaxRowPerFile).CopyToDataTable();

                    report = new SLDocument(TemplateStream, ExportModule.ToString());
                    report.InsertRow(ExcelStartRow, dt.Rows.Count - 1);
                    report.ImportDataTable(ExcelStartColumn + ExcelStartRow, dt, false);

                    styleExcel?.Invoke(report);

                    Console.WriteLine(string.Format("Save {0} file", ExportModule));
                    using (UNCAccessWithCredentials unc = new UNCAccessWithCredentials())
                    {
                        string exportPath       = exportConfig.Path;
                        string exportUsername   = exportConfig.Username;
                        string exportDomainName = exportConfig.DomainName;
                        string exportPassword   = exportConfig.Password;
                        if (unc.NetUseWithCredentials(exportPath, exportUsername, exportDomainName, exportPassword))
                        {
                            report.SaveAs(string.Format("{0}{1}", exportPath, strFileName));
                        }
                        else
                        {
                            string strError = string.Format("Cannot access path '{0}'", exportPath);
                            Console.WriteLine(strError);
                            unc.Dispose();
                            throw new Exception(strError);
                        }
                        unc.Dispose();
                    }

                    report.Dispose();
                    report = null;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (report != null)
                {
                    report.Dispose();
                }
                report         = null;
                TemplateStream = null;
            }
        }
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                System.IO.FileStream fs = new
                                          System.IO.FileStream(workbookPath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                fs.CopyTo(stream);


                using (OfficeOpenXml.ExcelPackage package = new OfficeOpenXml.ExcelPackage(stream))
                {
                    var worksheet = package.Workbook.Worksheets.First();
                    int rowCount  = worksheet.Dimension.End.Row;

                    string newfolderPath = "";
                    var    folderName    = "";
                    for (int row = 3; row <= rowCount; row++)
                    {
                        var serialNum  = "";
                        var issoftware = "";
                        var iswindows  = "";
                        var ID         = worksheet.Cells[row, 1].Value == null ?"No values" : worksheet.Cells[row, 1].Value.ToString();
                        var Type       = worksheet.Cells[row, 2].Value == null ? "No values" : worksheet.Cells[row, 2].Value.ToString();
                        var status     = worksheet.Cells[row, 3].Value == null ? "No values" : worksheet.Cells[row, 3].Value.ToString();
                        var user       = worksheet.Cells[row, 4].Value == null ? "No values" : worksheet.Cells[row, 4].Value.ToString();

                        if (Type == "laptop")
                        {
                            if (worksheet.Cells[row, 5].Value == null)
                            {
                                serialNum = "Please Input values!!";
                            }
                            else
                            {
                                serialNum = worksheet.Cells[row, 5].Value.ToString();
                            }
                            if (worksheet.Cells[row, 6].Value == null)
                            {
                                issoftware = "Please Input values!!";
                            }
                            else
                            {
                                issoftware = worksheet.Cells[row, 6].Value.ToString();
                            }
                            if (worksheet.Cells[row, 7].Value == null)
                            {
                                iswindows = "Please Input values!!";
                            }
                            else
                            {
                                iswindows = worksheet.Cells[row, 6].Value.ToString();
                            }
                        }
                        else
                        {
                            serialNum  = worksheet.Cells[row, 5].Value == null ? "No values" : worksheet.Cells[row, 5].Value.ToString();
                            issoftware = worksheet.Cells[row, 6].Value == null ? "No values" : worksheet.Cells[row, 6].Value.ToString();
                            iswindows  = worksheet.Cells[row, 7].Value == null ? "No values" : worksheet.Cells[row, 7].Value.ToString();
                        }

                        var rowValue = "Inventory ID = " + ID + "\n" + "Inventory Type = " + Type + "\n" + "Rented  Cubo =  " + status + "\n" + "User = "******"\n" +
                                       "Serial Number = " + serialNum + "\n" + "Softwares Installed = " + issoftware + "\n" + "Windows Installed= " + iswindows;



                        var qrId = ID;


                        QRCodeGenerator qrGenerator = new QRCodeGenerator();
                        QRCodeData      qrCodeData  = qrGenerator.CreateQrCode(rowValue, QRCodeGenerator.ECCLevel.Q);
                        QRCode          qrCode      = new QRCode(qrCodeData);
                        Bitmap          bmp         = qrCode.GetGraphic(20, System.Drawing.Color.Black, System.Drawing.Color.White, true);

                        folderName = DateTime.Now.ToString("dddd - ddMMMM yyyy HH - mm");


                        newfolderPath = folderpath + "/" + folderName;
                        if (!Directory.Exists(newfolderPath))
                        {
                            Directory.CreateDirectory(newfolderPath);
                        }

                        using (MemoryStream ms = new MemoryStream())
                        {
                            bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                            byte[] byteImage         = ms.ToArray();
                            System.Drawing.Image img = System.Drawing.Image.FromStream(ms);
                            img.Save(newfolderPath + "/" + qrId + ".Jpeg", System.Drawing.Imaging.ImageFormat.Jpeg);
                        }
                    }
                    FileNameTextBox.Text  = "";
                    FileNameTextBox2.Text = "";
                    if (FileNameTextBox.Text != " " &&
                        FileNameTextBox2.Text != " ")
                    {
                        txtblk.Text  = "File was successfully copied!!!!";
                        txtblk2.Text = newfolderPath;
                    }
                }
            }
        }
Beispiel #56
0
        private void SaveExcelToSharePath(DataTable dtExport)
        {
            MemoryStream TemplateStream = new System.IO.MemoryStream();

            try
            {
                string strDateTimeFileName = DateTime.Now.ToString("yyyyMMdd_HHmm");
                string strFileName         = string.Empty;
                string tmpPath             = string.Format("{0}\\Template\\Excel\\{1}", System.AppDomain.CurrentDomain.BaseDirectory, "WSLogINS_Template.xlsx");

                ErrorStep = "Read WSLog template file";
                Console.WriteLine(ErrorStep);
                using (var TemplateBase = new System.IO.FileStream(tmpPath, System.IO.FileMode.Open))
                {
                    TemplateBase.CopyTo(TemplateStream);
                    TemplateBase.Close();
                    TemplateStream.Seek(0, SeekOrigin.Begin);
                }

                ErrorStep = "Prepare WSLog data";
                Console.WriteLine(ErrorStep);

                int iAllExcelRow   = dtExport.Rows.Count;
                int iMaxRowPerFile = Convert.ToInt32(AppConstant.MaxExcelRowPerFile);
                int iNoOfExcelFile = Convert.ToInt32(Math.Ceiling(Convert.ToDouble(iAllExcelRow) / Convert.ToDouble(iMaxRowPerFile)));

                Console.WriteLine(string.Format("All Excel row(s) : {0}", iAllExcelRow));
                Console.WriteLine(string.Format("Max Row per file : {0}", iMaxRowPerFile));
                Console.WriteLine(string.Format("Number of Excel file : {0}", iNoOfExcelFile));

                for (int i = 0; i < iNoOfExcelFile; i++)
                {
                    if (iNoOfExcelFile == 1)
                    {
                        strFileName = string.Format("WSLogINS_{0}.xlsx", strDateTimeFileName);
                    }
                    else
                    {
                        strFileName = string.Format("WSLogINS_{0}_{1}.xlsx", strDateTimeFileName, i + 1);
                    }

                    DataTable dt = dtExport.AsEnumerable().Select(x => x).Skip(i * iMaxRowPerFile).Take(iMaxRowPerFile).CopyToDataTable();

                    var report = new SLDocument(TemplateStream, "WSLOGINS");
                    report.InsertRow(2, dt.Rows.Count - 1);
                    report.ImportDataTable("A" + 2, dt, false);

                    ErrorStep = "Save WSLog file";
                    Console.WriteLine(ErrorStep);
                    using (UNCAccessWithCredentials unc = new UNCAccessWithCredentials())
                    {
                        if (unc.NetUseWithCredentials(AppConstant.ExportWSLogPath, AppConstant.ExportWSLogUsername, AppConstant.ExportWSLogDomainName, AppConstant.ExportWSLogPassword))
                        {
                            report.SaveAs(string.Format("{0}{1}", AppConstant.ExportWSLogPath, strFileName));
                        }
                        else
                        {
                            ErrorDetail = string.Format("Cannot access path '{0}'", AppConstant.ExportWSLogPath);
                            Console.WriteLine(ErrorDetail);
                        }
                        unc.Dispose();
                    }

                    report.Dispose();
                    report = null;
                }
            }
            catch (Exception ex)
            {
                ErrorDetail = ex.ToString();
                Console.WriteLine(ErrorDetail);
            }
            finally
            {
                TemplateStream.Close();
                TemplateStream = null;
            }
        }
Beispiel #57
0
        private void Optimize()
        {
            string ExeToUse = string.Empty;

            if (Environment.Is64BitOperatingSystem == true)
            {
                ExeToUse = "gifopt64.exe";
            }
            else
            {
                ExeToUse = "gifopt32.exe";
            }

            ProcessStartInfo psi = new ProcessStartInfo();

            psi.CreateNoWindow  = true;
            psi.UseShellExecute = false;
            psi.WindowStyle     = ProcessWindowStyle.Hidden;
            psi.FileName        = ExeToUse;

            string CompressValue = comboBoxCompressLevel.Text;

            StringBuilder ArgsString = new StringBuilder();


            ArgsString.Append(" -" + CompressValue + " ");

            if (numericUpDownLossy.Value > 0)
            {
                ArgsString.Append(" --lossy=" + numericUpDownLossy.Value.ToString());
            }

            if (numericUpDownColor.Value > 0)
            {
                ArgsString.Append(" --colors=" + numericUpDownColor.Value.ToString());
            }

            if (textBoxWidth.Text != "0" && textBoxHeight.Text != "0")
            {
                ArgsString.Append(" --resize-fit " + textBoxWidth.Text + "X" + textBoxHeight + " ");
            }

            ArgsString.Append("\"" + textBoxPath.Text + "\"");
            ArgsString.Append(" -o " + "\"" + "temp.gif" + "\"");

            psi.Arguments = ArgsString.ToString();

            Process.Start(psi).WaitForExit();

            using (var fs = new System.IO.FileStream("temp.gif", System.IO.FileMode.Open, System.IO.FileAccess.Read))
            {
                var ms = new System.IO.MemoryStream();
                fs.CopyTo(ms);
                ms.Position = 0;

                if (pictureBoxTarget.Image != null)
                {
                    pictureBoxTarget.Image.Dispose();
                }

                pictureBoxTarget.Image = Image.FromStream(ms);
            }
        }
Beispiel #58
0
        protected void Page_Load(object sender, EventArgs e)
        {
            _log.Info("ExportToExcel : start");
            try
            {
                if (Session["DatableExcelExport"] != null)
                {
                    DataTable dtExport = (Session["DatableExcelExport"] as DataTable).Copy();
                    Session["DatableExcelExport"] = null;

                    if (dtExport.Rows.Count <= 0)
                    {
                        dtExport.Rows.Add(dtExport.NewRow());
                    }

                    string strFileName = string.Format("ผลงานของTelesales_{0}.xlsx", DateTime.Now.ToString("yyyyMMdd_hhmm"));

                    string tmpPath = Path.Combine(Server.MapPath("~"), "ExcelTemplate\\TelesalesPerformance_Template.xlsx");

                    MemoryStream TemplateStream = new System.IO.MemoryStream();
                    using (var TemplateBase = new System.IO.FileStream(tmpPath, System.IO.FileMode.Open))
                    {
                        TemplateBase.CopyTo(TemplateStream);
                        TemplateBase.Close();
                        TemplateStream.Seek(0, SeekOrigin.Begin);
                    }

                    var report = new SLDocument(TemplateStream, "ผลงานของ Telesales");
                    report.InsertRow(2, dtExport.Rows.Count - 1);
                    report.ImportDataTable("A" + 2, dtExport, false);

                    var stream = new FileStream(Path.GetTempFileName(), FileMode.Create, FileAccess.ReadWrite, FileShare.Read, 4096, FileOptions.DeleteOnClose);
                    report.SaveAs(stream);
                    stream.Seek(0, SeekOrigin.Begin); // Reset pointer for reuse.

                    TemplateStream.Close();
                    report.Dispose();
                    report         = null;
                    TemplateStream = null;
                    ///////////////////////////////////////////////////////////////////

                    stream.Flush();
                    stream.Position = 0;

                    Response.ClearContent();
                    Response.Clear();
                    Response.Buffer  = true;
                    Response.Charset = "";


                    Response.ClearHeaders();
                    Response.HeaderEncoding  = Request.Browser.IsBrowser("CHROME") ? Encoding.UTF8 : Encoding.Default;
                    Response.ContentEncoding = System.Text.Encoding.Default;
                    Response.AddHeader("content-disposition", string.Format("attachment;filename={0}", (Request.Browser.IsBrowser("IE") ? HttpUtility.UrlEncode(strFileName) : strFileName)));
                    Response.ContentType = "application/ms-excel";
                    byte[] data1 = new byte[stream.Length];
                    stream.Read(data1, 0, data1.Length);
                    stream.Close();
                    stream = null;
                    Response.BinaryWrite(data1);
                    Response.Flush();
                    Response.End();
                }
            }
            catch (Exception ex)
            {
                string message = ex.InnerException != null ? ex.InnerException.Message : ex.Message;
                _log.Error(message);
            }
        }