ReadBlock() public method

public ReadBlock ( char buffer, int index, int count ) : int
buffer char
index int
count int
return int
Example #1
1
        /// <summary>
        /// Read the data file, skipping over data we're not interested in
        /// but parsing and storing the contents of the first data channel
        /// </summary>
        public static void Read()
        {
            OriginalValues.Clear();

            using (StreamReader r = new StreamReader("ECGSAMPLE.txt"))
            {
                int bytesRead = 0;
                char[] buffer = new char[24];

                while (!r.EndOfStream)
                {
                    bytesRead = r.ReadBlock(buffer, 0, 8);
                    if (bytesRead != 8)
                        break;

                    bytesRead = r.ReadBlock(buffer, 0, 24);
                    if (bytesRead != 24)
                        break;
                    else
                        ParseData(buffer);

                    bytesRead = r.ReadBlock(buffer, 0, 2);
                    if (bytesRead != 2)
                        break;
                }
            }

            return;
        }
Example #2
0
 static void Main(string[] args)
 {
     using (StreamReader reader = new StreamReader(@"c:\files\inputFile.txt"))
     using (StreamWriter writer = new StreamWriter(@"c:\files\outputFile.txt", false))
     {
         int position = 0;
         while (!reader.EndOfStream)
         {
             char[] buffer = new char[16];
             int charactersRead = reader.ReadBlock(buffer, 0, 16);
             writer.Write("{0}: ", String.Format("{0:x4}", position));
             position += charactersRead;
             for (int i = 0; i < 16; i++)
             {
                 if (i < charactersRead)
                 {
                     string hex = String.Format("{0:x2}", (byte)buffer[i]);
                     writer.Write(hex + " ");
                 }
                 else
                     writer.Write("   ");
                 if (i == 7) { writer.Write("-- "); }
                 if (buffer[i] < 32 || buffer[i] > 250) { buffer[i] = '.'; }
             }
             string bufferContents = new string(buffer);
             writer.WriteLine("   " + bufferContents.Substring(0, charactersRead));
         }
     }
 }
        public async Task TestManifest()
        {

            var stream = new MemoryStream();
            var cli = new SpeechClient();
            cli.SetStream(stream);
            await cli.SendManifest();

            stream.Seek(0, SeekOrigin.Begin);
            var reader = new StreamReader(stream);

            var size = Convert.ToInt32(reader.ReadLine());
            var outp = new char[size];
            reader.ReadBlock(outp, 0, size);

            var str = new String(outp);

            var re = new Regex(@"^([A-Z_]*)");
            Assert.IsTrue(re.Match(str).Value == "APP_MANIFEST");
            var jsonstr = str.TrimStart(re.Match(str).Value.ToCharArray());

            var jsonstream = new MemoryStream(Encoding.UTF8.GetBytes(jsonstr));

            var ser = new DataContractJsonSerializer(typeof(Manifest));
            Manifest jsonobj = (Manifest)ser.ReadObject(jsonstream);
            Assert.IsTrue(jsonobj.Version == "0.0.1");
            Assert.IsTrue(jsonobj.Name == "speech-recognizer");
            Assert.IsTrue(jsonobj.DisplayName == "Mycroft Networked Speech Recognizer");
            Assert.IsTrue(jsonobj.Description == "Lets applications register speech triggers for Mycroft to look for.");
            Assert.IsTrue(jsonobj.InstanceId == "primary");
        }
        private void btn_select_output_click(object sender, RoutedEventArgs e)
        {
            box_eval.Document.Blocks.Clear();
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
            dlg.InitialDirectory = @"c:\CNTK\nets\";
            var result = dlg.ShowDialog();

            if (result.HasValue && result.Value)
            {
                outputFile = dlg.FileName;
                lbl_output.Content = dlg.FileName;
            }

            btn_selectMappingFile.IsEnabled = true;
            btn_writeMappings.IsEnabled = true;
            var reader = new StreamReader(new FileStream(outputFile, FileMode.Open));
            char[] buf = new char[10];
            reader.BaseStream.Seek(-10, SeekOrigin.End);
            reader.ReadBlock(buf, 0, 10);
            string strBuf = new string(buf);
            if (strBuf.Contains("mapped"))
            {
                lbl_mapping.Content = "already mapped";
                btn_selectMappingFile.IsEnabled = false;
                btn_writeMappings.IsEnabled = false;
            }
            reader.Close();

        }
Example #5
0
        public void FillAdresTable()
        {
            string fADRES = this.localPath + "\\" + "ADRES." + ext;
            if (File.Exists(fADRES))
            {

                StreamReader sr = new StreamReader(fADRES, Encoding.GetEncoding(866));
                char[] buffer = new char[6400];
                while (!sr.EndOfStream)
                {
                    sr.ReadBlock(buffer, 0, 6400);

                    Address sAdres = new Address();
                    //sAdres = &buffer;

                    OrganizationDataSet.AdresTableRow newrow = this.dataset.AdresTable.NewAdresTableRow();
                    int tna = (int)buffer[1];
                    tna = tna << 4;
                    tna &= (int)buffer[0];
                    newrow.tna = tna;
                    this.dataset.AdresTable.AddAdresTableRow(newrow);
                }
                sr.Close();

            }
            else
                System.Windows.Forms.MessageBox.Show("Сбой при открытии ADRES", "ADRES");
        }
Example #6
0
        internal static SourceText Decode(Stream stream, Encoding encoding, SourceHashAlgorithm checksumAlgorithm, bool throwIfBinaryDetected, bool canBeEmbedded)
        {
            stream.Seek(0, SeekOrigin.Begin);

            long longLength = stream.Length;
            if (longLength == 0)
            {
                return SourceText.From(string.Empty, encoding, checksumAlgorithm);
            }

            var maxCharRemainingGuess = encoding.GetMaxCharCountOrThrowIfHuge(stream);
            Debug.Assert(longLength > 0 && longLength <= int.MaxValue); // GetMaxCharCountOrThrowIfHuge should have thrown.
            int length = (int)longLength;

            using (var reader = new StreamReader(stream, encoding, detectEncodingFromByteOrderMarks: true, bufferSize: Math.Min(length, 4096), leaveOpen: true))
            {
                ArrayBuilder<char[]> chunks = ArrayBuilder<char[]>.GetInstance(1 + maxCharRemainingGuess / ChunkSize);
                while (!reader.EndOfStream)
                {
                    var nextChunkSize = ChunkSize;
                    if (maxCharRemainingGuess < ChunkSize)
                    {
                        // maxCharRemainingGuess typically overestimates a little
                        // so we will first fill a slightly smaller (maxCharRemainingGuess - 64) chunk
                        // and then use 64 char tail, which is likley to be resized.
                        nextChunkSize = Math.Max(maxCharRemainingGuess - 64, 64);
                    }

                    char[] chunk = new char[nextChunkSize];

                    int charsRead = reader.ReadBlock(chunk, 0, chunk.Length);
                    if (charsRead == 0)
                    {
                        break;
                    }

                    maxCharRemainingGuess -= charsRead;

                    if (charsRead < chunk.Length)
                    {
                        Array.Resize(ref chunk, charsRead);
                    }

                    // Check for binary files
                    if (throwIfBinaryDetected && IsBinary(chunk))
                    {
                        throw new InvalidDataException();
                    }

                    chunks.Add(chunk);
                }

                // We must compute the checksum and embedded text blob now while we still have the original bytes in hand.
                // We cannot re-encode to obtain checksum and blob as the encoding is not guaranteed to round-trip.
                var checksum = CalculateChecksum(stream, checksumAlgorithm);
                var embeddedTextBlob = canBeEmbedded ? EmbeddedText.CreateBlob(stream) : default(ImmutableArray<byte>);
                return new LargeText(chunks.ToImmutableAndFree(), reader.CurrentEncoding, checksum, checksumAlgorithm, embeddedTextBlob);
            }
        }
Example #7
0
        public static NamedTag parse(StreamReader sr, TagType type)
        {
            var name = "";

            //read the name length
            var buffer = new char[2];
            sr.ReadBlock(buffer, 0, 2);
            var bytebuf = new byte[] {(byte) buffer[1], (byte) buffer[0]};
            short length = BitConverter.ToInt16(bytebuf, 0);

            buffer = new char[length];
            sr.ReadBlock(buffer, 0, length);
            name = new string(buffer);

            Type t = GetClrTypeForTag(type);
            return (NamedTag)Activator.CreateInstance(t, sr, name, type);
        }
Example #8
0
        public static void ConvertStandartToRegions(string fnameIn, string fnameOut)
        {
            var fin = new StreamReader(fnameIn);
            var fout = new StreamWriter(fnameOut);
            const int bufferSize = 5000;
            var buff = new char[bufferSize];
            string residual = "";

            string lastPerson = "";
            var adjacentRegions = new List<string>();

            while(!fin.EndOfStream)
            {
                fin.ReadBlock(buff, 0, bufferSize);

                var buffer = new string(buff);
                var strs = new List<string>();

                if(residual != "" && residual[residual.Length - 1] == ']')
                    strs.Add(residual);
                strs.AddRange(buffer.Split(new[] { ';', '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries));
                if(residual != "" && residual[residual.Length - 1] != ']')
                    strs[0] = residual + strs[0];
                residual = strs.Last();

                string bufferOut = "";

                for(int i = 0; i < strs.Count - 1; i++)
                {
                    string[] edge = strs[i].Split(new[] { ' ', '-', '>' }, StringSplitOptions.RemoveEmptyEntries);
                    if(edge.Count() != 3 || edge[2][3] == '4')
                        continue;
                    if(edge[0][0] == 'f')
                    {
                        bufferOut += edge[0] + " -> " + edge[1] + "	" + "1\r\n";
                    }
                    if(edge[0][0] == 'p')
                    {
                        if(lastPerson != edge[0])
                        {
                            for(var regIn = 0; regIn < adjacentRegions.Count; regIn++)
                                for(var regOut = regIn + 1; regOut < adjacentRegions.Count; regOut++)
                                {
                                    bufferOut += adjacentRegions[regIn] + " -> " + adjacentRegions[regOut] + "	" + 1.0 / (adjacentRegions.Count - 1.0) + "\r\n";
                                    bufferOut += adjacentRegions[regOut] + " -> " + adjacentRegions[regIn] + "	" + 1.0 / (adjacentRegions.Count - 1.0) + "\r\n";
                                }
                            adjacentRegions = new List<string>();
                        }
                        adjacentRegions.Add(edge[1]);
                    }
                    lastPerson = edge[0];
                }
                fout.Write(bufferOut);
            }

            fin.Close();
            fout.Close();
        }
Example #9
0
 public override void Read(StreamReader reader)
 {
     base.Read(reader);
     // Line ending 
     var buffer = new char[2];
     var read = reader.ReadBlock(buffer, 0, buffer.Length);
     if (read != 2 || buffer != "\r\n".ToArray())
         throw new LeituraException("Final de linha não encontrado.");
 }
        static void Main(string[] args)
        {
            const byte INPUT_FILENAME = 0;
            const byte OUTPUT_FILENAME = 1;

            CharacterFrequency[] characterArray = new CharacterFrequency[256];

            for (int i = 0; i < 256; i++)
            {
                characterArray[i] = new CharacterFrequency((char)i);
                characterArray[i].setCharacter((char)i);
            }

            if (args.Length != 2)
            {
                Console.WriteLine("Usage:  CommandLine [input filename] [output file name]");
                Environment.Exit(0);
            }

            Console.WriteLine("The input filename is: {0}", args[INPUT_FILENAME]);
            Console.WriteLine("The output filename is: {0}", args[OUTPUT_FILENAME]);

            using (StreamReader SR = new StreamReader(args[INPUT_FILENAME]))
            {
                int read;
                FileInfo file = new FileInfo(args[INPUT_FILENAME]);
                long fileLength = file.Length;
                int f = Convert.ToInt32(fileLength);

                string path = File.ReadAllText(args[INPUT_FILENAME]);

                // Step 1
                char[] block = new char[1024];
                for (int k = 0; k < (f/1024); k++)
                {
                    // Step 2
                    read = SR.ReadBlock(block, 0, block.Length);

                    // Step 3
                    for (int i = 0; i < read; i++)
                    {
                        characterArray[(block[i])].increment();
                    }
                }

                // Step 4
                string text;
                int Cfrequency=0;

                for (int i = 0; i < characterArray.Length; i++)
                {
                    text = ((("") + (char)i + ("(") + i.ToString()) + (")") + "     " + characterArray[i].getFrequency(Cfrequency).ToString() + Environment.NewLine);
                    File.AppendAllText(args[OUTPUT_FILENAME], text, Encoding.UTF8);
                }
            }
        }
Example #11
0
        List<Show> Grab(GrabParametersBase p,ILogger logger)
        {
            var pp = (CyfraPlus.GrabParameters)p;
            var shows = new List<Show>();
            var wr = WebRequest.Create(string.Format(urlFormat, pp.Date.ToString(DateFormat)));
            logger.WriteEntry(string.Format("Grabbing Cyfra+ date {0} ...", pp.Date.ToString(DateFormat)), LogType.Info);
            var res = (HttpWebResponse)wr.GetResponse();
            const int ChannelDepth = 2;

            using (var sr = new StreamReader(res.GetResponseStream()))
            {
                var startDownloadTime = DateTime.Now;
                var data = new StringBuilder();
                int blockSize = 16384;
                while (!sr.EndOfStream)
                {
                    var buf = new char[blockSize];
                    var totalRead = sr.ReadBlock(buf, 0, blockSize);
                    data.Append(buf);
                    if (DateTime.Now - startDownloadTime > TimeSpan.FromSeconds(1))
                    {
                        startDownloadTime = DateTime.Now;
                        logger.WriteEntry(string.Format("Downloaded {0:#,##0} bytes so far", data.Length), LogType.Info);
                    }
                }

                var r = new Newtonsoft.Json.JsonTextReader(new StringReader(data.ToString()));

                while (r.Read())
                {
                    r.Read();
                    var channelNumber = r.ReadAsInt32();
                    var channelName = r.ReadAsString();
                    r.Read();
                    r.Read();
                    while (r.Depth > ChannelDepth)
                    {
                        var show = new Show();
                        show.Channel = channelName.Trim();
                        var programId = r.ReadAsInt32();
                        show.Title = Tools.CleanupText(r.ReadAsString());

                        show.StartTime = new DateTime(1970, 1, 1).Add(TimeSpan.FromSeconds(r.ReadAsInt32().Value));
                        show.EndTime = show.StartTime.Add(TimeSpan.FromSeconds(Convert.ToDouble(r.ReadAsInt32())));
                        var num = r.ReadAsInt32();
                        shows.Add(show);
                        var depth = r.Depth;
                        while (r.Depth == depth)
                            r.Read();
                        r.Read();
                    }
                }

            }
            return shows;
        }
Example #12
0
        public override void AddFile(String path, Stream data)
        {
            String adjustedPath = GetFullPath(path);
            String dir = Path.GetDirectoryName(adjustedPath);
            if(Directory.Exists(dir) == false)
                Directory.CreateDirectory(dir);

            FileStream fs = new FileStream(adjustedPath, FileMode.Create);

            //byte[] bytes = HttpFunction.ReadFromStream(data,8192);
			StreamReader sreader = new StreamReader (data);
			char[] bytes = new char[8192];
			int bytesread = sreader.ReadBlock (bytes, 0, 8192);
			while(bytesread > 0) {
				fs.Write (System.Text.Encoding.Default.GetBytes(bytes,0,bytesread), 0, bytesread);
				bytesread = sreader.ReadBlock (bytes, 0, 8192);
			}
			sreader.Close ();
			fs.Close ();
        }
Example #13
0
        internal static SourceText Decode(Stream stream, Encoding encoding, SourceHashAlgorithm checksumAlgorithm, bool throwIfBinaryDetected)
        {
            stream.Seek(0, SeekOrigin.Begin);

            int length = (int)stream.Length;
            if (length == 0)
            {
                return SourceText.From(string.Empty, encoding, checksumAlgorithm);
            }

            var maxCharRemainingGuess = encoding.GetMaxCharCount(length);

            using (var reader = new StreamReader(stream, encoding, detectEncodingFromByteOrderMarks: true, bufferSize: Math.Min(length, 4096), leaveOpen: true))
            {
                ArrayBuilder<char[]> chunks = ArrayBuilder<char[]>.GetInstance(1 + maxCharRemainingGuess / ChunkSize);
                while (!reader.EndOfStream)
                {
                    var nextChunkSize = ChunkSize;
                    if (maxCharRemainingGuess < ChunkSize)
                    {
                        // maxCharRemainingGuess typically overestimates a little
                        // so we will first fill a slightly smaller (maxCharRemainingGuess - 64) chunk
                        // and then use 64 char tail, which is likley to be resized.
                        nextChunkSize = Math.Max(maxCharRemainingGuess - 64, 64);
                    }

                    char[] chunk = new char[nextChunkSize];

                    int charsRead = reader.ReadBlock(chunk, 0, chunk.Length);
                    if (charsRead == 0)
                    {
                        break;
                    }

                    maxCharRemainingGuess -= charsRead;

                    if (charsRead < chunk.Length)
                    {
                        Array.Resize(ref chunk, charsRead);
                    }

                    // Check for binary files
                    if (throwIfBinaryDetected && IsBinary(chunk))
                    {
                        throw new InvalidDataException();
                    }

                    chunks.Add(chunk);
                }

                var checksum = CalculateChecksum(stream, checksumAlgorithm);
                return new LargeText(chunks.ToImmutableAndFree(), reader.CurrentEncoding, checksum, checksumAlgorithm);
            }
        }
        //public IObservable<string> TailV2(IFile file)
        //{
        //    return ObservableFile.WatchLines(file.GetNativePath(), Encoding.Default);
        //}

        public IObservable<string> Tail(IFile file, IScheduler scheduler = null)
        {
            return Observable.Create<string>(subj =>
            {
                var disposable = new CompositeDisposable();
                scheduler = scheduler ?? RxApp.TaskpoolScheduler;
                var abortSignal = new ManualResetEvent(false);

                disposable.Add(Disposable.Create(() => abortSignal.Set()));

                disposable.Add(scheduler.Schedule(abortSignal, (sched, state) =>
                {
                    using (var reader = new StreamReader(
                        file.GetContent().OpenStream(FileMode.Open, FileAccess.Read, FileShare.ReadWrite)))
                    {
                        long lastOffset = reader.BaseStream.Length;
                        if (reader.BaseStream.Length > 0)
                        {
                            // Send the last 10 kb of text to the reader.
                            lastOffset = Math.Max(0, reader.BaseStream.Length - (1024 * 10));
                        }

                        while (!state.WaitOne(100))
                        {
                            // Idle if file hasn't changed.
                            if (reader.BaseStream.Length <= lastOffset)
                            {
                                if (reader.BaseStream.Length < lastOffset)
                                {
                                    lastOffset = reader.BaseStream.Length;
                                }
                                continue;
                            }

                            // Read the data.
                            reader.BaseStream.Seek(lastOffset, SeekOrigin.Begin);
                            var delta = reader.BaseStream.Length - lastOffset;
                            var buffer = new char[delta];
                            reader.ReadBlock(buffer, 0, buffer.Length);

                            // Publish the data.
                            subj.OnNext(new string(buffer));

                            // Update the offset.
                            lastOffset = reader.BaseStream.Position;
                        }
                    }
                    return Disposable.Empty;
                }));

                return disposable;
            });
        }
Example #15
0
        public void KekeMethod()
        {
            string url = parseReturns.Text.Substring( parseReturns.Text.IndexOf( "http://" ) );
            int n = url.IndexOf( ' ' );
            if ( n != -1 )
                url = url.Substring( 0, n );

            HttpWebRequest htp = null;
            try {
                htp = (HttpWebRequest)WebRequest.Create( url );
            }
            catch (UriFormatException) {
                returns = new string[] {
                    BoldNickReturn( parseReturns.User.Nickname, parseReturns.Channel.Name, "Bad URL."),
                };
                return;
            }

            HttpWebResponse htpr = null;
            try {
                htpr = (HttpWebResponse)htp.GetResponse();
            }
            catch {
                returns = new string[] {
                    BoldNickReturn( parseReturns.User.Nickname, parseReturns.Channel.Name, "HTTP Request not completed."),
                };
                return;
            }

            StreamReader res = new StreamReader(htpr.GetResponseStream());

            char[] buf = new char[1024];
            int x = 0;
            string title = null;
            ASCIIEncoding ae = new ASCIIEncoding();
            StringBuilder sb = new StringBuilder();
            while ( ( x = res.ReadBlock( buf, 0, 1024 ) ) > 0 ) {
                string s = sb.Append( buf ).ToString();
                int starttag = s.IndexOf( "<title>" );
                if ( starttag == -1 )
                    continue;
                s = s.Substring( starttag + 7 );
                title = s.Substring( 0, s.IndexOf( "</title>" ) );
                title = title.Trim();//title.Trim( '\r', '\n', '\t' );
            }

            res.Close();

            if ( title != null ) {
                returns = new string[] { BoldNickReturn( parseReturns.User.Nickname, parseReturns.Channel.Name, title) , };
            }
            else returns = null;
        }
Example #16
0
File: Program.cs Project: xAVK/Pi
        static void Main(string[] args)
        {
            bool GoodOpen = false;
            try
            {
                System.IO.FileStream fs = new System.IO.FileStream(@"pi-billion.txt", System.IO.FileMode.Open, System.IO.FileAccess.Read, FileShare.Read);
                StreamReader sr = new StreamReader(fs);
                char[] b = new char[1000001537];
                sr.ReadBlock(b, 0, 1000001537);
                GoodOpen = true;
            }
            catch (Exception)
            {
                Console.WriteLine("error opening \"pi-billion.txt\"");
            }

            while (GoodOpen)
            {
                Console.WriteLine("Enter the date in the format DDMMYY");
                string strRead = Console.ReadLine();
                List<char> BuffList = new List<char>();
                for (int i = 0; i < strRead.Length; i++)
                {
                    BuffList.Add(strRead[i]);
                }
                string BuffString = "";
                for (int i = 0; i < BuffList.Count; i++)
                {
                    BuffString += Convert.ToString(BuffList[i]);
                }
                decimal BuffLong = Convert.ToDecimal(BuffString);
                for (long i = 2; i < 1000001537; i++)
                {
                    string str = "";
                    for (long j = i; j < i + BuffList.Count; j++)
                    {
                        str += Convert.ToString(b[j]);
                    }
                    decimal strLong = Convert.ToDecimal(str);
                    if (strLong == BuffLong)
                    {
                        Console.WriteLine(i - 1);
                        break;
                    }
                    else if (i == 1000001536)
                    {
                        Console.WriteLine("No matches found");
                    }
                }
                System.Threading.Thread.Sleep(2000);
            }
        }
Example #17
0
 void OpenFile()
 {
     if (openFileDialog.ShowDialog() == DialogResult.OK)
     {
         // Stream and Stream Reader were also likely candidates.
         //	They allow opening of existing files, as well as read access from them.
         Stream file = openFileDialog.OpenFile();
         StreamReader reader = new StreamReader(file);
         char[] text = new char[file.Length];
         reader.ReadBlock(text, 0, (int)file.Length);
         textEditor.Text = new String(text);
         reader.Close();
     }
 }
Example #18
0
        private string GetJsonPart(Stream stream)
        {
            stream.Seek(JsonBegin, SeekOrigin.Begin);

            const int searchStringLength = 6;

            using (var streamReader = new StreamReader(stream))
            {
                var buffer = new char[searchStringLength];

                int charsCount = 0;

                bool jsonEndIsFound = false;

                while (!streamReader.EndOfStream)
                {
                    streamReader.ReadBlock(buffer, 0, searchStringLength);

                    if (new string(buffer).Equals("}}star"))
                    {
                        jsonEndIsFound = true;
                        break;
                    }

                    streamReader.BaseStream.Seek(JsonBegin + charsCount, SeekOrigin.Begin);

                    charsCount++;

                    streamReader.DiscardBufferedData();
                }

                if (!jsonEndIsFound)
                {
                    throw new NotSupportedException();
                }

                stream.Seek(JsonBegin, SeekOrigin.Begin);

                var bytesLengths = (charsCount * 2);
                var jsonBytes = new byte[bytesLengths];
                stream.Read(jsonBytes, 0, bytesLengths);

                var str = Encoding.UTF8.GetString(jsonBytes);

                return str.Substring(0, str.LastIndexOf("}}star", StringComparison.InvariantCulture) + 2);
            }
        }
        private void LoadStreamBuffer()
        {
            Match m1 = Regex.Match(this.text, @"stream\s*");
            this.streamStartOffset = m1.Index + m1.Value.Length;
            this.streamLength = this.length - this.streamStartOffset;
            this.streamBuffer = new byte[this.streamLength];
            this.PdfFile.memory.Seek(this.address+this.streamStartOffset, SeekOrigin.Begin);
            this.PdfFile.memory.Read(this.streamBuffer, 0,this.streamLength);

            this.PdfFile.memory.Seek(this.address,SeekOrigin.Begin);
            StreamReader sr = new StreamReader(this.PdfFile.memory);
            char[] startChars = new char[this.streamStartOffset];
            sr.ReadBlock(startChars, 0, this.streamStartOffset);
            StringBuilder sb = new StringBuilder();
            sb.Append(startChars);
            this.text = sb.ToString();
        }
Example #20
0
 private string FindTo(StreamReader reader, long startPos, long endPos)
 {
     long pos = FindStringInStream(reader, "<To>", startPos, endPos);
     if (pos == -1)
         return string.Empty;
     reader.BaseStream.Seek(pos, SeekOrigin.Begin);
     reader.DiscardBufferedData();
     char[] buffer = new char[4096];
     int charsRead = reader.ReadBlock(buffer, 0, buffer.Length);
     string str = new string(buffer, 0, charsRead);
     Match m = Regex.Match(str, @".*?<To>(.*?)(</).*", RegexOptions.IgnoreCase);
     if (m != null && m.Success)
     {
         return m.Groups[1].Value;
     }
     return string.Empty;
 }
Example #21
0
 public IStaticGatewayHandler GetGatewayHandler(IContext objContext)
 {
     using (System.IO.Stream stream = Assembly.GetExecutingAssembly()
                    .GetManifestResourceStream("Bronze.Controls.VWG.OtherResources.PIE.htc"))
     using (StreamReader reader = new StreamReader(stream))
     {
         char[] objBuffer = new char[stream.Length];
         reader.ReadBlock(objBuffer, 0, (int)stream.Length);
         objContext.HttpContext.Response.Expires = 60*24*370;
         objContext.HttpContext.Response.Cache.SetExpires(DateTime.Now.AddYears(1));
         objContext.HttpContext.Response.Cache.SetCacheability(System.Web.HttpCacheability.Public);
         objContext.HttpContext.Response.ContentType = "text/x-component";
         objContext.HttpContext.Response.Write(objBuffer, 0, objBuffer.Length);
         objContext.HttpContext.Response.Flush();
     }
     return null;
 }
Example #22
0
        public void Parse(StreamReader reader)
        {
            if (Token != null)
            {
                reader.BaseStream.Seek(Token.Length, SeekOrigin.Current);
            }

            int longestTokenLength = 0;

            foreach (TokenParserBase token in PossibleNextToken)
            {
                if (token.Token != null)
                {
                    longestTokenLength = Math.Max(longestTokenLength, token.Token.Length);
                }
            }

            char[] buffer = new char[longestTokenLength];
            reader.ReadBlock(buffer, 0, longestTokenLength);
            reader.BaseStream.Seek(-longestTokenLength, SeekOrigin.Current);

            foreach (TokenParserBase token in PossibleNextToken)
            {
                if (token.Token == null)
                    continue;

                bool success = true;
                for (int i=0;i<token.Token.Length; ++i)
                {
                    char tc = token.Token[i];
                    char c = buffer[i];
                    if (Char.ToUpperInvariant(tc) != Char.ToUpperInvariant(c))
                    {
                        success = false;
                        break;
                    }
                }

                if (success)
                {
                    token.Parse(reader);
                }
            }
        }
Example #23
0
 private void themdata(string p)
 {
     using (var input=new StreamReader("t.txt"))
     using (var output=new StreamWriter("t.txt.tep",true,Encoding.UTF8))
     {
         var buf= new char[4096];
         int read = 0;
         output.WriteLine(p);
         do
         {
             read = input.ReadBlock(buf, 0, buf.Length);
             output.Write(buf, 0, read);
         } while (read>0);
         output.Flush();
         output.Close();
         input.Close();
     }
     File.Replace("t.txt.tep", "t.txt", "t.txt.back");
     File.Delete("t.txt.back");
 }
        public static int CountLines(string path)
        {
            int lines = 0;
            char[] buffer = new char[4096];

            using (StreamReader reader = new StreamReader(path))
            {
                while (!reader.EndOfStream)
                {
                    reader.ReadBlock(buffer, 0, buffer.Length);

                    for (int i = 0; i < buffer.Length; i++)
                    {
                        if (buffer[i] == '\n')
                            lines++;
                    }
                }
            }

            return lines;
        }
Example #25
0
        internal static SourceText Decode(Stream stream, Encoding encoding, SourceHashAlgorithm checksumAlgorithm, bool throwIfBinaryDetected)
        {
            stream.Seek(0, SeekOrigin.Begin);

            int length = (int)stream.Length;
            if (length == 0)
            {
                return SourceText.From(string.Empty, encoding, checksumAlgorithm);
            }

            using (var reader = new StreamReader(stream, encoding, detectEncodingFromByteOrderMarks: true, bufferSize: Math.Min(length, 4096), leaveOpen: true))
            {
                ArrayBuilder<char[]> chunks = ArrayBuilder<char[]>.GetInstance(1 + length / ChunkSize);
                while (!reader.EndOfStream)
                {
                    char[] chunk = new char[ChunkSize];
                    int charsRead = reader.ReadBlock(chunk, 0, ChunkSize);
                    if (charsRead == 0)
                    {
                        break;
                    }

                    if (charsRead < ChunkSize)
                    {
                        Array.Resize(ref chunk, charsRead);
                    }

                    // Check for binary files
                    if (throwIfBinaryDetected && IsBinary(chunk))
                    {
                        throw new InvalidDataException();
                    }

                    chunks.Add(chunk);
                }

                var checksum = CalculateChecksum(stream, checksumAlgorithm);
                return new LargeText(chunks.ToImmutableAndFree(), reader.CurrentEncoding, checksum, checksumAlgorithm);
            }
        }
Example #26
0
        public string GetNext(string mobileNumber)
        {
            var sub = subscriptions.SingleOrDefault(s => s.Number == mobileNumber);

            if(sub == null)
            {
                throw new ArgumentException("Subscription not found for mobile number: " + mobileNumber);
            }

            var buffer = new char[PAGE_SIZE];

            using (var stream = GetStream(sub.BookId))
            using (var reader = new StreamReader(stream))
            {
                stream.Seek(sub.Index, SeekOrigin.Begin);
                reader.ReadBlock(buffer, 0, PAGE_SIZE);
            }

            sub.Index += PAGE_SIZE;

            return new string(buffer);
        }
Example #27
0
        public void WriteOneRecord()
        {
            MARCWriter writer = new MARCWriter("onerecord.dat");
            foreach (MARCRecord record in oneRecord)
            {
                writer.Write(record);
            }
            writer.Close();
            StreamReader answer = new StreamReader(@"C:\Documents and Settings\wkurt\My Documents\Visual Studio 2008\Projects\TestMARC\TestMARC\one.dat");
            StreamReader result = new StreamReader("onerecord.dat");
            char[] answerBuffer = new char[1];
            char[] resultBuffer = new char[1];

            while(answer.Peek() != -1 && result.Peek() != -1)
            {
                answer.ReadBlock(answerBuffer,0,1);
                result.ReadBlock(resultBuffer,0,1);
                Assert.Equals(answerBuffer[0],resultBuffer[0]);
            
            }
                
        }
Example #28
0
 private string FindMethod(StreamReader reader, long startPos, long endPos)
 {
     long pos = FindStringInStream(reader, "Body", startPos, endPos);
     if (pos == -1)
         return string.Empty;
     reader.BaseStream.Seek(pos, SeekOrigin.Begin);
     reader.DiscardBufferedData();
     char[] buffer = new char[200];
     int charsRead = reader.ReadBlock(buffer, 0, buffer.Length);
     string str = new string(buffer, 0, charsRead);
     Match m = Regex.Match(str, @".*?<(.*?)( |>).*", RegexOptions.IgnoreCase);
     if (m != null && m.Success)
     {
         string method = m.Groups[1].Value;
         if (method.Contains(":"))
         {
             method = method.Split(':')[1];
         }
         return method;
     }
     return string.Empty;
 }
        public void Given_a_hash_checksum_transcoder_When_written_to_the_transcoder_Then_the_inner_stream_contains_the_written_data_followed_by_its_hash()
        {
            var hashAlgorithm = SHA256.Create();
            var streamHashGenerator = new CryptoStreamHashGenerator(hashAlgorithm);
            var hashChecksumTranscodingStreamFactory =
                new HashChecksumTranscodingStreamFactory(streamHashGenerator);

            const int HashByteCount = 32;
            const string TestText = "Test";

            using (var innerStream = new MemoryStream())
            using (var hashChecksumTranscodingStream = hashChecksumTranscodingStreamFactory.CreateTrancodingStream(innerStream))
            {
                var writer = new StreamWriter(hashChecksumTranscodingStream);
                writer.Write(TestText);
                writer.Flush();
                hashChecksumTranscodingStream.Flush();

                innerStream.Position = 0;
                var reader = new StreamReader(innerStream);
                var stringBuffer = new char[4];
                reader.ReadBlock(stringBuffer, 0, 4);

                var expectedInnerStreamLength = TestText.Length + HashByteCount;
                Assert.AreEqual(expectedInnerStreamLength, innerStream.Length);

                const string ExpectedString = TestText;
                var actualString = new string(stringBuffer);
                Assert.AreEqual(ExpectedString, actualString);

                const string ExpectedHash =
                    "53-2E-AA-BD-95-74-88-0D-BF-76-B9-B8-CC-00-83-2C-20-A6-EC-11-3D-68-22-99-55-0D-7A-6E-0F-34-5E-25";
                innerStream.Position = 4;
                var hashBuffer = new byte[innerStream.Length - innerStream.Position];
                innerStream.Read(hashBuffer, 0, HashByteCount);
                var actualHash = BitConverter.ToString(hashBuffer);
                Assert.AreEqual(ExpectedHash, actualHash);
            }
        }
        public static bool Check()
        {
            string cpuid = MachineInfo.GetCPUID();

            char[] crcInfo = CRC32.GetCRC32(cpuid).ToCharArray();            
            char[] licenseInfo = new char[8];

            string licenseFile = HttpContext.Current.Server.MapPath("~/App_Data/erp_license.lic");
            if (!File.Exists(licenseFile))
            {
                return false;
            }
            StreamReader sr = new StreamReader(licenseFile);            
            sr.ReadBlock(licenseInfo, 0, 8);
            sr.Close();

            for (int i = 0; i < 8; i++)
            {
                if (crcInfo[i] != licenseInfo[i])
                    return false;
            }
            return true;
        }