Beispiel #1
0
        private static void PrintXMLFileToScreen()
        {
            ITextReader textReader = new TextFileReaderModule(XMLFile);
            String      text       = textReader.Read();

            output.Write(text);
            output.Write(Environment.NewLine);
            output.Write(Environment.NewLine);
        }
Beispiel #2
0
        public static async Tasks.Task <bool> Join(this ITextWriter me, Generic.IEnumerator <string> items, string separator = null)
        {
            bool result = items.MoveNext() && await me.Write(items.Current);

            while (result && items.MoveNext())
            {
                if (separator.NotNull())
                {
                    result &= await me.Write(separator);
                }
                result &= await me.Write(items.Current);
            }
            return(result);
        }
Beispiel #3
0
        public void Handle(object model)
        {
            // Find the full path to the template file,
            // using current directory if argument isn't fully qualified
            string templatePath = GetTemplatePath();

            DebugTrace.Trace(this, "Rendering:" + templatePath);
            DebugTrace.Trace(this, "Model:" + model.ToString());

            var templateName    = Path.GetFileName(templatePath);
            var templateDirPath = Path.GetDirectoryName(templatePath);

            SparkViewEngine engine = new SparkEngineFactory().GetSparkEngine <TView>(templateDirPath);

            try
            {
                // compile and instantiate the template
                string templateResult = ProcessViewTemplate(engine, templateName, model);

                _fileWriter.Write(templateResult);
            }
            catch (Exception ex)
            {
                throw new SparkReportGenerationException("An exception occurred:" + ex.GetType().Name + "\r\n" +
                                                         ex.Message, ex);
            }
        }
Beispiel #4
0
        private void WriteResultMessage(int correctResult, int userAnswer)
        {
            var wasUserAnswerCorrect    = correctResult == userAnswer;
            var wasAnswerCorrectMessage = GetWasAnswerCorrectMessage(wasUserAnswerCorrect);
            var messageType             = GetMessageType(wasUserAnswerCorrect);

            string message = $"Vaše odpověď \"{userAnswer}\" {wasAnswerCorrectMessage}";

            textWriter.Write(message, messageType);
        }
        private void WriteValueWithPadding(
            ITextWriter textWriter,
            MessageTemplate.ArgumentToken arg,
            string formatedValue)
        {
            if (arg.Alignment > 0)
            {
                int padLeft = arg.Alignment - formatedValue.Length;
                textWriter.Write(' ', padLeft);
            }

            textWriter.Write(formatedValue);

            if (arg.Alignment < 0)
            {
                int padRight = -arg.Alignment - formatedValue.Length;
                textWriter.Write(' ', padRight);
            }
        }
Beispiel #6
0
        public async Task SendMessage(int projectId, int jobQueueId, string taskName, string message)
        {
            var           group  = GetGroupName(jobQueueId.ToString());
            List <string> groups = new List <string>()
            {
                group
            };
            await _textWriter.Write($"{JobQueueLog.FolderNamePrefix}_{projectId}_{jobQueueId}", taskName ?? "job", message);

            await Clients.Groups(groups).SendAsync("ReceiveMessage", taskName, message);
        }
Beispiel #7
0
        /// <summary>
        /// Writes the hash file (hash.extension) from a text.
        /// </summary>
        /// <param name="text">The text, null is equal as an empty string.</param>
        /// <param name="writer">The textwriter for the output.</param>
        /// <exception cref="ArgumentNullException"><paramref name="writer"/>is null</exception>
        public void WriteHashFromString(string text, ITextWriter writer)
        {
            if (writer == null)
            {
                throw new ArgumentNullException("writer");
            }

            string hash = this.GetHashFromString(text);

            writer.Write(hash);
        }
Beispiel #8
0
        /// <summary>
        /// Writes the hash value file (filename.extension) from the content of a File.
        /// </summary>
        /// <param name="reader">The reader for the input data.</param>
        /// <param name="writer">The textwriter for the output.</param>
        /// <exception cref="ArgumentNullException"><paramref name="reader"/>is null</exception>
        /// <exception cref="ArgumentNullException"><paramref name="writer"/>is null</exception>
        public void WriteHash(ITextReader reader, ITextWriter writer)
        {
            if (writer == null)
            {
                throw new ArgumentNullException("writer");
            }

            string hash = this.GetHashFromReader(reader);

            writer.Write(hash);
        }
Beispiel #9
0
        static void Main(string[] args)
        {
            //initialize the Unity IoC Container and Dependency Injection
            Bootstrap.Init();
            Initiator init = DependencyInjector.Retrieve <Initiator>();

            //Instantiate the apireader and console writer objects
            _reader = init.GetReader();
            _writer = init.GetWriter();
            _reader.SetClient(uriAddress);

            //attempt to read from the Web API
            try
            {
                //Write out to the console Message 1 and 2 from the API
                _writer.Write(_reader.GetMessage(1).Result);
                _writer.Write("<Press any key to exit>");
                Console.ReadLine();
                _writer.Write(_reader.GetMessage(2).Result);

                //pause for 1 second and exit
                System.Threading.Thread.Sleep(1000);
            }
            //If an error occurs, print out teh error message and exit.
            catch (Exception ex)
            {
                _writer.Write(ex.InnerException.Message);
                _writer.Write("Please ensure the target API application is running, and the server is accessable");
                _writer.Write("<Press any key to exit>");
                Console.ReadLine();
            }
        }
 public void Flush()
 {
     char[] copy = _empty;
     lock (_synchro)
     {
         if (_buffer.Count > 0)
         {
             copy = _buffer.ToArray();
             _buffer.Clear();
         }
     }
     if (copy.Length > 0)
     {
         _writer.Write(copy);
     }
 }
Beispiel #11
0
        private void PrintSuggestions()
        {
            var joined = "        " + string.Join("\r\n", _suggestions.OrderBy(x => x).ToArray()).Replace("\r\n", "\r\n        ");

            string classFormat     = @"

namespace Your.Namespace.Here 
{{
    [StorEvil.Context]
    public class StubContextClass 
    {{
{0}
    }}
}}";
            var    classDefinition = string.Format(classFormat, joined);

            SuggestionWriter.Write(classDefinition);
        }
        public void Write(
            MessageTemplate messageTemplate,
            IReadOnlyList <object> args,
            ITextWriter textWriter,
            IFormatProvider formatProvider = null)
        {
            if (messageTemplate == null)
            {
                throw new ArgumentNullException(nameof(messageTemplate));
            }
            if (args == null)
            {
                throw new ArgumentNullException(nameof(args));
            }
            if (textWriter == null)
            {
                throw new ArgumentNullException(nameof(textWriter));
            }

            var formatter = GetFormatter(formatProvider);

            foreach (var token in messageTemplate.Tokens)
            {
                switch (token)
                {
                case MessageTemplate.TextToken text:
                    textWriter.Write(text.Text);
                    break;

                case MessageTemplate.ArgumentToken arg:
                    var    value         = args[arg.Index];
                    string formatedValue = _valueFormatter.Format(value, arg.Format, formatProvider, formatter);
                    WriteValueWithPadding(textWriter, arg, formatedValue);
                    break;

                default:
                    throw new FormatException($"Unknown format token `{token?.GetType().Name}`.");
                }
            }
        }
Beispiel #13
0
        /// <summary>
        /// Run the program
        /// </summary>
        public void Run()
        {
            string result;

            // for each string that is read
            try
            {
                foreach (string inputString in reader.Read())
                {
                    try
                    {
                        // encode input string
                        result = encoder.Encode(inputString);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("Encoding error\r\n{0}", e.Message);
                        break;
                    }

                    try
                    {
                        // write to output
                        writer.Write(result);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("Data output error\r\n{0}", e.Message);
                        break;
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Data input error\r\n{0}", e.Message);
            }
        }
Beispiel #14
0
 public static Tasks.Task <bool> Write(this ITextWriter me, params char[] buffer)
 {
     return(me.Write((Generic.IEnumerable <char>)buffer));
 }
Beispiel #15
0
 protected void Write(string str) => _textWriter.Write(str);
Beispiel #16
0
 private void Line(string text)
 {
     _w.Write(GetCurrentIndent());
     _w.WriteLine(text);
 }
        public async Task Acquire(Acquirable acquirable)
        {
            var result = await acquirable.Fetch(_httpClient);

            if (!result.IsSuccess)
            {
                return;
            }

            if (await CheckSdkExists(result.Version))
            {
                _textWriter.WriteLine($"SDK version {result.Version} is already installed.");
                return;
            }

            using var channelResponse = await JsonDocument.ParseAsync(await _httpClient.GetStreamAsync(result.ChannelJson));

            var file = channelResponse
                       .RootElement.GetProperty("releases").EnumerateArray()
                       .SelectMany(x =>
            {
                IEnumerable <JsonElement> GetSdks()
                {
                    yield return(x.GetProperty("sdk"));

                    if (x.TryGetProperty("sdks", out var sdks))
                    {
                        foreach (var y in sdks.EnumerateArray())
                        {
                            yield return(y);
                        }
                    }
                }

                return(GetSdks());
            })
                       .First(x => x.GetProperty("version").GetString() == result.Version)
                       .GetProperty("files")
                       .EnumerateArray()
                       .First(FileFilter);

            var name         = file.GetProperty("name").GetString();
            var installerUrl = file.GetProperty("url").GetString();
            var fileHash     = file.GetProperty("hash").GetString();

            var filePath = Path.Combine(Path.GetTempPath(), name);

            _textWriter.WriteLine($"Starting download of .NET Core SDK Version {result.Version}");
            using (var installerStream = await _httpClient.GetStreamAsync(installerUrl))
            {
                using var fileStream = new FileStream(filePath, FileMode.Create);
                var progress = new Progress <long>();

                var lastReportedBytesMbs = 0;
                progress.ProgressChanged += (sender, totalBytes) =>
                {
                    var currentBytesMbs = (int)Math.Floor(totalBytes / Math.Pow(2, 20));
                    if (currentBytesMbs <= lastReportedBytesMbs)
                    {
                        return;
                    }
                    lastReportedBytesMbs = currentBytesMbs;
                    _textWriter.SetCursorPosition(0, Console.CursorTop);
                    _textWriter.Write($"Downloading: {currentBytesMbs}MB");
                };

                await CopyToWithProgress(installerStream, fileStream, progress);
            }

            CheckHash(filePath, fileHash);
            _installerLauncher.Launch(filePath);
        }
Beispiel #18
0
 public void Handle(SessionFinished eventToHandle)
 {
     _fileWriter.Write(_doc.OuterXml);
 }
Beispiel #19
0
 public static async Tasks.Task <bool> WriteLine(this ITextWriter me, Generic.IEnumerator <char> value)
 {
     return(await me.Write(value) && await me.WriteLine());
 }
Beispiel #20
0
 /// <summary>
 /// Decorate and passes to next writer
 /// </summary>
 /// <param name="data">output string, could be null</param>
 public void Write(string data)
 {
     writer.Write(Decorate(data));
 }
Beispiel #21
0
 public static Tasks.Task <bool> Write(this ITextWriter me, string format, params object[] arguments)
 {
     return(me.Write(string.Format(format, arguments)));
 }
Beispiel #22
0
 public static Tasks.Task <bool> WriteLine(this ITextWriter me)
 {
     return(me.Write('\n'));            // The newline characters are converted by bool Write(this ITextWriter me, Generic.IEnumerable<char> buffer)
 }
 /// <summary>
 /// 容器起始标签
 /// </summary>
 public IDisposable Begin()
 {
     _writer.Write(GetBeginResult());
     return(new ContainerWrapper <T>(this));
 }
        public async Task Acquire(string version)
        {
            var channelVersion = ParseChannelVersion(version);
            var platform       = _platformIdentifier.GetPlatform();

            using var releasesResponse = await JsonDocument.ParseAsync(await _httpClient.GetStreamAsync(ReleaseIndex));

            var channel = releasesResponse.RootElement.GetProperty("releases-index").EnumerateArray()
                          .First(x => x.GetProperty("channel-version").GetString() == channelVersion);

            var channelJson = channel.GetProperty("releases.json").GetString();

            using var channelResponse = await JsonDocument.ParseAsync(await _httpClient.GetStreamAsync(channelJson));

            var file = channelResponse
                       .RootElement.GetProperty("releases").EnumerateArray()
                       .SelectMany(x =>
            {
                IEnumerable <JsonElement> GetSdks()
                {
                    yield return(x.GetProperty("sdk"));

                    if (x.TryGetProperty("sdks", out var sdks))
                    {
                        foreach (var y in sdks.EnumerateArray())
                        {
                            yield return(y);
                        }
                    }
                }

                return(GetSdks());
            })
                       .First(x => x.GetProperty("version").GetString() == version)
                       .GetProperty("files")
                       .EnumerateArray()
                       .First(x => x.GetProperty("rid").GetString() == platform);

            var name         = file.GetProperty("name").GetString();
            var installerUrl = file.GetProperty("url").GetString();
            var fileHash     = file.GetProperty("hash").GetString();

            var filePath = Path.Combine(Path.GetTempPath(), name);

            using var installerStream = await _httpClient.GetStreamAsync(installerUrl);

            using var fileStream = new FileStream(filePath, FileMode.Create);
            var progress = new Progress <long>();

            var lastReportedBytesMbs = 0;

            progress.ProgressChanged += (sender, totalBytes) =>
            {
                var currentBytesMbs = (int)Math.Floor(totalBytes / Math.Pow(2, 20));
                if (currentBytesMbs <= lastReportedBytesMbs)
                {
                    return;
                }
                lastReportedBytesMbs = currentBytesMbs;
                _textWriter.SetCursorPosition(0, Console.CursorTop);
                _textWriter.Write($"Downloading: {currentBytesMbs}MB");
            };
            await CopyToWithProgress(installerStream, fileStream, progress);

            CheckHash(filePath, fileHash);

            _installerLauncher.Launch(filePath);
        }
Beispiel #25
0
        /// <summary>
        /// Writes the hash value file (filename.extension) from the content of a File.
        /// </summary>
        /// <param name="reader">The reader for the input data.</param>
        /// <param name="writer">The textwriter for the output.</param>
        /// <exception cref="ArgumentNullException"><paramref name="reader"/>is null</exception>
        /// <exception cref="ArgumentNullException"><paramref name="writer"/>is null</exception>
        public void WriteHash(ITextReader reader, ITextWriter writer)
        {
            if (writer == null)
            {
                throw new ArgumentNullException("writer");
            }

            string hash = this.GetHashFromReader(reader);
            writer.Write(hash);
        }
Beispiel #26
0
 public static Tasks.Task <bool> Write(this ITextWriter me, Generic.IEnumerable <char> buffer)
 {
     return(me.Write(buffer?.GetEnumerator()));
 }
Beispiel #27
0
        /// <summary>
        /// Writes the hash file (hash.extension) from a text.
        /// </summary>
        /// <param name="text">The text, null is equal as an empty string.</param>
        /// <param name="writer">The textwriter for the output.</param>
        /// <exception cref="ArgumentNullException"><paramref name="writer"/>is null</exception>
        public void WriteHashFromString(string text, ITextWriter writer)
        {
            if (writer == null)
            {
                throw new ArgumentNullException("writer");
            }

            string hash = this.GetHashFromString(text);
            writer.Write(hash);
        }
Beispiel #28
0
 public void Write(string text)
 {
     writer.Write(text);
 }
Beispiel #29
0
 public static async Tasks.Task <bool> Write(this ITextWriter me, string value)
 {
     return(value.IsEmpty() || await me.Write((Generic.IEnumerable <char>) value));
 }
Beispiel #30
0
 public async Task Add(string name, string value, CancellationToken cancellationToken = default(CancellationToken))
 {
     var protectedValue = _protector.Protect(value);
     await _textWriter.Write(FolderName, name, protectedValue);
 }
Beispiel #31
0
 public static Tasks.Task <bool> Write <T>(this ITextWriter me, T value) where T : IConvertible
 {
     return(me.Write(value.ToString((IFormatProvider)System.Globalization.CultureInfo.InvariantCulture.GetFormat(typeof(T)))));
 }