ReadAsync() public method

public ReadAsync ( char buffer, int index, int count ) : Task
buffer char
index int
count int
return Task
示例#1
0
        private async Task logFromStream(Stream stream, CancellationToken token, string category, Func<bool> isComplete)
        {
            char[] buffer = new char[128];

            using (var sr = new StreamReader(stream))
            {
                while (true)
                {
                    token.ThrowIfCancellationRequested();

                    var outBytesRead = await sr.ReadAsync(buffer, 0, buffer.Length);

                    if (outBytesRead == 0)
                    {
                        if (isComplete())
                            break;
                        else
                            await Task.Delay(100);
                    }
                    else
                    {
                        var outText = new string(buffer, 0, outBytesRead);

                        if (!string.IsNullOrEmpty(outText))
                            this.newLogEntry(outText, category, true, true);
                    }
                }
            }
        }
示例#2
0
 public override async Task ReadAsync(StreamReader reader)
 {
     var buffer = new char[valorFixo.Length];
     var read = await reader.ReadAsync(buffer, 0, buffer.Length);
     if (read != buffer.Length || new string(buffer) != valorFixo)
         throw new LeituraException($"O valor fixo '{valorFixo}' não foi encontrado.");
 }
 private async Task<DataBlock> ReadBlockAsync(StreamReader reader, DataBlock target)
 {
     var readBytes = await reader.ReadAsync(target.Data, 0, BufferSize);
     if (readBytes != BufferSize)
     {
         target.ResizeData(readBytes);
     }
     return target;
 }
示例#4
0
        public static async Task<IHttpPost> Create(StreamReader reader, int postContentLength)
        {
            char[] rawEncoded = new char[postContentLength];
            
            int readBytes = await reader.ReadAsync(rawEncoded, 0, rawEncoded.Length);

            byte[] raw = Encoding.UTF8.GetBytes(rawEncoded, 0, readBytes);
            
            return new HttpPost(raw, readBytes);
        }
示例#5
0
        public static async void CreateListener(Action<string> action, TcpClient tcpClient)
        {
            var networkStream = tcpClient.GetStream();
            var r = new StreamReader(networkStream);
            var buffer = new char[1];
            while (true)
            {
                if (r.EndOfStream)
                {
                    Task.Delay(500);
                    continue;
                }

                await r.ReadAsync(buffer, 0, buffer.Length);
                action(new string(buffer));
            }
        }
示例#6
0
        /// <summary>
        /// Utility method that fills a StringBuilder
        /// </summary>
        /// <param name="data">Stream containing document data.</param>
        /// <returns>Content of the stream as a string.</returns>
        public static async Task<string> ReadStreamAsync(Stream data, int blockSize=4096)
        {
            var buffer = new char[blockSize];
            var builder = new StringBuilder();

            using (var reader = new StreamReader(data))
            {
                while (!reader.EndOfStream)
                {
                    // StreamReader.ReadAsync() returns number of *chars* read, not number of bytes, in 
                    // spite of what the API docs say. I read the code (MW 2015.11.06)
                    var charsRead = await reader.ReadAsync(buffer, 0, blockSize).ConfigureAwait(false);
                    builder.Append(buffer, 0, charsRead);
                }
            }

            return builder.ToString();
        }
示例#7
0
        /// <summary>
        /// Asynchronous method to analyze the data stream.
        /// </summary>
        /// <param name="data">Data stream to analyze.</param>
        /// <param name="blockSize">Max number of characters to read at a time.</param>
        /// <returns>Result of the analysis.</returns>
        public async Task<IAnalyzerResult> AnalyzeAsync(Stream data, int blockSize = 1024)
        {
            var result = new CharacterAnalyzerResult();
            var buffer = new char[blockSize];

            using (var reader = new StreamReader(data))
            {
                var lastCharType = CharacterType.Invalid;

                while (!reader.EndOfStream)
                {
                    var count = await reader.ReadAsync(buffer, 0, blockSize).ConfigureAwait(false);

                    lastCharType = AnalyzeBuffer(buffer, count, result, lastCharType);
                }   
            }

            return result;
        }
示例#8
0
        public static async Task <int> ReadToMemoryAsync(this StreamReader stream, Memory <char> memory)
        {
            var buffer = BufferArrayPool <char> .Rent(memory.Length);

            var totalRead = 0;

            try
            {
                totalRead = await stream.ReadAsync(buffer, 0, memory.Length);

                buffer.AsSpan().Slice(0, totalRead).CopyTo(memory.Span);
            }
            finally
            {
                Array.Clear(buffer, 0, totalRead);
                BufferArrayPool <char> .Return(buffer);
            }
            return(totalRead);
        }
示例#9
0
文件: File.cs 项目: zeroyou/corefx
        private static async Task <string> InternalReadAllTextAsync(string path, Encoding encoding, CancellationToken cancellationToken)
        {
            Debug.Assert(!string.IsNullOrEmpty(path));
            Debug.Assert(encoding != null);

            char[]        buffer = null;
            StringBuilder sb     = null;
            StreamReader  sr     = AsyncStreamReader(path, encoding);

            try
            {
                cancellationToken.ThrowIfCancellationRequested();
                sb     = StringBuilderCache.Acquire();
                buffer = ArrayPool <char> .Shared.Rent(sr.CurrentEncoding.GetMaxCharCount(DefaultBufferSize));

                for (;;)
                {
                    int read = await sr.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false);

                    if (read == 0)
                    {
                        return(sb.ToString());
                    }

                    sb.Append(buffer, 0, read);
                    cancellationToken.ThrowIfCancellationRequested();
                }
            }
            finally
            {
                sr.Dispose();
                if (buffer != null)
                {
                    ArrayPool <char> .Shared.Return(buffer);
                }

                if (sb != null)
                {
                    StringBuilderCache.Release(sb);
                }
            }
        }
示例#10
0
        private static async Task<bool> WaitForPrompt(StreamReader reader, string prompt)
        {
            var buffer = new char[1024];
            int read;
            var readString = string.Empty;

            while ((read = await reader.ReadAsync(buffer, 0, buffer.Length)) > 0)
            {
                readString += new string(buffer, 0, read);

                if (readString.TrimEnd().EndsWith(prompt))
                {
                    Console.Write(readString);
                    return true;
                }
            }

            Console.Write(readString);
            return false;
        }
        public static async Task HandleClientAccessPolicy(TcpClient client, string policyResponse)
        {
            using (var clientStream = client.GetStream())
            {
                string request = string.Empty;

                var reader = new StreamReader(clientStream);
                var charArray = new char[2048];
                var length = await reader.ReadAsync(charArray, 0, 2048);
                request = new String(charArray, 0, length);

                if (request == PolicyRequest)
                {
                    var writer = new StreamWriter(clientStream, Encoding.UTF8);
                    writer.AutoFlush = true;
                    await writer.WriteAsync(policyResponse);
                }
            }

            client.Close();
        }
示例#12
0
        static async Task ReadStreamToEnd(StreamReader stream, IObserver<string> observable) {
            try {
                var readBuffer = new char[1];
                var lineBuffer = new StringBuilder();
                while ((await stream.ReadAsync(readBuffer, 0, 1).ConfigureAwait(false)) > 0) {
                    var c = readBuffer[0];
                    lineBuffer.Append(c);
                    // This does not account for unterminated lines.... like 'verifying download...'
                    // We would be able to do this by sending the data also byte by byte to the receivers, but for little gain.
                    if (c != '\r' && c != '\n')
                        continue;
                    observable.OnNext(lineBuffer.ToString());
                    lineBuffer.Clear();
                }

                if (lineBuffer.Length > 0)
                    observable.OnNext(lineBuffer.ToString());
            } finally {
                observable.OnCompleted();
            }
        }
示例#13
0
        /// <summary>
        /// Lee el archivo en pedazos de 4096 bytes, y llena el diccionario indicando
        /// que letras existen en el archivo y cuantas veces aparece cada una de ellas.
        /// </summary>
        /// <returns>
        /// Retorna una tarea ya que es un proceso que puede ejecutarse en otro 
        /// hilo para no bloquear la UI.
        /// </returns>
        public async Task<DocumentoProcesado> Procesar()
        {
            var palabras = new SortedDictionary<string, int>();
            var letras = new SortedDictionary<char, int>();
            var signos = new SortedDictionary<char, int>();
            var simbolos = new SortedDictionary<char, int>();

            int palabrasCantidad = 0;
            int letrasCantidad = 0;
            int signosCantidad = 0;
            int simbolosCantidad = 0;

            int bytesLeidos = 0;

            // Se asume que todos los archivos tendrán encoding de UTF8
            // a menos que el sistema pueda detectarlo por el order de bytes.
            using (var reader = new StreamReader(rutaArchivo, Encoding.UTF8, detectEncodingFromByteOrderMarks: true, bufferSize: bufferSize))
            {
                var letrasPalabra = new List<char>();
                var buffer = new char[bufferSize];
                var count = 0;

                do
                {
                    // se lee un fragmento de 4096 bytes del archivo
                    count = await reader.ReadAsync(buffer, 0, bufferSize);


                    // Se analiza cada una de esas 4096 letras leídas
                    // y si no se encuentran en el diccionario aún se
                    // agregan con valor de uno,
                    // pero si la letra ya existe en el diccionario,
                    // solo se incrementa en uno su valor.
                    for (int i = 0; i < count; i++)
                    {
                        var caracter = buffer[i];

                        if (char.IsLetter(caracter))
                        {
                            letrasCantidad++;

                            var c = char.ToLowerInvariant(caracter);

                            letrasPalabra.Add(c);

                            if (letras.ContainsKey(c))
                            {
                                letras[c]++;
                            }
                            else
                            {
                                letras.Add(c, 1);
                            }
                        }
                        else if (letrasPalabra.Count > 0)
                        {

                            if (letrasPalabra.Count <= 5)
                            {
                                palabrasCantidad++;

                                var palabra = new string(letrasPalabra.ToArray()).ToLowerInvariant();

                                if (palabras.ContainsKey(palabra))
                                {
                                    palabras[palabra]++;
                                }
                                else
                                {
                                    palabras.Add(palabra, 1);
                                }
                            }

                            letrasPalabra.Clear();

                        }

                        if (char.IsPunctuation(caracter))
                        {
                            signosCantidad++;

                            if (signos.ContainsKey(caracter))
                            {
                                signos[caracter]++;
                            }
                            else
                            {
                                signos.Add(caracter, 1);
                            }
                        }

                        if (char.IsSymbol(caracter))
                        {

                            simbolosCantidad++;

                            if (simbolos.ContainsKey(caracter))
                            {
                                simbolos[caracter]++;
                            }
                            else
                            {
                                simbolos.Add(caracter, 1);
                            }
                        }
                    }

                    // se lleva la cuenta de la cantidad de bytes que se van leyendo hasta el momento.
                    bytesLeidos += count;

                    // Se notifica el avance con la nueva cantidad de bytes para que la UI pueda
                    // conocer el avance y actualizar un progressbar o algo por el estilo.
                    NotificarAvance(bytesLeidos);

                } while (count != 0);

                NotificarAvance(pesoArchivo);
            }

            return new DocumentoProcesado
            {
                Letras = letras,
                Palabras = palabras,
                Signos = signos,
                Simbolos = simbolos//,
                //CantidadLetras = letrasCantidad,
                //CantidadPalabras = palabrasCantidad,
                //CantidadSignos = signosCantidad,
                //CantidadSimbolos = simbolosCantidad
            };
        }
        /*
        *METHOD		    :	clientThread
        *
        *DESCRIPTION	:	Method to listen to a spesific users pipe
         *                  Is creates the connection, listens for a command
         *                  then acts acordingly based on that command
        *
        *PARAMETERS		:	object sender:  Opject relaying information on where the even call came from
        *                   EventArgs e:    Object that contains data about the event
        *  
        *RETURNS		:	void
        *
        */
        private async void clientThread(object clientPipeName)
        {
            string serverName = "";
            string pipeName = (string)clientPipeName;
            
            NamedPipeClientStream client;
            NamedPipeServerStream server;
            StreamReader input;
            StreamWriter output;

            DAL dal = new DAL();
            string userName = "";

            //set up pipe security
            PipeSecurity ps = new PipeSecurity();
            System.Security.Principal.SecurityIdentifier sid = new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WellKnownSidType.WorldSid, null);
            PipeAccessRule par = new PipeAccessRule(sid, PipeAccessRights.ReadWrite, System.Security.AccessControl.AccessControlType.Allow);
            ps.AddAccessRule(par);

            Logger.Log("Client thread started");

            //wait for user to connect
            server = new NamedPipeServerStream(clientPipeName + "service", PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 5000, 5000, ps);
            server.WaitForConnection();
            input = new StreamReader(server);

            Logger.Log("Client connected to pipe: " + clientPipeName);

            //get the name of the computer to connect back to
            serverName = input.ReadLine();

            //connect back
            try
            {
                client = new NamedPipeClientStream(serverName, clientPipeName + "User");
                client.Connect(30);
                output = new StreamWriter(client);

                Logger.Log("User thread connected to pipe: " + clientPipeName);

                //start loop to watch the pipe 
                while (!Done)
                {
                    //async read from pipe
                    char[] temp = new char[5000];
                    await input.ReadAsync(temp, 0, 5000);
                    //move data from pipe to a string (padded with somthing, not sure what)
                    string userCommand = new string(temp);
                    //all commands end in a period. if there is no period then the user left
                    if (!userCommand.Contains("."))
                    {
                        Logger.Log("Pipe: " + clientPipeName + "userLeft");
                        //close connection
                        output.Dispose();
                        input.Dispose();
                        //remove from repo
                        clients.DeleteClient((string)clientPipeName);
                        break;
                    }
                    //if the command is valid
                    //remove the period and all padded data
                    userCommand = userCommand.Remove(userCommand.IndexOf('.'));

                    Logger.Log("Pipe: " + clientPipeName + " Got Command: " + userCommand);
                    //select the command entered
                    if (userCommand == "NewUser")
                    {
                        Logger.Log("Pipe: " + clientPipeName + "in newUser command code");
                        //read in user name
                        userName = input.ReadLine();
                        //add to database
                        output.WriteLine("OK");
                        output.Flush();
                        //if user not in database add
                        dal.OpenConnection();
                        bool isUserTaken = dal.IsNameInDatabase(userName);
                        dal.CloseConnection();
                        if (isUserTaken == false)
                        {
                            dal.OpenConnection();
                            dal.StoreUserName(userName);
                            dal.InitializeUserInLeaderboard(userName, 1);
                            dal.CloseConnection();
                        }
                    }
                    else if (userCommand == "GetQuestion")
                    {
                        Logger.Log("Pipe: " + clientPipeName + "in GetQuestion command code.");
                        string[] splitbuffer = new string[5];
                        
                        //read in question number
                        string buffer = input.ReadLine();
                        int questionNumber = Int32.Parse(buffer);
                        Logger.Log("Pipe: " + clientPipeName + "in GetQuestion command code. Getting Question: " + questionNumber);
                        // get question and answers from database
                        dal.OpenConnection();
                        string questionFromDatabase = dal.GetQuestionAndAnswers(questionNumber);
                        dal.CloseConnection();

                        //get question data
                        //put it in questionFromDatabase
                        splitbuffer = questionFromDatabase.Split('|');
                        output.WriteLine(splitbuffer[0]);//question
                        output.Flush();
                        output.WriteLine(splitbuffer[1]);//answer1
                        output.Flush();
                        output.WriteLine(splitbuffer[2]);//answer2
                        output.Flush();
                        output.WriteLine(splitbuffer[3]);//answer3
                        output.Flush();
                        output.WriteLine(splitbuffer[4]);//answer4
                        output.Flush();
                        output.WriteLine(splitbuffer[5]);//correct answer
                        output.Flush();
                    }
                    else if (userCommand == "QuestionAnswered")
                    {
                        Logger.Log("Pipe: " + clientPipeName + "in QuestionAnswered command code");
                        //read in question number
                        string questionNumber = input.ReadLine();
                        int intQuestionNumber = Convert.ToInt32(questionNumber);
                        //read in users answer
                        string answer = input.ReadLine();
                        //read in user score
                        string score = input.ReadLine();
                        int intScore = Convert.ToInt32(score);

                        //send to database
                        dal.OpenConnection();
                        dal.StoreUserAnswer(userName, 1, intQuestionNumber, answer, intScore);
                        dal.CloseConnection();

                        output.WriteLine("OK");
                        output.Flush();
                    }
                    else if (userCommand == "GameDone")
                    {
                        Logger.Log("Pipe: " + clientPipeName + "in GameDone command code");
              
                        //read in users score for the game
                        string gameScore = input.ReadLine();
                        int intGameScore = Convert.ToInt32(gameScore);
                        //save to database
                        dal.OpenConnection();
                        dal.AlterLeaderboard(1, userName, intGameScore);
                        dal.CloseConnection();

                        //get leaderboard from database
                        dal.OpenConnection();
                        string leaderboard = dal.Leaderboard(1); //get leaderboard from database
                        dal.CloseConnection();
                        //send leaderboard to user
                        output.WriteLine(leaderboard);
                        output.Flush();
                    }
                    else if (userCommand == "GetLeaderboard")
                    {
                        Logger.Log("Pipe: " + clientPipeName + "in GetLeaderboard command code");
                        dal.OpenConnection();
                        string leaderboard = dal.Leaderboard(1); //get leaderboard from database
                        dal.CloseConnection();
                        //send leaderboard to user
                        output.WriteLine(leaderboard);
                        output.Flush();
                    }
                    else if (userCommand == "GetCurrentStatus")
                    {
                        Logger.Log("Pipe: " + clientPipeName + "in GetCurrentStatus command code");
                        dal.OpenConnection();
                        string currentStatus = dal.GetCurrentStatus(1); //get currentStatus from database
                        dal.CloseConnection();
                        //send currentStatus to user
                        output.WriteLine(currentStatus);
                        output.Flush();
                    }
                    else if (userCommand == "SaveQuestion")
                    {
                        Logger.Log("Pipe: " + clientPipeName + "in SaveQuestion command code");
                        int questionNumber = Int32.Parse(input.ReadLine());
                        string question = input.ReadLine();
                        string answer1 = input.ReadLine();
                        string answer2 = input.ReadLine();
                        string answer3 = input.ReadLine();
                        string answer4 = input.ReadLine();
                        int correctAnswer = Int32.Parse(input.ReadLine());

                        //send question to database
                        dal.OpenConnection();
                        dal.UpdateQuestionAndAnswer(questionNumber, question, answer1, answer2, answer3, answer4, correctAnswer);
                        dal.CloseConnection();

                        output.WriteLine("ok");
                        output.Flush();
                    }
                    else if (userCommand == "GetExcel")
                    {
                        Logger.Log("Pipe: " + clientPipeName + "in GetExcel command code");

                        //send all of the questions
                        for (int counter = 0; counter < 10; counter++)
                        {
                            dal.OpenConnection();
                            String question = dal.GetQuestion(counter + 1);
                            dal.CloseConnection();
                            output.WriteLine(question);
                            output.Flush();
                        }

                        //send the average time to answer correctly
                        for (int counter = 0; counter < 10; counter++)
                        {
                            dal.OpenConnection();
                            float currentAverageTime = dal.GetAverageTimeToAnswerCorrectly(counter + 1);
                            dal.CloseConnection();
                            output.WriteLine(currentAverageTime);
                            output.Flush();
                        }

                        //send the percent of users who answered correctly
                        for (int counter = 0; counter < 10; counter++)
                        {
                            dal.OpenConnection();
                            float currentQuestionPercent = dal.GetPercentOfUsersWhoAnsweredCorrectly(counter + 1);
                            dal.CloseConnection();
                            output.WriteLine(currentQuestionPercent);
                            output.Flush();
                        }
                    }
                    else if (userCommand == "Quit")
                    {
                        Logger.Log("Pipe: " + clientPipeName + "Closing");
                        //close connection
                        output.Dispose();
                        input.Dispose();
                        //remove from repo
                        clients.DeleteClient((string)clientPipeName);
                        //change user to inactive
                        dal.OpenConnection();
                        dal.SetUserToInactive(userName);
                        dal.CloseConnection();
                        break;
                    }
                    else
                    {
                        Logger.Log("Pipe: " + clientPipeName + "Command not recognized");
                    }
                }
                //when the loop is done then the user is no longer active
                dal.OpenConnection();
                dal.SetUserToInactive(userName);
                dal.CloseConnection();
            }
            catch(Exception ex)
            {
                Logger.Log("Pipe: " + clientPipeName + " unknown error: " + ex.Message);
                clients.DeleteClient((string)clientPipeName);

                dal.OpenConnection();
                dal.SetUserToInactive(userName);
                dal.CloseConnection();
            }
        }
示例#15
0
        /// <summary>
        /// Handle an incoming SMTP connection, from connection to completion.
        /// </summary>
        /// <param name="parameters">SmtpProxyConnectionArguments object containing all parameters for this connection.</param>
        private async void ProcessConnection(object parameters)
        {
            // Cast the passed-in parameters back to their original objects.
            SmtpProxyConnectionArguments arguments = (SmtpProxyConnectionArguments)parameters;

            // The overall number of bytes transmitted on this connection.
            ulong bytesTransmitted = 0;

            TcpClient client = null;
            Stream clientStream = null;
            StreamReader clientStreamReader = null;
            StreamWriter clientStreamWriter = null;

            string ip = "";

            try
            {
                client = arguments.TcpClient;
                clientStream = client.GetStream();

                // Placeholder variables to be populated throughout the client session.
                NetworkCredential credential = arguments.RemoteServerCredential;
                string fromAddress = "";
                string identity = "";
                List<string> toList = new List<string>();
                bool sending = false, inPlainAuth = false, inLoginAuth = false;

                // A byte array to streamline bit shuffling.
                char[] buffer = new char[Constants.SMALLBUFFERSIZE];

                // Capture the client's IP information.
                PropertyInfo pi = clientStream.GetType().GetProperty("Socket", BindingFlags.NonPublic | BindingFlags.Instance);
                ip = ((Socket)pi.GetValue(clientStream, null)).RemoteEndPoint.ToString();
                if (ip.IndexOf(":") > -1)
                    ip = ip.Substring(0, ip.IndexOf(":"));

                // If the IP address range filter contains the localhost entry 0.0.0.0, check if the client IP is a local address and update it to 0.0.0.0 if so.
                if (arguments.AcceptedIPs.IndexOf("0.0.0.0") > -1)
                {
                    if (ip == "127.0.0.1")
                        ip = "0.0.0.0";
                    else
                    {
                        IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName());
                        foreach (IPAddress hostIP in hostEntry.AddressList)
                        {
                            if (hostIP.ToString() == ip)
                            {
                                ip = "0.0.0.0";
                                break;
                            }
                        }
                    }
                }

                clientStreamReader = new StreamReader(clientStream);
                clientStreamWriter = new StreamWriter(clientStream);
                clientStreamWriter.AutoFlush = true;

                // Validate that the IP address is within an accepted range.
                if (!ProxyFunctions.ValidateIP(arguments.AcceptedIPs, ip))
                {
                    ProxyFunctions.Log(LogWriter, SessionId, arguments.ConnectionId, "Connection rejected from {" + ip + "} due to its IP address.", Proxy.LogLevel.Warning, LogLevel);

                    await Functions.SendStreamStringAsync(clientStreamWriter, "500 IP address [" + ip + "] rejected.\r\n");
                    ProxyFunctions.Log(LogWriter, SessionId, arguments.ConnectionId, "S: 500 IP address [" + ip + "] rejected.", Proxy.LogLevel.Raw, LogLevel);

                    if (clientStream != null)
                        clientStream.Dispose();
                    if (client != null)
                        client.Close();

                    return;
                }

                ProxyFunctions.Log(LogWriter, SessionId, arguments.ConnectionId, "New connection established from {" + ip + "}.", Proxy.LogLevel.Information, LogLevel);

                // Send our welcome message.
                await Functions.SendStreamStringAsync(clientStreamWriter, "220 " + WelcomeMessage + "\r\n");
                ProxyFunctions.Log(LogWriter, SessionId, arguments.ConnectionId, "220 " + WelcomeMessage, Proxy.LogLevel.Raw, LogLevel);

                // Instantiate an SmtpClient for sending messages to the remote server.
                using (OpaqueMail.Net.SmtpClient smtpClient = new OpaqueMail.Net.SmtpClient(arguments.RemoteServerHostName, arguments.RemoteServerPort))
                {
                    smtpClient.EnableSsl = arguments.RemoteServerEnableSsl;
                    smtpClient.Credentials = arguments.RemoteServerCredential;

                    if (arguments.SmimeValidCertificates != null)
                        smtpClient.SmimeValidCertificates = arguments.SmimeValidCertificates;

                    // Loop through each received command.
                    string command = "";
                    bool stillReceiving = true;
                    while (Started && stillReceiving)
                    {
                        int bytesRead = await clientStreamReader.ReadAsync(buffer, 0, Constants.SMALLBUFFERSIZE);

                        if (bytesRead > 0)
                        {
                            bytesTransmitted += (ulong)bytesRead;

                            command += new string(buffer, 0, bytesRead);

                            if (command.EndsWith("\r\n"))
                            {
                                // Handle continuations of current "DATA" commands.
                                if (sending)
                                {
                                    // Handle the finalization of a "DATA" command.
                                    if (command.EndsWith("\r\n.\r\n"))
                                    {
                                        sending = false;

                                        string messageFrom = "", messageSubject = "", messageSize = "";
                                        try
                                        {
                                            string messageText = command.Substring(0, command.Length - 5);

                                            // Export the message to a local directory.
                                            if (!string.IsNullOrEmpty(arguments.ExportDirectory))
                                            {
                                                string messageId = Functions.ReturnBetween(messageText.ToLower(), "message-id: <", ">");
                                                if (string.IsNullOrEmpty(messageId))
                                                    messageId = Guid.NewGuid().ToString();

                                                string userName = "";
                                                if (smtpClient.Credentials != null)
                                                    userName = ((NetworkCredential)smtpClient.Credentials).UserName;

                                                string fileName = ProxyFunctions.GetExportFileName(arguments.ExportDirectory, messageId, arguments.InstanceId, userName);
                                                File.WriteAllText(fileName, messageText);
                                            }

                                            ReadOnlyMailMessage message = new ReadOnlyMailMessage(messageText, ReadOnlyMailMessageProcessingFlags.IncludeRawHeaders | ReadOnlyMailMessageProcessingFlags.IncludeRawBody);

                                            if (!string.IsNullOrEmpty(arguments.FixedFrom))
                                            {
                                                message.From = Functions.FromMailAddressString(arguments.FixedFrom)[0];

                                                if (message.RawHeaders.Contains("From: "))
                                                    message.RawHeaders = Functions.ReplaceBetween(message.RawHeaders, "From: ", "\r\n", Functions.ToMailAddressString(message.From));
                                                else
                                                    message.RawHeaders = message.RawHeaders.Replace("\r\nSubject: ", "\r\nFrom: " + Functions.ToMailAddressString(message.From) + "\r\nSubject: ");
                                            }

                                            if (!string.IsNullOrEmpty(arguments.FixedTo))
                                            {
                                                MailAddressCollection addresses = Functions.FromMailAddressString(arguments.FixedTo);
                                                foreach (MailAddress address in addresses)
                                                {
                                                    bool addressFound = false;
                                                    foreach (MailAddress existingAddress in message.To)
                                                    {
                                                        if (existingAddress.Address.ToUpper() == address.Address.ToUpper())
                                                            addressFound = true;
                                                    }

                                                    if (!addressFound)
                                                        message.To.Add(address);
                                                }

                                                if (message.RawHeaders.Contains("To: "))
                                                    message.RawHeaders = Functions.ReplaceBetween(message.RawHeaders, "To: ", "\r\n", Functions.ToMailAddressString(message.To));
                                                else
                                                    message.RawHeaders = message.RawHeaders.Replace("\r\nSubject: ", "\r\nTo: " + Functions.ToMailAddressString(message.To) + "\r\nSubject: ");
                                            }

                                            if (!string.IsNullOrEmpty(arguments.FixedCC))
                                            {
                                                MailAddressCollection addresses = Functions.FromMailAddressString(arguments.FixedCC);
                                                foreach (MailAddress address in addresses)
                                                {
                                                    bool addressFound = false;
                                                    foreach (MailAddress existingAddress in message.CC)
                                                    {
                                                        if (existingAddress.Address.ToUpper() == address.Address.ToUpper())
                                                            addressFound = true;
                                                    }

                                                    if (!addressFound)
                                                        message.CC.Add(address);
                                                }

                                                if (message.RawHeaders.Contains("CC: "))
                                                    message.RawHeaders = Functions.ReplaceBetween(message.RawHeaders, "CC: ", "\r\n", Functions.ToMailAddressString(message.To));
                                                else
                                                    message.RawHeaders = message.RawHeaders.Replace("\r\nSubject: ", "\r\nTo: " + Functions.ToMailAddressString(message.To) + "\r\nSubject: ");
                                            }

                                            if (!string.IsNullOrEmpty(arguments.FixedBcc))
                                            {
                                                MailAddressCollection addresses = Functions.FromMailAddressString(arguments.FixedBcc);
                                                foreach (MailAddress address in addresses)
                                                {
                                                    bool addressFound = false;
                                                    foreach (MailAddress existingAddress in message.Bcc)
                                                    {
                                                        if (existingAddress.Address.ToUpper() == address.Address.ToUpper())
                                                            addressFound = true;
                                                    }

                                                    if (!addressFound)
                                                        message.Bcc.Add(address);
                                                }
                                            }

                                            // Insert the fixed signature if one exists.
                                            if (!string.IsNullOrEmpty(arguments.FixedSignature))
                                            {
                                                int endBodyPos = message.Body.IndexOf("</BODY>", StringComparison.OrdinalIgnoreCase);
                                                if (endBodyPos > -1)
                                                    message.Body = message.Body.Substring(0, endBodyPos) + arguments.FixedSignature + message.Body.Substring(endBodyPos);
                                                else
                                                    message.Body += arguments.FixedSignature;
                                            }

                                            // If the received message is already signed or encrypted and we don't want to remove previous S/MIME operations, forward it as-is.
                                            string contentType = message.ContentType;
                                            if ((contentType.StartsWith("application/pkcs7-mime") || contentType.StartsWith("application/x-pkcs7-mime") || contentType.StartsWith("application/x-pkcs7-signature")) && !arguments.SmimeRemovePreviousOperations)
                                            {
                                                message.SmimeSigned = message.SmimeEncryptedEnvelope = message.SmimeTripleWrapped = false;
                                                await smtpClient.SendAsync(message);
                                                ProxyFunctions.Log(LogWriter, SessionId, arguments.ConnectionId, "S: " + message, Proxy.LogLevel.Raw, LogLevel);
                                            }
                                            else
                                            {
                                                messageFrom = message.From.Address;
                                                messageSubject = message.Subject;
                                                messageSize = message.Size.ToString("N0");

                                                ProxyFunctions.Log(LogWriter, SessionId, arguments.ConnectionId, "Forwarding message from {" + message.From.Address + "} with subject {" + message.Subject + "} and size of {" + message.Size.ToString("N0") + "}.", Proxy.LogLevel.Verbose, LogLevel);

                                                foreach (string toListAddress in toList)
                                                {
                                                    if (!message.AllRecipients.Contains(toListAddress))
                                                    {
                                                        message.AllRecipients.Add(toListAddress);
                                                        message.Bcc.Add(toListAddress);
                                                    }
                                                }

                                                // Attempt to sign and encrypt the envelopes of all messages, but still send if unable to.
                                                message.SmimeSettingsMode = SmimeSettingsMode.BestEffort;

                                                // Apply S/MIME settings.
                                                message.SmimeSigned = arguments.SmimeSigned;
                                                message.SmimeEncryptedEnvelope = arguments.SmimeEncryptedEnvelope;
                                                message.SmimeTripleWrapped = arguments.SmimeTripleWrapped;

                                                // Look up the S/MIME signing certificate for the current sender.  If it doesn't exist, create one.
                                                message.SmimeSigningCertificate = CertHelper.GetCertificateBySubjectName(StoreLocation.LocalMachine, message.From.Address);
                                                if (message.SmimeSigningCertificate == null)
                                                    message.SmimeSigningCertificate = CertHelper.CreateSelfSignedCertificate("E=" + message.From.Address, message.From.Address, StoreLocation.LocalMachine, true, 4096, 10);

                                                ProxyFunctions.Log(LogWriter, SessionId, arguments.ConnectionId, "C: " + message.RawHeaders + "\r\n\r\n" + message.RawBody, Proxy.LogLevel.Raw, LogLevel);

                                                // Send the message.
                                                await smtpClient.SendAsync(message.AsMailMessage());

                                                // Check the signing certificate's expiration to determine if we should send a reminder.
                                                if (arguments.SendCertificateReminders && message.SmimeSigningCertificate != null)
                                                {
                                                    string expirationDateString = message.SmimeSigningCertificate.GetExpirationDateString();
                                                    TimeSpan expirationTime = DateTime.Parse(expirationDateString) - DateTime.Now;
                                                    if (expirationTime.TotalDays < 30)
                                                    {
                                                        bool sendReminder = true;
                                                        if (CertificateReminders.ContainsKey(message.SmimeSigningCertificate))
                                                        {
                                                            TimeSpan timeSinceLastReminder = DateTime.Now - CertificateReminders[message.SmimeSigningCertificate];
                                                            if (timeSinceLastReminder.TotalHours < 24)
                                                                sendReminder = false;
                                                        }

                                                        // Send the reminder message.
                                                        if (sendReminder)
                                                        {
                                                            OpaqueMail.Net.MailMessage reminderMessage = new OpaqueMail.Net.MailMessage(message.From, message.From);
                                                            reminderMessage.Subject = "OpaqueMail: S/MIME Certificate Expires " + expirationDateString;
                                                            reminderMessage.Body = "Your OpaqueMail S/MIME Certificate will expire in " + ((int)expirationTime.TotalDays) + " days on " + expirationDateString + ".\r\n\r\n" +
                                                                "Certificate Subject Name: " + message.SmimeSigningCertificate.Subject + "\r\n" +
                                                                "Certificate Serial Number: " + message.SmimeSigningCertificate.SerialNumber + "\r\n" +
                                                                "Certificate Issuer: " + message.SmimeSigningCertificate.Issuer + "\r\n\r\n" +
                                                                "Please renew or enroll a new certificate to continue protecting your e-mail privacy.\r\n\r\n" +
                                                                "This is an automated message sent from the OpaqueMail Proxy on " + Functions.GetLocalFQDN() + ".  " +
                                                                "For more information, visit http://opaquemail.org/.";

                                                            reminderMessage.SmimeEncryptedEnvelope = message.SmimeEncryptedEnvelope;
                                                            reminderMessage.SmimeEncryptionOptionFlags = message.SmimeEncryptionOptionFlags;
                                                            reminderMessage.SmimeSettingsMode = message.SmimeSettingsMode;
                                                            reminderMessage.SmimeSigned = message.SmimeSigned;
                                                            reminderMessage.SmimeSigningCertificate = message.SmimeSigningCertificate;
                                                            reminderMessage.SmimeSigningOptionFlags = message.SmimeSigningOptionFlags;
                                                            reminderMessage.SmimeTripleWrapped = message.SmimeTripleWrapped;

                                                            ProxyFunctions.Log(LogWriter, SessionId, arguments.ConnectionId, "Certificate with Serial Number {" + message.SmimeSigningCertificate.SerialNumber + "} expiring.  Sending reminder to {" + message.From.Address + "}.", Proxy.LogLevel.Information, LogLevel);

                                                            await smtpClient.SendAsync(reminderMessage);

                                                            CertificateReminders[message.SmimeSigningCertificate] = DateTime.Now;
                                                        }
                                                    }
                                                }
                                            }

                                            await Functions.SendStreamStringAsync(clientStreamWriter, "250 Forwarded\r\n");
                                            ProxyFunctions.Log(LogWriter, SessionId, arguments.ConnectionId, "S: 250 Forwarded", Proxy.LogLevel.Raw, LogLevel);

                                            ProxyFunctions.Log(LogWriter, SessionId, arguments.ConnectionId, "Message from {" + message.From.Address + "} with subject {" + message.Subject + "} and size of {" + message.Size.ToString("N0") + "} successfully forwarded.", Proxy.LogLevel.Verbose, LogLevel);
                                        }
                                        catch (Exception ex)
                                        {
                                            // Report if an exception was encountering sending the message.
                                            Functions.SendStreamString(clientStreamWriter, "500 Error occurred when forwarding\r\n");
                                            ProxyFunctions.Log(LogWriter, SessionId, arguments.ConnectionId, "S: 500 Error occurred when forwarding", Proxy.LogLevel.Raw, LogLevel);

                                            if (arguments.DebugMode || System.Diagnostics.Debugger.IsAttached)
                                                ProxyFunctions.Log(LogWriter, SessionId, arguments.ConnectionId, "Error when forwarding message from {" + messageFrom + "} with subject {" + messageSubject + "} and size of {" + messageSize + "}.  Exception: " + ex.ToString(), Proxy.LogLevel.Error, LogLevel);
                                            else
                                                ProxyFunctions.Log(LogWriter, SessionId, arguments.ConnectionId, "Error when forwarding message from {" + messageFrom + "} with subject {" + messageSubject + "} and size of {" + messageSize + "}.  Exception: " + ex.Message, Proxy.LogLevel.Error, LogLevel);
                                        }
                                        command = "";
                                    }
                                }
                                else
                                {
                                    ProxyFunctions.Log(LogWriter, SessionId, arguments.ConnectionId, "C: " + new string(buffer, 0, bytesRead), Proxy.LogLevel.Raw, LogLevel);

                                    // Handle continuations of current "AUTH PLAIN" commands.
                                    if (inPlainAuth)
                                    {
                                        inPlainAuth = false;
                                        // Split up an AUTH PLAIN handshake into its components.
                                        string authString = Encoding.UTF8.GetString(Convert.FromBase64String(command));
                                        string[] authStringParts = authString.Split(new char[] { '\0' }, 3);
                                        if (authStringParts.Length > 2 && arguments.RemoteServerCredential == null)
                                            smtpClient.Credentials = new NetworkCredential(authStringParts[1], authStringParts[2]);

                                        await Functions.SendStreamStringAsync(clientStreamWriter, "235 OK\r\n");
                                        ProxyFunctions.Log(LogWriter, SessionId, arguments.ConnectionId, "S: 235 OK", Proxy.LogLevel.Raw, LogLevel);

                                        command = "";
                                    }
                                    // Handle continuations of current "AUTH LOGIN" commands.
                                    else if (inLoginAuth)
                                    {
                                        if (smtpClient.Credentials == null)
                                        {
                                            // Handle the username being received for the first time.
                                            smtpClient.Credentials = new NetworkCredential();
                                            ((NetworkCredential)smtpClient.Credentials).UserName = Functions.FromBase64(command.Substring(0, command.Length - 2));

                                            await Functions.SendStreamStringAsync(clientStreamWriter, "334 UGFzc3dvcmQ6\r\n");
                                            ProxyFunctions.Log(LogWriter, SessionId, arguments.ConnectionId, "S: 334 UGFzc3dvcmQ6", Proxy.LogLevel.Raw, LogLevel);
                                        }
                                        else
                                        {
                                            // Handle the password.
                                            inLoginAuth = false;
                                            ((NetworkCredential)smtpClient.Credentials).Password = Functions.FromBase64(command.Substring(0, command.Length - 2));

                                            await Functions.SendStreamStringAsync(clientStreamWriter, "235 OK\r\n");
                                            ProxyFunctions.Log(LogWriter, SessionId, arguments.ConnectionId, "S: 235 OK", Proxy.LogLevel.Raw, LogLevel);
                                        }
                                        command = "";
                                    }
                                    else
                                    {
                                        // Otherwise, look at the verb of the incoming command.
                                        string[] commandParts = command.Substring(0, command.Length - 2).Replace("\r", "").Split(new char[] { ' ' }, 2);

                                        if (LogLevel == Proxy.LogLevel.Verbose)
                                            ProxyFunctions.Log(LogWriter, SessionId, arguments.ConnectionId, "Command {" + commandParts[0] + "} received.", Proxy.LogLevel.Verbose, LogLevel);

                                        switch (commandParts[0].ToUpper())
                                        {
                                            case "AUTH":
                                                // Support authentication.
                                                if (commandParts.Length > 1)
                                                {
                                                    commandParts = command.Substring(0, command.Length - 2).Replace("\r", "").Split(new char[] { ' ' });
                                                    switch (commandParts[1].ToUpper())
                                                    {
                                                        case "PLAIN":
                                                            // Prepare to handle a continuation command.
                                                            inPlainAuth = true;
                                                            await Functions.SendStreamStringAsync(clientStreamWriter, "334 Proceed\r\n");
                                                            ProxyFunctions.Log(LogWriter, SessionId, arguments.ConnectionId, "S: 334 Proceed", Proxy.LogLevel.Raw, LogLevel);

                                                            break;
                                                        case "LOGIN":
                                                            inLoginAuth = true;
                                                            if (commandParts.Length > 2)
                                                            {
                                                                // Parse the username and request a password.
                                                                smtpClient.Credentials = new NetworkCredential();
                                                                ((NetworkCredential)smtpClient.Credentials).UserName = Functions.FromBase64(commandParts[2]);

                                                                await Functions.SendStreamStringAsync(clientStreamWriter, "334 UGFzc3dvcmQ6\r\n");
                                                                ProxyFunctions.Log(LogWriter, SessionId, arguments.ConnectionId, "S: 334 UGFzc3dvcmQ6", Proxy.LogLevel.Raw, LogLevel);
                                                            }
                                                            else
                                                            {
                                                                // Request a username only.
                                                                await Functions.SendStreamStringAsync(clientStreamWriter, "334 VXNlcm5hbWU6\r\n");
                                                                ProxyFunctions.Log(LogWriter, SessionId, arguments.ConnectionId, "S: 334 VXNlcm5hbWU6", Proxy.LogLevel.Raw, LogLevel);
                                                            }
                                                            break;
                                                        default:
                                                            // Split up an AUTH PLAIN handshake into its components.
                                                            string authString = Encoding.UTF8.GetString(Convert.FromBase64String(commandParts[1].Substring(6)));
                                                            string[] authStringParts = authString.Split(new char[] { '\0' }, 3);
                                                            if (authStringParts.Length > 2 && arguments.RemoteServerCredential == null)
                                                                smtpClient.Credentials = new NetworkCredential(authStringParts[1], authStringParts[2]);

                                                            await Functions.SendStreamStringAsync(clientStreamWriter, "235 OK\r\n");
                                                            ProxyFunctions.Log(LogWriter, SessionId, arguments.ConnectionId, "S: 235 OK", Proxy.LogLevel.Raw, LogLevel);
                                                            break;
                                                    }
                                                }
                                                else
                                                {
                                                    await Functions.SendStreamStringAsync(clientStreamWriter, "500 Unknown verb\r\n");
                                                    ProxyFunctions.Log(LogWriter, SessionId, arguments.ConnectionId, "S: 500 Unknown verb", Proxy.LogLevel.Raw, LogLevel);
                                                }
                                                break;
                                            case "DATA":
                                                // Prepare to handle continuation data.
                                                sending = true;
                                                command = command.Substring(6);
                                                await Functions.SendStreamStringAsync(clientStreamWriter, "354 Send message content; end with <CRLF>.<CRLF>\r\n");
                                                ProxyFunctions.Log(LogWriter, SessionId, arguments.ConnectionId, "S: 354 Send message content; end with <CRLF>.<CRLF>", Proxy.LogLevel.Raw, LogLevel);
                                                break;
                                            case "EHLO":
                                                // Proceed with the login and send a list of supported commands.
                                                if (commandParts.Length > 1)
                                                    identity = commandParts[1] + " ";
                                                if (arguments.LocalEnableSsl)
                                                {
                                                    await Functions.SendStreamStringAsync(clientStreamWriter, "250-Hello " + identity + "[" + ip + "], please proceed\r\n250-AUTH LOGIN PLAIN\r\n250-RSET\r\n250 STARTTLS\r\n");
                                                    ProxyFunctions.Log(LogWriter, SessionId, arguments.ConnectionId, "S: 250-Hello " + identity + "[" + ip + "], please proceed\r\n250-AUTH LOGIN PLAIN\r\n250-RSET\r\n250 STARTTLS", Proxy.LogLevel.Raw, LogLevel);
                                                }
                                                else
                                                {
                                                    await Functions.SendStreamStringAsync(clientStreamWriter, "250-Hello " + identity + "[" + ip + "], please proceed\r\n250-AUTH LOGIN PLAIN\r\n250 RSET\r\n");
                                                    ProxyFunctions.Log(LogWriter, SessionId, arguments.ConnectionId, "S: 250-Hello " + identity + "[" + ip + "], please proceed\r\n250-AUTH LOGIN PLAIN\r\n250 RSET", Proxy.LogLevel.Raw, LogLevel);
                                                }
                                                break;
                                            case "HELO":
                                                // Proceed with the login.
                                                if (commandParts.Length > 1)
                                                    identity = commandParts[1];
                                                await Functions.SendStreamStringAsync(clientStreamWriter, "250 Hello " + identity + " [" + ip + "], please proceed\r\n");
                                                ProxyFunctions.Log(LogWriter, SessionId, arguments.ConnectionId, "S: Hello " + identity + " [" + ip + "], please proceed", Proxy.LogLevel.Raw, LogLevel);
                                                break;
                                            case "MAIL":
                                            case "SAML":
                                            case "SEND":
                                            case "SOML":
                                                // Accept the from address.
                                                if (commandParts.Length > 1 && commandParts[1].Length > 5)
                                                    fromAddress = commandParts[1].Substring(5);
                                                await Functions.SendStreamStringAsync(clientStreamWriter, "250 OK\r\n");
                                                ProxyFunctions.Log(LogWriter, SessionId, arguments.ConnectionId, "S: 250 OK", Proxy.LogLevel.Raw, LogLevel);
                                                break;
                                            case "NOOP":
                                                // Prolong the current session.
                                                await Functions.SendStreamStringAsync(clientStreamWriter, "250 Still here\r\n");
                                                ProxyFunctions.Log(LogWriter, SessionId, arguments.ConnectionId, "S: 250 Still here", Proxy.LogLevel.Raw, LogLevel);
                                                break;
                                            case "PASS":
                                                // Support authentication.
                                                if (commandParts.Length > 1 && arguments.RemoteServerCredential == null)
                                                    ((NetworkCredential)smtpClient.Credentials).Password = commandParts[1];
                                                await Functions.SendStreamStringAsync(clientStreamWriter, "235 OK\r\n");
                                                ProxyFunctions.Log(LogWriter, SessionId, arguments.ConnectionId, "S: 235 OK", Proxy.LogLevel.Raw, LogLevel);
                                                break;
                                            case "QUIT":
                                                // Wait one second then force the current connection closed.
                                                await Functions.SendStreamStringAsync(clientStreamWriter, "221 Bye\r\n");
                                                ProxyFunctions.Log(LogWriter, SessionId, arguments.ConnectionId, "S: 221 Bye", Proxy.LogLevel.Raw, LogLevel);

                                                Thread.Sleep(1000);

                                                if (clientStream != null)
                                                    clientStream.Dispose();
                                                if (client != null)
                                                    client.Close();
                                                break;
                                            case "RCPT":
                                                // Acknolwedge recipients.
                                                if (commandParts.Length > 1 && commandParts[1].Length > 6)
                                                    toList.Add(commandParts[1].Substring(5, commandParts[1].Length - 6));
                                                await Functions.SendStreamStringAsync(clientStreamWriter, "250 OK\r\n");
                                                ProxyFunctions.Log(LogWriter, SessionId, arguments.ConnectionId, "S: 250 OK", Proxy.LogLevel.Raw, LogLevel);
                                                break;
                                            case "RSET":
                                                // Reset the current message arguments.
                                                fromAddress = "";
                                                toList.Clear();

                                                await Functions.SendStreamStringAsync(clientStreamWriter, "250 OK\r\n");
                                                ProxyFunctions.Log(LogWriter, SessionId, arguments.ConnectionId, "S: 250 OK", Proxy.LogLevel.Raw, LogLevel);
                                                break;
                                            case "STARTTLS":
                                                // If supported, upgrade the session's security through a TLS handshake.
                                                if (arguments.LocalEnableSsl)
                                                {
                                                    await Functions.SendStreamStringAsync(clientStreamWriter, "220 Go ahead\r\n");
                                                    ProxyFunctions.Log(LogWriter, SessionId, arguments.ConnectionId, "S: 220 Go ahead", Proxy.LogLevel.Raw, LogLevel);

                                                    if (!(clientStream is SslStream))
                                                    {
                                                        clientStream = new SslStream(clientStream);
                                                        ((SslStream)clientStream).AuthenticateAsServer(arguments.Certificate);

                                                        clientStreamReader = new StreamReader(clientStream);
                                                        clientStreamWriter = new StreamWriter(clientStream);
                                                        clientStreamWriter.AutoFlush = true;
                                                    }
                                                }
                                                else
                                                {
                                                    await Functions.SendStreamStringAsync(clientStreamWriter, "500 Unknown verb\r\n");
                                                    ProxyFunctions.Log(LogWriter, SessionId, arguments.ConnectionId, "S: 500 Unknown verb", Proxy.LogLevel.Raw, LogLevel);
                                                }
                                                break;
                                            case "USER":
                                                // Support authentication.
                                                if (commandParts.Length > 1 && arguments.RemoteServerCredential == null)
                                                    ((NetworkCredential)smtpClient.Credentials).UserName = commandParts[1];

                                                await Functions.SendStreamStringAsync(clientStreamWriter, "235 OK\r\n");
                                                ProxyFunctions.Log(LogWriter, SessionId, arguments.ConnectionId, "S: 235 OK", Proxy.LogLevel.Raw, LogLevel);
                                                break;
                                            case "VRFY":
                                                // Notify that we can't verify addresses.
                                                await Functions.SendStreamStringAsync(clientStreamWriter, "252 I'm just a proxy\r\n");
                                                ProxyFunctions.Log(LogWriter, SessionId, arguments.ConnectionId, "S: 252 I'm just a proxy", Proxy.LogLevel.Raw, LogLevel);
                                                break;
                                            default:
                                                await Functions.SendStreamStringAsync(clientStreamWriter, "500 Unknown verb\r\n");
                                                ProxyFunctions.Log(LogWriter, SessionId, arguments.ConnectionId, "S: 500 Unknown verb", Proxy.LogLevel.Raw, LogLevel);
                                                break;
                                        }

                                        command = "";
                                    }
                                }
                            }
                        }
                        else
                            stillReceiving = false;
                    }
                }
            }
            catch (ObjectDisposedException)
            {
                // Ignore either stream being closed.
            }
            catch (SocketException ex)
            {
                if (arguments.DebugMode || System.Diagnostics.Debugger.IsAttached)
                    ProxyFunctions.Log(LogWriter, SessionId, arguments.ConnectionId, "Exception communicating with {" + arguments.RemoteServerHostName + "} on port {" + arguments.RemoteServerPort + "}: " + ex.ToString(), Proxy.LogLevel.Error, LogLevel);
                else
                    ProxyFunctions.Log(LogWriter, SessionId, arguments.ConnectionId, "Exception communicating with {" + arguments.RemoteServerHostName + "} on port {" + arguments.RemoteServerPort + "}: " + ex.Message, Proxy.LogLevel.Error, LogLevel);
            }
            catch (Exception ex)
            {
                if (arguments.DebugMode || System.Diagnostics.Debugger.IsAttached)
                    ProxyFunctions.Log(LogWriter, SessionId, arguments.ConnectionId, "Exception: " + ex.ToString(), Proxy.LogLevel.Error, LogLevel);
                else
                    ProxyFunctions.Log(LogWriter, SessionId, arguments.ConnectionId, "Exception: " + ex.Message, Proxy.LogLevel.Error, LogLevel);
            }
            finally
            {
                ProxyFunctions.Log(LogWriter, SessionId, arguments.ConnectionId, "Connection from {" + ip + "} closed after transmitting {" + bytesTransmitted.ToString("N0") + "} bytes.", Proxy.LogLevel.Information, LogLevel);

                // Clean up after any unexpectedly closed connections.
                if (clientStreamWriter != null)
                    clientStreamWriter.Dispose();
                if (clientStreamReader != null)
                    clientStreamReader.Dispose();
                if (clientStream != null)
                    clientStream.Dispose();
                if (client != null)
                    client.Close();
            }
        }
示例#16
0
        public async Task<bool> readPackageAsync(StorageFile file)
        {
            this.deckDescriptionFound = false;
            this.deck.filename = file.Name;
            bool result = false;
            //Locate Archive based on this.packagePath
            var folder = ApplicationData.Current.TemporaryFolder;
            //Open Archive
            Stream stream = await file.OpenStreamForReadAsync();
            using (ZipArchive archive = new ZipArchive(stream, ZipArchiveMode.Read))
            {
                foreach (ZipArchiveEntry en in archive.Entries)
                {             //Iterate through Entries
                    if (en.FullName.Contains("deckdescription.xml"))
                    {
                        char[] output = new char[en.Length];
                        this.deckDescriptionFound = true;
                        //Open deckdescription.xml and save it into deckXml
                        using (StreamReader sr = new StreamReader(en.Open()))
                        {
                            await sr.ReadAsync(output, 0, (int)en.Length);
                            //There was some weirdness here, which I'm documenting for the sake of my Memento-esque memory.
                            //We were hitting all kinds of weird XMLExceptions at the end of certain files (XMLExceptions around the Null character 0x00).
                            //The UTF-8 files effected always involved some characters that required two bytes. We'd hit this exception after the closing tag ("</deck>")
                            //When I inspected these files in a Hex editor, there were never any null characters at the end of the file, which was weird.
                            //My hypothesis was that when we built the output char array using en.Length, that length was returning the length in Bytes, which 
                            //was not the same as the number of characters (since some required 2 bytes). The result was that the output array was longer
                            //than the string that it was representing, and those extra slots were NULL (excess length was a function of the number of characters 
                            //requiring 2 bytes). Thus, I am trimming the null chars off the end.
                            //tl;dr: ZipArchiveEntry.Length doesn't actually return the number of characters in the file. This seems obvious in retrospect. 
                            this.deckXml = new String(output).TrimEnd('\0');
                        }
                    }
                    if (en.FullName.EndsWith(".jpg") || en.FullName.EndsWith(".jpeg") || en.FullName.EndsWith(".png"))
                    {
                        //Copy Images to LocalStorage - Tmp Folder
                        using (Stream picdata = en.Open())
                        {
                            StorageFile outfile = await folder.CreateFileAsync(en.Name, CreationCollisionOption.ReplaceExisting);
                            using (Stream outputfilestream = await outfile.OpenStreamForWriteAsync())
                            {
                                await picdata.CopyToAsync(outputfilestream);
                                await outputfilestream.FlushAsync(); //flush makes sure all the bits are written
                            }

                        }
                    }
                }
            }
            //kick off processXml, return result of that.
            if (this.deckDescriptionFound)
            {
                try
                {
                    result = processXml();
                }
                catch (XmlException e)
                {
                    result = false;
                }
            }
            else
            {
                result = false;
            }
            return result;
        }
        private async Task<Document> LoadFileAsync(ILoader loader, string path, CancellationToken cancellationToken)
        {
            try
            {
                using (var file = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, true))
                using (var reader = new StreamReader(file))
                {
                    var count = 0;
                    var buffer = new char[4096];
                    while ((count = await reader.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false)) > 0)
                    {
                        // Check for cancellation
                        cancellationToken.ThrowIfCancellationRequested();

                        // Add the data to the document
                        if (!loader.AddData(buffer, count))
                        {
                            throw new IOException("The data could not be added to the loader.");
                        }
                    }

                    return loader.ConvertToDocument();
                }
            }
            catch
            {
                loader.Release();
                throw;
            }
        }
 private static async Task<char> ReadChar(StreamReader sr, char[] buf)
 {
     await sr.ReadAsync(buf, 0, 1);
     return buf[0];
 }
示例#19
0
 /// <summary>
 /// Loads a file using background document loader, background task (outside UI thread)
 /// </summary>
 /// <param name="loader">ILoader instance created with CreateLoader() method</param>
 /// <param name="path"></param>
 /// <param name="cancellationToken"></param>
 /// <param name="encoding"></param>
 /// <param name="detectBOM"></param>
 /// <returns></returns>
 private async Task<Document> LoadDocument(ILoader loader, string path, CancellationToken cancellationToken, Encoding encoding = null, bool detectBOM = true) {
     var buffer = new char[LoadingBufferSize];
     var count = 0;
     try {
         using (var file = new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite, bufferSize: LoadingBufferSize, useAsync: true)) {
             if (encoding != null) Encoding = encoding;
             else if (Encoding == null) Encoding = Encoding.UTF8;
             using (var reader = new StreamReader(file, Encoding, detectBOM, LoadingBufferSize)) {
                 while ((count = await reader.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false)) > 0) {
                     cancellationToken.ThrowIfCancellationRequested();
                     if (!loader.AddData(buffer, count)) throw new IOException("The data could not be added to the loader.");
                 }
                 return loader.ConvertToDocument();
             }
         }
     } catch {
         loader.Release();
         throw;
     }
 }
        private async void monitorStream(StreamReader streamReader, StandardStreamType type) {
            try {
                char[] buffer = new char[1024];

                using (streamReader)
                    while (!streamReader.EndOfStream) {
                        int read = await streamReader.ReadAsync(buffer, 0, 1024);
                        if (read > 0)
                            OnStandardDataReceived(streamReader, new StandardDataReceivedEventArgs(type, new string(buffer, 0, read)));
                    }
            }
            catch (ObjectDisposedException) { } // in case the stream gets closed elsewhere
            catch (NullReferenceException) { }

            StandardInputEnabled = false;

            Debug.WriteLine("end standard " + type + " stream monitor");
        }
示例#21
0
        /// <summary>
        /// Sends the specified message to an SMTP server for delivery without making modifications to the body.
        /// Necessary because the standard SmtpClient.Send() may slightly alter messages, invalidating signatures.
        /// </summary>
        /// <param name="message">An OpaqueMail.MailMessage that contains the message to send.</param>
        private async Task SmimeSendRawAsync(MailMessage message)
        {
            // Connect to the SMTP server.
            TcpClient SmtpTcpClient = new TcpClient();
            SmtpTcpClient.Connect(Host, Port);
            Stream SmtpStream = SmtpTcpClient.GetStream();

            // Use stream readers and writers to simplify I/O.
            StreamReader reader = new StreamReader(SmtpStream);
            StreamWriter writer = new StreamWriter(SmtpStream);
            writer.AutoFlush = true;

            // Read the welcome message.
            string response = await reader.ReadLineAsync();

            // Send EHLO and find out server capabilities.
            await writer.WriteLineAsync("EHLO " + Host);
            char[] charBuffer = new char[Constants.SMALLBUFFERSIZE];
            int bytesRead = await reader.ReadAsync(charBuffer, 0, Constants.SMALLBUFFERSIZE);
            response = new string(charBuffer, 0, bytesRead);
            if (!response.StartsWith("2"))
                throw new SmtpException("Unable to connect to remote server '" + Host + "'.  Sent 'EHLO' and received '" + response + "'.");

            // Stand up a TLS/SSL stream.
            if (EnableSsl)
            {
                await writer.WriteLineAsync("STARTTLS");
                response = await reader.ReadLineAsync();
                if (!response.StartsWith("2"))
                    throw new SmtpException("Unable to start TLS/SSL protection with '" + Host + "'.  Received '" + response + "'.");

                SmtpStream = new SslStream(SmtpStream);
                ((SslStream)SmtpStream).AuthenticateAsClient(Host);

                reader = new StreamReader(SmtpStream);
                writer = new StreamWriter(SmtpStream);
                writer.AutoFlush = true;
            }

            // Authenticate using the AUTH LOGIN command.
            if (Credentials != null)
            {
                NetworkCredential cred = (NetworkCredential)Credentials;
                await writer.WriteLineAsync("AUTH LOGIN");
                response = await reader.ReadLineAsync();
                if (!response.StartsWith("3"))
                    throw new SmtpException("Unable to authenticate with server '" + Host + "'.  Received '" + response + "'.");
                await writer.WriteLineAsync(Functions.ToBase64String(cred.UserName));
                response = await reader.ReadLineAsync();
                await writer.WriteLineAsync(Functions.ToBase64String(cred.Password));
                response = await reader.ReadLineAsync();
                if (!response.StartsWith("2"))
                    throw new SmtpException("Unable to authenticate with server '" + Host + "'.  Received '" + response + "'.");
            }

            // Build our raw headers block.
            StringBuilder rawHeaders = new StringBuilder(Constants.SMALLSBSIZE);

            // Specify who the message is from.
            rawHeaders.Append(Functions.SpanHeaderLines("From: " + Functions.EncodeMailHeader(Functions.ToMailAddressString(message.From))) + "\r\n");
            await writer.WriteLineAsync("MAIL FROM:<" + message.From.Address + ">");
            response = await reader.ReadLineAsync();
            if (!response.StartsWith("2"))
                throw new SmtpException("Exception communicating with server '" + Host + "'.  Sent 'MAIL FROM' and received '" + response + "'.");

            // Identify all recipients of the message.
            if (message.To.Count > 0)
                rawHeaders.Append(Functions.SpanHeaderLines("To: " + Functions.EncodeMailHeader(Functions.ToMailAddressString(message.To))) + "\r\n");
            foreach (MailAddress address in message.To)
            {
                await writer.WriteLineAsync("RCPT TO:<" + address.Address + ">");
                response = await reader.ReadLineAsync();
                if (!response.StartsWith("2"))
                    throw new SmtpException("Exception communicating with server '" + Host + "'.  Sent 'RCPT TO' and received '" + response + "'.");
            }

            if (message.CC.Count > 0)
                rawHeaders.Append(Functions.SpanHeaderLines("CC: " + Functions.EncodeMailHeader(Functions.ToMailAddressString(message.CC))) + "\r\n");
            foreach (MailAddress address in message.CC)
            {
                await writer.WriteLineAsync("RCPT TO:<" + address.Address + ">");
                response = await reader.ReadLineAsync();
                if (!response.StartsWith("2"))
                    throw new SmtpException("Exception communicating with server '" + Host + "'.  Sent 'RCPT TO' and received '" + response + "'.");
            }

            foreach (MailAddress address in message.Bcc)
            {
                await writer.WriteLineAsync("RCPT TO:<" + address.Address + ">");
                response = await reader.ReadLineAsync();
                if (!response.StartsWith("2"))
                    throw new SmtpException("Exception communicating with server '" + Host + "'.  Sent 'RCPT TO' and received '" + response + "'.");
            }

            // Send the raw message.
            await writer.WriteLineAsync("DATA");
            response = await reader.ReadLineAsync();
            if (!response.StartsWith("3"))
                throw new SmtpException("Exception communicating with server '" + Host + "'.  Sent 'DATA' and received '" + response + "'.");

            // If a read-only mail message is passed in with its raw headers and body, save a few steps by sending that directly.
            if (message is ReadOnlyMailMessage)
                await writer.WriteAsync(((ReadOnlyMailMessage)message).RawHeaders + "\r\n" + ((ReadOnlyMailMessage)message).RawBody + "\r\n.\r\n");
            else
            {
                rawHeaders.Append(Functions.SpanHeaderLines("Subject: " + Functions.EncodeMailHeader(message.Subject)) + "\r\n");
                foreach (string rawHeader in message.Headers)
                {
                    switch (rawHeader.ToUpper())
                    {
                        case "BCC":
                        case "CC":
                        case "FROM":
                        case "SUBJECT":
                        case "TO":
                            break;
                        default:
                            rawHeaders.Append(Functions.SpanHeaderLines(rawHeader + ": " + message.Headers[rawHeader]) + "\r\n");
                            break;
                    }
                }

                await writer.WriteAsync(rawHeaders.ToString() + "\r\n" + message.Body + "\r\n.\r\n");
            }

            response = await reader.ReadLineAsync();
            if (!response.StartsWith("2"))
                throw new SmtpException("Exception communicating with server '" + Host + "'.  Sent message and received '" + response + "'.");

            // Clean up this connection.
            await writer.WriteLineAsync("QUIT");

            writer.Dispose();
            reader.Dispose();

            SmtpStream.Dispose();
            SmtpTcpClient.Close();
        }
示例#22
0
 public static async Task <int> ReadAsync(this StreamReader reader, char[] buffer)
 {
     return(await reader.ReadAsync(buffer, 0, buffer.Length));
 }
示例#23
0
        /// <summary>
        /// Sends the specified message to an SMTP server for delivery without making modifications to the body.
        /// Necessary because the standard SmtpClient.Send() may slightly alter messages, invalidating signatures.
        /// </summary>
        /// <param name="message">An OpaqueMail.MailMessage that contains the message to send.</param>
        private async Task SmimeSendRawAsync(MailMessage message)
        {
            // Connect to the SMTP server.
            TcpClient SmtpTcpClient = new TcpClient();
            SmtpTcpClient.Connect(Host, Port);
            Stream SmtpStream = SmtpTcpClient.GetStream();

            // Use stream readers and writers to simplify I/O.
            StreamReader reader = new StreamReader(SmtpStream);
            StreamWriter writer = new StreamWriter(SmtpStream);
            writer.AutoFlush = true;

            // Read the welcome message.
            string response = await reader.ReadLineAsync();

            // Send EHLO and find out server capabilities.
            await writer.WriteLineAsync("EHLO " + Host);
            char[] charBuffer = new char[Constants.SMALLBUFFERSIZE];
            int bytesRead = await reader.ReadAsync(charBuffer, 0, Constants.SMALLBUFFERSIZE);
            response = new string(charBuffer, 0, bytesRead);
            if (!response.StartsWith("2"))
                throw new SmtpException("Unable to connect to remote server '" + Host + "'.  Sent 'EHLO' and received '" + response + "'.");

            // Stand up a TLS/SSL stream.
            if (EnableSsl)
            {
                await writer.WriteLineAsync("STARTTLS");
                response = await reader.ReadLineAsync();
                if (!response.StartsWith("2"))
                    throw new SmtpException("Unable to start TLS/SSL protection with '" + Host + "'.  Received '" + response + "'.");

                SmtpStream = new SslStream(SmtpStream);
                ((SslStream)SmtpStream).AuthenticateAsClient(Host);

                reader = new StreamReader(SmtpStream);
                writer = new StreamWriter(SmtpStream);
                writer.AutoFlush = true;

                await writer.WriteLineAsync("EHLO " + Host);
                bytesRead = await reader.ReadAsync(charBuffer, 0, Constants.SMALLBUFFERSIZE);
                response = new string(charBuffer, 0, bytesRead);
            }

            // Authenticate using the AUTH LOGIN command.
            if (Credentials != null)
            {
                NetworkCredential cred = (NetworkCredential)Credentials;
                await writer.WriteLineAsync("AUTH LOGIN");
                response = await reader.ReadLineAsync();
                if (!response.StartsWith("3"))
                    throw new SmtpException("Unable to authenticate with server '" + Host + "'.  Received '" + response + "'.");
                await writer.WriteLineAsync(Functions.ToBase64String(cred.UserName));
                response = await reader.ReadLineAsync();
                await writer.WriteLineAsync(Functions.ToBase64String(cred.Password));
                response = await reader.ReadLineAsync();
                if (!response.StartsWith("2"))
                    throw new SmtpException("Unable to authenticate with server '" + Host + "'.  Received '" + response + "'.");
            }

            // Build our raw headers block.
            StringBuilder rawHeaders = new StringBuilder(Constants.SMALLSBSIZE);

            // Specify who the message is from.
            rawHeaders.Append(Functions.SpanHeaderLines("From: " + Functions.EncodeMailHeader(Functions.ToMailAddressString(message.From))) + "\r\n");
            await writer.WriteLineAsync("MAIL FROM:<" + message.From.Address + ">");
            response = await reader.ReadLineAsync();
            if (!response.StartsWith("2"))
                throw new SmtpException("Exception communicating with server '" + Host + "'.  Sent 'MAIL FROM' and received '" + response + "'.");

            // Identify all recipients of the message.
            if (message.To.Count > 0)
                rawHeaders.Append(Functions.SpanHeaderLines("To: " + Functions.EncodeMailHeader(message.To.ToString())) + "\r\n");
            foreach (MailAddress address in message.To)
            {
                await writer.WriteLineAsync("RCPT TO:<" + address.Address + ">");
                response = await reader.ReadLineAsync();
                if (!response.StartsWith("2"))
                    throw new SmtpException("Exception communicating with server '" + Host + "'.  Sent 'RCPT TO' and received '" + response + "'.");
            }

            if (message.CC.Count > 0)
                rawHeaders.Append(Functions.SpanHeaderLines("CC: " + Functions.EncodeMailHeader(message.CC.ToString())) + "\r\n");
            foreach (MailAddress address in message.CC)
            {
                await writer.WriteLineAsync("RCPT TO:<" + address.Address + ">");
                response = await reader.ReadLineAsync();
                if (!response.StartsWith("2"))
                    throw new SmtpException("Exception communicating with server '" + Host + "'.  Sent 'RCPT TO' and received '" + response + "'.");
            }

            foreach (MailAddress address in message.Bcc)
            {
                await writer.WriteLineAsync("RCPT TO:<" + address.Address + ">");
                response = await reader.ReadLineAsync();
                if (!response.StartsWith("2"))
                    throw new SmtpException("Exception communicating with server '" + Host + "'.  Sent 'RCPT TO' and received '" + response + "'.");
            }

            // Ensure a content type is set.
            if (string.IsNullOrEmpty(message.ContentType))
            {
                if (Functions.AppearsHTML(message.Body))
                    message.ContentType = "text/html";
                else
                    message.ContentType = "text/plain";
            }
            message.Headers["Content-Type"] = message.ContentType + (!string.IsNullOrEmpty(message.CharSet) ? "; charset=\"" + message.CharSet + "\"" : "");

            // If the body hasn't been processed, handle encoding of extended characters.
            if (string.IsNullOrEmpty(message.RawBody))
            {
                bool extendedCharacterFound = false;
                foreach (char headerCharacter in message.Body.ToCharArray())
                {
                    if (headerCharacter > 127)
                    {
                        extendedCharacterFound = true;
                        break;
                    }
                }

                if (extendedCharacterFound)
                {
                    message.Headers["Content-Transfer-Encoding"] = "base64";
                    message.Body = Functions.ToBase64String(message.Body);
                }

                message.RawBody = message.Body;
            }

            // Send the raw message.
            await writer.WriteLineAsync("DATA");
            response = await reader.ReadLineAsync();
            if (!response.StartsWith("3"))
                throw new SmtpException("Exception communicating with server '" + Host + "'.  Sent 'DATA' and received '" + response + "'.");

            rawHeaders.Append(Functions.SpanHeaderLines("Subject: " + Functions.EncodeMailHeader(message.Subject)) + "\r\n");
            foreach (string rawHeader in message.Headers)
            {
                switch (rawHeader.ToUpper())
                {
                    case "BCC":
                    case "CC":
                    case "FROM":
                    case "SUBJECT":
                    case "TO":
                        break;
                    default:
                        rawHeaders.Append(Functions.SpanHeaderLines(rawHeader + ": " + message.Headers[rawHeader]) + "\r\n");
                        break;
                }
            }

            await writer.WriteAsync(rawHeaders.ToString() + "\r\n" + message.RawBody + "\r\n.\r\n");

            response = await reader.ReadLineAsync();
            if (!response.StartsWith("2"))
                throw new SmtpException("Exception communicating with server '" + Host + "'.  Sent message and received '" + response + "'.");

            // Clean up this connection.
            await writer.WriteLineAsync("QUIT");

            writer.Dispose();
            reader.Dispose();

            SmtpStream.Dispose();
            SmtpTcpClient.Close();
        }
        public async Task<TryResult<string>> TryReadTextFileAsync(string path, CancellationToken cancellationToken)
        {
            var contentStringBuilder = new StringBuilder();
            var operationSucceeded = await TryReadFileCommonAsync(path, async stream =>
            {
                using (var reader = new StreamReader(stream))
                {
                    var buffer = new char[BufferSize];

                    while (reader.Peek() > 0)
                    {
                        if (cancellationToken.IsCancellationRequested)
                            return false;

                        var charsRead = await reader.ReadAsync(buffer, 0, BufferSize);

                        contentStringBuilder.Append(buffer, 0, charsRead);
                    }
                    return true;
                };
            }).ConfigureAwait(false);

            return TryResult.Create(operationSucceeded, operationSucceeded ? contentStringBuilder.ToString() : string.Empty);
        }
示例#25
0
 /// <summary>
 /// Returns string representation of message sent over stream.
 /// </summary>
 /// <param name="streamReader">StreamReader to receive message from.</param>
 /// <param name="buffer">A character array to streamline bit shuffling.</param>
 /// <returns>Any text read from the stream connection.</returns>
 public async static Task<string> ReadStreamStringAsync(StreamReader streamReader, char[] buffer)
 {
     int bytesRead = await streamReader.ReadAsync(buffer, 0, buffer.Length);
     return new string(buffer, 0, bytesRead);
 }
 public async Task CopyFilesAsync(StreamReader source, StreamWriter destination)
 {
     _logger.Info("[NextPvr] Start CopyFiles Async");
     char[] buffer = new char[0x1000];
     int numRead;
     while ((numRead = await source.ReadAsync(buffer, 0, buffer.Length)) != 0)
     {
         await destination.WriteAsync(buffer, 0, numRead);
     }
 }
示例#27
0
 /// <summary>
 /// Returns string representation of message sent over stream.
 /// </summary>
 /// <param name="streamReader">StreamReader to receive message from.</param>
 /// <param name="buffer">A character array to streamline bit shuffling.</param>
 /// <param name="maximumBytes">Maximum number of bytes to receive.</param>
 /// <returns>Any text read from the stream connection.</returns>
 public async static Task<string> ReadStreamStringAsync(StreamReader streamReader, char[] buffer, int maximumBytes)
 {
     int bytesRead = await streamReader.ReadAsync(buffer, 0, maximumBytes);
     return new string(buffer, 0, bytesRead);
 }
示例#28
0
        public async Task<Dictionary<string, UInt16>> readFileAsync()
        {
            FileStream inFS = null;
            try
            {
                inFS = new FileStream(inFileName, FileMode.Open, FileAccess.Read);
                using (StreamReader txtReader = new StreamReader(inFS))
                {
                    inBuffer = new char[txtReader.BaseStream.Length];
                    await txtReader.ReadAsync(inBuffer, 0, (int)inBuffer.Length);
                }
                foreach (char c in inBuffer)
                {
                    /*if (Char.IsControl(c) || Char.IsHighSurrogate(c) || Char.IsLowSurrogate(c) ||
                        Char.IsSeparator(c) || Char.IsSurrogate(c))
                    {
                        //do nothig here
                    }
                    else
                    {
                        if (lettersDic.ContainsKey(c.ToString()))
                            lettersDic[c.ToString()]++;
                        else
                            lettersDic[c.ToString()] = 1;
                    }*/

                    switch (c)
                    {
                        case '\n':
                        case '\t':
                        case '\f':
                        case '\r':
                        case '\v':
                        case ' ':
                            break;
                        default:

                            if (lettersDic.ContainsKey(c.ToString()))
                                lettersDic[c.ToString()]++;
                            else
                                lettersDic[c.ToString()] = 1;
                            break;
                    }
                }
            }
            finally
            {
                if (inFS != null)
                    inFS.Dispose();
            }

            string outputString = "";
            foreach (string s in lettersDic.Keys)
            {
                outputString += "Key: " + s + "\tTimes: " + lettersDic[s] + "\n";
            }

            //using(new FileStream(inFileName, FileMode.Open, FileAccess.Read),
            //                                 new FileStream(outFilename, FileMode.Create, FileAccess.Write)
            return lettersDic;
        }
示例#29
0
        /// <summary>
        /// Save an embedded resource file to the file system.
        /// </summary>
        /// <param name="resourceFileName">Identifier of the embedded resource.</param>
        /// <param name="resourcePath">Full path to the embedded resource.</param>
        /// <param name="filePath">File system location to save the file.</param>
        private async void SaveResourceFile(string resourceFileName, string resourcePath, string filePath)
        {
            if (!File.Exists(filePath + "\\" + resourceFileName))
            {
                using (StreamReader resourceReader = new StreamReader(Assembly.GetAssembly(GetType()).GetManifestResourceStream(resourcePath + "." + resourceFileName)))
                {
                    using (StreamWriter fileWriter = new StreamWriter(filePath + "\\" + resourceFileName))
                    {
                        char[] buffer = new char[Constants.SMALLBUFFERSIZE];

                        int bytesRead;
                        while ((bytesRead = await resourceReader.ReadAsync(buffer, 0, buffer.Length)) > 0)
                            await fileWriter.WriteAsync(buffer, 0, bytesRead);
                    }
                }
            }
        }