Пример #1
0
        public static BitmapImage LoadImage(string path)
        {
            try
            {
                var fs = new System.IO.FileStream(path, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                fs.Seek(0, System.IO.SeekOrigin.Begin);
                byte[] bytes = new byte[fs.Length];
                fs.Read(bytes, 0, (int)fs.Length);
                fs.Close();

                var ms = new System.IO.MemoryStream(bytes);
                ms.Position = 0;
                var image = new BitmapImage();
                image.BeginInit();
                image.CreateOptions = BitmapCreateOptions.IgnoreColorProfile;
                image.CacheOption = BitmapCacheOption.OnLoad;
                image.StreamSource = ms;
                image.EndInit();
                return image;
            }
            catch (Exception ex)
            {
            }
            return null;
        }
Пример #2
0
        public byte[] FileToByteArray(string _FileName)
        {
            byte[] _Buffer = null;

            try
            {

                // Open file for reading
                System.IO.FileStream _FileStream = new System.IO.FileStream(_FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);

                // attach filestream to binary reader
                System.IO.BinaryReader _BinaryReader = new System.IO.BinaryReader(_FileStream);

                // get total byte length of the file
                long _TotalBytes = new System.IO.FileInfo(_FileName).Length;

                // read entire file into buffer
                _Buffer = _BinaryReader.ReadBytes((Int32)(_TotalBytes));
                // close file reader
                _FileStream.Close();
                _FileStream.Dispose();
                _BinaryReader.Close();
            }

            catch (Exception _Exception)
            {
                // Error
                Console.WriteLine("Exception caught in process: {0}", _Exception.ToString());
            }

            return _Buffer;
        }
Пример #3
0
        public static DateTime GetBulidTime()
        {
            var filePath = System.Reflection.Assembly.GetCallingAssembly().Location;
            const int cPeHeaderOffset = 60;
            const int cLinkerTimestampOffset = 8;
            var b = new byte[2048];
            System.IO.Stream s = null;

            try
            {
                s = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                s.Read(b, 0, 2048);
            }
            finally
            {
                if (s != null)
                {
                    s.Close();
                }
            }

            var i = BitConverter.ToInt32(b, cPeHeaderOffset);
            var secondsSince1970 = BitConverter.ToInt32(b, i + cLinkerTimestampOffset);
            var dt = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
            dt = dt.AddSeconds(secondsSince1970);
            dt = dt.ToLocalTime();
            return dt;
        }
Пример #4
0
        public void CreateReportAsPDF(long? orderID, long? orderProductID, string fileName)
        {

            try
            {
                this.SP_MaterialDetailsTableAdapter.Fill(this.OrderManagerDBDataSet.SP_MaterialDetails, orderProductID, orderID);
                this.SP_MaterialOtherCostDetailsTableAdapter.Fill(this.OrderManagerDBOtherCostDataSet.SP_MaterialOtherCostDetails, orderProductID);

                // Variables
                Warning[] warnings;
                string[] streamIds;
                string mimeType = string.Empty;
                string encoding = string.Empty;
                string extension = string.Empty;


                // Setup the report viewer object and get the array of bytes
                byte[] bytes = reportViewer1.LocalReport.Render("PDF", null, out mimeType, out encoding, out extension, out streamIds, out warnings);

                using (System.IO.FileStream sw = new System.IO.FileStream(fileName, System.IO.FileMode.Create))
                {
                    sw.Write(bytes, 0, bytes.Length);
                    sw.Close();
                }
            }
            catch (Exception ex)
            {

            }
        }
Пример #5
0
        /// <summary>
        /// Компрессия или декомпрессия файла
        /// </summary>
        /// <param name="fromFile">Исходный файл для компрессии или декомпрессии</param>
        /// <param name="toFile">Целевой файл</param>
        /// <param name="compressionMode">Указывает на компрессию или декомпрессию</param>
        private static void CompressOrDecompressFile(string fromFile, string toFile, System.IO.Compression.CompressionMode compressionMode)
        {
            System.IO.FileStream toFs = null;
            System.IO.Compression.GZipStream gzStream = null;
            System.IO.FileStream fromFs = new System.IO.FileStream(fromFile, System.IO.FileMode.Open, System.IO.FileAccess.Read);

            try
            {
                toFs = new System.IO.FileStream(toFile, System.IO.FileMode.Create, System.IO.FileAccess.Write);
                gzStream = new System.IO.Compression.GZipStream(toFs, compressionMode);
                byte[] buf = new byte[fromFs.Length];
                fromFs.Read(buf, 0, buf.Length);
                gzStream.Write(buf, 0, buf.Length);
            }
            finally
            {
                if (gzStream != null)
                    gzStream.Close();

                if (toFs != null)
                    toFs.Close();

                fromFs.Close();
            }
        }
        private void loadToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                SkeletDrawInfo _sdi;
                System.IO.Stream stream = new System.IO.FileStream(ofd.FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read);
                try
                {
                    _sdi = (SkeletDrawInfo)formatter.Deserialize(stream);
                    if (_sdi.nodes.Length == skelet.bones.Length && _sdi.relations.Length == sdi.relations.Length)
                    {
                        _sdi.sk = skelet;
                        for (int o = 0; o < _sdi.nodes.Length; o++)
                            _sdi.nodes[o].bone = skelet.bones[_sdi.nodes[o].index];
                        sdi = _sdi;
                        Invalidate();
                    }

                }
                catch (System.Runtime.Serialization.SerializationException)
                {
                    System.Windows.Forms.MessageBox.Show("Wrong file format");
                }
                catch (Exception ex)
                {
                    System.Windows.Forms.MessageBox.Show(ex.ToString());
                }
                finally
                {
                    stream.Close();
                }
            }
        }
Пример #7
0
        public static int Execute( List<string> args )
        {
            if ( args.Count < 2 ) {
                Console.WriteLine( "Usage: ByteHotfix [filename] [location-byte] [location-byte] etc." );
                Console.WriteLine( "example: ByteHotfix 325.new 3A9A3-94 3AA72-A4 3AA73-32 3AB53-51" );
                return -1;
            }

            /*
            args = new string[] { @"c:\#gn_chat\scenario.dat.ext.ex\325.new" ,
                "3A9A3-94", "3AA72-A4", "3AA73-32", "3AB53-51" };
             */

            try {
                string inFilename = args[0];

                using ( var fi = new System.IO.FileStream( inFilename, System.IO.FileMode.Open ) ) {
                    for ( int i = 1; i < args.Count; i++ ) {
                        String[] v = args[i].Split( new char[] { '-' } );
                        int location = int.Parse( v[0], NumberStyles.AllowHexSpecifier );
                        byte value = byte.Parse( v[1], NumberStyles.AllowHexSpecifier );
                        fi.Position = location;
                        fi.WriteByte( value );
                    }
                    fi.Close();
                }

                return 0;

            } catch ( Exception ex ) {
                Console.WriteLine( "Exception: " + ex.Message );
                return -1;
            }
        }
Пример #8
0
        private DateTime RetrieveLinkerTimestamp()
        {
            string filePath = System.Reflection.Assembly.GetCallingAssembly().Location;
            const int c_PeHeaderOffset = 60;
            const int c_LinkerTimestampOffset = 8;
            byte[] b = new byte[2048];
            System.IO.Stream s = null;

            try
            {
                s = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                s.Read(b, 0, 2048);
            }
            finally
            {
                if (s != null)
                {
                    s.Close();
                }
            }

            int i = System.BitConverter.ToInt32(b, c_PeHeaderOffset);
            int secondsSince1970 = System.BitConverter.ToInt32(b, i + c_LinkerTimestampOffset);
            DateTime dt = new DateTime(1970, 1, 1, 0, 0, 0);
            dt = dt.AddSeconds(secondsSince1970);
            dt = dt.AddHours(TimeZone.CurrentTimeZone.GetUtcOffset(dt).Hours);
            return dt;
        }
Пример #9
0
        //下载网络文件
        /// <summary>
        /// 下载网络文件 带进度条
        /// </summary>
        /// <param name="URL"></param>
        /// <param name="fileName"></param>
        /// <param name="progressBar1"></param>
        /// <returns></returns>
        public static bool DownloadFile(string URL, string fileName,ProgressBar progressBar1)
        {
            try
            {
                System.Net.HttpWebRequest httpWebRequest1 = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(URL);
                System.Net.HttpWebResponse httpWebResponse1 = (System.Net.HttpWebResponse)httpWebRequest1.GetResponse();

                long totalLength = httpWebResponse1.ContentLength;
                progressBar1.Maximum = (int)totalLength;

                System.IO.Stream stream1 = httpWebResponse1.GetResponseStream();
                System.IO.Stream stream2 = new System.IO.FileStream(fileName, System.IO.FileMode.Create);

                long currentLength = 0;
                byte[] by = new byte[1024];
                int osize = stream1.Read(by, 0, (int)by.Length);
                while (osize > 0)
                {
                    currentLength = osize + currentLength;
                    stream2.Write(by, 0, osize);

                    progressBar1.Value = (int)currentLength;
                    osize = stream1.Read(by, 0, (int)by.Length);
                }

                stream2.Close();
                stream1.Close();

                return (currentLength == totalLength);
            }
            catch
            {
                return false;
            }
        }
Пример #10
0
		public void GuardarRecursoIncrustado()
		{
			// get a reference to the current assembly
			Assembly a = Assembly.GetExecutingAssembly();
        
			// get a list of resource names from the manifest
			string [] resNames = a.GetManifestResourceNames();

			foreach(string s in resNames)
			{
				if (!s.EndsWith("resources") && !s.EndsWith("licenses") && !s.EndsWith("license") && !s.EndsWith("ico"))
				{	
					if(!System.IO.File.Exists(Environment.GetFolderPath(System.Environment.SpecialFolder.Personal) + "\\"+s))
					{
						System.IO.Stream aStream;
						aStream = this.GetType().Assembly.GetManifestResourceStream(s);
						System.IO.FileStream aFileStream=new System.IO.FileStream(Environment.GetFolderPath(System.Environment.SpecialFolder.Personal) + "\\"+s,System.IO.FileMode.Create,System.IO.FileAccess.Write);
						int Length = 256;
						Byte [] buffer = new Byte[Length];
						int bytesRead = aStream.Read(buffer,0,Length);
						while( bytesRead > 0 )
						{
							aFileStream.Write(buffer,0,bytesRead);
							bytesRead = aStream.Read(buffer,0,Length);
						}
						aStream.Close();
						aFileStream.Close();
					}
				}
			}
		}
Пример #11
0
        public void CreateReportAsPDF(int? supplierID, long? jobOrderId, string fileName)
        {
            try
            {
                this.SP_JoGRNTableAdapter.Fill(this.joGRNReportDataSet.SP_JoGRN, supplierID, jobOrderId);

                // Variables
                Warning[] warnings;
                string[] streamIds;
                string mimeType = string.Empty;
                string encoding = string.Empty;
                string extension = string.Empty;

                reportViewer1.LocalReport.Refresh();
                // Setup the report viewer object and get the array of bytes
                byte[] bytes = reportViewer1.LocalReport.Render("PDF", null, out mimeType, out encoding, out extension, out streamIds, out warnings);

                using (System.IO.FileStream sw = new System.IO.FileStream(fileName, System.IO.FileMode.Create))
                {
                    sw.Write(bytes, 0, bytes.Length);
                    sw.Close();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Пример #12
0
        private void button1_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                //Открываем файл картинки...
                System.IO.FileStream fs = new System.IO.FileStream(openFileDialog1.FileName, System.IO.FileMode.Open);
                System.Drawing.Image img = System.Drawing.Image.FromStream(fs);
                fs.Close();
                //Помещаем исходное изображение в PictureBox1
                pictureBox1.Image = img;

                var bmp = new Bitmap(img);
                label1.Text = "";
                label1.Text = label1.Text + DateTime.Now.Second.ToString() + "." + DateTime.Now.Millisecond.ToString() + " - "; //Время начала обработки (секунды и миллисекунды).
                //Преобразуем картинку
                MakeGray(bmp);
                //Crop(bmp, new Rectangle(0, 0, bmp.Height, bmp.Width));
                Bitmap cropBmp = bmp.Clone(new Rectangle(0, 0, bmp.Width / 2, bmp.Height / 2), bmp.PixelFormat);
                label1.Text = label1.Text + DateTime.Now.Second.ToString() + "." + DateTime.Now.Millisecond.ToString(); //Время окончания обработки (секунды и миллисекунды).
                //Помещаем преобразованное изображение в PictureBox2
                pictureBox2.Image = cropBmp;
                Bitmap cropcloneBmp = cropBmp.Clone(new Rectangle(0, 0, cropBmp.Width, cropBmp.Height), cropBmp.PixelFormat);
                MakeGray(cropcloneBmp);
                //Crop(bmp, new Rectangle(0, 0, bmp.Height, bmp.Width));
                Bitmap cropnewBmp = cropcloneBmp.Clone(new Rectangle(0, 0, cropcloneBmp.Width / 2, cropcloneBmp.Height / 2), cropcloneBmp.PixelFormat);
                label1.Text = label1.Text + DateTime.Now.Second.ToString() + "." + DateTime.Now.Millisecond.ToString(); //Время окончания обработки (секунды и миллисекунды).
                //Помещаем преобразованное изображение в PictureBox2
                pictureBox3.Image = cropnewBmp;
            }

        }
Пример #13
0
        private void OnAsyncCompressed(object Sender, Archive.ArchiveEventArgs e)
        {
            this.Logger?.WriteLine("Compress end event.");

            // 圧縮に成功したならアップロードします。
            if (!this.m_Zipper.IsCompressed)
            {
                return;
            }

            System.IO.FileStream Data = null;

            try {
                // アーカイブをファイルストリームで開きます。
                Data = new System.IO.FileStream(e.Destnation, System.IO.FileMode.Open, System.IO.FileAccess.Read);

                // オブジェクトストレージの指定コンテナにアーカイブをアップロードします。
                OpenStack.CreateObject(Options.UseContainerName, System.IO.Path.GetFileName(e.Destnation), Data, eContentType.CONTENTS_ARCHIVE_ZIP);

                this.Logger?.WriteLine("Archive file uploaded.");
            } catch (System.Exception ex) {
                this.Logger?.WriteLine(ex.Message, eLogLevel.ERROR);
            } finally{
                // ストリームを必ず閉じます。
                Data?.Close();
                Data?.Dispose();

                // 圧縮したファイルとテンポラリディレクトリを片付けます。
                System.IO.File.Delete(this.TemporaryPath + "/" + e.Destnation);
                System.IO.Directory.Delete(this.TemporaryPath, true);
            }
        }
Пример #14
0
        /// <summary>
        /// Returns the path to the sketch image just created
        /// <param name="mask">Mask image of the button</param>
        /// <param name="texture">Texture image of the item</param>
        /// <param name="nameSketch">Name of the image to create</param>
        public static string CreateSketchesPath(string mask, string texture, string nameSketch)
        {
            MagickImage Mask = new MagickImage(mask);

            MagickImage Texture = new MagickImage(texture);

            Texture.Crop(Mask.Width, Mask.Height);

            Texture.Composite(Mask, CompositeOperator.CopyAlpha);
            Mask.Composite(Texture, CompositeOperator.Multiply);
            MagickImage sketch = Mask;

            try
            {
                // sketch.Write(Helpers.ResourcesHelper.SketchesPath() + nameSketch);
                string p = Helpers.ResourcesHelper.SketchesPath() + nameSketch;
                System.IO.Stream s = new System.IO.FileStream(p, System.IO.FileMode.Create);

                sketch.Write(s);
                s.Close();
            }
            catch (MagickException ex)
            {
                string s= ex.Message;
            }
            catch
            {

            }
            sketch.Dispose();
            sketch = null;
            string path = Helpers.ResourcesHelper.SketchesPath() + nameSketch;
            return path;
        }
Пример #15
0
        public void InitializeTwitter()
        {
            try
            {
                System.Xml.Serialization.XmlSerializer serializer =
                    new System.Xml.Serialization.XmlSerializer(typeof(saveSettings));
                System.IO.FileStream fs = new System.IO.FileStream(
                    @"settings.xml", System.IO.FileMode.Open);
                saveSettings setting = (saveSettings)serializer.Deserialize(fs);
                fs.Close();
                textBox1.Enabled = false;
                //accToken = setting.AccToken;
                token.AccessToken = setting.AccToken;
                //accTokenSec = setting.AccTokenSec;
                token.AccessTokenSecret = setting.AccTokenSec;

                var Stream = new TwitterStream(token, "Feedertter", null);

                StatusCreatedCallback statusCreatedCallback = new StatusCreatedCallback(StatusCreatedCallback);
                RawJsonCallback rawJsonCallback = new RawJsonCallback(RawJsonCallback);

                Stream.StartUserStream(null, null,
                    /*(x) => { label1.Text += x.Text; }*/
                    statusCreatedCallback,
                    null, null, null, null, rawJsonCallback);
            }
            catch
            {
                Process.Start(OAuthUtility.BuildAuthorizationUri(req.Token).ToString());
            }

            //Process.Start(OAuthUtility.BuildAuthorizationUri(req.Token).ToString());
        }
Пример #16
0
        private static void SaveHeightMaps(bool saveBMP)
        {
            foreach (string i in Map.Map.heightmapBuilder.Keys)
            {
                System.IO.FileStream fs = null;
                try
                {
                    if (Map.Map.heightmapBuilder[i].MinX == 0 && Map.Map.heightmapBuilder[i].MaxX == 0)
                    {
                        continue;
                    }

                    fs = new System.IO.FileStream("DB/HeightMaps/" + i + ".builder", System.IO.FileMode.Create);
                    Map.Map.heightmapBuilder[i].ToStream(fs);
                    if (saveBMP)
                    {
                        Map.Map.heightmapBuilder[i].ToBMP("DB/HeightMaps/" + i + ".psd");
                    }
                }
                catch (Exception ex)
                {
                    Logger.Log.Error(ex);
                }
                finally
                {
                    fs?.Close();
                }
            }

            Logger.Log.Info("Heightmaps saved");
        }
Пример #17
0
        public static void SaveToExcel(Microsoft.Reporting.WinForms.ReportViewer reportviewer, string outputfilename)
        {
            string deviceinfo = null;
            string mimetype = null;
            string encoding = null;
            string filenamextension = null;
            string[] streams;
            Microsoft.Reporting.WinForms.Warning[] warnings;

            string format = "Excel";

            var bytes = reportviewer.LocalReport.Render(
                format,
                deviceinfo,
                out mimetype,
                out encoding,
                out filenamextension,
                out streams,
                out warnings);


            using (var fs = new System.IO.FileStream(outputfilename, System.IO.FileMode.Create))
            {
                fs.Write(bytes, 0, bytes.Length);
                fs.Close();
            }
        }
Пример #18
0
 public static void Dump(string fileName, byte[] bytes)
 {
     System.IO.FileStream s = new System.IO.FileStream(fileName, System.IO.FileMode.OpenOrCreate);
     s.Write(bytes, 0, bytes.Length);
     s.Flush();
     s.Close();
 }
Пример #19
0
        public void Load()
        {
            System.IO.FileStream file = new System.IO.FileStream("data.dat",System.IO.FileMode.Open ) ;
            Byte[] buffer1 = System.BitConverter.GetBytes( Existe[0] ) ;
            Byte[] buffer2 = System.BitConverter.GetBytes( Left[0] ) ;
            Byte[] buffer3 = System.BitConverter.GetBytes( Top[0] ) ;
            Byte[] buffer4 = System.BitConverter.GetBytes( Color[0].ToArgb() ) ;
            Byte[] buffer5 = System.Text.Encoding.BigEndianUnicode.GetBytes( Text[0], 0 , Text[0].Length ) ;

            Byte[] bufferM1 = System.BitConverter.GetBytes( MainLeft ) ;
            Byte[] bufferM2 = System.BitConverter.GetBytes( MainTop ) ;
            file.Read( bufferM1, 0, bufferM1.Length ) ;
            MainLeft = System.BitConverter.ToInt32( bufferM1 , 0 ) ;
            file.Read( bufferM2, 0, bufferM2.Length ) ;
            MainTop = System.BitConverter.ToInt32( bufferM2 , 0 ) ;

            for ( int i = 0 ; i < MAX_POSTS ; i++ )
            {
                file.Read( buffer1, 0, buffer1.Length ) ;
                Existe[i] = System.BitConverter.ToBoolean( buffer1 , 0 ) ;
                file.Read( buffer2, 0, buffer2.Length ) ;
                Left[i] = System.BitConverter.ToInt32( buffer2 , 0 ) ;
                file.Read( buffer3, 0, buffer3.Length ) ;
                Top[i] = System.BitConverter.ToInt32( buffer3 , 0 ) ;
                file.Read( buffer4, 0, buffer4.Length ) ;
                Color[i] = System.Drawing.Color.FromArgb( System.BitConverter.ToInt32(buffer4, 0 ) ) ;
                file.Read( buffer5, 0, buffer5.Length ) ;
                Text[i] = System.Text.Encoding.BigEndianUnicode.GetChars( buffer5 ) ;
            }
            file.Close() ;
        }
Пример #20
0
        public static DateTime GetBuildTimestamp()
        {
            string filePath = Assembly.GetCallingAssembly().Location;
            const int c_PeHeaderOffset = 60;
            const int c_LinkerTimestampOffset = 8;
            byte[] b = new byte[2048];
            System.IO.Stream s = null;

            try
            {
                s = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                s.Read(b, 0, 2048);
            }
            finally
            {
                if (s != null)
                {
                    s.Close();
                }
            }

            int i = BitConverter.ToInt32(b, c_PeHeaderOffset);
            int secondsSince1970 = BitConverter.ToInt32(b, i + c_LinkerTimestampOffset);
            DateTime dt = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
            dt = dt.AddSeconds(secondsSince1970);
            dt = dt.ToUniversalTime();
            return dt;
        }
Пример #21
0
        public static void Main(string[] args)
        {
            // https://projecteuler.net/problem=18
            // https://projecteuler.net/problem=67
            int size = 100;//size of triangle from inputFilePath
            int[][] triangle = new int[size][];
            for (int i = 0; i < size; i++)
                triangle [i] = new int[i + 1];

            string inputFilePath = "test67.txt";//source file
            var fileStream = new System.IO.FileStream (inputFilePath, System.IO.FileMode.Open);
            var file = new System.IO.StreamReader(fileStream, System.Text.Encoding.UTF8);
            int lineCounter = 0;
            string lineOfText;
            while ((lineOfText = file.ReadLine()) != null) {
                var values = lineOfText.Split(' ');
                for (int j = 0; j < triangle [lineCounter].Length; j++)
                    triangle [lineCounter] [j] = Int32.Parse (values [j]);
                lineCounter++;
            }
            file.Close ();
            fileStream.Close ();

            //go from the bottom of triangle to the top
            //replace value in the line with maximum sum path from the botoom of the triangle to this point
            for (int k = size-2; k >= 0; k--) {
                var currentMaxValues = MaxPathSum (triangle [k+1], triangle [k]);
                for (int r = 0; r < currentMaxValues.Length; r++)
                    triangle [k] [r] = currentMaxValues [r];
            }
            Console.WriteLine ("Maximum path sum - {0}", triangle[0][0]);
        }
        public static bool ByteArrayToFile(string fileName, byte[] data)
        {
            try
              {
             // Open file for reading
             System.IO.FileStream _FileStream =
                new System.IO.FileStream(fileName, System.IO.FileMode.Create,
                                         System.IO.FileAccess.Write);
             // Writes a block of bytes to this stream using data from
             // a byte array.
             _FileStream.Write(data, 0, data.Length);

             // close file stream
             _FileStream.Close();

             return true;
              }
              catch (Exception _Exception)
              {
             // Error
             Console.WriteLine("Exception caught in process: {0}",
                               _Exception.ToString());
              }

              // error occured, return false
              return false;
        }
Пример #23
0
        protected void BackupCompradoresLinkButton_Click(object sender, EventArgs e)
        {
            if (CedWebRN.Fun.NoEstaLogueadoUnUsuarioPremium((CedWebEntidades.Sesion)Session["Sesion"]))
            {
                ClientScript.RegisterStartupScript(GetType(), "Message", "<SCRIPT LANGUAGE='javascript'>alert('Esta funcionalidad es exclusiva del SERVICIO PREMIUM.  Contáctese con Cedeira Software Factory para acceder al servicio.');</script>");
            }
            else
            {
                List<CedWebEntidades.Comprador> compradores = CedWebRN.Comprador.Lista(((CedWebEntidades.Sesion)Session["Sesion"]).Cuenta, (CedEntidades.Sesion)Session["Sesion"], false);
                if (compradores.Count == 0)
                {
                    ClientScript.RegisterStartupScript(GetType(), "Message", "<SCRIPT LANGUAGE='javascript'>alert('No hay datos de Compradores para descargar.');</script>");
                }
                else
                {
                    System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(compradores.GetType());
                    System.IO.MemoryStream m = new System.IO.MemoryStream();
                    System.Xml.XmlWriter writerdememoria = new System.Xml.XmlTextWriter(m, System.Text.Encoding.GetEncoding("ISO-8859-1"));
                    x.Serialize(writerdememoria, compradores);
                    m.Seek(0, System.IO.SeekOrigin.Begin);
                    string nombreArchivo = "eFact-Compradores-" + ((CedWebEntidades.Sesion)Session["Sesion"]).Cuenta.Id.Replace(".", String.Empty).ToUpper() + ".xml";
                    System.IO.FileStream fs = new System.IO.FileStream(Server.MapPath(@"~/Temp/" + nombreArchivo), System.IO.FileMode.Create);
                    m.WriteTo(fs);
                    fs.Close();
                    Server.Transfer("~/DescargaTemporarios.aspx?archivo=" + nombreArchivo, false);
                }

            }
        }
 public static void SaveAssembly(string assemblyName, string destinationPath)
 {
     string sql = @"SELECT af.name, af.content FROM sys.assemblies a INNER JOIN sys.assembly_files af ON a.assembly_id = af.assembly_id WHERE a.name = @assemblyname";
     using (SqlConnection conn = new SqlConnection("context connection=true"))   //Create current context connection
     {
         using (SqlCommand cmd = new SqlCommand(sql, conn))
         {
             SqlParameter param = new SqlParameter("@assemblyname", System.Data.SqlDbType.NVarChar);
             param.Value = assemblyName;
             // param.Size = 128;
             cmd.Parameters.Add(param);
             cmd.Connection.Open();  //Open the context connetion
             using (SqlDataReader reader = cmd.ExecuteReader())
             {
                 while (reader.Read()) //Iterate through assembly files
                 {
                     string assemblyFileName = reader.GetString(0);  //get assembly file name from the name (first) column
                     System.Data.SqlTypes.SqlBytes bytes = reader.GetSqlBytes(1);         //get assembly binary data from the content (second) column
                     string outputFile = System.IO.Path.Combine(destinationPath, assemblyFileName);
                     SqlContext.Pipe.Send(string.Format("Exporting assembly file [{0}] to [{1}]", assemblyFileName, outputFile)); //Send information about exported file back to the calling session
                     using (System.IO.FileStream byteStream = new System.IO.FileStream(outputFile, System.IO.FileMode.CreateNew))
                     {
                         byteStream.Write(bytes.Value, 0, (int)bytes.Length);
                         byteStream.Close();
                     }
                 }
             }
         }
         conn.Close();
     }
 }
        private void button1_Click(object sender, EventArgs e)
        {
            if (listBox1.SelectedItem!=null)
            {
                SaveFileDialog sav=new SaveFileDialog();
                sav.Filter = "*.hex|*.hex|*.*|*'.*";
                DialogResult res = sav.ShowDialog();
                if (res==DialogResult.OK)
                {
                    try
                    {
                        
                        byte[] blk = myConn.PLCGetBlockInMC7(listBox1.SelectedItem.ToString());

                        System.IO.FileStream _FileStream = new System.IO.FileStream(sav.FileName,
                                                                                    System.IO.FileMode.Create,
                                                                                    System.IO.FileAccess.Write);
                        _FileStream.Write(blk, 0, blk.Length);
                        _FileStream.Close();

                        MessageBox.Show("Block " + listBox1.SelectedItem.ToString() + " saved to: " + sav.FileName);
                    }
                    catch(Exception ex)
                    {
                        MessageBox.Show("Error: " + ex.Message);
                    }
                }
            }
        }
Пример #26
0
 protected void BackupVendedorLinkButton_Click(object sender, EventArgs e)
 {
     try
     {
         if (CedWebRN.Fun.NoEstaLogueadoUnUsuarioPremium((CedWebEntidades.Sesion)Session["Sesion"]))
         {
             ClientScript.RegisterStartupScript(GetType(), "Message", "<SCRIPT LANGUAGE='javascript'>alert('Esta funcionalidad es exclusiva del SERVICIO PREMIUM.  Contáctese con Cedeira Software Factory para acceder al servicio.');</script>");
         }
         else
         {
             CedWebEntidades.Vendedor vendedor = new CedWebEntidades.Vendedor();
             vendedor.IdCuenta = ((CedWebEntidades.Sesion)Session["Sesion"]).Cuenta.Id;
             CedWebRN.Vendedor.Leer(vendedor, (CedEntidades.Sesion)Session["Sesion"]);
             System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(vendedor.GetType());
             System.IO.MemoryStream m = new System.IO.MemoryStream();
             System.Xml.XmlWriter writerdememoria = new System.Xml.XmlTextWriter(m, System.Text.Encoding.GetEncoding("ISO-8859-1"));
             x.Serialize(writerdememoria, vendedor);
             m.Seek(0, System.IO.SeekOrigin.Begin);
             string nombreArchivo = "eFact-Vendedor-" + ((CedWebEntidades.Sesion)Session["Sesion"]).Cuenta.Id.Replace(".", String.Empty).ToUpper() + ".xml";
             System.IO.FileStream fs = new System.IO.FileStream(Server.MapPath(@"~/Temp/" + nombreArchivo), System.IO.FileMode.Create);
             m.WriteTo(fs);
             fs.Close();
             Server.Transfer("~/DescargaTemporarios.aspx?archivo=" + nombreArchivo, false);
         }
     }
     catch (Microsoft.ApplicationBlocks.ExceptionManagement.Validaciones.ElementoInexistente)
     {
         ClientScript.RegisterStartupScript(GetType(), "Message", "<SCRIPT LANGUAGE='javascript'>alert('No hay datos del Vendedor para descargar.');</script>");
     }
     catch (Exception ex)
     {
         ClientScript.RegisterStartupScript(GetType(), "Message", "<SCRIPT LANGUAGE='javascript'>alert('" + ex.Message.ToString() + "');</script>");
     }
 }
Пример #27
0
        //Code PES
        private string GetBuildNumber()
        {
            string strBuildNumber = string.Empty, timestamp = string.Empty;
            string filePath = System.Reflection.Assembly.GetCallingAssembly().Location;
            const int c_PeHeaderOffset = 60;
            const int c_LinkerTimestampOffset = 8;
            byte[] b = new byte[2048];
            System.IO.Stream s = null;

            try
            {
                s = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                s.Read(b, 0, 2048);
            }
            finally
            {
                if (s != null)
                {
                    s.Close();
                }
            }

            int i = System.BitConverter.ToInt32(b, c_PeHeaderOffset);
            int secondsSince1970 = System.BitConverter.ToInt32(b, i + c_LinkerTimestampOffset);
            DateTime dtDate = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
            dtDate = dtDate.AddSeconds(secondsSince1970);
            dtDate = dtDate.ToLocalTime();
            timestamp = dtDate.ToString("yyyyMMddHHmmss");
            if (timestamp == string.Empty)
            { timestamp = "UNKOWN!"; }
            strBuildNumber = "Build  : " + timestamp;
            return strBuildNumber;
        }
Пример #28
0
        public MailMsg(Outlook.MailItem msg, string user)
        {
            this._User = user;
            this._id = msg.EntryID;
            timestamp = msg.SentOn;
            this._Subject = msg.Subject;
            this._Body = msg.Body;

            if (msg.Attachments.Count>0)
            {
                //we will add all attachements to a list
                List<Attachement> oList = new List<Attachement>();
                foreach (Outlook.Attachment att in msg.Attachments)
                {
                    //need to save file temporary to get contents
                    string filename = System.IO.Path.GetTempFileName();
                    att.SaveAsFile(filename);
                    System.IO.FileStream fs=new System.IO.FileStream(filename,System.IO.FileMode.Open);
                    oList.Add(new Attachement(fs, att.FileName));
                    fs.Close();
                    System.IO.File.Delete(filename);
                }
                this._Attachements = oList.ToArray();
                this.attList.AddRange(oList);
            }
        }
Пример #29
0
 //---------- 一些静态方法 ----------
 // 下载文件到指定的路径
 public static void DownloadFile(string URL, string filename)
 {
     try
     {
         System.Net.HttpWebRequest Myrq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(URL);
         System.Net.HttpWebResponse myrp = (System.Net.HttpWebResponse)Myrq.GetResponse();
         long totalBytes = myrp.ContentLength;
         System.IO.Stream st = myrp.GetResponseStream();
         System.IO.Stream so = new System.IO.FileStream(filename, System.IO.FileMode.Create);
         long totalDownloadedByte = 0;
         byte[] by = new byte[1024];
         int osize = st.Read(by, 0, (int)by.Length);
         while (osize > 0)
         {
             totalDownloadedByte = osize + totalDownloadedByte;
             System.Windows.Forms.Application.DoEvents();
             so.Write(by, 0, osize);
             osize = st.Read(by, 0, (int)by.Length);
         }
         so.Close();
         st.Close();
     }
     catch (Exception ex)
     {
         logLog(ex.ToString());
     }
 }
 public void Save()
 {
     System.IO.FileStream stream = new System.IO.FileStream(this.fileName, System.IO.FileMode.Create);
     XmlSerializer serializer = new XmlSerializer(typeof(CryptoPasswordProperties));
     serializer.Serialize(stream, this);
     stream.Close();
 }
Пример #31
0
        public static string GetMD5(string filePath)
        {
            string strResult = "";
            string strHashData = "";

            byte[] arrbytHashValue;
            System.IO.FileStream oFileStream = null;

            System.Security.Cryptography.MD5CryptoServiceProvider oMD5Hasher =
                       new System.Security.Cryptography.MD5CryptoServiceProvider();

            try
            {
                oFileStream = new System.IO.FileStream(filePath, System.IO.FileMode.Open,
                      System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite);
                arrbytHashValue = oMD5Hasher.ComputeHash(oFileStream);//计算指定Stream 对象的哈希值
                oFileStream.Close();
                //由以连字符分隔的十六进制对构成的String,其中每一对表示value 中对应的元素;例如“F-2C-4A”
                strHashData = System.BitConverter.ToString(arrbytHashValue);
                //替换-
                strHashData = strHashData.Replace("-", "");
                strResult = strHashData;
            }
            catch (System.Exception ex)
            {

            }

            return strResult;
        }
Пример #32
0
        public void Dispose()
        {
            if (_logfile != null)
            {
                _logfile.Close();
                GC.SuppressFinalize(_logfile); //Will skip finalizer method below
                _logfile = null;
            }

            _logfile?.Close();
        }
Пример #33
0
        private bool UploadFile(string yyyyMMddHHmmss, string filename)
        {
            var b = false;

            try
            {
                var strFile = System.IO.Path.GetFileName(filename);

                using (var srv = new maionemikyWS.EmailSending())
                {
                    var fInfo    = new System.IO.FileInfo(filename);
                    var numBytes = fInfo.Length;

                    try
                    {
                        using (var fStream = new System.IO.FileStream(filename, System.IO.FileMode.Open, System.IO.FileAccess.Read))
                            using (var br = new System.IO.BinaryReader(fStream))
                            {
                                var data = br.ReadBytes(Convert.ToInt32(numBytes));

                                br.Close();
                                fStream.Close();

                                var R = srv.UploadFileRC(Credenziali, data, strFile);

                                try
                                {
                                    switch (R)
                                    {
                                    case maionemikyWS.CredenzialiRisultato.TuttoOK:
                                        return(true);

                                    case maionemikyWS.CredenzialiRisultato.FileInviato:
                                        return(true);

                                    case maionemikyWS.CredenzialiRisultato.Presente_PasswordErrata:
                                        throw new Exception("Password errata!");

                                    case maionemikyWS.CredenzialiRisultato.Assente:
                                        throw new Exception("DB assente!");

                                    case maionemikyWS.CredenzialiRisultato.Errore:
                                        throw new Exception("Errore!");

                                    case maionemikyWS.CredenzialiRisultato.ProgrammaNonAutorizzato:
                                        throw new Exception("Programma non autorizzato!");

                                    case maionemikyWS.CredenzialiRisultato.DBSulServerEPiuRecente:
                                        throw new Exception("DB sul server è più recente!");
                                    }
                                }
                                catch (Exception exv1)
                                {
                                    cGB.MsgBox(exv1.Message, System.Windows.Forms.MessageBoxIcon.Error);
                                }
                            }
                    }
                    catch
                    {
                        //error
                        b = false;
                    }
                }
            }
            catch
            {
                // display an error message to the user
                b = false;
            }

            return(b);
        }
Пример #34
0
        /// <summary>Loads the black-box logs from the previous simulation run</summary>
        internal static void LoadLogs()
        {
            string BlackBoxFile = OpenBveApi.Path.CombineFile(Program.FileSystem.SettingsFolder, "logs.bin");

            try
            {
                using (System.IO.FileStream Stream = new System.IO.FileStream(BlackBoxFile, System.IO.FileMode.Open, System.IO.FileAccess.Read))
                {
                    using (System.IO.BinaryReader Reader = new System.IO.BinaryReader(Stream, System.Text.Encoding.UTF8))
                    {
                        byte[]      Identifier = new byte[] { 111, 112, 101, 110, 66, 86, 69, 95, 76, 79, 71, 83 };
                        const short Version    = 1;
                        byte[]      Data       = Reader.ReadBytes(Identifier.Length);
                        for (int i = 0; i < Identifier.Length; i++)
                        {
                            if (Identifier[i] != Data[i])
                            {
                                throw new System.IO.InvalidDataException();
                            }
                        }
                        short Number = Reader.ReadInt16();
                        if (Version != Number)
                        {
                            throw new System.IO.InvalidDataException();
                        }
                        Game.LogRouteName = Reader.ReadString();
                        Game.LogTrainName = Reader.ReadString();
                        Game.LogDateTime  = DateTime.FromBinary(Reader.ReadInt64());
                        Interface.CurrentOptions.GameMode = (Interface.GameMode)Reader.ReadInt16();
                        Game.BlackBoxEntryCount           = Reader.ReadInt32();
                        Game.BlackBoxEntries = new Game.BlackBoxEntry[Game.BlackBoxEntryCount];
                        for (int i = 0; i < Game.BlackBoxEntryCount; i++)
                        {
                            Game.BlackBoxEntries[i].Time           = Reader.ReadDouble();
                            Game.BlackBoxEntries[i].Position       = Reader.ReadDouble();
                            Game.BlackBoxEntries[i].Speed          = Reader.ReadSingle();
                            Game.BlackBoxEntries[i].Acceleration   = Reader.ReadSingle();
                            Game.BlackBoxEntries[i].ReverserDriver = Reader.ReadInt16();
                            Game.BlackBoxEntries[i].ReverserSafety = Reader.ReadInt16();
                            Game.BlackBoxEntries[i].PowerDriver    = (Game.BlackBoxPower)Reader.ReadInt16();
                            Game.BlackBoxEntries[i].PowerSafety    = (Game.BlackBoxPower)Reader.ReadInt16();
                            Game.BlackBoxEntries[i].BrakeDriver    = (Game.BlackBoxBrake)Reader.ReadInt16();
                            Game.BlackBoxEntries[i].BrakeSafety    = (Game.BlackBoxBrake)Reader.ReadInt16();
                            Game.BlackBoxEntries[i].EventToken     = (Game.BlackBoxEventToken)Reader.ReadInt16();
                        }
                        Game.ScoreLogCount             = Reader.ReadInt32();
                        Game.ScoreLogs                 = new Game.ScoreLog[Game.ScoreLogCount];
                        Game.CurrentScore.CurrentValue = 0;
                        for (int i = 0; i < Game.ScoreLogCount; i++)
                        {
                            Game.ScoreLogs[i].Time          = Reader.ReadDouble();
                            Game.ScoreLogs[i].Position      = Reader.ReadDouble();
                            Game.ScoreLogs[i].Value         = Reader.ReadInt32();
                            Game.ScoreLogs[i].TextToken     = (Game.ScoreTextToken)Reader.ReadInt16();
                            Game.CurrentScore.CurrentValue += Game.ScoreLogs[i].Value;
                        }
                        Game.CurrentScore.Maximum = Reader.ReadInt32();
                        Identifier = new byte[] { 95, 102, 105, 108, 101, 69, 78, 68 };
                        Data       = Reader.ReadBytes(Identifier.Length);
                        for (int i = 0; i < Identifier.Length; i++)
                        {
                            if (Identifier[i] != Data[i])
                            {
                                throw new System.IO.InvalidDataException();
                            }
                        }
                        Reader.Close();
                    } Stream.Close();
                }
            }
            catch
            {
                Game.LogRouteName       = "";
                Game.LogTrainName       = "";
                Game.LogDateTime        = DateTime.Now;
                Game.BlackBoxEntries    = new Game.BlackBoxEntry[256];
                Game.BlackBoxEntryCount = 0;
                Game.ScoreLogs          = new Game.ScoreLog[64];
                Game.ScoreLogCount      = 0;
            }
        }
Пример #35
0
 /// <summary>
 /// Serialize the whole UI to filename.
 /// Note: serialization have some limitation and things that will not be included in xml,
 /// like even handlers. Please read docs carefuly to know what to expect.
 /// </summary>
 /// <param name="path">Filename to serialize into.</param>
 public void Serialize(string path)
 {
     System.IO.FileStream file = System.IO.File.Create(path);
     Serialize(file);
     file.Close();
 }
        public override bool Obtain()
        {
            lock (this)
            {
                if (LockExists())
                {
                    // Our instance is already locked:
                    return(false);
                }

                // Ensure that lockDir exists and is a directory.
                bool tmpBool;
                if (System.IO.File.Exists(lockDir.FullName))
                {
                    tmpBool = true;
                }
                else
                {
                    tmpBool = System.IO.Directory.Exists(lockDir.FullName);
                }
                if (!tmpBool)
                {
                    try
                    {
                        System.IO.Directory.CreateDirectory(lockDir.FullName);
                    }
                    catch
                    {
                        throw new System.IO.IOException("Cannot create directory: " + lockDir.FullName);
                    }
                }
                else if (!System.IO.Directory.Exists(lockDir.FullName))
                {
                    throw new System.IO.IOException("Found regular file where directory expected: " + lockDir.FullName);
                }

                System.String canonicalPath = path.FullName;

                bool markedHeld = false;

                try
                {
                    // Make sure nobody else in-process has this lock held
                    // already, and, mark it held if not:

                    lock (LOCK_HELD)
                    {
                        if (LOCK_HELD.Contains(canonicalPath))
                        {
                            // Someone else in this JVM already has the lock:
                            return(false);
                        }
                        else
                        {
                            // This "reserves" the fact that we are the one
                            // thread trying to obtain this lock, so we own
                            // the only instance of a channel against this
                            // file:
                            LOCK_HELD.Add(canonicalPath, canonicalPath);
                            markedHeld = true;
                        }
                    }

                    try
                    {
                        f = new System.IO.FileStream(path.FullName, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite);
                    }
                    catch (System.IO.IOException e)
                    {
                        // On Windows, we can get intermittent "Access
                        // Denied" here.  So, we treat this as failure to
                        // acquire the lock, but, store the reason in case
                        // there is in fact a real error case.
                        failureReason = e;
                        f             = null;
                    }

                    if (f != null)
                    {
                        try
                        {
                            channel      = f;
                            lock_Renamed = false;
                            try
                            {
                                channel.Lock(0, channel.Length);
                                lock_Renamed = true;
                            }
                            catch (System.IO.IOException e)
                            {
                                // At least on OS X, we will sometimes get an
                                // intermittent "Permission Denied" IOException,
                                // which seems to simply mean "you failed to get
                                // the lock".  But other IOExceptions could be
                                // "permanent" (eg, locking is not supported via
                                // the filesystem).  So, we record the failure
                                // reason here; the timeout obtain (usually the
                                // one calling us) will use this as "root cause"
                                // if it fails to get the lock.
                                failureReason = e;
                            }
                            finally
                            {
                                if (lock_Renamed == false)
                                {
                                    try
                                    {
                                        channel.Close();
                                    }
                                    finally
                                    {
                                        channel = null;
                                    }
                                }
                            }
                        }
                        finally
                        {
                            if (channel == null)
                            {
                                try
                                {
                                    f.Close();
                                }
                                finally
                                {
                                    f = null;
                                }
                            }
                        }
                    }
                }
                finally
                {
                    if (markedHeld && !LockExists())
                    {
                        lock (LOCK_HELD)
                        {
                            if (LOCK_HELD.Contains(canonicalPath))
                            {
                                LOCK_HELD.Remove(canonicalPath);
                            }
                        }
                    }
                }
                return(LockExists());
            }
        }
Пример #37
0
        /// <summary>Saves the current in-game black box log</summary>
        internal static void SaveLogs()
        {
            if (Interface.CurrentOptions.BlackBox == false)
            {
                return;
            }
            string BlackBoxFile = OpenBveApi.Path.CombineFile(Program.FileSystem.SettingsFolder, "logs.bin");

            try
            {
                using (System.IO.FileStream Stream = new System.IO.FileStream(BlackBoxFile, System.IO.FileMode.Create, System.IO.FileAccess.Write))
                {
                    //TODO: This code recreates the file every frame.....
                    //It should be possible to spin up a stream in a separate thread which then continously appends
                    using (System.IO.BinaryWriter Writer = new System.IO.BinaryWriter(Stream, System.Text.Encoding.UTF8))
                    {
                        byte[]      Identifier = new byte[] { 111, 112, 101, 110, 66, 86, 69, 95, 76, 79, 71, 83 };
                        const short Version    = 1;
                        Writer.Write(Identifier);
                        Writer.Write(Version);
                        Writer.Write(Game.LogRouteName);
                        Writer.Write(Game.LogTrainName);
                        Writer.Write(Game.LogDateTime.ToBinary());
                        Writer.Write((short)Interface.CurrentOptions.GameMode);
                        Writer.Write(Game.BlackBoxEntryCount);
                        for (int i = 0; i < Game.BlackBoxEntryCount; i++)
                        {
                            Writer.Write(Game.BlackBoxEntries[i].Time);
                            Writer.Write(Game.BlackBoxEntries[i].Position);
                            Writer.Write(Game.BlackBoxEntries[i].Speed);
                            Writer.Write(Game.BlackBoxEntries[i].Acceleration);
                            Writer.Write(Game.BlackBoxEntries[i].ReverserDriver);
                            Writer.Write(Game.BlackBoxEntries[i].ReverserSafety);
                            Writer.Write((short)Game.BlackBoxEntries[i].PowerDriver);
                            Writer.Write((short)Game.BlackBoxEntries[i].PowerSafety);
                            Writer.Write((short)Game.BlackBoxEntries[i].BrakeDriver);
                            Writer.Write((short)Game.BlackBoxEntries[i].BrakeSafety);
                            Writer.Write((short)Game.BlackBoxEntries[i].EventToken);
                        }

                        Writer.Write(Game.ScoreLogCount);
                        for (int i = 0; i < Game.ScoreLogCount; i++)
                        {
                            Writer.Write(Game.ScoreLogs[i].Time);
                            Writer.Write(Game.ScoreLogs[i].Position);
                            Writer.Write(Game.ScoreLogs[i].Value);
                            Writer.Write((short)Game.ScoreLogs[i].TextToken);
                        }

                        Writer.Write(Game.CurrentScore.Maximum);
                        Identifier = new byte[] { 95, 102, 105, 108, 101, 69, 78, 68 };
                        Writer.Write(Identifier);
                        Writer.Close();
                    }

                    Stream.Close();
                }
            }
            catch
            {
                Interface.CurrentOptions.BlackBox = false;
                Interface.AddMessage(MessageType.Error, false, "An unexpected error occurred whilst attempting to write to the black box log- Black box has been disabled.");
            }
        }
Пример #38
0
        private void button1_Click(object sender, EventArgs e)
        {
            if (txt_filename.get_value() == "")
            {
                MessageBox.Show("文件名不能为空 ! ");
                return;
            }

            DateTime mydate = import_date.Value;

            成品库房DAL dal = new 成品库房DAL();

            if (dal.getInfoByDate(mydate).Rows.Count > 0)
            {
                if (MessageBox.Show("选择的月份已有数据, 真的要继续导入吗 ? ", "警 告", MessageBoxButtons.YesNo) != DialogResult.Yes)
                {
                    return;
                }
            }

            string          filename = txt_filename.get_value();
            string          strConn  = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + filename + ";" + "Extended Properties=Excel 8.0;";
            OleDbConnection conn     = new OleDbConnection(strConn);

            conn.Open();
            string strExcel = "";

            OleDbDataReader dr;
            OleDbCommand    myCommand = new OleDbCommand();

            strExcel = @"select rtrim(工号), 金额 from [库存信息$]";

            myCommand.Connection  = conn;
            myCommand.CommandText = strExcel;
            dr = myCommand.ExecuteReader();
            库房信息        mycls;
            List <库房信息> mylist = new List <库房信息>();


            if (dr.HasRows)
            {
                while (dr.Read())
                {
                    mycls = new 库房信息();

                    mycls.workno = dr.GetString(0);
                    mycls.income = decimal.Parse(dr.GetValue(1).ToString());
                    mycls.mydate = import_date.Value;

                    mylist.Add(mycls);
                }
            }
            dr.Close();

            工号表DAL ghdal       = new 工号表DAL();
            bool   wrongflag   = false;
            string wrongworkno = "";

            foreach (库房信息 mycls1 in mylist)
            {
                if (!ghdal.IsIn工号表(mycls1.workno))
                {
                    //MessageBox.Show("工号 :" + mycls1.工号 + "  不存在 !");
                    wrongflag    = true;
                    wrongworkno += mycls1.workno + "\r\n";
                }
            }
            if (wrongflag)
            {
                MessageBox.Show(wrongworkno, "错误工号");

                System.IO.FileStream fs = new System.IO.FileStream("E:/错误工号.TXT", System.IO.FileMode.OpenOrCreate);
                byte[] data             = System.Text.Encoding.Default.GetBytes(wrongworkno);

                fs.Write(data, 0, data.Length);
                fs.Close();
                return;
            }

            成品库房DAL dal1 = new 成品库房DAL();

            foreach (库房信息 mycls1 in mylist)
            {
                //DataGridViewRow myrow = new DataGridViewRow();

                //myrow.Cells[0].Value = mycls1.workno;
                //myrow.Cells[1].Value = mycls1.mydate;
                //myrow.Cells[2].Value = mycls1.income;

                dal1.insert成品库房表(mycls1.workno, mycls1.mydate, mycls1.income * (-1));
            }
        }
Пример #39
0
        // GetConnectionSpeed


        // http://support.microsoft.com/kb/812406
        // COR.ASP.NET.SafeDownloadFile(strFileName, strClientFileName)
        public static void SafeDownloadFile(string strFilePath, string strClientFileName)
        {
            byte[] buffer = new byte[10001];
            // Buffer to read 10K bytes in chunk:
            int length = 0;
            // Length of the file:
            long dataToRead = 0;

            // Total bytes to read

            try {
                System.IO.FileInfo fiDownloadFile = new System.IO.FileInfo(strFilePath);
                if (fiDownloadFile.Exists)
                {
                    System.Web.HttpContext.Current.Response.Clear();
                    // Open the file.
                    using (System.IO.FileStream iStream = new System.IO.FileStream(strFilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read))
                    {
                        // Total bytes to read:
                        dataToRead = iStream.Length;

                        System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment; filename=\"{0}\"", strClientFileName));
                        System.Web.HttpContext.Current.Response.AddHeader("Pragma", "public");
                        System.Web.HttpContext.Current.Response.AddHeader("Expires", "0");
                        System.Web.HttpContext.Current.Response.AddHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
                        System.Web.HttpContext.Current.Response.AddHeader("Content-Transfer-Encoding", "binary");
                        System.Web.HttpContext.Current.Response.AddHeader("Content-Length", fiDownloadFile.Length.ToString());
                        //Response.ContentType = "application/pdf"
                        System.Web.HttpContext.Current.Response.ContentType = "application/octet-stream";

                        // Read the bytes.
                        while (dataToRead > 0)
                        {
                            // Verify that the client is connected.
                            if (System.Web.HttpContext.Current.Response.IsClientConnected)
                            {
                                // Read the data in buffer
                                length = iStream.Read(buffer, 0, 10000);

                                // Write the data to the current output stream.
                                System.Web.HttpContext.Current.Response.OutputStream.Write(buffer, 0, length);

                                // Flush the data to the HTML output.
                                System.Web.HttpContext.Current.Response.Flush();

                                buffer = new byte[10001];
                                // Clear the buffer
                                dataToRead = dataToRead - length;
                            }
                            else
                            {
                                //prevent infinite loop if user disconnects
                                dataToRead = -1;
                            }
                        }

                        if (iStream != null)
                        {
                            // Close the file.
                            iStream.Close();
                        }
                    }
                }
                else
                {
                    //COR.Debug.Output.MsgBox("Diese Datei ist auf dem Datenträger nicht vorhanden.")
                }
            } catch (Exception ex) {
                // Trap the error, if any.
                System.Web.HttpContext.Current.Response.Write("Error : " + ex.Message);
            } finally {
                System.Web.HttpContext.Current.Response.Close();
                //System.Web.HttpContext.Current.Response.End()
            }
        }
Пример #40
0
        public static string DownloadAddonPackage(string _FTPDownloadAddress, int _AddonPackageFileSize, Action <float> _DownloadProgress = null)
        {
            try
            {
                int fileNameStartIndex = _FTPDownloadAddress.LastIndexOf('\\');
                if (fileNameStartIndex == -1 || fileNameStartIndex < _FTPDownloadAddress.LastIndexOf('/'))
                {
                    fileNameStartIndex = _FTPDownloadAddress.LastIndexOf('/');
                }
                string fileName = StaticValues.LauncherDownloadsDirectory + _FTPDownloadAddress.Substring(fileNameStartIndex + 1);

                FtpWebRequest    ftpRequest  = null;
                FtpWebResponse   ftpResponse = null;
                System.IO.Stream ftpStream   = null;
                /* Create an FTP Request */
                ftpRequest = (FtpWebRequest)FtpWebRequest.Create(_FTPDownloadAddress);
                _DownloadProgress(0.1f);
                /* Log in to the FTP Server with the User Name and Password Provided */
                ftpRequest.Credentials = new NetworkCredential("WowLauncherUpdater", "");
                /* When in doubt, use these options */
                ftpRequest.UseBinary  = true;
                ftpRequest.UsePassive = true;
                ftpRequest.KeepAlive  = true;
                /* Specify the Type of FTP Request */
                ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;
                /* Establish Return Communication with the FTP Server */
                ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
                _DownloadProgress(0.2f);
                /* Get the FTP Server's Response Stream */
                ftpStream = ftpResponse.GetResponseStream();
                /* Open a File Stream to Write the Downloaded File */
                Utility.AssertFilePath(fileName);
                System.IO.FileStream localFileStream = new System.IO.FileStream(fileName, System.IO.FileMode.Create);
                _DownloadProgress(0.3f);
                /* Buffer for the Downloaded Data */
                byte[] byteBuffer = new byte[2048];
                int    bytesRead  = ftpStream.Read(byteBuffer, 0, 2048);
                /* Download the File by Writing the Buffered Data Until the Transfer is Complete */
                int totalDownloaded = 0;
                try
                {
                    while (bytesRead > 0)
                    {
                        localFileStream.Write(byteBuffer, 0, bytesRead);
                        totalDownloaded += bytesRead;
                        if (_AddonPackageFileSize != 0)
                        {
                            float progressValue = 0.3f + ((float)totalDownloaded / (float)_AddonPackageFileSize) * 0.65f;
                            if (progressValue <= 0.95f)
                            {
                                _DownloadProgress(progressValue);
                            }
                        }
                        bytesRead = ftpStream.Read(byteBuffer, 0, 2048);
                    }
                }
                catch (Exception ex) { Logger.LogException(ex); }
                /* Resource Cleanup */
                localFileStream.Close();
                ftpStream.Close();
                ftpResponse.Close();
                ftpRequest = null;
                _DownloadProgress(1.0f);
                return(fileName);
            }
            catch (Exception ex) { Logger.LogException(ex); }
            return("");
        }
Пример #41
0
        internal bool ParseFile(ProgramName name, string referrer, Span location, System.Threading.CancellationToken ctok, out ParseResult pr)
        {
            parseResult = new ParseResult(new Program(name));
            pr          = parseResult;
            bool result;

            try
            {
                var fi = new System.IO.FileInfo(name.Uri.AbsolutePath);
                if (!fi.Exists)
                {
                    var badFile = new Flag(
                        SeverityKind.Error,
                        default(Span),
                        referrer == null ?
                        Constants.BadFile.ToString(string.Format("The file {0} does not exist", name.ToString(envParams))) :
                        Constants.BadFile.ToString(string.Format("The file {0} referred to in {1} ({2}, {3}) does not exist", name.ToString(envParams), referrer, location.StartLine, location.StartCol)),
                        Constants.BadFile.Code,
                        parseResult.Program.Node.Name);
                    parseResult.AddFlag(badFile);
                    parseResult.Program.Node.GetNodeHash();
                    return(false);
                }

                var str = new System.IO.FileStream(name.Uri.AbsolutePath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                ((Scanner)Scanner).SetSource(str);
                ((Scanner)Scanner).ParseResult = parseResult;
                ResetState();

                result = Parse(ctok);
                str.Close();
            }
            catch (Exception e)
            {
                var badFile = new Flag(
                    SeverityKind.Error,
                    default(Span),
                    referrer == null ?
                    Constants.BadFile.ToString(e.Message) :
                    Constants.BadFile.ToString(string.Format("{0} referred to in {1} ({2}, {3})", e.Message, referrer, location.StartLine, location.StartCol)),
                    Constants.BadFile.Code,
                    parseResult.Program.Node.Name);
                parseResult.AddFlag(badFile);
                parseResult.Program.Node.GetNodeHash();
                return(false);
            }

            if (ctok.IsCancellationRequested)
            {
                var badFile = new Flag(
                    SeverityKind.Error,
                    default(Span),
                    referrer == null ?
                    Constants.OpCancelled.ToString(string.Format("Cancelled parsing of {0}", name.ToString(envParams))) :
                    Constants.OpCancelled.ToString(string.Format("Cancelled parsing of {0} referred to in {1} ({2}, {3})", name.ToString(envParams), referrer, location.StartLine, location.StartCol)),
                    Constants.OpCancelled.Code,
                    parseResult.Program.Node.Name);
                parseResult.AddFlag(badFile);
                parseResult.Program.Node.GetNodeHash();
                return(false);
            }

            parseResult.Program.Node.GetNodeHash();
            return(result);
        }
Пример #42
0
        }/* onFormLoaded(object sender, EventArgs e)*/

        public void initScreen()
        {
            // get device orientation
            try
            {
                var detectOrientationProcess = new Process();
                setProcessStartInfo(detectOrientationProcess, @"shell ""dumpsys input | grep SurfaceOrientation""");
                detectOrientationProcess.Start();
                string output = detectOrientationProcess.StandardOutput.ReadToEnd();
                detectOrientationProcess.WaitForExit();
                foreach (char C in output)
                {
                    if (C == '0' || C == '1' || C == '2' || C == '3')
                    {
                        orientation = short.Parse(C.ToString());
                    }
                }



                var downloadScreenshotProcess = new Process();
                var captureScreenshotProcess  = new Process();

                setProcessStartInfo(captureScreenshotProcess, @"shell /system/bin/screencap -p /sdcard/screenshot.png");
                captureScreenshotProcess.Start();
                captureScreenshotProcess.WaitForExit();

                setProcessStartInfo(downloadScreenshotProcess, @"pull /sdcard/screenshot.png screenshot.png");
                downloadScreenshotProcess.Start();
                downloadScreenshotProcess.WaitForExit();
            }
            catch (Exception e)
            {
                set_txtbox_debugmessage("initScreen(): exception, did you place adb.exe at the same path?");
                return;
            }
            if (System.IO.File.Exists(AppConst.ScreenshotFileName))
            {
                try
                {
                    System.IO.FileStream fs = new System.IO.FileStream(AppConst.ScreenshotFileName, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read);
                    calculateScaleFactor(fs);

                    System.Drawing.Image img = System.Drawing.Image.FromStream(fs);
                    switch (orientation)
                    {
                    case 3:
                        img.RotateFlip(RotateFlipType.Rotate90FlipNone);
                        break;

                    case 1:
                        img.RotateFlip(RotateFlipType.Rotate270FlipNone);
                        break;

                    case 0:
                        break;
                    }
                    rotateScreenshot(orientation);
                    pbox_screen.Image = img;
                    fs.Close();
                }
                catch (Exception e)
                {
                    System.Text.StringBuilder eMsg = new System.Text.StringBuilder();
                    eMsg.Append("calculateScaleFactor: ");
                    eMsg.Append(e.ToString());
                    EventLog.Write(eMsg.ToString());
                    text_debugmessage.Text = e.ToString() + "@ initScreen()";
                }
                text_debugmessage.Text = "Application started successfully.";
            } /* if (System.IO.File.Exists("screenshot.png")) */
            else
            {
                text_debugmessage.Text = "Device not online. Connect device via USB and power on it.";
            }
        } /* public void initScreen() */
Пример #43
0
        public void inClassUpdateScreen(int everyMilliSecond)
        {
            System.Threading.Thread.Sleep(everyMilliSecond);

            var downloadScreenshotProcess = new Process();
            var captureScreenshotProcess  = new Process();
            var detectOrientationProcess  = new Process();

            setProcessStartInfo(detectOrientationProcess, @"shell ""dumpsys input | grep SurfaceOrientation""");
            detectOrientationProcess.Start();
            string output = detectOrientationProcess.StandardOutput.ReadToEnd();

            detectOrientationProcess.WaitForExit();
            int orient = 0;

            foreach (char C in output)
            {
                if (C == '0' || C == '1' || C == '2' || C == '3')
                {
                    orient = int.Parse(C.ToString());
                }
            }

            setProcessStartInfo(captureScreenshotProcess, @"shell /system/bin/screencap -p /sdcard/screenshot.png");
            captureScreenshotProcess.Start();
            captureScreenshotProcess.WaitForExit();

            setProcessStartInfo(downloadScreenshotProcess, @"pull /sdcard/screenshot.png screenshot.png");
            downloadScreenshotProcess.Start();
            downloadScreenshotProcess.WaitForExit();

            try
            {
                System.IO.FileStream fs  = new System.IO.FileStream(AppConst.ScreenshotFileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                System.Drawing.Image img = System.Drawing.Image.FromStream(fs);
                switch (orient)
                {
                case 3:
                    img.RotateFlip(RotateFlipType.Rotate90FlipNone);
                    rotateScreenshot(orient);
                    break;

                case 1:
                    img.RotateFlip(RotateFlipType.Rotate270FlipNone);
                    rotateScreenshot(orient);
                    break;

                case 0:
                    rotateScreenshot(orient);
                    break;
                }
                pbox_screen.Image = img;
                fs.Close();
            }
            catch (Exception ee)
            {
                System.Text.StringBuilder eMsg = new System.Text.StringBuilder();
                eMsg.Append("inClassUpdateScreen: ");
                eMsg.Append(ee.ToString());
                EventLog.Write(eMsg.ToString());
                text_debugmessage.Text = ee.ToString() + "@ inClassUpdateScreen()";
            }
        } /*public void inClassUpdateScreen(int everyMilliSecond)*/
Пример #44
0
 public static void CloseCollection()
 {
     FileStream.Close();
     FileStream.Dispose();
     FileStream = null;
 }
Пример #45
0
        static void save()
        {
            using (System.IO.FileStream fileStream = new System.IO.FileStream("pass.bin", System.IO.FileMode.Create)) {
                string dictString = JsonSerializer.Serialize(dict, dict.GetType());

                string encryptedDictString = EncryptionHelper.Encrypt(dictString, ask <string>("Enter password (If this is the first save, enter anything, but write it down!): "));
                try {
                    //bf.Serialize(fileStream, dict);
                    using (System.IO.BinaryWriter bw = new System.IO.BinaryWriter(fileStream)) {
                        try {
                            bw.Write(encryptedDictString);
                            bw.Close();
                            Console.WriteLine("Save successful!");
                            System.Threading.Thread.Sleep(1000);
                            Console.Clear();
                            Console.WriteLine(helpText);
                        } catch (Exception e) {
                            if (e is System.IO.IOException)
                            {
                                Console.WriteLine("An error occurred while writing to file.");
                            }
                            else if (e is System.IO.InternalBufferOverflowException)
                            {
                                Console.WriteLine("Internal buffer has overflown, maybe try saving more often?");
                            }
                            else if (e is ArgumentNullException)
                            {
                                Console.WriteLine("Cannot write null to filestream. Why? I don't know. You just can't. Period.");
                            }
                            else if (e is ObjectDisposedException)
                            {
                                Console.WriteLine("Cannot write to disposed object! If you see this message, you didn't screw" +
                                                  " up, I did. Just open up an issue at https://github.com/Catz1301/PasswordManager/issues and provide the following information:");
                            }
                            else
                            {
                                Console.WriteLine("An unexpexted error occured! If you see this message, you didn't screw" +
                                                  " up, I did. Just open up an issue at https://github.com/Catz1301/PasswordManager/issues and provide the following information:");
                            }
                            Console.WriteLine(Environment.NewLine + e.Message);
                            Console.WriteLine(Environment.NewLine + "-+-+-+-+-+-+-+-+-+-+-+-+-" + Environment.NewLine);
                            Console.WriteLine(e.StackTrace);
                            Console.WriteLine(Environment.NewLine + "Source: " + e.Source);
                            Console.WriteLine(Environment.NewLine + "Extra Data: ");
                            Console.WriteLine(e.Data);
                            throw;
                        } finally {
                            bw.Close();
                        }
                    }
                } catch (SerializationException e) {
                    Console.BackgroundColor = ConsoleColor.Red;
                    Console.ForegroundColor = ConsoleColor.Black;
                    Console.Clear();
                    Console.WriteLine("Failed to serialize! Reason: " + e.Message);
                    throw;
                } finally {
                    fileStream.Close();
                }
            }
        }
Пример #46
0
        private void imprimiPDF()
        {
            try
            {
                //Cria a iTextSharp Table da DataTable
                iTextSharp.text.pdf.PdfPTable pdfTable = new iTextSharp.text.pdf.PdfPTable(dgvConsulta.ColumnCount);
                pdfTable.DefaultCell.Padding             = 0;
                pdfTable.DefaultCell.PaddingBottom       = 5;
                pdfTable.DefaultCell.PaddingTop          = 5;
                pdfTable.WidthPercentage                 = 100;
                pdfTable.DefaultCell.BorderWidth         = 0;
                pdfTable.DefaultCell.HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER;
                var font = iTextSharp.text.FontFactory.GetFont("Arial", 8.5f);
                pdfTable.DefaultCell.Phrase = new iTextSharp.text.Phrase()
                {
                    Font = font
                };



                //Adiciona a linha do cabeçalho
                foreach (DataGridViewColumn column in dgvConsulta.Columns)
                {
                    iTextSharp.text.pdf.PdfPCell cell = new iTextSharp.text.pdf.PdfPCell(new iTextSharp.text.Phrase(column.HeaderText));
                    cell.BackgroundColor     = new iTextSharp.text.BaseColor(240, 240, 240);
                    cell.HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER;
                    cell.BorderWidth         = 0;
                    pdfTable.AddCell(new iTextSharp.text.Phrase(column.HeaderText.ToString(), font));
                    //pdfTable.AddCell(cell);
                    //pdfTable.AddCell(new Phrase(cell.ToString(), font));
                }

                //Adiciona as linhas
                foreach (DataGridViewRow row in dgvConsulta.Rows)
                {
                    foreach (DataGridViewCell cell in row.Cells)
                    {
                        pdfTable.AddCell(new iTextSharp.text.Phrase(cell.Value.ToString(), font));
                    }
                }

                //Exporta para PDF
                string folderPath = @"\\10.0.3.35\d\Debug\report\RELATÓRIO DE " + frmMenu.lbTitulo.Text + ".pdf";

                using (System.IO.FileStream stream = new System.IO.FileStream(folderPath, System.IO.FileMode.Create))
                {
                    //Configurando e adicionando os paragrafos

                    iTextSharp.text.Paragraph ph1 = new iTextSharp.text.Paragraph("RELATÓRIO DE " + frmMenu.lbTitulo.Text);
                    ph1.Alignment = iTextSharp.text.Element.ALIGN_CENTER;
                    ph1.Font.SetStyle(5);

                    iTextSharp.text.Paragraph ph2 = new iTextSharp.text.Paragraph(lbDeveloped.Text);
                    //ph2.Alignment = iTextSharp.text.Element.ALIGN_CENTER;

                    iTextSharp.text.Paragraph ph3 = new iTextSharp.text.Paragraph(lbRaf.Text);
                    //ph3.Alignment = iTextSharp.text.Element.ALIGN_CENTER;
                    ph3.Font.SetStyle(1);                     // 1 - negrito;

                    iTextSharp.text.Paragraph ph4 = new iTextSharp.text.Paragraph(lLemail.Text);
                    //ph4.Alignment = iTextSharp.text.Element.ALIGN_CENTER;

                    iTextSharp.text.Document pdfDoc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4.Rotate(), 10, 10, 10, 10);
                    iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDoc, stream);


                    pdfDoc.Open();
                    iTextSharp.text.Image logo = iTextSharp.text.Image.GetInstance(@"\\10.0.3.35\d\Debug\image\logo_nova.JPG");
                    logo.ScalePercent(0.3f * 100);
                    logo.Alignment = iTextSharp.text.Element.ALIGN_CENTER;
                    pdfDoc.Add(logo);
                    pdfDoc.Add(ph1);
                    //pdfDoc.Add(new iTextSharp.text.Paragraph(" ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------"));
                    pdfDoc.Add(new iTextSharp.text.Paragraph(" "));
                    pdfDoc.Add(new iTextSharp.text.Paragraph("Período.......: " + txtInicio.Text + " à " + txtFim.Text));
                    pdfDoc.Add(new iTextSharp.text.Paragraph("Usuário.......: " + frmMenu.lbNome.Text));
                    pdfDoc.Add(new iTextSharp.text.Paragraph("Emitido em.: " + DateTime.Now.ToString()));
                    pdfDoc.Add(ph2);
                    pdfDoc.Add(ph3);
                    pdfDoc.Add(ph4);
                    pdfDoc.Add(new iTextSharp.text.Paragraph(" "));
                    pdfDoc.Add(pdfTable);
                    pdfDoc.Close();
                    stream.Close();
                    System.Diagnostics.Process.Start(folderPath);

                    //	iTextSharp.text.Document doc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4);
                    //	string caminho = Application.StartupPath + @"\Exemplo.pdf";
                    //	iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(doc, new System.IO.FileStream(caminho, System.IO.FileMode.Create));

                    //	try
                    //	{

                    //		doc.SetMargins(30, 30, 70, 70);
                    //		doc.AddCreationDate();
                    //		doc.Open();
                    //		iTextSharp.text.Paragraph par = new iTextSharp.text.Paragraph(brocaFornecedor().ToString());
                    //		par.Alignment = iTextSharp.text.Element.ALIGN_JUSTIFIED;
                    //		par.Add("Teste na criação de um arquivo PDF");
                    //		doc.Add(par);
                    //		doc.Close();
                    //		System.Diagnostics.Process.Start(caminho);
                    //	}
                    //	catch (Exception Ex)
                    //	{
                    //		MessageBox.Show("Ocorreu um erro ao gerar o PDF - Erro:", Ex.Message);
                    //	}
                    //}
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("OPSS.. OCORREU UM ERRO! " + ex.Message);
            }
        }
Пример #47
0
        public static void Main(string[] args)
        {
            File fileToc1 = new File("tmp/umdbuffer1.toc");
            File fileIso1 = new File("tmp/umdbuffer1.iso");
            File fileToc2 = new File("tmp/umdbuffer2.toc");
            File fileIso2 = new File("tmp/umdbuffer2.iso");
            File fileToc  = new File("tmp/umdbuffer.toc");
            File fileIso  = new File("tmp/umdbuffer.iso");

            try
            {
                System.IO.FileStream fosToc  = new System.IO.FileStream(fileToc, System.IO.FileMode.Create, System.IO.FileAccess.Write);
                System.IO.FileStream fosIso  = new System.IO.FileStream(fileIso, System.IO.FileMode.Create, System.IO.FileAccess.Write);
                System.IO.FileStream fisToc1 = new System.IO.FileStream(fileToc1, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                System.IO.FileStream fisIso1 = new System.IO.FileStream(fileIso1, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                System.IO.FileStream fisToc2 = new System.IO.FileStream(fileToc2, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                DataOutput           toc     = new DataOutputStream(fosToc);
                DataOutput           iso     = new DataOutputStream(fosIso);
                DataInput            toc1    = new DataInputStream(fisToc1);
                DataInput            iso1    = new DataInputStream(fisIso1);
                DataInput            toc2    = new DataInputStream(fisToc2);
                RandomAccessFile     iso2    = new RandomAccessFile(fileIso2, "r");

                int numSectors      = toc1.readInt();
                int numSectorsMerge = toc2.readInt();
                toc.writeInt(System.Math.Max(numSectors, numSectorsMerge));

                Dictionary <int, int> tocHashMap = new Dictionary <int, int>();
                for (int i = 4; i < fileToc1.Length(); i += 8)
                {
                    int sectorNumber         = toc1.readInt();
                    int bufferedSectorNumber = toc1.readInt();
                    tocHashMap[sectorNumber] = bufferedSectorNumber;
                    toc.writeInt(sectorNumber);
                    toc.writeInt(bufferedSectorNumber);
                }

                sbyte[] buffer = new sbyte[sectorLength];
                for (int i = 0; i < fileIso1.Length(); i += buffer.Length)
                {
                    iso1.readFully(buffer);
                    iso.write(buffer);
                }

                int nextFreeBufferedSectorNumber = (int)(fileIso1.Length() / sectorLength);
                for (int i = 4; i < fileToc2.Length(); i += 8)
                {
                    int sectorNumber         = toc2.readInt();
                    int bufferedSectorNumber = toc2.readInt();
                    if (!tocHashMap.ContainsKey(sectorNumber))
                    {
                        iso2.seek(bufferedSectorNumber * (long)sectorLength);
                        iso2.readFully(buffer);
                        iso.write(buffer);

                        toc.writeInt(sectorNumber);
                        toc.writeInt(nextFreeBufferedSectorNumber);
                        tocHashMap[sectorNumber] = nextFreeBufferedSectorNumber;
                        nextFreeBufferedSectorNumber++;
                    }
                }

                fosToc.Close();
                fosIso.Close();
                fisToc1.Close();
                fisIso1.Close();
                fisToc2.Close();
                iso2.close();
            }
            catch (FileNotFoundException e)
            {
                Console.WriteLine(e.ToString());
                Console.Write(e.StackTrace);
            }
            catch (IOException e)
            {
                Console.WriteLine(e.ToString());
                Console.Write(e.StackTrace);
            }
        }
Пример #48
0
        /// <summary>
        /// Start processing post back data from the request.
        /// </summary>
        /// <param name="request">The http request context.</param>
        /// <param name="uploadDirectory">The upload directory path where files are placed; else uploaded files are ingored.</param>
        public void ProcessPostBack(System.Net.HttpListenerRequest request, string uploadDirectory = null)
        {
            System.IO.Stream       input            = null;
            System.IO.FileStream   localDestination = null;
            System.IO.MemoryStream memoryFormData   = null;

            try
            {
                // If no directory path then only get the form post back data.
                if (String.IsNullOrEmpty(uploadDirectory))
                {
                    // Create a new memory stream that will contain the form data
                    using (memoryFormData = new System.IO.MemoryStream())
                    {
                        input = request.InputStream;

                        // Copy the request stream data to the file stream.
                        Nequeo.Net.Http.Utility.TransferData(input, memoryFormData);

                        // Flush the streams.
                        input.Flush();
                        memoryFormData.Flush();

                        // Close the local file.
                        memoryFormData.Close();
                        input.Close();
                    }

                    // Get the form data uploaded from the request stream
                    // within the memory stream
                    byte[] formByteData   = memoryFormData.ToArray();
                    string formStringData = Encoding.ASCII.GetString(formByteData);

                    // Get the enumerable collection of for data lines.
                    IEnumerable <string> formLines = formStringData.Split(new string[] { "\r\n" }, StringSplitOptions.None).AsEnumerable();

                    // Get the form post back data.
                    _form        = Nequeo.Net.Http.Utility.FormParser(formLines);
                    _uploadFiles = new string[0];
                }
                else
                {
                    string directory = uploadDirectory.TrimEnd('\\') + "\\";

                    // The request is a file uploader.
                    Nequeo.Net.Http.Utility.CreateDirectory(directory);
                    string localFileName = directory + Guid.NewGuid().ToString() + ".txt";

                    // Create the new file and start the transfer process.
                    using (localDestination = new System.IO.FileStream(localFileName, System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.ReadWrite))
                    {
                        input = request.InputStream;

                        // Copy the request stream data to the file stream.
                        Nequeo.Net.Http.Utility.TransferData(input, localDestination);

                        // Flush the streams.
                        input.Flush();
                        localDestination.Flush();

                        // Close the local file.
                        localDestination.Close();
                        input.Close();
                    }

                    // Get the form post back data.
                    _form = Nequeo.Net.Http.Utility.FormParser(System.IO.File.ReadLines(localFileName));

                    // Get the upload file collection.
                    _uploadFiles = Nequeo.Net.Http.Utility.ParseUploadedFileEx(localFileName);
                }
            }
            catch (Exception ex)
            {
                // Log the error.
                LogHandler.WriteTypeMessage(
                    ex.Message,
                    MethodInfo.GetCurrentMethod(),
                    Nequeo.Net.Common.Helper.EventApplicationName);

                throw;
            }
            finally
            {
                try
                {
                    if (input != null)
                    {
                        input.Close();
                    }
                }
                catch { }

                try
                {
                    if (memoryFormData != null)
                    {
                        memoryFormData.Close();
                    }
                }
                catch { }

                try
                {
                    if (localDestination != null)
                    {
                        localDestination.Close();
                    }
                }
                catch { }
            }
        }
Пример #49
0
        public static void  Main(System.String[] args)
        {
            System.String filename = null;
            bool          extract  = false;

            for (int i = 0; i < args.Length; ++i)
            {
                if (args[i].Equals("-extract"))
                {
                    extract = true;
                }
                else if (filename == null)
                {
                    filename = args[i];
                }
            }

            if (filename == null)
            {
                System.Console.Out.WriteLine("Usage: Lucene.Net.index.IndexReader [-extract] <cfsfile>");
                return;
            }

            Directory          dir = null;
            CompoundFileReader cfr = null;

            try
            {
                System.IO.FileInfo file    = new System.IO.FileInfo(filename);
                System.String      dirname = new System.IO.FileInfo(file.FullName).DirectoryName;
                filename = file.Name;
                dir      = FSDirectory.GetDirectory(dirname, false);
                cfr      = new CompoundFileReader(dir, filename);

                System.String[] files = cfr.List();
                System.Array.Sort(files);                 // sort the array of filename so that the output is more readable

                for (int i = 0; i < files.Length; ++i)
                {
                    long len = cfr.FileLength(files[i]);

                    if (extract)
                    {
                        System.Console.Out.WriteLine("extract " + files[i] + " with " + len + " bytes to local directory...");
                        IndexInput ii = cfr.OpenInput(files[i]);

                        System.IO.FileStream f = new System.IO.FileStream(files[i], System.IO.FileMode.Create);

                        // read and write with a small buffer, which is more effectiv than reading byte by byte
                        byte[] buffer = new byte[1024];
                        int    chunk  = buffer.Length;
                        while (len > 0)
                        {
                            int bufLen = (int)System.Math.Min(chunk, len);
                            ii.ReadBytes(buffer, 0, bufLen);

                            byte[] byteArray = new byte[buffer.Length];
                            for (int index = 0; index < buffer.Length; index++)
                            {
                                byteArray[index] = (byte)buffer[index];
                            }

                            f.Write(byteArray, 0, bufLen);

                            len -= bufLen;
                        }

                        f.Close();
                        ii.Close();
                    }
                    else
                    {
                        System.Console.Out.WriteLine(files[i] + ": " + len + " bytes");
                    }
                }
            }
            catch (System.IO.IOException ioe)
            {
                System.Console.Error.WriteLine(ioe.StackTrace);
            }
            finally
            {
                try
                {
                    if (dir != null)
                    {
                        dir.Close();
                    }
                    if (cfr != null)
                    {
                        cfr.Close();
                    }
                }
                catch (System.IO.IOException ioe)
                {
                    System.Console.Error.WriteLine(ioe.StackTrace);
                }
            }
        }
Пример #50
0
        static int Main(string[] args)
        {
            int exitCode = 0;

            if (args.Length < 2)
            {
                WriteHelp();
                return(2);
            }

            YCrCb c = new YCrCb(args[0]);

            if (!c.IsCorrect())
            {
                Console.WriteLine("File read error!");
                return(2);
            }

            c.RGB2YCrCb();

            bool   debug = false;
            string pass  = "";
            bool   uPass = false;
            bool   crc   = false;

            foreach (string s in args)
            {
                if (s.ToUpper() == "-CRCNO")
                {
                    crc = true;
                }
                if (s.ToUpper() == "-H" || s.ToUpper() == "-?" || s.ToUpper() == "/?")
                {
                    WriteHelp(); return(0);
                }

                if (s.ToUpper() == "-DEBUG" || s.ToUpper() == "-D")
                {
                    debug = true;
                }
                if (s.Substring(0, 2).ToUpper() == "-P")
                {
                    pass  = s.Substring(2);
                    uPass = true;
                }
            }



            YCrCb tmp = c.GetCopy();

            if (debug)
            {
                tmp.convMono();
                tmp.writeBMP("Y.bmp");
                tmp = c.GetCopy();
                tmp.convCr();
                tmp.writeBMP("Cr.bmp");
                tmp = c.GetCopy();
                tmp.convCb();
                tmp.writeBMP("Cb.bmp");
            }

            //if (c.isMono())
            //    c.convMono();

            c.getBaseColor();

            c.makeBlock();

            if (debug)
            {
                tmp = c.GetCopy();
                tmp.drawBlock();
                tmp.convMono();
                tmp.writeBMP("Y_b.bmp");

                tmp = c.GetCopy();
                tmp.drawBlock();
                tmp.convCr();
                tmp.writeBMP("Cr_b.bmp");

                tmp = c.GetCopy();
                tmp.drawBlock();
                tmp.convCb();
                tmp.writeBMP("Cb_b.bmp");

                tmp = c.GetCopy();
                tmp.convMono();
                tmp.drawZone(0);
                tmp.YCrCb2RGB();
                tmp.writeBMP("Y_Z.bmp");

                tmp = c.GetCopy();
                tmp.convCr();
                tmp.drawZone(1);
                tmp.YCrCb2RGB();
                tmp.writeBMP("Cr_Z.bmp");

                tmp = c.GetCopy();
                tmp.convCb();
                tmp.drawZone(2);
                tmp.YCrCb2RGB();
                tmp.writeBMP("Cb_Z.bmp");
            }

            System.IO.FileStream fs = new System.IO.FileStream(args[1] + ".YCC", System.IO.FileMode.Create);


            byte[] bInt;
            bInt = BitConverter.GetBytes('Y'); fs.Write(bInt, 0, 1);
            bInt = BitConverter.GetBytes('C'); fs.Write(bInt, 0, 1);
            bInt = BitConverter.GetBytes('C'); fs.Write(bInt, 0, 1);
            if (uPass)
            {
                bInt[0] = (byte)4;
            }
            else
            {
                bInt[0] = (byte)3;
            }
            fs.Write(bInt, 0, 1);

            bInt = BitConverter.GetBytes(c.chanel); fs.Write(bInt, 0, 4);
            bInt = BitConverter.GetBytes(c.width); fs.Write(bInt, 0, 4);
            bInt = BitConverter.GetBytes(c.height); fs.Write(bInt, 0, 4);
            bInt = BitConverter.GetBytes(c.widthR); fs.Write(bInt, 0, 4);

            byte[] bB = new byte[4];

            if (c.baseColor != null)
            {
                bB[0] = (byte)1;
                bB[1] = c.baseColor.Y;
                bB[2] = c.baseColor.Cr;
                bB[3] = c.baseColor.Cb;
            }
            else
            {
                bB[0] = (byte)0;
            }

            fs.Write(bB, 0, 4);

            _Rijndael crpt = new _Rijndael();

            crpt.Key = pass;

            for (int i = 0; i < c.ZoneQTY; i++)
            {
                byte[] bQQ = c.getZoneBytes(i, crc);
                byte[] b;
                if (bQQ.Length > 0)
                {
                    if (uPass)
                    {
                        b = crpt.Encrypt(bQQ);
                    }
                    else
                    {
                        b = bQQ;
                    }

                    try
                    {
                        int    Q  = b.Length;
                        byte[] bQ = BitConverter.GetBytes(b.Length);

                        fs.Write(bQ, 0, bQ.Length);
                        fs.Write(b, 0, b.Length);
                    }
                    catch /*(Exception ex)*/ {
                        exitCode = 3;
                    }
                    finally
                    {
                    }
                }
            }
            fs.Close();
            return(exitCode);
        }
Пример #51
0
        public async void Returns_ParentDirectoryAndStatus200OK_whenSuccessDeletedDirectory()
        {
            IDatabaseContext    databaseContext     = DatabaseTestHelper.GetContext();
            MapperConfiguration mapperConfiguration = new MapperConfiguration(conf =>
            {
                conf.AddProfile(new Directory_to_DirectoryOut());
            });

            IMapper mapper = mapperConfiguration.CreateMapper();

            IFileService fileService = new FileService(databaseContext, mapper);

            string userId = (await databaseContext.Users.FirstOrDefaultAsync(_ => _.UserName == "*****@*****.**")).Id;

            Directory directoryToDelete = new Directory
            {
                ResourceType = ResourceType.DIRECTORY,
                Name         = "ToDeleteDirectory",
                OwnerID      = userId
            };

            await databaseContext.Directories.AddAsync(directoryToDelete);

            await databaseContext.SaveChangesAsync();

            string pathToFile = System.IO.Path.Combine(_pathToUpload, Guid.NewGuid().ToString());

            System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(Encoding.UTF8.GetBytes("Test file"));
            System.IO.FileStream   fileStream   = new System.IO.FileStream(pathToFile, System.IO.FileMode.Create);
            await memoryStream.CopyToAsync(fileStream);

            fileStream.Close();

            Assert.True(System.IO.File.Exists(pathToFile));

            File file1InDirectoryToDelete = new File
            {
                ResourceType      = ResourceType.FILE,
                Name              = "file1.txt",
                OwnerID           = userId,
                ParentDirectoryID = directoryToDelete.ID,
                Path              = pathToFile,
                CreatedDateTime   = DateTime.Now
            };

            await databaseContext.Files.AddAsync(file1InDirectoryToDelete);

            await databaseContext.SaveChangesAsync();

            Assert.True(databaseContext.Files.Any(_ => _.ID == file1InDirectoryToDelete.ID));

            Directory directoryInDirectoryToDelete = new Directory
            {
                ResourceType      = ResourceType.DIRECTORY,
                Name              = "Directory1",
                OwnerID           = userId,
                ParentDirectoryID = directoryToDelete.ID,
                CreatedDateTime   = DateTime.Now
            };

            await databaseContext.Directories.AddAsync(directoryInDirectoryToDelete);

            await databaseContext.SaveChangesAsync();

            string pathToFile2 = System.IO.Path.Combine(_pathToUpload, Guid.NewGuid().ToString());

            memoryStream = new System.IO.MemoryStream(Encoding.UTF8.GetBytes("Test file2"));
            fileStream   = new System.IO.FileStream(pathToFile2, System.IO.FileMode.Create);
            await memoryStream.CopyToAsync(fileStream);

            fileStream.Close();

            Assert.True(System.IO.File.Exists(pathToFile));

            File file2InDirectoryToDelete = new File
            {
                ResourceType      = ResourceType.FILE,
                Name              = "file2.txt",
                OwnerID           = userId,
                ParentDirectoryID = directoryInDirectoryToDelete.ID,
                Path              = pathToFile2,
                CreatedDateTime   = DateTime.Now
            };

            await databaseContext.Files.AddAsync(file2InDirectoryToDelete);

            await databaseContext.SaveChangesAsync();

            Assert.True(databaseContext.Files.Any(_ => _.ID == file2InDirectoryToDelete.ID));

            StatusCode <DirectoryOut> status = await fileService.DeleteByIdAndUser(directoryToDelete.ID, "*****@*****.**");

            Assert.NotNull(status);
            Assert.True(status.Code == StatusCodes.Status200OK);
            Assert.True(status.Body.ID == null);
            Assert.False(databaseContext.Files.Any(_ => _.ID == file1InDirectoryToDelete.ID));
            Assert.False(System.IO.File.Exists(pathToFile));

            Assert.False(databaseContext.Files.Any(_ => _.ID == file2InDirectoryToDelete.ID));
            Assert.False(System.IO.File.Exists(pathToFile2));

            Assert.False(databaseContext.Files.Any(_ => _.ID == directoryToDelete.ID));
            Assert.False(databaseContext.Files.Any(_ => _.ID == directoryInDirectoryToDelete.ID));
        }
        private void GenerateClaimDateRangeDC()
        {
            int    index     = 1;
            string sFileName = System.IO.Path.GetRandomFileName().Substring(0, 8);
            string sGenName  = "ReportClaimDateRangeDC.csv";

            using (System.IO.StreamWriter SW = new System.IO.StreamWriter(Server.MapPath("Upload/" + sFileName + ".csv")))
            {
                SW.WriteLine(String.Format("STORE CLAIMS - {0} TO {1}", TextBoxDateFrom.Text, TextBoxDateTo.Text));
                SW.WriteLine(String.Format("{0} - {1}", DropDownListSupplier.SelectedItem.Text, DropDownListLocation.SelectedItem.Text));
                SW.WriteLine("");
                SW.WriteLine("STORE, CLAIM NO., CLAIM DATE, EXPIRED STOCK AMT EXC, EXPIRED STOCK VAT AMT, EXPIRED STOCK AMT INC, FACTORY FAULT AMT EXC, FACTORY FAULT VAT AMT, FACTORY FAULT AMT INC, DEMO/PROMO EXC, DEMO/PROMO VAT AMT, DEMO/PROMO AMT INC, EXPLANATION, CAPTURED BY");
                string row = "";
                SW.WriteLine(row);
                List <ClaimSchedule> cs = ClaimSchedule.GetReportClaimDateRangeDC(Convert.ToDateTime(TextBoxDateFrom.Text), Convert.ToDateTime(TextBoxDateTo.Text), Convert.ToInt32(DropDownListLocation.SelectedValue), DropDownListSupplier.SelectedItem.Text, DropDownListLocation.SelectedItem.Text);
                if (cs.Count > 0)
                {
                    foreach (ClaimSchedule claim in cs)
                    {
                        row = String.Format("{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13}", claim.Store, claim.ClaimNumber, claim.ClaimDate.ToString("yyyy/MM/dd"), claim.ExpStockExcVAT, claim.ExpStockVATAmount, claim.ExpStockIncVAT, claim.FactoryFaultExcVAT, claim.FactoryFaultVATAmount, claim.FactoryFaultIncVAT, claim.DemoPromoExcVAT, claim.DemoPromoVATAmount, claim.DemoPromoIncVAT, claim.Explanation, claim.ModifiedUser);
                        SW.WriteLine(row);
                        index++;
                    }

                    SW.WriteLine("");

                    SW.WriteLine(String.Format("TOTAL FOR {0} TO {12},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11}", TextBoxDateFrom.Text, "", "", cs[0].TotalExpStockExcVAT, cs[0].TotalExpStockVATAmount, cs[0].TotalExpStockIncVAT, cs[0].TotalFactoryFaultExcVAT, cs[0].TotalFactoryFaultVATAmount, cs[0].TotalFactoryFaultIncVAT, cs[0].TotalDemoPromoExcVAT, cs[0].TotalDemoPromoVATAmount, cs[0].TotalDemoPromoIncVAT, TextBoxDateTo.Text));

                    SW.WriteLine(String.Format("TOTAL FOR {0} TO {4} EXCL VAT,{1},{2},{3}", TextBoxDateFrom.Text, "", "", cs[0].TotalMonthExcVAT, TextBoxDateTo.Text));

                    SW.WriteLine(String.Format("ADD TOTAL VAT{0},{1},{2},{3}", "", "", "", cs[0].TotalAddVAT));

                    SW.WriteLine(String.Format("TOTAL VALUE FOR CLAIM{0},{1},{2},{3}", "", "", "", cs[0].TotalClaim));

                    SW.WriteLine("");
                    SW.WriteLine(String.Format("Sent to {0}(Date){1}", DropDownListSupplier.SelectedItem.Text, "".PadRight(20, '_')));

                    SW.WriteLine("");

                    SW.WriteLine(String.Format("RECIPIENT OF CLAIMS{0}Order Number{1}", "".PadRight(20, ' '), "".PadRight(40, '_')));
                    SW.WriteLine("");

                    SW.WriteLine(String.Format("NAME{0}", "".PadRight(30, '_')));
                    SW.WriteLine("");

                    SW.WriteLine(String.Format("SIGNATURE{0}", "".PadRight(25, '_')));
                    SW.WriteLine("");

                    SW.WriteLine(String.Format("DATE{0}", "".PadRight(20, '_')));

                    SW.Close();
                }
                else
                {
                    LabelError.Text    = "No rows returned.";
                    PanelError.Visible = true;
                }
            }

            System.IO.FileStream fs = null;
            fs = System.IO.File.Open(Server.MapPath("Upload/" + sFileName + ".csv"), System.IO.FileMode.Open);
            byte[] btFile = new byte[fs.Length];
            fs.Read(btFile, 0, Convert.ToInt32(fs.Length));
            fs.Close();
            Response.AddHeader("Content-disposition", "attachment; filename=" + sGenName);
            Response.ContentType = "application/octet-stream";
            Response.BinaryWrite(btFile);
            Response.End();
        }
Пример #53
0
        // Проверка таблицы с индексами
        static void Main5(string[] args)
        {
            Console.WriteLine("Start");
            string   path     = @"..\..\..\Databases\";
            string   filename = path + "table.pac";
            Random   rnd      = new Random(3333);
            PaCell   table    = new PaCell(new PTypeSequence(new PType(PTypeEnumeration.integer)), filename, false);
            DateTime tt0      = DateTime.Now;
            int      nvalues  = 1000000000;

            bool toload = false;

            if (toload)
            {
                table.Clear();
                table.Fill(new object[0]);
                for (int i = 0; i < nvalues; i++)
                {
                    table.Root.AppendElement(i);
                }
                table.Flush();
                Console.WriteLine("Load ok. duration={0}", (DateTime.Now - tt0).Ticks / 10000L); tt0 = DateTime.Now;
                return;
            }
            int portion = 100000;

            for (int i = 0; i < portion; i++)
            {
                int ind = rnd.Next(nvalues - 1);
                var v   = table.Root.Element(ind).Get();
            }
            Console.WriteLine("Test1 ok. duration={0}", (DateTime.Now - tt0).Ticks / 10000L); tt0 = DateTime.Now;

            table.Close();
            System.IO.Stream       fs = new System.IO.FileStream(filename, System.IO.FileMode.Open, System.IO.FileAccess.Read);
            System.IO.BinaryReader br = new System.IO.BinaryReader(fs);
            for (int i = 0; i < portion; i++)
            {
                int  ind = rnd.Next(nvalues - 1);
                long off = 40 + (long)ind * 4;
                fs.Position = off;
                int v = br.ReadInt32();
            }

            fs.Close();
            Console.WriteLine("Test2 ok. duration={0}", (DateTime.Now - tt0).Ticks / 10000L); tt0 = DateTime.Now;
            using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(filename))
            {
                for (int i = 0; i < portion; i++)
                {
                    int  ind = rnd.Next(nvalues - 1);
                    long off = 40 + (long)ind * 4;
                    using (var accessor = mmf.CreateViewAccessor(off, 4))
                    {
                        int v = accessor.ReadInt32(0);
                    }
                }
                Console.WriteLine("Test3 ok. duration={0}", (DateTime.Now - tt0).Ticks / 10000L); tt0 = DateTime.Now;
                using (var accessor = mmf.CreateViewAccessor(0, (long)nvalues * 4 + 40))
                {
                    tt0 = DateTime.Now;
                    for (int i = 0; i < portion; i++)
                    {
                        int  ind = rnd.Next(nvalues - 1);
                        long off = 40 + (long)ind * 4;
                        //using (var accessor = mmf.CreateViewAccessor(off, 4))
                        //{
                        //    int v = accessor.ReadInt32(0);
                        //}
                        int v = accessor.ReadInt32(off);
                    }
                }
            }
            Console.WriteLine("Test4 ok. duration={0}", (DateTime.Now - tt0).Ticks / 10000L); tt0 = DateTime.Now;
        }
Пример #54
0
        /// <summary>
        /// Read bytes from memory of target process.
        /// Returns read bytes into bytes array.
        /// Returns false if failed.
        /// </summary>

        public bool GetBytes(ulong address, ref byte[] bytes)
        {
            //Only accept EE searches for now
            ulong endAddr = address + (ulong)bytes.Length;

            if (address < 0x00080000 || address >= 0x02000000)
            {
                return(false);
            }
            if (endAddr < 0x00080000 || endAddr >= 0x02000000)
            {
                return(false);
            }

            if (true)
            {
                ulong dSize = endAddr - address;
                if (dSize < 0x1000)
                {
                    endAddr = address + 0x1000;
                }

                string arg = "ntpbclient.exe -D " + address.ToString("X8") + " " + endAddr.ToString("X8") + " temp.bin -ip " + ipAddr;
                CallCommand(arg);

                if (System.IO.File.Exists(curPath + "\\temp.bin"))
                {
                    if (dSize < 0x1000)
                    {
                        System.IO.FileStream fs = System.IO.File.OpenRead(curPath + "\\temp.bin");

                        for (ulong x = 0; x < dSize; x++)
                        {
                            bytes[x] = (byte)fs.ReadByte();
                        }

                        fs.Close();
                    }
                    else
                    {
                        bytes = System.IO.File.ReadAllBytes(curPath + "\\temp.bin");
                    }
                    System.IO.File.Delete(curPath + "\\temp.bin");

                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            else
            {
                bytes = ntpb.DumpRAM((uint)address, (uint)endAddr);
                if (bytes != null)
                {
                    return(true);
                }
            }

            return(false);
        }
        /// <summary>
        /// 比较两个文件内容是否相同。注意:两个文件都不存在视为相同。
        /// </summary>
        /// <param name="sourceFileName">原始文件。</param>
        /// <param name="destFileName">待比较文件。</param>
        /// <returns></returns>
        private static bool CompareFile(string sourceFileName, string destFileName)
        {
            System.IO.FileInfo sourceFileInfo = new System.IO.FileInfo(sourceFileName);
            System.IO.FileInfo destFileInfo   = new System.IO.FileInfo(destFileName);
            if (!sourceFileInfo.Exists && !destFileInfo.Exists)
            {
                return(true);
            }
            if (sourceFileInfo.Exists != destFileInfo.Exists)
            {
                return(false);
            }
            if (sourceFileInfo.Length != destFileInfo.Length)//根据文件长度判断两文件是否相同。
            {
                return(false);
            }

            System.IO.FileStream sourceFileStream = null;
            System.IO.FileStream destFileStream   = null;
            try
            {
                sourceFileStream = sourceFileInfo.OpenRead();
                destFileStream   = destFileInfo.OpenRead();
                if (sourceFileStream.Length != destFileStream.Length)//根据文件长度判断两文件是否相同。
                {
                    return(false);
                }

                #region 循环比较文件内容是否相同。
                byte[] sourceBuffer = new byte[sourceFileStream.Length > 1024 * 8 ? 1024 * 8 : sourceFileStream.Length];
                byte[] destBuffer   = new byte[destFileStream.Length > 1024 * 8 ? 1024 * 8 : destFileStream.Length];
                int    sourceCount  = 0;
                int    destCount    = 0;
                while (sourceFileStream.Position < sourceFileStream.Length)
                {
                    sourceCount = sourceFileStream.Read(sourceBuffer, 0, sourceBuffer.Length);
                    destCount   = destFileStream.Read(destBuffer, 0, destBuffer.Length);
                    if (sourceCount != destCount)
                    {
                        return(false);
                    }
                    for (int i = 0; i < sourceCount; i++)
                    {
                        if (sourceBuffer[i] != destBuffer[i])
                        {
                            return(false);
                        }
                    }
                }
                #endregion

                return(true);
            }
            finally
            {
                if (sourceFileStream != null)
                {
                    sourceFileStream.Close();
                    sourceFileStream = null;
                }
                if (destFileStream != null)
                {
                    destFileStream.Close();
                    destFileStream = null;
                }
            }
        }
Пример #56
0
        public void CreateFromDirectory(string Dir, string Outfile, string[] FileOrder)
        {
            List <string> Filepaths = new List <string>();

            foreach (string f in FileOrder)
            {
                Filepaths.Add(System.IO.Path.Combine(Dir, f));
            }
            var Filestream = new System.IO.FileStream(Outfile, System.IO.FileMode.Create);


            uint RequiredBytesForHeader;
            uint Filecount = (uint)Filepaths.Count;
            uint TotalFilesize;

            Xorbyte = 0x55;
            //Xorbyte = 0x00;

            // 0x20 Header + 0x28 per file
            RequiredBytesForHeader = NumberUtils.Align(Filecount * 0x28u + 0x20u, 0x20u);

            TotalFilesize = RequiredBytesForHeader;
            foreach (string Path in Filepaths)
            {
                TotalFilesize += (uint)(new System.IO.FileInfo(Path).Length);
                TotalFilesize  = TotalFilesize.Align(0x20u);
            }

            // header
            Filestream.WriteByte((byte)'R'); Filestream.WriteByte((byte)'T');
            Filestream.WriteByte((byte)'D'); Filestream.WriteByte((byte)'P');
            Filestream.Write(BitConverter.GetBytes(RequiredBytesForHeader), 0, 4);
            Filestream.Write(BitConverter.GetBytes(Filecount), 0, 4);
            Filestream.Write(BitConverter.GetBytes(TotalFilesize), 0, 4);
            Filestream.WriteByte(Xorbyte);
            Filestream.WriteByte(0x28); Filestream.WriteByte(0x25);
            while (Filestream.Length < 0x20)
            {
                Filestream.WriteByte(0x00);
            }

            // header file info
            uint ptr = 0;

            foreach (string Path in Filepaths)
            {
                var  fi   = new System.IO.FileInfo(Path);
                uint size = (uint)(fi.Length);

                byte[] name = Encoding.ASCII.GetBytes(fi.Name);
                Filestream.Write(name, 0, Math.Min(0x20, name.Length));
                for (int i = name.Length; i < 0x20; ++i)
                {
                    Filestream.WriteByte(0x00);
                }

                Filestream.Write(BitConverter.GetBytes(size), 0, 4);
                Filestream.Write(BitConverter.GetBytes(ptr), 0, 4);

                ptr = NumberUtils.Align(ptr + size, 0x20u);
            }
            while (Filestream.Length < RequiredBytesForHeader)
            {
                Filestream.WriteByte(0x00);
            }

            // files
            foreach (string Path in Filepaths)
            {
                var File = new System.IO.FileStream(Path, System.IO.FileMode.Open);

                while (true)
                {
                    int b = File.ReadByte();
                    if (b == -1)
                    {
                        break;
                    }
                    Filestream.WriteByte((byte)(b ^ Xorbyte));
                }

                File.Close();
                while (Filestream.Length % 0x20 != 0)
                {
                    Filestream.WriteByte(0x00);
                }
            }

            Filestream.Close();
        }
Пример #57
0
        public static void populate(bool forceChooseLanguage)
        {
            moreThanOneLanguageFileDetected = true;
            string languageFilePath = "";

            if (
                !forceChooseLanguage &&
                Form1.options.languageFile.Length > 0
                )
            {
                languageFilePath = Form1.options.languageFile;

                try
                {
                    System.IO.FileStream file1 = new System.IO.FileStream(languageFilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                }
                catch                 //( System.Exception e )
                {
                    forceChooseLanguage = true;
                }
            }

            if (
                forceChooseLanguage ||
                languageFilePath == ""
                )
            {
                string[] strList1 = System.IO.Directory.GetFiles(Form1.appPath + "\\languages\\");

                int   pos     = 0;
                int[] refer   = new int[strList1.Length];
                int   english = 0;

                for (int i = 0; i < strList1.Length; i++)
                {
                    if (System.IO.Path.GetExtension(strList1[i]) == ".lng")
                    {
                        if (System.IO.Path.GetFileNameWithoutExtension(strList1[i]).ToLower() == "english")
                        {
                            english = pos;
                        }

                        refer[pos] = i;
                        pos++;
                    }
                }

                if (pos == 0)
                {
                    System.Windows.Forms.MessageBox.Show("Sorry, no language files detected. Make sure you have the .lng files in the same directory than pocketHumanity.exe!", "Error");
                    //	Application.End();
                }
                else if (pos == 1)
                {
                    languageFilePath = strList1[refer[0]];
                    moreThanOneLanguageFileDetected = false;
                }
                else
                {
                    moreThanOneLanguageFileDetected = true;
                    string[] strList3 = new string[pos];
                    for (int i = 0; i < pos; i++)
                    {
                        strList3[i] = System.IO.Path.GetFileNameWithoutExtension(strList1[refer[i]]);
                    }

                    userChoice ui = new userChoice(
                        "Language file",
                        "Please choose a language",
                        strList3,
                        english,
                        "Ok",
                        "Default"
                        );
                    platformSpec.cursor.showWaitCursor = false;
                    ui.ShowDialog();
                    int res = ui.result;

                    if (res == -1)
                    {
                        res = english;
                    }

                    languageFilePath = strList1[refer[res]];
                }
            }

            System.IO.FileStream   file = new System.IO.FileStream(languageFilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
            System.IO.StreamReader sr   = new System.IO.StreamReader(file, true);


            //		structures.cfgFile cfgFile = cfgOut.getValues; // =
            //		cfgFile.languageFile = languageFilePath;
            Form1.options.languageFile = languageFilePath;

            //		cfgOut.getValues = cfgFile;
            //		cfgOut.writeCfgFile();
            Form1.options.save();

            string fullList = sr.ReadToEnd();

            string[] temp = fullList.Split("\n".ToCharArray());

            int tot = 0;

            //System.Collections.BitArray isOk = new System.Collections.BitArray( temp.Length, false );
            bool[] isOk = new bool[temp.Length];
            for (int i = 0; i < temp.Length; i++)
            {
                temp[i] = temp[i].TrimEnd("\r".ToCharArray());

                if (
                    temp[i] != "" &&
                    !temp[i].StartsWith("//")
                    )
                {
                    isOk[i] = true;
                    tot++;
                }
            }

            list = new string[tot];
            int pos1 = 0;

            for (int i = 0; i < temp.Length; i++)
            {
                if (isOk[i])
                {
                    list[pos1] = temp[i];
                    pos1++;
                }
            }

            curLanguage = languageFilePath;

            sr.Close();
            file.Close();
        }
Пример #58
0
        public static void  Main(System.String[] args)
        {
            // get command line arguments
            System.String prologFilename = null;             // name of file "wn_s.pl"
            System.String indexDir       = null;
            if (args.Length == 2)
            {
                prologFilename = args[0];
                indexDir       = args[1];
            }
            else
            {
                Usage();
                System.Environment.Exit(1);
            }

            // ensure that the prolog file is readable
            if (!(new System.IO.FileInfo(prologFilename)).Exists)
            {
                err.WriteLine("Error: cannot read Prolog file: " + prologFilename);
                System.Environment.Exit(1);
            }
            // exit if the target index directory already exists
            if (System.IO.Directory.Exists((new System.IO.FileInfo(indexDir)).FullName))
            {
                err.WriteLine("Error: index directory already exists: " + indexDir);
                err.WriteLine("Please specify a name of a non-existent directory");
                System.Environment.Exit(1);
            }

            o.WriteLine("Opening Prolog file " + prologFilename);
            System.IO.FileStream   fis = new System.IO.FileStream(prologFilename, System.IO.FileMode.Open, System.IO.FileAccess.Read);
            System.IO.StreamReader br  = new System.IO.StreamReader(new System.IO.StreamReader(fis, System.Text.Encoding.Default).BaseStream, new System.IO.StreamReader(fis, System.Text.Encoding.Default).CurrentEncoding);
            System.String          line;

            // maps a word to all the "groups" it's in
            System.Collections.IDictionary word2Nums = new System.Collections.SortedList();
            // maps a group to all the words in it
            System.Collections.IDictionary num2Words = new System.Collections.SortedList();
            // number of rejected words
            int ndecent = 0;

            // status output
            int mod = 1;
            int row = 1;

            // parse prolog file
            o.WriteLine("[1/2] Parsing " + prologFilename);
            while ((line = br.ReadLine()) != null)
            {
                // occasional progress
                if ((++row) % mod == 0)
                // periodically print out line we read in
                {
                    mod *= 2;
                    o.WriteLine("\t" + row + " " + line + " " + word2Nums.Count + " " + num2Words.Count + " ndecent=" + ndecent);
                }

                // syntax check
                if (!line.StartsWith("s("))
                {
                    err.WriteLine("OUCH: " + line);
                    System.Environment.Exit(1);
                }

                // parse line
                line = line.Substring(2);
                int           comma = line.IndexOf((System.Char) ',');
                System.String num   = line.Substring(0, (comma) - (0));
                int           q1    = line.IndexOf((System.Char) '\'');
                line = line.Substring(q1 + 1);
                int           q2   = line.IndexOf((System.Char) '\'');
                System.String word = line.Substring(0, (q2) - (0)).ToLower();

                // make sure is a normal word
                if (!IsDecent(word))
                {
                    ndecent++;
                    continue;                     // don't store words w/ spaces
                }

                // 1/2: word2Nums map
                // append to entry or add new one
                System.Collections.IList lis = (System.Collections.IList)word2Nums[word];
                if (lis == null)
                {
                    lis = new System.Collections.ArrayList();
                    lis.Add(num);
                    word2Nums[word] = lis;
                }
                else
                {
                    lis.Add(num);
                }

                // 2/2: num2Words map
                lis = (System.Collections.IList)num2Words[num];
                if (lis == null)
                {
                    lis = new System.Collections.ArrayList();
                    lis.Add(word);
                    num2Words[num] = lis;
                }
                else
                {
                    lis.Add(word);
                }
            }

            // close the streams
            fis.Close();
            br.Close();

            // create the index
            o.WriteLine("[2/2] Building index to store synonyms, " + " map sizes are " + word2Nums.Count + " and " + num2Words.Count);
            Index(indexDir, word2Nums, num2Words);
        }
Пример #59
0
        public static void  Main(System.String[] args)
        {
            var s = new PorterStemmer();

            for (int i = 0; i < args.Length; i++)
            {
                try
                {
                    System.IO.Stream in_Renamed = new System.IO.FileStream(args[i], System.IO.FileMode.Open, System.IO.FileAccess.Read);
                    var buffer = new byte[1024];

                    int bufferLen = in_Renamed.Read(buffer, 0, buffer.Length);
                    int offset    = 0;
                    s.Reset();

                    while (true)
                    {
                        int ch;
                        if (offset < bufferLen)
                        {
                            ch = buffer[offset++];
                        }
                        else
                        {
                            bufferLen = in_Renamed.Read(buffer, 0, buffer.Length);
                            offset    = 0;
                            if (bufferLen < 0)
                            {
                                ch = -1;
                            }
                            else
                            {
                                ch = buffer[offset++];
                            }
                        }

                        if (Char.IsLetter((char)ch))
                        {
                            s.Add(Char.ToLower((char)ch));
                        }
                        else
                        {
                            s.Stem();
                            Console.Out.Write(s.ToString());
                            s.Reset();
                            if (ch < 0)
                            {
                                break;
                            }
                            else
                            {
                                System.Console.Out.Write((char)ch);
                            }
                        }
                    }

                    in_Renamed.Close();
                }
                catch (System.IO.IOException)
                {
                    Console.Out.WriteLine("error reading " + args[i]);
                }
            }
        }
Пример #60
-1
        // GET: Home/GZPost
        public FileResult GZPost(int id = 0)
        {
            if (id <= 0)
            { return null; }
            else
            {
                string fileName = GetFilePath(id);
                if (System.IO.File.Exists(fileName))
                {
                    System.IO.MemoryStream postMemory = new System.IO.MemoryStream();
                    using (System.IO.FileStream postFile = new System.IO.FileStream(fileName, System.IO.FileMode.Open))
                    {
                        postFile.CopyTo(postMemory);
                        postFile.Close();
                    }
                    postMemory.Position = 0;
                    FileStreamResult model = new FileStreamResult(postMemory, "application/json");
                    Response.AppendHeader("Content-Encoding", "gzip");

                    return model;
                }
                else
                { return null; }
            }
        }