Exemple #1
0
        public IEnumerable <UserData> GetData(string input, string start, string end)
        {
            input = "giffiles";
            string lineOfText1 = "";
            var    filestream  = new System.IO.FileStream("./app_data/" + input + ".txt",
                                                          System.IO.FileMode.Open,
                                                          System.IO.FileAccess.Read,
                                                          System.IO.FileShare.ReadWrite);

            System.IO.BufferedStream bs = new System.IO.BufferedStream(filestream);

            var             file = new System.IO.StreamReader(bs, System.Text.Encoding.UTF8, true, 128);
            List <UserData> lst  = new List <UserData>();

            while ((lineOfText1 = file.ReadLine()) != null)
            {
                try
                {
                    UserData obj = new UserData();
                    obj.name    = betweenStrings(lineOfText1, "1  ", "\"");
                    lineOfText1 = file.ReadLine();
                    obj.species = betweenStrings(lineOfText1, "1  ", "\"");
                    lineOfText1 = file.ReadLine();
                    obj.info1   = betweenStrings(lineOfText1, "1  ", "\"");
                    lineOfText1 = file.ReadLine();
                    obj.info2   = betweenStrings(lineOfText1, "1  ", "\"");
                    lst.Add(obj);
                }
                catch (Exception ex)
                {
                }
            }
            return(lst.Take(28));
        }
Exemple #2
0
 private void LoadTagsDB()
 {
     try
     {
         Ares.Tags.ITagsDBFiles tagsDBFiles = Ares.Tags.TagsModule.GetTagsDB().FilesInterface;
         String filePath = System.IO.Path.Combine(Ares.Settings.Settings.Instance.MusicDirectory, tagsDBFiles.DefaultFileName);
         // if reading from a smb share, copy the database to a local file since SQLite can't open databases from input streams or memory bytes
         if (filePath.IsSmbFile())
         {
             String cacheFileName = System.IO.Path.GetTempFileName();
             try
             {
                 using (var ifs = new System.IO.BufferedStream(SambaHelpers.GetSambaInputStream(filePath)))
                     using (var ofs = System.IO.File.Create(cacheFileName))
                     {
                         ifs.CopyTo(ofs);
                     }
             }
             catch (System.IO.IOException ioEx)
             {
                 LogException(ioEx);
                 ShowToast(String.Format(Resources.GetString(Resource.String.tags_db_error), ioEx.Message));
                 return;
             }
             filePath = cacheFileName;
         }
         tagsDBFiles.OpenOrCreateDatabase(filePath);
     }
     catch (Ares.Tags.TagsDbException ex)
     {
         LogException(ex);
         ShowToast(String.Format(Resources.GetString(Resource.String.tags_db_error), ex.Message));
     }
 }
 protected void Page_Load(object sender, EventArgs e)
 {
     try
     {
         //if (this.Request.HttpMethod != "POST")
         //{
         //    this.Response.Write("Request method must be POST");
         //    return;
         //}
         // handle as image
         //string device = this.Request.Form["deviceid"].ToString();
         using (SmartCityEntities ctx = new SmartCityEntities())
         {
             SampledImage sImage = new SampledImage();
             sImage.device_id = Convert.ToInt32(this.Request.QueryString["device"]);
             sImage.image_timestamp = DateTime.Now;
             System.IO.BufferedStream bufRead = new System.IO.BufferedStream(this.Request.Files[0].InputStream);
             System.IO.BinaryReader binaryRead = new System.IO.BinaryReader(bufRead);
             sImage.imagesample = binaryRead.ReadBytes(this.Request.Files[0].ContentLength);
             ctx.SampledImage.Add(sImage);
             ctx.SaveChanges();
         }
         return;
     }
     catch (Exception ex)
     {
         this.Response.Write(ex.ToString());
         return;
     }
 }
Exemple #4
0
        public override InStream @in(Long bufSize)
        {
            try
              {
            System.IO.Stream ins;
            if (m_parent is Zip)
            {
              // never buffer if using ZipInputStream
              ins = new ZipEntryInputStream((m_parent as Zip).m_zipIn);
            }
            else
            {
              ins = (m_parent as ZipFile).GetInputStream(m_entry);

              // buffer if specified
              if (bufSize != null && bufSize.longValue() != 0)
            ins = new System.IO.BufferedStream(ins, bufSize.intValue());
            }

            // return as fan stream
            return new SysInStream(ins);
              }
              catch (System.IO.IOException e)
              {
            throw IOErr.make(e).val;
              }
        }
 protected void Page_Load(object sender, EventArgs e)
 {
     try
     {
         //if (this.Request.HttpMethod != "POST")
         //{
         //    this.Response.Write("Request method must be POST");
         //    return;
         //}
         // handle as image
         //string device = this.Request.Form["deviceid"].ToString();
         using (SmartCityEntities ctx = new SmartCityEntities())
         {
             SampledImage sImage = new SampledImage();
             sImage.device_id       = Convert.ToInt32(this.Request.QueryString["device"]);
             sImage.image_timestamp = DateTime.Now;
             System.IO.BufferedStream bufRead    = new System.IO.BufferedStream(this.Request.Files[0].InputStream);
             System.IO.BinaryReader   binaryRead = new System.IO.BinaryReader(bufRead);
             sImage.imagesample = binaryRead.ReadBytes(this.Request.Files[0].ContentLength);
             ctx.SampledImage.Add(sImage);
             ctx.SaveChanges();
         }
         return;
     }
     catch (Exception ex)
     {
         this.Response.Write(ex.ToString());
         return;
     }
 }
        public static string Sha1(string fileName)
        {
            string returnValue = null;

            using (System.IO.FileStream fs = System.IO.File.OpenRead(fileName))
            {
                using (System.IO.BufferedStream bs = new System.IO.BufferedStream(fs))
                {
                    using (System.Security.Cryptography.SHA1 sha1 = System.Security.Cryptography.SHA1.Create())
                    {
                        byte[] hash = sha1.ComputeHash(bs);
                        System.Text.StringBuilder formatted = new System.Text.StringBuilder(2 * hash.Length);

                        for (int i = 0; i < hash.Length; ++i)
                        {
                            formatted.AppendFormat(System.Globalization.CultureInfo.InvariantCulture, "{0:x2}", hash[i]);
                        } // Next b

                        returnValue      = formatted.ToString();
                        formatted.Length = 0;
                        formatted        = null;
                    } // End Sha1
                }     // End Using bs
            }         // End Using fs

            return(returnValue);
        } // End Function Sha1
Exemple #7
0
        public override InStream @in(Long bufSize)
        {
            try
            {
                System.IO.Stream ins;
                if (m_parent is Zip)
                {
                    // never buffer if using ZipInputStream
                    ins = new ZipEntryInputStream((m_parent as Zip).m_zipIn);
                }
                else
                {
                    ins = (m_parent as ZipFile).GetInputStream(m_entry);

                    // buffer if specified
                    if (bufSize != null && bufSize.longValue() != 0)
                    {
                        ins = new System.IO.BufferedStream(ins, bufSize.intValue());
                    }
                }

                // return as fan stream
                return(new SysInStream(ins));
            }
            catch (System.IO.IOException e)
            {
                throw IOErr.make(e).val;
            }
        }
            public virtual void  load()
            {
                if (loaded)
                {
                    return;
                }
                try
                {
                    System.IO.Stream      inStream = new System.IO.BufferedStream(System.Net.WebRequest.Create(this.url).GetResponse().GetResponseStream());
                    XmlSAXDocumentManager factory  = XmlSAXDocumentManager.NewInstance();
                    factory.NamespaceAllowed = false;                     // FIXME

                    XLRHandler   xmlHandler   = new XLRHandler(Enclosing_Instance.nodedict, prefix);
                    CDATAHandler cdataHandler = new CDATAHandler(xmlHandler);

                    XmlSAXDocumentManager parser = XmlSAXDocumentManager.CloneInstance(factory);
                    //UPGRADE_TODO: Method 'javax.xml.parsers.SAXParser.setProperty' was converted to 'XmlSAXDocumentManager.setProperty' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaxxmlparsersSAXParsersetProperty_javalangString_javalangObject'"
                    parser.setProperty("http://xml.org/sax/properties/lexical-handler", cdataHandler);
                    parser.parse(inStream, xmlHandler);
                }
                catch (System.Exception e)
                {
                    SupportClass.WriteStackTrace(e, Console.Error);
                }
                loaded = true;
            }
Exemple #9
0
            public Connection(TcpClient connection)
            {
                _connection = connection;
                _connection.NoDelay = true;

                _stream = new BufferedStream(_connection.GetStream());
                _reader = new BinaryReader(_stream);
                _writer = new BinaryWriter(_stream);
            }
Exemple #10
0
        public void DumpFields(System.IO.BufferedStream stream)
        {
            StringBuilder fieldBuilder = new StringBuilder();

            this.BuildFields(ref fieldBuilder);

            byte[] fieldBytes = Encoding.UTF8.GetBytes(fieldBuilder.ToString());
            stream.Write(fieldBytes, 0, fieldBytes.Length);
        }
Exemple #11
0
        protected internal virtual System.IO.Stream openInput(System.String fileName)
        {
            // ensure name is abstract path name
            System.IO.FileInfo       file   = new System.IO.FileInfo(fileName);
            System.IO.Stream         fileIn = new System.IO.FileStream(file.FullName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
            System.IO.BufferedStream bufIn  = new System.IO.BufferedStream(fileIn);

            return(bufIn);
        }
        public void Copy(Context context, string fromFileName, Android.Net.Uri toUri, int bufferSize = 1024, CancellationToken?token = null)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (string.IsNullOrEmpty(fromFileName))
            {
                throw new ArgumentNullException(nameof(fromFileName));
            }

            if (toUri == null)
            {
                throw new ArgumentNullException(nameof(toUri));
            }

            if (!System.IO.File.Exists(fromFileName))
            {
                throw new System.IO.FileNotFoundException(fromFileName);
            }

            if (token == null)
            {
                token = CancellationToken.None;
            }

            var buffer = new byte[bufferSize];

            using (var readStream = System.IO.File.OpenRead(fromFileName))
            {
                using (var openFileDescriptor = context.ContentResolver.OpenFileDescriptor(toUri, "w"))
                {
                    using (var fileOutputStream = new Java.IO.FileOutputStream(openFileDescriptor.FileDescriptor))
                    {
                        using (var bufferedStream = new System.IO.BufferedStream(readStream))
                        {
                            int count;
                            while ((count = bufferedStream.Read(buffer, 0, bufferSize)) > 0)
                            {
                                if (token.Value.IsCancellationRequested)
                                {
                                    return;
                                }

                                fileOutputStream.Write(buffer, 0, count);
                            }

                            fileOutputStream.Close();
                            openFileDescriptor.Close();
                        }
                    }
                }
            }
        }
Exemple #13
0
 /// <summary>
 /// Gets the hash of a given stream's contents.
 /// </summary>
 public static Hash256 GetContentsHash(System.IO.Stream stream)
 {
     using (System.IO.BufferedStream bufferedStream = new System.IO.BufferedStream(stream, 1200000))
     {
         using (SHA256Managed sha = new SHA256Managed())
         {
             byte[] hashBytes = sha.ComputeHash(bufferedStream);
             return(new Hash256(hashBytes));
         }
     }
 }
Exemple #14
0
 public Tresponse SendRequest(Trequest requestMessage)
 {
     //Using a buffered stream speeds things up by making fewer/larger
     //writes to the pipe.
     using (var bufferedStream = new System.IO.BufferedStream(_streamPair.OutgoingRequestStream))
     {
         _formatter.Serialize(bufferedStream, requestMessage);
     }
     _streamPair.IncomingResponseStream.CheckRemainingByteChunkSize();
     return((Tresponse)_formatter.Deserialize(_streamPair.IncomingResponseStream));
 }
Exemple #15
0
		/// <summary>
		/// Obtém logotipo do repositório
		/// </summary>
		/// <returns>Imagem contendo logotipo</returns>
		private static Image ObterLogotipoOriginal()
		{
			Image logotipo;
			System.IO.BufferedStream buffer = new System.IO.BufferedStream(
				Assembly.GetExecutingAssembly().GetManifestResourceStream("Apresentação.Mercadoria.Etiqueta.Impressão.Layout.Logo.jpg"));

			logotipo = Image.FromStream(buffer);

			buffer.Close();

			return logotipo;
		}
Exemple #16
0
        public static string GenerateMD5Hash(this System.IO.FileInfo file)
        {
            if (file == null || !file.Exists)
            {
                return(null);
            }
            var md5gen = System.Security.Cryptography.MD5.Create();

            using (var stream = new System.IO.BufferedStream(file.OpenRead(), 1200000))
            {
                return(BitConverter.ToString(md5gen.ComputeHash(stream)));
            }
        }
 private static void copyStreamToFile(System.IO.Stream stream, string destination)
 {
     using (System.IO.BufferedStream bs = new System.IO.BufferedStream(stream))
     {
         using (System.IO.FileStream os = System.IO.File.OpenWrite(destination))
         {
             byte[] buffer = new byte[2 * 4096];
             int    nBytes;
             while ((nBytes = bs.Read(buffer, 0, buffer.Length)) > 0)
             {
                 os.Write(buffer, 0, nBytes);
             }
         }
     }
 }
Exemple #18
0
 public static string hs1FileHash(System.IO.Stream FileStream)
 {
     using (System.IO.BufferedStream bs = new System.IO.BufferedStream(FileStream))
     {
         using (System.Security.Cryptography.SHA1Managed sha1 = new System.Security.Cryptography.SHA1Managed())
         {
             byte[] hash = sha1.ComputeHash(bs);
             System.Text.StringBuilder formatted = new System.Text.StringBuilder(2 * hash.Length);
             foreach (byte b in hash)
             {
                 formatted.AppendFormat("{0:X2}", b);
             }
             return(formatted.ToString());
         }
     }
 }
Exemple #19
0
        public async Task ChangeAvatarAsync([Remainder] string args)
        {
            var client = new HttpClient();

            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("image/*"));
            client.DefaultRequestHeaders.Add("User-Agent", Utils.UserAgent);

            var stream = await client.GetStreamAsync(args);

            var img = new System.IO.BufferedStream(stream);

            await Context.Client.CurrentUser.ModifyAsync(x => x.Avatar = new Image(img));

            await ReplyAsync("Success changing my avatar, does it look good?");
        }
        public RunProcessForm(System.Diagnostics.Process process)
        {
            InitializeComponent();
            _process = process;
            _out = new System.IO.BufferedStream(_process.StandardOutput.BaseStream);
            _err = new System.IO.BufferedStream(_process.StandardError.BaseStream);
            // TODO: use async IO here
            if (_out.CanTimeout)
                _out.ReadTimeout = 1;

            if (_err.CanTimeout)
                _err.ReadTimeout = 1;

            _outReader = new System.IO.StreamReader(_out);
            _errReader = new System.IO.StreamReader(_err);
            timer1.Start();
        }
Exemple #21
0
        /// <summary>
        /// Salva todos os relatórios em um único PDF.
        /// </summary>
        /// <param name="p_filename">Nome do arquivo PDF a ser salvo.</param>
        public void SaveMerged(string p_filename)
        {
            PDFjet.NET.PDF             v_pdf;
            System.IO.BufferedStream   v_buffer;
            System.IO.FileStream       f;
            Spartacus.Reporting.Report v_report;
            double v_perc, v_percstep, v_lastperc;

            try
            {
                f        = new System.IO.FileStream(p_filename, System.IO.FileMode.Create);
                v_buffer = new System.IO.BufferedStream(f);

                v_pdf = new PDFjet.NET.PDF(v_buffer);

                v_perc     = 0.0;
                v_percstep = 100.0 / (double)this.v_reports.Count;
                v_lastperc = v_percstep;

                for (int k = 0; k < this.v_reports.Count; k++)
                {
                    v_report = this.v_reports[k];

                    v_report.v_perc     = v_perc;
                    v_report.v_percstep = v_percstep;
                    v_report.v_lastperc = v_lastperc;

                    v_report.SavePartial(v_pdf);

                    v_perc      = v_lastperc;
                    v_lastperc += v_percstep;
                }

                v_pdf.Flush();
                v_buffer.Close();
            }
            catch (Spartacus.Reporting.Exception e)
            {
                throw e;
            }
            catch (System.Exception e)
            {
                throw new Spartacus.Reporting.Exception("Erro ao gerar o pacote PDF de saída.", e);
            }
        }
Exemple #22
0
 void Connect()
 {
     socket             = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp);
     socket.NoDelay     = true;
     socket.SendTimeout = SendTimeout;
     socket.Connect(Host, Port);
     if (!socket.Connected)
     {
         socket.Close();
         socket = null;
         return;
     }
     bstream = new System.IO.BufferedStream(new System.Net.Sockets.NetworkStream(socket), 16 * 1024);
     if (Password != null)
     {
         SendExpectSuccess("AUTH", Password);
     }
 }
Exemple #23
0
            public Connection(string hostname, int port)
            {
                try
                {
                    _connection = new TcpClient(hostname, port);
                    _connection.NoDelay = true;

                    _stream = new BufferedStream(_connection.GetStream());
                    _reader = new BinaryReader(_stream);
                    _writer = new BinaryWriter(_stream);
                }
                catch (SocketException)
                {
                    _connection = null;
                    _stream = null;

                    throw new ConnectionException("Failed to connect to server");
                }
            }
 public static Task<Uri> DownloadUserIcon(Uri dataUrl)
 {
     Uri tmp;
     if (_cacheDictionary.TryGetValue(dataUrl, out tmp))
         return Task.Factory.StartNew(obj => (Uri)obj, tmp);
     else
         return Task.Factory.StartNew(() =>
             {
                 var req = System.Net.HttpWebRequest.Create(dataUrl);
                 var res = (System.Net.HttpWebResponse)req.GetResponse();
                 var cacheFilePath = System.IO.Path.GetTempFileName();
                 int recieveByte;
                 byte[] buff = new byte[1024];
                 using (var nstrm = new System.IO.BufferedStream(res.GetResponseStream()))
                 using (var fstrm = System.IO.File.OpenWrite(cacheFilePath))
                     while ((recieveByte = nstrm.Read(buff, 0, buff.Length)) > 0)
                         fstrm.Write(buff, 0, recieveByte);
                 return new Uri(cacheFilePath);
             });
 }
        public RunProcessForm(System.Diagnostics.Process process)
        {
            InitializeComponent();
            _process = process;
            _out     = new System.IO.BufferedStream(_process.StandardOutput.BaseStream);
            _err     = new System.IO.BufferedStream(_process.StandardError.BaseStream);
            // TODO: use async IO here
            if (_out.CanTimeout)
            {
                _out.ReadTimeout = 1;
            }

            if (_err.CanTimeout)
            {
                _err.ReadTimeout = 1;
            }

            _outReader = new System.IO.StreamReader(_out);
            _errReader = new System.IO.StreamReader(_err);
            timer1.Start();
        }
Exemple #26
0
        private static void copyStreamToFile(System.IO.Stream stream, string destination)
        {
            System.Diagnostics.Debug.Assert(stream != null);

            if (destination == null || destination == string.Empty)
            {
                return;
            }

            using (System.IO.BufferedStream bs = new System.IO.BufferedStream(stream))
            {
                using (System.IO.FileStream os = System.IO.File.OpenWrite(destination))
                {
                    byte[] buffer = new byte[2 * 4096];
                    int    nBytes;
                    while ((nBytes = bs.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        os.Write(buffer, 0, nBytes);
                    }
                }
            }
        }
Exemple #27
0
 public static System.IO.MemoryStream GetFile(AmazonS3 s3Client, string filekey)
 {
     using (s3Client)
     {
         S3_KEY = filekey;
         System.IO.MemoryStream file = new System.IO.MemoryStream();
         try
         {
             GetObjectResponse r = s3Client.GetObject(new GetObjectRequest()
             {
                 BucketName = BUCKET_NAME,
                 Key        = S3_KEY
             });
             try
             {
                 long transferred = 0L;
                 System.IO.BufferedStream stream2 = new System.IO.BufferedStream(r.ResponseStream);
                 byte[] buffer = new byte[0x2000];
                 int    count  = 0;
                 while ((count = stream2.Read(buffer, 0, buffer.Length)) > 0)
                 {
                     file.Write(buffer, 0, count);
                 }
             }
             finally
             {
             }
             return(file);
         }
         catch (AmazonS3Exception)
         {
             //Show exception
         }
     }
     return(null);
 }
		// Uncomment these cases & run them on an older Lucene
		// version, to generate an index to test backwards
		// compatibility.  Then, cd to build/test/index.cfs and
		// run "zip index.<VERSION>.cfs.zip *"; cd to
		// build/test/index.nocfs and run "zip
		// index.<VERSION>.nocfs.zip *".  Then move those 2 zip
		// files to your trunk checkout and add them to the
		// oldNames array.
		
		/*
		public void testCreatePreLocklessCFS() throws IOException {
		createIndex("index.cfs", true);
		}
		
		public void testCreatePreLocklessNoCFS() throws IOException {
		createIndex("index.nocfs", false);
		}
		*/
		
		/* Unzips dirName + ".zip" --> dirName, removing dirName
		first */
		public virtual void  Unzip(System.String zipName, System.String destDirName)
		{
#if SHARP_ZIP_LIB
			// get zip input stream
			ICSharpCode.SharpZipLib.Zip.ZipInputStream zipFile;
			zipFile = new ICSharpCode.SharpZipLib.Zip.ZipInputStream(System.IO.File.OpenRead(zipName + ".zip"));

			// get dest directory name
			System.String dirName = FullDir(destDirName);
			System.IO.FileInfo fileDir = new System.IO.FileInfo(dirName);

			// clean up old directory (if there) and create new directory
			RmDir(fileDir.FullName);
			System.IO.Directory.CreateDirectory(fileDir.FullName);

			// copy file entries from zip stream to directory
			ICSharpCode.SharpZipLib.Zip.ZipEntry entry;
			while ((entry = zipFile.GetNextEntry()) != null)
			{
				System.IO.Stream streamout = new System.IO.BufferedStream(new System.IO.FileStream(new System.IO.FileInfo(System.IO.Path.Combine(fileDir.FullName, entry.Name)).FullName, System.IO.FileMode.Create));
				
				byte[] buffer = new byte[8192];
				int len;
				while ((len = zipFile.Read(buffer, 0, buffer.Length)) > 0)
				{
					streamout.Write(buffer, 0, len);
				}
				
				streamout.Close();
			}
			
			zipFile.Close();
#else
			Assert.Fail("Needs integration with SharpZipLib");
#endif
		}
        // Uncomment these cases & run them on an older Lucene
        // version, to generate an index to test backwards
        // compatibility.  Then, cd to build/test/index.cfs and
        // run "zip index.<VERSION>.cfs.zip *"; cd to
        // build/test/index.nocfs and run "zip
        // index.<VERSION>.nocfs.zip *".  Then move those 2 zip
        // files to your trunk checkout and add them to the
        // oldNames array.

        /*
         * public void testCreatePreLocklessCFS() throws IOException {
         * createIndex("index.cfs", true);
         * }
         *
         * public void testCreatePreLocklessNoCFS() throws IOException {
         * createIndex("index.nocfs", false);
         * }
         */

        /* Unzips dirName + ".zip" --> dirName, removing dirName
         * first */
        public virtual void  Unzip(System.String zipName, System.String destDirName)
        {
#if SHARP_ZIP_LIB
            // get zip input stream
            ICSharpCode.SharpZipLib.Zip.ZipInputStream zipFile;
            zipFile = new ICSharpCode.SharpZipLib.Zip.ZipInputStream(System.IO.File.OpenRead(zipName + ".zip"));

            // get dest directory name
            System.String      dirName = FullDir(destDirName);
            System.IO.FileInfo fileDir = new System.IO.FileInfo(dirName);

            // clean up old directory (if there) and create new directory
            RmDir(fileDir.FullName);
            System.IO.Directory.CreateDirectory(fileDir.FullName);

            // copy file entries from zip stream to directory
            ICSharpCode.SharpZipLib.Zip.ZipEntry entry;
            while ((entry = zipFile.GetNextEntry()) != null)
            {
                System.IO.Stream streamout = new System.IO.BufferedStream(new System.IO.FileStream(new System.IO.FileInfo(System.IO.Path.Combine(fileDir.FullName, entry.Name)).FullName, System.IO.FileMode.Create));

                byte[] buffer = new byte[8192];
                int    len;
                while ((len = zipFile.Read(buffer, 0, buffer.Length)) > 0)
                {
                    streamout.Write(buffer, 0, len);
                }

                streamout.Close();
            }

            zipFile.Close();
#else
            Assert.Fail("Needs integration with SharpZipLib");
#endif
        }
Exemple #30
0
        public IEnumerable <UserData> GetUserData(string input)
        {
            string lineOfText1 = "";
            string lineOfText2 = "";

            try {
                var filestream = new System.IO.FileStream("./app_data/" + input + ".txt",
                                                          System.IO.FileMode.Open,
                                                          System.IO.FileAccess.Read,
                                                          System.IO.FileShare.ReadWrite);


                System.IO.BufferedStream bs = new System.IO.BufferedStream(filestream);

                var             file = new System.IO.StreamReader(bs, System.Text.Encoding.UTF8, true, 128);
                List <UserData> lst  = new List <UserData>();
                while ((lineOfText1 = file.ReadLine()) != null)
                {
                    UserData obj = new UserData();
                    lineOfText2 = file.ReadLine();
                    Boolean found;
                    //Do something with the lineOfText(
                    if (lineOfText2.Contains("profile"))
                    {
                        obj.name = lineOfText1.Replace("FileName: ", "");
                        obj.name = "www.facebook.com/" + obj.name;

                        string output = lineOfText2.Split(':', ',')[1];
                        obj.age = output.Replace("\"", "");
                        obj.age = "http://graph.facebook.com/" + obj.age + "/picture?type=large#/1039660954";

                        var lineOfText3 = file.ReadLine();
                        if (lineOfText3 != null)
                        {
                            obj.occupation = lineOfText3.Replace("FileName: ", "");
                            obj.name       = "www.facebook.com/" + obj.occupation;
                        }
                        var lineOfText4 = file.ReadLine();
                        if (lineOfText4 != null)
                        {
                            string output1 = lineOfText4.Split(':', ',')[1];
                            obj.species = output1.Replace("\"", "");
                            obj.species = "http://graph.facebook.com/" + obj.species + "/picture?type=large#/1039660954";
                        }

                        var lineOfText5 = file.ReadLine();
                        if (lineOfText5 != null)
                        {
                            obj.info1 = lineOfText5.Replace("FileName: ", "");
                            obj.info1 = "www.facebook.com/" + obj.info1;
                        }
                        var lineOfText6 = file.ReadLine();
                        if (lineOfText6 != null)
                        {
                            string output2 = lineOfText6.Split(':', ',')[1];
                            obj.info2 = output2.Replace("\"", "");
                            obj.info2 = "http://graph.facebook.com/" + obj.info2 + "/picture?type=large#/1039660954";
                        }



                        //obj.species = obj.species.Replace("entity_id\":\"","");
                        lst.Add(obj);
                    }
                    else
                    {
                        continue;
                    }
                }
                var rng = new Random();
                // lst =ShuffleList(lst);

                List <UserData> FINALDATA = new List <UserData>();
                Random          r         = new Random();
                for (int i = 0; i < 299; i++)
                {
                    FINALDATA.Insert(i, lst[r.Next(0, lst.Count)]);
                }
                // return lst.Take(1000);
                return(FINALDATA.Take(200));
            }
            catch (Exception ex)
            {
                return(null);
            }
            //return Enumerable.Range(1, 5).Select(index => new UserData
            //{
            //    name=  "http://facebook.com/e.melism",
            //     age= "http://graph.facebook.com/100001538625944/picture?type=normal#/100001538625944",
            //     species= "http://graph.facebook.com/1039660954/picture?type=large#/1039660954",
            //     occupation= "http://graph.facebook.com/1830700925/picture?type=normal#/1830700925"
            //});
        }
        /// <summary>
        /// Salva como PDF.
        /// </summary>
        /// <param name="p_filename">Nome do arquivo PDF.</param>
        public void Save(string p_filename)
        {
            PDFjet.NET.PDF v_pdf;
            System.IO.BufferedStream v_buffer;
            System.IO.FileStream f;
            PDFjet.NET.Table v_dataheadertable = null, v_datatable;
            float[] v_layout;
            PDFjet.NET.Page v_page;
            System.Collections.Generic.List<System.Collections.Generic.List<PDFjet.NET.Cell>> v_rendered;
            int v_numpages, v_currentpage;
            Spartacus.Utils.Cryptor v_cryptor;
            string v_datafilename;
            System.IO.StreamReader v_reader;

            // se o relatório não tiver dados, não faz nada
            if (this.v_table.Rows.Count == 0)
                return;

            try
            {
                this.v_progress.FireEvent("Spartacus.Reporting.Report", "ExportPDF", this.v_perc, "Renderizando relatorio " + this.v_reportid.ToString() + " no arquivo " + p_filename);
                this.v_inc = this.v_percstep / (double) this.v_table.Rows.Count;
                this.v_renderedrows = 0;

                f = new System.IO.FileStream(p_filename, System.IO.FileMode.Create);
                v_buffer = new System.IO.BufferedStream(f);

                v_pdf = new PDFjet.NET.PDF(v_buffer);

                if (this.v_settings.v_layout == Spartacus.Reporting.PageLayout.LANDSCAPE)
                    v_layout = PDFjet.NET.A4.LANDSCAPE;
                else
                    v_layout = PDFjet.NET.A4.PORTRAIT;

                v_page = new PDFjet.NET.Page(v_pdf, v_layout);

                // tabela de cabecalho de dados

                if (this.v_settings.v_showdataheader)
                {
                    v_dataheadertable = new PDFjet.NET.Table();
                    v_dataheadertable.SetPosition(this.v_settings.v_leftmargin, this.v_settings.v_topmargin  + this.v_header.v_height);

                    v_rendered = this.RenderDataHeader(
                        v_page.GetHeight(),
                        v_page.GetWidth(),
                        this.v_settings.v_dataheaderfont.GetFont(v_pdf)
                    );

                    v_dataheadertable.SetData(v_rendered, PDFjet.NET.Table.DATA_HAS_0_HEADER_ROWS);
                    //v_dataheadertable.SetCellBordersWidth(1.5f);
                }

                // tabela de dados

                v_datatable = new PDFjet.NET.Table();
                //v_datatable.SetPosition(this.v_settings.v_leftmargin, this.v_settings.v_topmargin  + this.v_header.v_height + ((this.v_settings.v_dataheaderfont.v_size + 2) * 1.8 * this.v_numrowsdetail));
                if (this.v_settings.v_showdataheader)
                    v_datatable.SetPosition(this.v_settings.v_leftmargin, this.v_settings.v_topmargin  + this.v_header.v_height + ((this.v_settings.v_dataheaderfont.v_size + 2) * 1.8 * this.v_numrowsdataheader));
                else
                    v_datatable.SetPosition(this.v_settings.v_leftmargin, this.v_settings.v_topmargin  + this.v_header.v_height);
                v_datatable.SetBottomMargin(this.v_settings.v_bottommargin + this.v_footer.v_height);

                this.BuildTemplates(
                    v_page.GetHeight(),
                    v_page.GetWidth(),
                    this.v_settings.v_datafieldfont.GetFont(v_pdf),
                    this.v_settings.v_groupheaderfont.GetFont(v_pdf),
                    this.v_settings.v_groupfooterfont.GetFont(v_pdf)
                );

                v_cryptor = new Spartacus.Utils.Cryptor("spartacus");
                v_datafilename = v_cryptor.RandomString() + ".tmp";
                this.v_datafile = System.IO.File.Open(
                    v_datafilename,
                    System.IO.FileMode.Create,
                    System.IO.FileAccess.ReadWrite
                );

                v_rendered = this.RenderData(
                    v_page.GetHeight(),
                    v_page.GetWidth(),
                    this.v_settings.v_datafieldfont.GetFont(v_pdf),
                    this.v_settings.v_groupheaderfont.GetFont(v_pdf),
                    this.v_settings.v_groupfooterfont.GetFont(v_pdf)
                );

                v_datatable.SetData(v_rendered, PDFjet.NET.Table.DATA_HAS_0_HEADER_ROWS);
                //v_datatable.SetCellBordersWidth(1.5f);

                this.v_datafile.Seek(0, System.IO.SeekOrigin.Begin);
                v_reader = new System.IO.StreamReader(this.v_datafile);

                // salvando PDF

                this.v_header.SetValues(this.v_table);
                this.v_footer.SetValues(this.v_table);

                v_numpages = v_datatable.GetNumberOfPages(v_page);
                v_currentpage = 1;
                while (v_datatable.HasMoreData())
                {
                    this.v_header.SetPageNumber(v_currentpage, v_numpages);
                    this.v_footer.SetPageNumber(v_currentpage, v_numpages);

                    this.v_header.Render(
                        this.v_settings.v_reportheaderfont,
                        this.v_settings.v_leftmargin,
                        this.v_settings.v_topmargin,
                        this.v_settings.v_rightmargin,
                        v_pdf,
                        v_page
                    );

                    if (this.v_settings.v_showdataheader)
                        v_dataheadertable.DrawOn(v_page);
                    v_datatable.ImprovedDrawOn(v_page, v_reader);

                    this.v_footer.Render(
                        this.v_settings.v_reportfooterfont,
                        this.v_settings.v_leftmargin,
                        v_page.GetHeight() - v_settings.v_bottommargin - v_footer.v_height,
                        this.v_settings.v_rightmargin,
                        v_pdf,
                        v_page
                    );

                    if (v_datatable.HasMoreData())
                    {
                        if (this.v_settings.v_showdataheader)
                            v_dataheadertable.ResetRenderedPagesCount();

                        v_page = new PDFjet.NET.Page(v_pdf, v_layout);
                        v_currentpage++;
                    }
                }

                v_pdf.Flush();
                v_buffer.Close();

                v_reader.Close();
                this.v_datafile.Close();
                (new System.IO.FileInfo(v_datafilename)).Delete();

                this.v_perc = this.v_lastperc;
                this.v_progress.FireEvent("Spartacus.Reporting.Report", "ExportPDF", this.v_perc, "Relatorio " + this.v_reportid.ToString() + " renderizado no arquivo " + p_filename);
            }
            catch (System.Exception e)
            {
                throw new Spartacus.Reporting.Exception("Erro ao gerar o arquivo PDF de saída.", e);
            }
        }
Exemple #32
0
		/// <summary>
		/// Save configuration to a XML file
		/// </summary>
		/// <param name="filename">The full path filename to save configuration</param>
		public void SaveToXml(string filename)
		{
			System.IO.BufferedStream xmlStream = null;
			byte [] xmlData;
			const int bufferSize = 4096;
			XmlDocument doc;

			#region Create doc, loading default xml

			// Load default xml from resource
			xmlStream = new System.IO.BufferedStream(
				Assembly.GetExecutingAssembly().GetManifestResourceStream("Report.Layout.Complex.DefaultLabelLayout.xml"),
				bufferSize);

			xmlData = new byte[xmlStream.Length];

			while (xmlStream.Position < xmlStream.Length)
				xmlStream.Read((byte[]) xmlData, (int) xmlStream.Position, (int) Math.Min(bufferSize, xmlStream.Length - xmlStream.Position));
				
			xmlStream.Close();

			string strDefaultXml = System.Text.Encoding.UTF8.GetString(xmlData);

			strDefaultXml = strDefaultXml.Substring(strDefaultXml.IndexOf('<'));

			doc = new XmlDocument();
			doc.LoadXml(strDefaultXml);

			#endregion

			SaveToXml(doc, doc["LabelLayout"]["ItemLayout"]);

			doc.Save(filename);
		}
		private static bool isZip(System.Uri url)
		{
			System.IO.Stream in_Renamed = new System.IO.BufferedStream(System.Net.WebRequest.Create(url).GetResponse().GetResponseStream());
			try
			{
				return isZip(in_Renamed);
			}
			finally
			{
				in_Renamed.Close();
			}
		}
Exemple #34
0
        /*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/

        /// <summary>Parse command line options and arguments to set various user-option
        /// flags and variables.
        /// </summary>
        /// <param name="argv">the command line arguments to be parsed.
        ///
        /// </param>
        protected internal static void  parse_args(string[] argv)
        {
            int len = argv.Length;
            int i;

            /* parse the options */
            for (i = 0; i < len; i++)
            {
                /* try to get the various options */
                if (argv[i].Equals("-namespace"))
                {
                    /* must have an arg */
                    if (++i >= len || argv[i].StartsWith("-") || argv[i].EndsWith(".cup"))
                    {
                        usage("-namespace must have a name argument");
                    }

                    /* record the name */
                    emit.namespace_name = argv[i];
                }
                else if (argv[i].Equals("-parser"))
                {
                    /* must have an arg */
                    if (++i >= len || argv[i].StartsWith("-") || argv[i].EndsWith(".cup"))
                    {
                        usage("-parser must have a name argument");
                    }

                    /* record the name */
                    emit.parser_class_name = argv[i];
                }
                else if (argv[i].Equals("-symbols"))
                {
                    /* must have an arg */
                    if (++i >= len || argv[i].StartsWith("-") || argv[i].EndsWith(".cup"))
                    {
                        usage("-symbols must have a name argument");
                    }

                    /* record the name */
                    emit.symbol_const_class_name = argv[i];
                }
                else if (argv[i].Equals("-nonterms"))
                {
                    include_non_terms = true;
                }
                else if (argv[i].Equals("-expect"))
                {
                    /* must have an arg */
                    if (++i >= len || argv[i].StartsWith("-") || argv[i].EndsWith(".cup"))
                    {
                        usage("-expect must have a name argument");
                    }

                    /* record the number */
                    try
                    {
                        expect_conflicts = System.Int32.Parse(argv[i]);
                    }
                    catch (System.FormatException)
                    {
                        usage("-expect must be followed by a decimal integer");
                    }
                }
                else if (argv[i].Equals("-compact_red"))
                {
                    opt_compact_red = true;
                }
                else if (argv[i].Equals("-nosummary"))
                {
                    no_summary = true;
                }
                else if (argv[i].Equals("-nowarn"))
                {
                    emit.nowarn = true;
                }
                else if (argv[i].Equals("-dump_states"))
                {
                    opt_dump_states = true;
                }
                else if (argv[i].Equals("-dump_tables"))
                {
                    opt_dump_tables = true;
                }
                else if (argv[i].Equals("-progress"))
                {
                    print_progress = true;
                }
                else if (argv[i].Equals("-dump_grammar"))
                {
                    opt_dump_grammar = true;
                }
                else if (argv[i].Equals("-dump"))
                {
                    opt_dump_states = opt_dump_tables = opt_dump_grammar = true;
                }
                else if (argv[i].Equals("-time"))
                {
                    opt_show_timing = true;
                }
                else if (argv[i].Equals("-debug"))
                {
                    opt_do_debug = true;
                }
                else if (argv[i].Equals("-nopositions"))
                {
                    lr_values = false;
                }
                else if (argv[i].Equals("-interface"))
                {
                    sym_interface = true;
                }
                else if (argv[i].Equals("-noscanner"))
                {
                    suppress_scanner = true;
                }
                else if (argv[i].Equals("-version"))
                {
                    System.Console.Out.WriteLine(version.title_str);
                    System.Environment.Exit(1);
                }
                else if (!argv[i].StartsWith("-") && i == len - 1)
                {
                    /* use input from file. */
                    try
                    {
                        input_file = new System.IO.BufferedStream(new System.IO.FileStream(argv[i], System.IO.FileMode.Open, System.IO.FileAccess.Read));
                    }
                    catch (System.IO.FileNotFoundException)
                    {
                        usage("Unable to open \"" + argv[i] + "\" for input");
                    }
                }
                else
                {
                    usage("Unrecognized option \"" + argv[i] + "\"");
                }
            }
        }
Exemple #35
0
 public static System.IO.MemoryStream GetFile(AmazonS3 s3Client, string filekey)
 {
     using (s3Client)
     {
         S3_KEY = filekey;
         System.IO.MemoryStream file = new System.IO.MemoryStream();
         try
         {
             GetObjectResponse r = s3Client.GetObject(new GetObjectRequest()
             {
                 BucketName = BUCKET_NAME,
                 Key = S3_KEY
             });
             try
             {
                 long transferred = 0L;
                 System.IO.BufferedStream stream2 = new System.IO.BufferedStream(r.ResponseStream);
                 byte[] buffer = new byte[0x2000];
                 int count = 0;
                 while ((count = stream2.Read(buffer, 0, buffer.Length)) > 0)
                 {
                     file.Write(buffer, 0, count);
                 }
             }
             finally
             {
             }
             return file;
         }
         catch (AmazonS3Exception)
         {
             //Show exception
         }
     }
     return null;
 }
Exemple #36
0
		/// <summary>
		/// Load settings from file
		/// </summary>
		/// <param name="filename">Xml filename</param>
		/// <param name="designMode">If layout is on design mode</param>
		public void LoadFromFile(string filename, bool designMode)
		{
			XmlDocument	doc;

			// Create new XmlDoc
			doc = new XmlDocument();

			// Check if file exists
			if (System.IO.File.Exists(filename))
			{
				// Load from file
				doc.Load(filename);
			}
			else
			{
				System.IO.BufferedStream xmlStream = null;
				byte [] xmlData;
				const int bufferSize = 4096;

				// Try to load from resource
				try
				{
					xmlStream = new System.IO.BufferedStream(
						xmlResourceAssembly.GetManifestResourceStream(filename),
						bufferSize);
				}
				catch
				{
					foreach (string name in xmlResourceAssembly.GetManifestResourceNames())
						if (name.EndsWith(filename))
						{
							xmlStream = new System.IO.BufferedStream(
								xmlResourceAssembly.GetManifestResourceStream(name),
								bufferSize);
							break;
						}
				}

				xmlData = new byte[xmlStream.Length];

				while (xmlStream.Position < xmlStream.Length)
					xmlStream.Read((byte[]) xmlData, (int) xmlStream.Position, (int) Math.Min(bufferSize, xmlStream.Length - xmlStream.Position));
				
				xmlStream.Close();

                string str = System.Text.Encoding.UTF8.GetString(xmlData);

				doc.LoadXml(str.Substring(str.IndexOf('<')));
			}
			
			LoadFromXml(doc, designMode);
		}
		public static void  Main(System.String[] args)
		{
			if (args.Length == 0)
			{
				System.Console.Error.WriteLine("Usage: java tools.SwfxPrinter [-encode] [-asm] [-abc] [-noactions] [-showdebugsource] [-showoffset] [-noglyphs] [-external] [-save file.swf] [-nofunctions] [-out file.swfx] file1.swf ...");
				System.Environment.Exit(1);
			}
			
			int index = 0;
			System.IO.StreamWriter out_Renamed = null;
			System.String outfile = null;
			
			while ((index < args.Length) && (args[index].StartsWith("-")))
			{
				if (args[index].Equals("-encode"))
				{
					encodeOption = true;
					++index;
				}
				else if (args[index].Equals("-save"))
				{
					++index;
					saveOption = true;
					outfile = args[index++];
				}
				else if (args[index].Equals("-decompile"))
				{
					decompileOption = true;
					++index;
				}
				else if (args[index].Equals("-nofunctions"))
				{
					defuncOption = false;
					++index;
				}
				else if (args[index].Equals("-asm"))
				{
					decompileOption = false;
					++index;
				}
				else if (args[index].Equals("-abc"))
				{
					abcOption = true;
					++index;
				}
				else if (args[index].Equals("-noactions"))
				{
					showActionsOption = false;
					++index;
				}
				else if (args[index].Equals("-showoffset"))
				{
					showOffsetOption = true;
					++index;
				}
				else if (args[index].Equals("-showdebugsource"))
				{
					showDebugSourceOption = true;
					++index;
				}
				else if (args[index].Equals("-noglyphs"))
				{
					glyphsOption = false;
					++index;
				}
				else if (args[index].Equals("-out"))
				{
					if (index + 1 == args.Length)
					{
						System.Console.Error.WriteLine("-out requires a filename or - for stdout");
						System.Environment.Exit(1);
					}
					if (!args[index + 1].Equals("-"))
					{
						
						outfile = args[index + 1];
						//UPGRADE_TODO: Constructor 'java.io.FileOutputStream.FileOutputStream' was converted to 'System.IO.FileStream.FileStream' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioFileOutputStreamFileOutputStream_javalangString_boolean'"
						out_Renamed = new System.IO.StreamWriter(SupportClass.GetFileStream(outfile, false), System.Text.Encoding.Default);
					}
					index += 2;
				}
				else if (args[index].Equals("-external"))
				{
					externalOption = true;
					++index;
				}
				else if (args[index].ToUpper().Equals("-tabbedGlyphs".ToUpper()))
				{
					tabbedGlyphsOption = true;
					++index;
				}
				else
				{
					System.Console.Error.WriteLine("unknown argument " + args[index]);
					++index;
				}
			}
			
			if (out_Renamed == null)
			{
				System.IO.StreamWriter temp_writer;
				temp_writer = new System.IO.StreamWriter(System.Console.OpenStandardOutput(), System.Text.Encoding.Default);
				temp_writer.AutoFlush = true;
				out_Renamed = temp_writer;
			}
			
			System.IO.FileInfo f = new System.IO.FileInfo(args[index]);
			System.Uri[] urls;
			bool tmpBool;
			if (System.IO.File.Exists(f.FullName))
				tmpBool = true;
			else
				tmpBool = System.IO.Directory.Exists(f.FullName);
			if (!tmpBool)
			{
				//UPGRADE_TODO: Class 'java.net.URL' was converted to a 'System.Uri' which does not throw an exception if a URL specifies an unknown protocol. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1132'"
				urls = new System.Uri[]{new System.Uri(args[index])};
			}
			else
			{
				if (System.IO.Directory.Exists(f.FullName))
				{
					System.IO.FileInfo[] list = FileUtils.listFiles(f);
					urls = new System.Uri[list.Length];
					for (int i = 0; i < list.Length; i++)
					{
						urls[i] = FileUtils.toURL(list[i]);
					}
				}
				else
				{
					urls = new System.Uri[]{FileUtils.toURL(f)};
				}
			}
			
			for (int i = 0; i < urls.Length; i++)
			{
				try
				{
					System.Uri url = urls[i];
					if (saveOption)
					{
						System.IO.Stream in_Renamed = new System.IO.BufferedStream(System.Net.WebRequest.Create(url).GetResponse().GetResponseStream());
						try
						{
							//UPGRADE_TODO: Constructor 'java.io.FileOutputStream.FileOutputStream' was converted to 'System.IO.FileStream.FileStream' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioFileOutputStreamFileOutputStream_javalangString'"
							System.IO.Stream fileOut = new System.IO.BufferedStream(new System.IO.FileStream(outfile, System.IO.FileMode.Create));
							try
							{
								int c;
								while ((c = in_Renamed.ReadByte()) != - 1)
								{
									fileOut.WriteByte((System.Byte) c);
								}
							}
							finally
							{
								fileOut.Close();
							}
						}
						finally
						{
							in_Renamed.Close();
						}
					}
					
					if (isSwf(url))
					{
						dumpSwf(out_Renamed, url, outfile);
					}
					else if (isZip(url) && !url.ToString().EndsWith(".abj"))
					{
						dumpZip(out_Renamed, url, outfile);
					}
					else
					{
						//UPGRADE_TODO: Method 'java.io.PrintWriter.println' was converted to 'System.IO.TextWriter.WriteLine' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioPrintWriterprintln_javalangString'"
						out_Renamed.WriteLine("<!-- Parsing actions from " + url + " -->");
						// we have no way of knowing the swf version, so assume latest
						System.Net.HttpWebRequest connection = (System.Net.HttpWebRequest) System.Net.WebRequest.Create(url);
						ActionDecoder actionDecoder = new ActionDecoder(new SwfDecoder(connection.GetResponse().GetResponseStream(), 7));
						actionDecoder.KeepOffsets = true;
						int ContentLength;
						try
						{
							ContentLength = System.Int32.Parse(connection.GetResponse().Headers.Get("Content-Length"));
						}
						catch (System.IO.IOException e)
						{
							ContentLength = -1;
						}
						ActionList actions = actionDecoder.decode(ContentLength);
						SwfxPrinter printer = new SwfxPrinter(out_Renamed);
						printer.decompile = decompileOption;
						printer.defunc = defuncOption;
						printer.printActions(actions);
					}
					out_Renamed.Flush();
				}
				catch (System.ApplicationException e)
				{
					if (Trace.error)
						SupportClass.WriteStackTrace(e, Console.Error);
					
					System.Console.Error.WriteLine("");
					System.Console.Error.WriteLine("An unrecoverable error occurred.  The given file " + urls[i] + " may not be");
					System.Console.Error.WriteLine("a valid swf.");
				}
				catch (System.IO.FileNotFoundException e)
				{
					//UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Throwable.getMessage' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'"
					System.Console.Error.WriteLine("Error: " + e.Message);
					System.Environment.Exit(1);
				}
			}
		}
Exemple #38
0
        /// <summary>
        /// 进入消息等待
        /// </summary>
        public void Process()
        {
            //用户发送队列
            m_userQueue = new RingQueue <byte>(1024);
            //vt220待解析数据
            m_telnetDataQueue = new RingQueue <byte>(8192);
            //消息处理
            new System.Threading.Thread(new System.Threading.ThreadStart(delegate()
            {
                //接收缓存队列
                var recvQueue = new RingQueue <byte>(8192);

                //发送缓存队列
                var sendQueue = new RingQueue <byte>(1024);

                var io         = m_conn.GetStream();
                var sendStream = new System.IO.BufferedStream(io);
                var recvStream = new System.IO.BufferedStream(io);

                while (m_conn != null && m_conn.Connected)
                {
                    //接收服务端数据
                    while (io.DataAvailable && recvQueue.Available > 0)
                    {
                        var b = io.ReadByte();
                        if (b == -1)
                        {
                            break;
                        }
                        recvQueue.Push((byte)b);
                    }
                    //解析Telnet协议 并 响应服务器
                    ParseTelnetCommand(recvQueue, sendQueue, m_telnetDataQueue);

                    //解析VT220协议
                    ParseVT220Command(m_telnetDataQueue);

                    //客户端发送数据
                    while (sendQueue.Count > 0 && m_conn.Connected)
                    {
                        var data = sendQueue.ToArray();
                        sendStream.Write(data, 0, data.Length);
                        sendStream.Flush();
                        sendQueue.Clear();
                    }

                    //发送用户数据
                    while (m_userQueue.Count > 0 && m_conn.Connected)
                    {
                        var data = m_userQueue.ToArray();
                        sendStream.Write(data, 0, data.Length);
                        sendStream.Flush();
                        m_userQueue.Clear();
                    }

                    //休眠100ms(文件输出时20ms)
                    System.Threading.Thread.Sleep(IsPrinting?10:100);

                    //检测终止标志(不确定)
                    if (m_conn != null && m_conn.Client.Poll(1, SelectMode.SelectRead) && m_conn.Client.Available == 0)
                    {
                        this.Disconnect();
                        Logger.Info("Telnet 连接关闭(收到服务端指令)");
                    }
                }
            })).Start();

            //绑定控件
            //绑定用户输入事件
            Screen.KeyPress += new System.Windows.Forms.KeyPressEventHandler(delegate(object sender, System.Windows.Forms.KeyPressEventArgs e)
            {
                m_userQueue.Push(Convert.ToByte(e.KeyChar));
            });

            Screen.KeyDown += new System.Windows.Forms.KeyEventHandler(delegate(object sender, System.Windows.Forms.KeyEventArgs e)
            {
                SendKey(e.KeyCode);
                //Console.WriteLine(e.KeyCode);
            });
            //绑定用户输入事件
        }
 /**
  * Reads in the binary file specified.
  *
  * <p>If there are any problems reading in the file, it gets classified as unidentified,
  * with an explanatory warning message.
  */
 private void readFile() {
     
     //If file is not readable or is empty, then it gets classified
     //as unidentified (with an explanatory warning)
     
     if( !file.Exists )
     {
         this.SetErrorIdentification();
         this.SetIdentificationWarning("File does not exist");
         return;
     }
     
     //TODO: figure out how to port this
     /*
     if( !file.canRead() )
     {
         this.SetErrorIdentification();
         this.SetIdentificationWarning("File cannot be read");
         return;
     }
     */
     
     if (System.IO.Directory.Exists(file.FullName))
     {
         this.SetErrorIdentification();
         this.SetIdentificationWarning("This is a directory, not a file");
         return;
     }
     
     //FileInputStream binStream;
     System.IO.FileStream binStream;
     
     try
     {
         binStream = new System.IO.FileStream(file.FullName, System.IO.FileMode.Open); //FileInputStream(file);
     }
     catch (System.IO.FileNotFoundException)
     {
         this.SetErrorIdentification();
         this.SetIdentificationWarning("File disappeared or cannot be read");
         return;
     }
     
     try {
         
         int numBytes = 100; //binStream.available();
         
         if (numBytes > 0)
         {
             //BufferedInputStream buffStream = new BufferedInputStream(binStream);
             System.IO.BufferedStream buffStream = new System.IO.BufferedStream(binStream);
             
             fileBytes = new byte[numBytes];
             int len = buffStream.Read(fileBytes, 0, numBytes);
             
             if(len != numBytes) {
                 //This means that all bytes were not successfully read
                 this.SetErrorIdentification();
                 this.SetIdentificationWarning("Error reading file: "+ len.ToString() + " bytes read from file when " + numBytes.ToString() + " were expected");
             }
             else if(len != -1)
             {
                 //This means that the end of the file was not reached
                 this.SetErrorIdentification();
                 this.SetIdentificationWarning("Error reading file: Unable to read to the end");
             }
             else
             {
                 myNumBytes = (long) numBytes;
             }
             
             buffStream.Close();
         } else {
             //If file is empty , status is error
             this.SetErrorIdentification();
             myNumBytes = 0L;
             this.SetIdentificationWarning("Zero-length file");
             
         }
         binStream.Close();
         
         isRandomAccess = false;
     } catch(System.IO.IOException e) {
         this.SetErrorIdentification();
         this.SetIdentificationWarning("Error reading file: " + e.ToString());
     }
     catch(System.OutOfMemoryException)
     {
         try {
             myRandomAccessFile = new System.IO.FileStream(file.FullName, System.IO.FileMode.Open); //RandomAccessFile(file,"r");
             isRandomAccess = true;
             
             //record the file size
             myNumBytes = myRandomAccessFile.Length;
             //try reading in a buffer
             myRandomAccessFile.Seek(0, System.IO.SeekOrigin.Begin); //(0L);
             bool tryAgain = true;
             while(tryAgain) {
                 try
                 {
                     fileBytes = new byte[(int)randomFileBufferSize];
                     myRandomAccessFile.Read(fileBytes, 0, randomFileBufferSize);
                     // .read(fileBytes);
                     tryAgain = false;
                 }
                 catch(OutOfMemoryException e4)
                 {
                     randomFileBufferSize = randomFileBufferSize/RAF_BUFFER_REDUCTION_FACTOR;
                     if(randomFileBufferSize< MIN_RAF_BUFFER_SIZE) {
                         throw e4;
                     }
                     
                 }
             }
             
             myRAFoffset = 0L;
         }
         catch (System.IO.FileNotFoundException)
         {
             this.SetErrorIdentification();
             this.SetIdentificationWarning("File disappeared or cannot be read");
         }
         catch(Exception e2)
         {
             try
             {
                 myRandomAccessFile.Close();
             }
             catch(System.IO.IOException)
             {
             }
             
             this.SetErrorIdentification();
             this.SetIdentificationWarning("Error reading file: " + e2.ToString());
         }
         
     }
 }    
Exemple #40
0
        //UPGRADE_NOTE: Synchronized keyword was removed from method 'convert'. Lock expression was added. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1027"'
        public virtual void  convert(System.IO.Stream sourceStream, System.String destName, ProgressListener progressListener, Decoder.Params decoderParams)
        {
            lock (this)
            {
                if (progressListener == null)
                {
                    progressListener = PrintWriterProgressListener.newStdOut(PrintWriterProgressListener.NO_DETAIL);
                }
                try
                {
                    if (!(sourceStream is System.IO.BufferedStream))
                    {
                        sourceStream = new System.IO.BufferedStream(sourceStream);
                    }
                    int frameCount = -1;
                    //UPGRADE_ISSUE: Method 'java.io.InputStream.markSupported' was not converted. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1000_javaioInputStreammarkSupported"'
                    if (sourceStream.markSupported())
                    {
                        //UPGRADE_ISSUE: Method 'java.io.InputStream.mark' was not converted. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1000_javaioInputStreammark_int"'
                        sourceStream.mark(-1);
                        frameCount = countFrames(sourceStream);
                        //UPGRADE_ISSUE: Method 'java.io.InputStream.reset' was not converted. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1000_javaioInputStreamreset"'
                        sourceStream.reset();
                    }
                    progressListener.converterUpdate(javazoom.jl.converter.Converter.ProgressListener_Fields.UPDATE_FRAME_COUNT, frameCount, 0);


                    Obuffer   output  = null;
                    Decoder   decoder = new Decoder(decoderParams);
                    Bitstream stream  = new Bitstream(sourceStream);

                    if (frameCount == -1)
                    {
                        frameCount = System.Int32.MaxValue;
                    }

                    int  frame     = 0;
                    long startTime = (System.DateTime.Now.Ticks - 621355968000000000) / 10000;

                    try
                    {
                        for (; frame < frameCount; frame++)
                        {
                            try
                            {
                                Header header = stream.readFrame();
                                if (header == null)
                                {
                                    break;
                                }

                                progressListener.readFrame(frame, header);

                                if (output == null)
                                {
                                    // REVIEW: Incorrect functionality.
                                    // the decoder should provide decoded
                                    // frequency and channels output as it may differ from
                                    // the source (e.g. when downmixing stereo to mono.)
                                    int channels = (header.mode() == Header.SINGLE_CHANNEL)?1:2;
                                    int freq     = header.frequency();
                                    output = new WaveFileObuffer(channels, freq, destName);
                                    decoder.OutputBuffer = output;
                                }

                                Obuffer decoderOutput = decoder.decodeFrame(header, stream);

                                // REVIEW: the way the output buffer is set
                                // on the decoder is a bit dodgy. Even though
                                // this exception should never happen, we test to be sure.
                                if (decoderOutput != output)
                                {
                                    throw new System.ApplicationException("Output buffers are different.");
                                }


                                progressListener.decodedFrame(frame, header, output);

                                stream.closeFrame();
                            }
                            catch (System.Exception ex)
                            {
                                bool stop = !progressListener.converterException(ex);

                                if (stop)
                                {
                                    throw new JavaLayerException(ex.Message, ex);
                                }
                            }
                        }
                    }
                    finally
                    {
                        if (output != null)
                        {
                            output.close();
                        }
                    }

                    int time = (int)((System.DateTime.Now.Ticks - 621355968000000000) / 10000 - startTime);
                    progressListener.converterUpdate(javazoom.jl.converter.Converter.ProgressListener_Fields.UPDATE_CONVERT_COMPLETE, time, frame);
                }
                catch (System.IO.IOException ex)
                {
                    throw new JavaLayerException(ex.Message, ex);
                }
            }
        }
Exemple #41
0
        //UPGRADE_NOTE: Synchronized keyword was removed from method 'convert'. Lock expression was added. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1027"'
        public virtual void convert(System.IO.Stream sourceStream, System.String destName, ProgressListener progressListener, Decoder.Params decoderParams)
        {
            lock (this)
            {
                if (progressListener == null)
                    progressListener = PrintWriterProgressListener.newStdOut(PrintWriterProgressListener.NO_DETAIL);
                try
                {
                    if (!(sourceStream is System.IO.BufferedStream))
                        sourceStream = new System.IO.BufferedStream(sourceStream);
                    int frameCount = - 1;
                    //UPGRADE_ISSUE: Method 'java.io.InputStream.markSupported' was not converted. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1000_javaioInputStreammarkSupported"'
                    if (sourceStream.markSupported())
                    {
                        //UPGRADE_ISSUE: Method 'java.io.InputStream.mark' was not converted. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1000_javaioInputStreammark_int"'
                        sourceStream.mark(- 1);
                        frameCount = countFrames(sourceStream);
                        //UPGRADE_ISSUE: Method 'java.io.InputStream.reset' was not converted. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1000_javaioInputStreamreset"'
                        sourceStream.reset();
                    }
                    progressListener.converterUpdate(javazoom.jl.converter.Converter.ProgressListener_Fields.UPDATE_FRAME_COUNT, frameCount, 0);

                    Obuffer output = null;
                    Decoder decoder = new Decoder(decoderParams);
                    Bitstream stream = new Bitstream(sourceStream);

                    if (frameCount == - 1)
                        frameCount = System.Int32.MaxValue;

                    int frame = 0;
                    long startTime = (System.DateTime.Now.Ticks - 621355968000000000) / 10000;

                    try
                    {
                        for (; frame < frameCount; frame++)
                        {
                            try
                            {
                                Header header = stream.readFrame();
                                if (header == null)
                                    break;

                                progressListener.readFrame(frame, header);

                                if (output == null)
                                {
                                    // REVIEW: Incorrect functionality.
                                    // the decoder should provide decoded
                                    // frequency and channels output as it may differ from
                                    // the source (e.g. when downmixing stereo to mono.)
                                    int channels = (header.mode() == Header.SINGLE_CHANNEL)?1:2;
                                    int freq = header.frequency();
                                    output = new WaveFileObuffer(channels, freq, destName);
                                    decoder.OutputBuffer = output;
                                }

                                Obuffer decoderOutput = decoder.decodeFrame(header, stream);

                                // REVIEW: the way the output buffer is set
                                // on the decoder is a bit dodgy. Even though
                                // this exception should never happen, we test to be sure.
                                if (decoderOutput != output)
                                    throw new System.ApplicationException("Output buffers are different.");

                                progressListener.decodedFrame(frame, header, output);

                                stream.closeFrame();
                            }
                            catch (System.Exception ex)
                            {
                                bool stop = !progressListener.converterException(ex);

                                if (stop)
                                {
                                    throw new JavaLayerException(ex.Message, ex);
                                }
                            }
                        }
                    }
                    finally
                    {

                        if (output != null)
                            output.close();
                    }

                    int time = (int) ((System.DateTime.Now.Ticks - 621355968000000000) / 10000 - startTime);
                    progressListener.converterUpdate(javazoom.jl.converter.Converter.ProgressListener_Fields.UPDATE_CONVERT_COMPLETE, time, frame);
                }
                catch (System.IO.IOException ex)
                {
                    throw new JavaLayerException(ex.Message, ex);
                }
            }
        }
        /**
         * Reads in the binary file specified.
         *
         * <p>If there are any problems reading in the file, it gets classified as unidentified,
         * with an explanatory warning message.
         */
        private void readFile()
        {
            //If file is not readable or is empty, then it gets classified
            //as unidentified (with an explanatory warning)

            if (!file.Exists)
            {
                this.SetErrorIdentification();
                this.SetIdentificationWarning("File does not exist");
                return;
            }

            //TODO: figure out how to port this

            /*
             * if( !file.canRead() )
             * {
             *  this.SetErrorIdentification();
             *  this.SetIdentificationWarning("File cannot be read");
             *  return;
             * }
             */

            if (System.IO.Directory.Exists(file.FullName))
            {
                this.SetErrorIdentification();
                this.SetIdentificationWarning("This is a directory, not a file");
                return;
            }

            //FileInputStream binStream;
            System.IO.FileStream binStream;

            try
            {
                binStream = new System.IO.FileStream(file.FullName, System.IO.FileMode.Open); //FileInputStream(file);
            }
            catch (System.IO.FileNotFoundException)
            {
                this.SetErrorIdentification();
                this.SetIdentificationWarning("File disappeared or cannot be read");
                return;
            }

            try {
                int numBytes = 100; //binStream.available();

                if (numBytes > 0)
                {
                    //BufferedInputStream buffStream = new BufferedInputStream(binStream);
                    System.IO.BufferedStream buffStream = new System.IO.BufferedStream(binStream);

                    fileBytes = new byte[numBytes];
                    int len = buffStream.Read(fileBytes, 0, numBytes);

                    if (len != numBytes)
                    {
                        //This means that all bytes were not successfully read
                        this.SetErrorIdentification();
                        this.SetIdentificationWarning("Error reading file: " + len.ToString() + " bytes read from file when " + numBytes.ToString() + " were expected");
                    }
                    else if (len != -1)
                    {
                        //This means that the end of the file was not reached
                        this.SetErrorIdentification();
                        this.SetIdentificationWarning("Error reading file: Unable to read to the end");
                    }
                    else
                    {
                        myNumBytes = (long)numBytes;
                    }

                    buffStream.Close();
                }
                else
                {
                    //If file is empty , status is error
                    this.SetErrorIdentification();
                    myNumBytes = 0L;
                    this.SetIdentificationWarning("Zero-length file");
                }
                binStream.Close();

                isRandomAccess = false;
            } catch (System.IO.IOException e) {
                this.SetErrorIdentification();
                this.SetIdentificationWarning("Error reading file: " + e.ToString());
            }
            catch (System.OutOfMemoryException)
            {
                try {
                    myRandomAccessFile = new System.IO.FileStream(file.FullName, System.IO.FileMode.Open); //RandomAccessFile(file,"r");
                    isRandomAccess     = true;

                    //record the file size
                    myNumBytes = myRandomAccessFile.Length;
                    //try reading in a buffer
                    myRandomAccessFile.Seek(0, System.IO.SeekOrigin.Begin); //(0L);
                    bool tryAgain = true;
                    while (tryAgain)
                    {
                        try
                        {
                            fileBytes = new byte[(int)randomFileBufferSize];
                            myRandomAccessFile.Read(fileBytes, 0, randomFileBufferSize);
                            // .read(fileBytes);
                            tryAgain = false;
                        }
                        catch (OutOfMemoryException e4)
                        {
                            randomFileBufferSize = randomFileBufferSize / RAF_BUFFER_REDUCTION_FACTOR;
                            if (randomFileBufferSize < MIN_RAF_BUFFER_SIZE)
                            {
                                throw e4;
                            }
                        }
                    }

                    myRAFoffset = 0L;
                }
                catch (System.IO.FileNotFoundException)
                {
                    this.SetErrorIdentification();
                    this.SetIdentificationWarning("File disappeared or cannot be read");
                }
                catch (Exception e2)
                {
                    try
                    {
                        myRandomAccessFile.Close();
                    }
                    catch (System.IO.IOException)
                    {
                    }

                    this.SetErrorIdentification();
                    this.SetIdentificationWarning("Error reading file: " + e2.ToString());
                }
            }
        }
		private static void  dumpZip(System.IO.StreamWriter out_Renamed, System.Uri url, System.String outfile)
		{
			System.IO.Stream in_Renamed = new System.IO.BufferedStream(System.Net.WebRequest.Create(url).GetResponse().GetResponseStream());
			try
			{
				//UPGRADE_ISSUE: Class 'java.util.zip.ZipInputStream' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javautilzipZipInputStream'"
				//UPGRADE_ISSUE: Constructor 'java.util.zip.ZipInputStream.ZipInputStream' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javautilzipZipInputStream'"
				ZipInputStream zipIn = new ZipInputStream(in_Renamed);
				//UPGRADE_ISSUE: Class 'java.util.zip.ZipEntry' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javautilzipZipEntry'"
				//UPGRADE_ISSUE: Method 'java.util.zip.ZipInputStream.getNextEntry' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javautilzipZipInputStream'"
				ZipEntry zipEntry = zipIn.getNextEntry();
				while ((zipEntry != null))
				{
					//UPGRADE_TODO: Class 'java.net.URL' was converted to a 'System.Uri' which does not throw an exception if a URL specifies an unknown protocol. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1132'"
					//UPGRADE_ISSUE: Method 'java.util.zip.ZipEntry.getName' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javautilzipZipEntry'"
					System.Uri fileUrl = new System.Uri("jar:" + url.ToString() + "!/" + zipEntry.getName());
					if (isSwf(fileUrl))
						dumpSwf(out_Renamed, fileUrl, outfile);
					//UPGRADE_ISSUE: Method 'java.util.zip.ZipInputStream.getNextEntry' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javautilzipZipInputStream'"
					zipEntry = zipIn.getNextEntry();
				}
			}
			finally
			{
				in_Renamed.Close();
			}
		}
		public virtual bool parse(System.String path)
		{
			// parser property names
			//UPGRADE_NOTE: Final was removed from the declaration of 'JAXP_SCHEMA_LANGUAGE '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
			System.String JAXP_SCHEMA_LANGUAGE = "http://java.sun.com/xml/jaxp/properties/schemaLanguage";
			//UPGRADE_NOTE: Final was removed from the declaration of 'JAXP_SCHEMA_SOURCE '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
			System.String JAXP_SCHEMA_SOURCE = "http://java.sun.com/xml/jaxp/properties/schemaSource";
			
			//UPGRADE_NOTE: Final was removed from the declaration of 'W3C_XML_SCHEMA '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
			System.String W3C_XML_SCHEMA = "http://www.w3.org/2001/XMLSchema";
			
			this.docPath = path;
			//this.outputHandler = handler;
			
			//UPGRADE_TODO: Constructor 'java.io.FileInputStream.FileInputStream' was converted to 'System.IO.FileStream.FileStream' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioFileInputStreamFileInputStream_javalangString'"
			System.IO.Stream in_Renamed = new System.IO.BufferedStream(new System.IO.FileStream(path, System.IO.FileMode.Open, System.IO.FileAccess.Read));
			XmlSAXDocumentManager parser;
			try
			{
				XmlSAXDocumentManager factory = XmlSAXDocumentManager.NewInstance();
				factory.IsValidating = true;
				factory.NamespaceAllowed = true;
				try
				{
					parser = XmlSAXDocumentManager.CloneInstance(factory);
					//UPGRADE_TODO: Method 'javax.xml.parsers.SAXParser.setProperty' was converted to 'XmlSAXDocumentManager.setProperty' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaxxmlparsersSAXParsersetProperty_javalangString_javalangObject'"
					parser.setProperty(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
					//UPGRADE_TODO: Method 'javax.xml.parsers.SAXParser.setProperty' was converted to 'XmlSAXDocumentManager.setProperty' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaxxmlparsersSAXParsersetProperty_javalangString_javalangObject'"
					GetType();
					//UPGRADE_TODO: Method 'java.lang.Class.getResource' was converted to 'System.Uri' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javalangClassgetResource_javalangString'"
					parser.setProperty(JAXP_SCHEMA_SOURCE, new XmlSourceSupport(new System.Uri(System.IO.Path.GetFullPath("swfx.xsd")).ToString()));
				}
				catch (System.Exception e)
				{
					if (e is ManagerNotRecognizedException)
					{
						// schema validation not supported... ignore
						factory.IsValidating = false;
						factory.NamespaceAllowed = true;
						parser = XmlSAXDocumentManager.CloneInstance(factory);
					}
					else if (e is System.IO.IOException)
					{
						throw (System.IO.IOException) e;
					}
					else
					{
						//UPGRADE_TODO: Class 'org.xml.sax.SAXException' was converted to 'System.Xml.XmlException' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073'"
						if (e is System.Xml.XmlException)
						{
							//UPGRADE_TODO: Class 'org.xml.sax.SAXException' was converted to 'System.Xml.XmlException' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073'"
							throw (System.Xml.XmlException) e;
						}
						else
						{
							SupportClass.WriteStackTrace(e, Console.Error);
							parser = null;
						}
					}
				}
				parser.parse(in_Renamed, this);
				return true;
			}
			//UPGRADE_TODO: Class 'org.xml.sax.SAXException' was converted to 'System.Xml.XmlException' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073'"
			catch (System.Xml.XmlException e)
			{
				// errors will have been reported already
				//e.printStackTrace();
				return false;
			}
			catch (System.Exception e)
			{
				//UPGRADE_ISSUE: Class 'javax.xml.parsers.ParserConfigurationException' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javaxxmlparsersParserConfigurationException'"
				if (e is ParserConfigurationException)
				{
					if (Trace.error)
						SupportClass.WriteStackTrace(e, Console.Error);
					
					return false;
				}
				else if (e is System.IO.IOException)
				{
					throw (System.IO.IOException) e;
				}
				else
				{
					SupportClass.WriteStackTrace(e, Console.Error);
					return true;
				}
			}
			finally
			{
				in_Renamed.Close();
			}
		}
Exemple #45
0
        protected internal virtual System.IO.Stream openInput(System.String fileName)
        {
            // ensure name is abstract path name
            System.IO.FileInfo file = new System.IO.FileInfo(fileName);
            System.IO.Stream fileIn = new System.IO.FileStream(file.FullName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
            System.IO.BufferedStream bufIn = new System.IO.BufferedStream(fileIn);

            return bufIn;
        }
		public static void  Main(System.String[] args)
		{
			System.String aspath = null;
			for (int i = 0; i < args.Length; i++)
			{
				if (args[i].Equals("-aspath"))
				{
					aspath = args[++i];
					continue;
				}
				TagEncoder encoder = new TagEncoder();
				//ConsoleOutputHandler tagHandler = new ConsoleOutputHandler(null, null);
				SwfxParser swfxParser = new SwfxParser(encoder, StringUtils.splitPath(aspath));
				bool success = swfxParser.parse(args[i]); //, tagHandler);
				if (success)
				{
					System.String swfFileName = args[i].Substring(0, (args[i].LastIndexOf('.')) - (0)) + ".swf";
					//UPGRADE_TODO: Constructor 'java.io.FileOutputStream.FileOutputStream' was converted to 'System.IO.FileStream.FileStream' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaioFileOutputStreamFileOutputStream_javalangString'"
					System.IO.Stream out_Renamed = new System.IO.BufferedStream(new System.IO.FileStream(swfFileName, System.IO.FileMode.Create));
					try
					{
						encoder.writeTo(out_Renamed);
					}
					finally
					{
						out_Renamed.Close();
					}
				}
				else
				{
					System.Environment.Exit(1);
				}
			}
		}
Exemple #47
0
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (this.Request.HttpMethod != "POST")
                {
                    this.Response.Write("Request method must be POST");
                    return;
                }

                System.IO.BufferedStream bufStream = new System.IO.BufferedStream(this.Request.InputStream);
                System.IO.StreamReader read = new System.IO.StreamReader(bufStream);

                string postData = read.ReadToEnd();
                System.Xml.XmlDocument xmldoc = new System.Xml.XmlDocument();
                xmldoc.LoadXml(postData);

                NumberFormatInfo numFormat = new NumberFormatInfo();
                numFormat.NumberDecimalSeparator = ".";
                using (SmartCityEntities ctx = new SmartCityEntities())
                {
                    Sample newSample = new Sample();
                    newSample.device_id = Convert.ToInt32(xmldoc["Measurements"]["Measurement"]["deviceId"].InnerText.ToString());
                    newSample.sample_time = DateTime.Now;
                    if (xmldoc["Measurements"]["Measurement"].GetElementsByTagName("latitude").Count > 0)
                    {
                        newSample.lat = Convert.ToDecimal(xmldoc["Measurements"]["Measurement"]["latitude"].InnerText.Replace(',', '.'), numFormat);
                    }
                    if (xmldoc["Measurements"]["Measurement"].GetElementsByTagName("longitude").Count > 0)
                    {
                        newSample.lon = Convert.ToDecimal(xmldoc["Measurements"]["Measurement"]["longitude"].InnerText.Replace(',', '.'), numFormat);
                    }
                    if (xmldoc["Measurements"]["Measurement"].GetElementsByTagName("temperature").Count > 0)
                    {
                        newSample.temperature = Convert.ToDouble(xmldoc["Measurements"]["Measurement"]["temperature"].InnerText.ToString().Replace(',', '.'), numFormat);
                    }
                    if (xmldoc["Measurements"]["Measurement"].GetElementsByTagName("humidity").Count > 0)
                    {
                        newSample.humidity = Convert.ToDouble(xmldoc["Measurements"]["Measurement"]["humidity"].InnerText.ToString().Replace(',', '.'), numFormat);
                    }
                    if (xmldoc["Measurements"]["Measurement"].GetElementsByTagName("pressure").Count > 0)
                    {
                        newSample.pressure = Convert.ToDouble(xmldoc["Measurements"]["Measurement"]["pressure"].InnerText.ToString().Replace(',', '.'), numFormat);
                    }
                    if (xmldoc["Measurements"]["Measurement"].GetElementsByTagName("sound").Count > 0)
                    {
                        newSample.sound = Convert.ToDouble(xmldoc["Measurements"]["Measurement"]["sound"].InnerText.ToString().Replace(',', '.'), numFormat);
                    }
                    if (xmldoc["Measurements"]["Measurement"].GetElementsByTagName("winddirection").Count > 0)
                    {
                        newSample.winddirection = Convert.ToDouble(xmldoc["Measurements"]["Measurement"]["winddirection"].InnerText.ToString().Replace(',', '.'), numFormat);
                    }
                    if (xmldoc["Measurements"]["Measurement"].GetElementsByTagName("uv").Count > 0)
                    {
                        newSample.uv = Convert.ToDouble(xmldoc["Measurements"]["Measurement"]["uv"].InnerText.ToString().Replace(',', '.'), numFormat);
                    }
                    if (xmldoc["Measurements"]["Measurement"].GetElementsByTagName("xacceleration").Count > 0)
                    {
                        newSample.xacceleration = Convert.ToDouble(xmldoc["Measurements"]["Measurement"]["xacceleration"].InnerText.ToString().Replace(',', '.'), numFormat);
                    }
                    if (xmldoc["Measurements"]["Measurement"].GetElementsByTagName("yacceleration").Count > 0)
                    {
                        newSample.yacceleration = Convert.ToDouble(xmldoc["Measurements"]["Measurement"]["yacceleration"].InnerText.ToString().Replace(',', '.'), numFormat);
                    }
                    if (xmldoc["Measurements"]["Measurement"].GetElementsByTagName("zacceleration").Count > 0)
                    {
                        newSample.zacceleration = Convert.ToDouble(xmldoc["Measurements"]["Measurement"]["zacceleration"].InnerText.ToString().Replace(',', '.'), numFormat);
                    }
                    if (xmldoc["Measurements"]["Measurement"].GetElementsByTagName("xrotation").Count > 0)
                    {
                        newSample.xrotation = Convert.ToDouble(xmldoc["Measurements"]["Measurement"]["xrotation"].InnerText.ToString().Replace(',', '.'), numFormat);
                    }
                    if (xmldoc["Measurements"]["Measurement"].GetElementsByTagName("yrotation").Count > 0)
                    {
                        newSample.yrotation = Convert.ToDouble(xmldoc["Measurements"]["Measurement"]["yrotation"].InnerText.ToString().Replace(',', '.'), numFormat);
                    }
                    if (xmldoc["Measurements"]["Measurement"].GetElementsByTagName("zrotation").Count > 0)
                    {
                        newSample.zrotation = Convert.ToDouble(xmldoc["Measurements"]["Measurement"]["zrotation"].InnerText.ToString().Replace(',', '.'), numFormat);
                    }
                    if (xmldoc["Measurements"]["Measurement"].GetElementsByTagName("xmagneticforce").Count > 0)
                    {
                        newSample.xmagneticforce = Convert.ToDouble(xmldoc["Measurements"]["Measurement"]["xmagneticforce"].InnerText.ToString().Replace(',', '.'), numFormat);
                    }
                    if (xmldoc["Measurements"]["Measurement"].GetElementsByTagName("ymagneticforce").Count > 0)
                    {
                        newSample.ymagneticforce = Convert.ToDouble(xmldoc["Measurements"]["Measurement"]["ymagneticforce"].InnerText.ToString().Replace(',', '.'), numFormat);
                    }
                    if (xmldoc["Measurements"]["Measurement"].GetElementsByTagName("zmagneticforce").Count > 0)
                    {
                        newSample.zmagneticforce = Convert.ToDouble(xmldoc["Measurements"]["Measurement"]["zmagneticforce"].InnerText.ToString().Replace(',', '.'), numFormat);
                    }
                    if (xmldoc["Measurements"]["Measurement"].GetElementsByTagName("accelerationmagnitude").Count > 0)
                    {
                        newSample.accelerationmagnitude = Convert.ToDouble(xmldoc["Measurements"]["Measurement"]["accelerationmagnitude"].InnerText.ToString().Replace(',', '.'), numFormat);
                    }
                    if (xmldoc["Measurements"]["Measurement"].GetElementsByTagName("battery").Count > 0)
                    {
                        newSample.battery = Convert.ToDouble(xmldoc["Measurements"]["Measurement"]["battery"].InnerText.ToString().Replace(',', '.'), numFormat);
                    }
                    if (xmldoc["Measurements"]["Measurement"].GetElementsByTagName("wind").Count > 0)
                    {
                        newSample.wind = Convert.ToDouble(xmldoc["Measurements"]["Measurement"]["wind"].InnerText.ToString().Replace(',', '.'), numFormat);
                    }
                    ctx.Sample.Add(newSample);
                    ctx.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                this.Response.Write(ex.ToString());
                return;
            }
        }
        /// <summary>
        /// Salva todos os relatórios em um único PDF.
        /// </summary>
        /// <param name="p_filename">Nome do arquivo PDF a ser salvo.</param>
        public void SaveMerged(string p_filename)
        {
            PDFjet.NET.PDF v_pdf;
            System.IO.BufferedStream v_buffer;
            System.IO.FileStream f;
            Spartacus.Reporting.Report v_report;
            double v_perc, v_percstep, v_lastperc;

            try
            {
                f = new System.IO.FileStream(p_filename, System.IO.FileMode.Create);
                v_buffer = new System.IO.BufferedStream(f);

                v_pdf = new PDFjet.NET.PDF(v_buffer);

                v_perc = 0.0;
                v_percstep = 100.0 / (double) this.v_reports.Count;
                v_lastperc = v_percstep;

                for (int k = 0; k < this.v_reports.Count; k++)
                {
                    v_report = (Spartacus.Reporting.Report) this.v_reports[k];

                    v_report.v_perc = v_perc;
                    v_report.v_percstep = v_percstep;
                    v_report.v_lastperc = v_lastperc;

                    v_report.SavePartial(v_pdf);

                    v_perc = v_lastperc;
                    v_lastperc += v_percstep;
                }

                v_pdf.Flush();
                v_buffer.Close();
            }
            catch (Spartacus.Reporting.Exception e)
            {
                throw e;
            }
            catch (System.Exception e)
            {
                throw new Spartacus.Reporting.Exception("Erro ao gerar o pacote PDF de saída.", e);
            }
        }
Exemple #49
0
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (this.Request.HttpMethod != "POST")
                {
                    this.Response.Write("Request method must be POST");
                    return;
                }

                System.IO.BufferedStream bufStream = new System.IO.BufferedStream(this.Request.InputStream);
                System.IO.StreamReader   read      = new System.IO.StreamReader(bufStream);

                string postData = read.ReadToEnd();
                System.Xml.XmlDocument xmldoc = new System.Xml.XmlDocument();
                xmldoc.LoadXml(postData);

                NumberFormatInfo numFormat = new NumberFormatInfo();
                numFormat.NumberDecimalSeparator = ".";
                using (SmartCityEntities ctx = new SmartCityEntities())
                {
                    Sample newSample = new Sample();
                    newSample.device_id   = Convert.ToInt32(xmldoc["Measurements"]["Measurement"]["deviceId"].InnerText.ToString());
                    newSample.sample_time = DateTime.Now;
                    if (xmldoc["Measurements"]["Measurement"].GetElementsByTagName("latitude").Count > 0)
                    {
                        newSample.lat = Convert.ToDecimal(xmldoc["Measurements"]["Measurement"]["latitude"].InnerText.Replace(',', '.'), numFormat);
                    }
                    if (xmldoc["Measurements"]["Measurement"].GetElementsByTagName("longitude").Count > 0)
                    {
                        newSample.lon = Convert.ToDecimal(xmldoc["Measurements"]["Measurement"]["longitude"].InnerText.Replace(',', '.'), numFormat);
                    }
                    if (xmldoc["Measurements"]["Measurement"].GetElementsByTagName("temperature").Count > 0)
                    {
                        newSample.temperature = Convert.ToDouble(xmldoc["Measurements"]["Measurement"]["temperature"].InnerText.ToString().Replace(',', '.'), numFormat);
                    }
                    if (xmldoc["Measurements"]["Measurement"].GetElementsByTagName("humidity").Count > 0)
                    {
                        newSample.humidity = Convert.ToDouble(xmldoc["Measurements"]["Measurement"]["humidity"].InnerText.ToString().Replace(',', '.'), numFormat);
                    }
                    if (xmldoc["Measurements"]["Measurement"].GetElementsByTagName("pressure").Count > 0)
                    {
                        newSample.pressure = Convert.ToDouble(xmldoc["Measurements"]["Measurement"]["pressure"].InnerText.ToString().Replace(',', '.'), numFormat);
                    }
                    if (xmldoc["Measurements"]["Measurement"].GetElementsByTagName("sound").Count > 0)
                    {
                        newSample.sound = Convert.ToDouble(xmldoc["Measurements"]["Measurement"]["sound"].InnerText.ToString().Replace(',', '.'), numFormat);
                    }
                    if (xmldoc["Measurements"]["Measurement"].GetElementsByTagName("winddirection").Count > 0)
                    {
                        newSample.winddirection = Convert.ToDouble(xmldoc["Measurements"]["Measurement"]["winddirection"].InnerText.ToString().Replace(',', '.'), numFormat);
                    }
                    if (xmldoc["Measurements"]["Measurement"].GetElementsByTagName("uv").Count > 0)
                    {
                        newSample.uv = Convert.ToDouble(xmldoc["Measurements"]["Measurement"]["uv"].InnerText.ToString().Replace(',', '.'), numFormat);
                    }
                    if (xmldoc["Measurements"]["Measurement"].GetElementsByTagName("xacceleration").Count > 0)
                    {
                        newSample.xacceleration = Convert.ToDouble(xmldoc["Measurements"]["Measurement"]["xacceleration"].InnerText.ToString().Replace(',', '.'), numFormat);
                    }
                    if (xmldoc["Measurements"]["Measurement"].GetElementsByTagName("yacceleration").Count > 0)
                    {
                        newSample.yacceleration = Convert.ToDouble(xmldoc["Measurements"]["Measurement"]["yacceleration"].InnerText.ToString().Replace(',', '.'), numFormat);
                    }
                    if (xmldoc["Measurements"]["Measurement"].GetElementsByTagName("zacceleration").Count > 0)
                    {
                        newSample.zacceleration = Convert.ToDouble(xmldoc["Measurements"]["Measurement"]["zacceleration"].InnerText.ToString().Replace(',', '.'), numFormat);
                    }
                    if (xmldoc["Measurements"]["Measurement"].GetElementsByTagName("xrotation").Count > 0)
                    {
                        newSample.xrotation = Convert.ToDouble(xmldoc["Measurements"]["Measurement"]["xrotation"].InnerText.ToString().Replace(',', '.'), numFormat);
                    }
                    if (xmldoc["Measurements"]["Measurement"].GetElementsByTagName("yrotation").Count > 0)
                    {
                        newSample.yrotation = Convert.ToDouble(xmldoc["Measurements"]["Measurement"]["yrotation"].InnerText.ToString().Replace(',', '.'), numFormat);
                    }
                    if (xmldoc["Measurements"]["Measurement"].GetElementsByTagName("zrotation").Count > 0)
                    {
                        newSample.zrotation = Convert.ToDouble(xmldoc["Measurements"]["Measurement"]["zrotation"].InnerText.ToString().Replace(',', '.'), numFormat);
                    }
                    if (xmldoc["Measurements"]["Measurement"].GetElementsByTagName("xmagneticforce").Count > 0)
                    {
                        newSample.xmagneticforce = Convert.ToDouble(xmldoc["Measurements"]["Measurement"]["xmagneticforce"].InnerText.ToString().Replace(',', '.'), numFormat);
                    }
                    if (xmldoc["Measurements"]["Measurement"].GetElementsByTagName("ymagneticforce").Count > 0)
                    {
                        newSample.ymagneticforce = Convert.ToDouble(xmldoc["Measurements"]["Measurement"]["ymagneticforce"].InnerText.ToString().Replace(',', '.'), numFormat);
                    }
                    if (xmldoc["Measurements"]["Measurement"].GetElementsByTagName("zmagneticforce").Count > 0)
                    {
                        newSample.zmagneticforce = Convert.ToDouble(xmldoc["Measurements"]["Measurement"]["zmagneticforce"].InnerText.ToString().Replace(',', '.'), numFormat);
                    }
                    if (xmldoc["Measurements"]["Measurement"].GetElementsByTagName("accelerationmagnitude").Count > 0)
                    {
                        newSample.accelerationmagnitude = Convert.ToDouble(xmldoc["Measurements"]["Measurement"]["accelerationmagnitude"].InnerText.ToString().Replace(',', '.'), numFormat);
                    }
                    if (xmldoc["Measurements"]["Measurement"].GetElementsByTagName("battery").Count > 0)
                    {
                        newSample.battery = Convert.ToDouble(xmldoc["Measurements"]["Measurement"]["battery"].InnerText.ToString().Replace(',', '.'), numFormat);
                    }
                    if (xmldoc["Measurements"]["Measurement"].GetElementsByTagName("wind").Count > 0)
                    {
                        newSample.wind = Convert.ToDouble(xmldoc["Measurements"]["Measurement"]["wind"].InnerText.ToString().Replace(',', '.'), numFormat);
                    }
                    ctx.Sample.Add(newSample);
                    ctx.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                this.Response.Write(ex.ToString());
                return;
            }
        }
Exemple #50
0
			public virtual void  load()
			{
				if (loaded)
				{
					return;
				}
				try
				{
					System.IO.Stream inStream = new System.IO.BufferedStream(System.Net.WebRequest.Create(this.url).GetResponse().GetResponseStream());
					XmlSAXDocumentManager factory = XmlSAXDocumentManager.NewInstance();
					factory.NamespaceAllowed = false; // FIXME
					
					XLRHandler xmlHandler = new XLRHandler(Enclosing_Instance.nodedict, prefix);
					CDATAHandler cdataHandler = new CDATAHandler(xmlHandler);
					
					XmlSAXDocumentManager parser = XmlSAXDocumentManager.CloneInstance(factory);
					//UPGRADE_TODO: Method 'javax.xml.parsers.SAXParser.setProperty' was converted to 'XmlSAXDocumentManager.setProperty' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javaxxmlparsersSAXParsersetProperty_javalangString_javalangObject'"
					parser.setProperty("http://xml.org/sax/properties/lexical-handler", cdataHandler);
                    parser.parse(inStream, xmlHandler);
				}
				catch (System.Exception e)
				{
					SupportClass.WriteStackTrace(e, Console.Error);
				}
				loaded = true;
			}