Here are the examples of the csharp api System.IO.StreamWriter.FlushAsync() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
119 Examples
19
Source : PackageImporterIntegrationTest.cs
with MIT License
from ai-traders
with MIT License
from ai-traders
[Fact]
public async Task ImportExamplePackages()
{
var importer = server.Host.Services.GetRequiredService<PackageImporter>();
using(var ms = new MemoryStream()) {
var writer = new StreamWriter(ms, Encoding.UTF8);
await importer.ImportAsync(TestResources.GetE2eInputDirectory(), writer);
await writer.FlushAsync();
string text = Encoding.UTF8.GetString(ms.ToArray());
replacedert.Contains("liget-test1.1.0.0.nupkg Success", text);
replacedert.Contains("liget-two.1.0.0.nupkg Success", text);
replacedert.Contains("liget-two.2.1.0.nupkg Success", text);
}
}
19
Source : JsonContent.cs
with MIT License
from AMalininHere
with MIT License
from AMalininHere
protected override async Task SerializeToStreamAsync(Stream stream, TransportContext context)
{
var streamWriter = new StreamWriter(stream);
_serializer.Serialize(streamWriter, _body, _bodyType);
await streamWriter.FlushAsync();
}
19
Source : AsciiFormatter.cs
with Apache License 2.0
from AppMetrics
with Apache License 2.0
from AppMetrics
public static async Task Write(Stream destination, IEnumerable<MetricFamily> metrics, NewLineFormat newLine)
{
var metricFamilies = metrics.ToArray();
using (var streamWriter = new StreamWriter(destination, Encoding) { NewLine = GetNewLineChar(newLine) })
{
foreach (var metricFamily in metricFamilies)
{
WriteFamily(streamWriter, metricFamily);
}
await streamWriter.FlushAsync();
}
}
19
Source : ElementCollectionTests.cs
with GNU General Public License v3.0
from asimmon
with GNU General Public License v3.0
from asimmon
[Fact]
public async Task LoadAsync_WhenSupportedElements_Works()
{
using (var stream = new MemoryStream())
using (var writer = new StreamWriter(stream))
{
await writer.WriteAsync(ValidJsonCollection);
await writer.FlushAsync();
stream.Seek(0, SeekOrigin.Begin);
var collection = new ElementCollection();
await collection.LoadAsync(stream);
replacedert.Equal(2, collection.Count);
var imageBase = replacedert.Single(collection, x => x.Name == ImageElement.Name);
var image = replacedert.IsType<ImageElement>(imageBase);
replacedert.NotSame(ImageElement, image);
var textBase = replacedert.Single(collection, x => x.Name == TextElement.Name);
var text = replacedert.IsType<TextElement>(textBase);
replacedert.NotSame(TextElement, text);
replacedert.Equal(ImageElement.Content, image.Content);
replacedert.Equal(ImageElement.Threshold, image.Threshold);
replacedert.Equal(ImageElement.Grayscale, image.Grayscale);
replacedert.Equal(TextElement.Content, text.Content);
replacedert.Equal(TextElement.Options, text.Options);
replacedert.Equal(TextElement.IgnoreCase, text.IgnoreCase);
}
}
19
Source : ElementCollectionTests.cs
with GNU General Public License v3.0
from asimmon
with GNU General Public License v3.0
from asimmon
[Fact]
public async Task LoadAsync_WhenNotSupportedElements_Works()
{
using (var stream = new MemoryStream())
using (var writer = new StreamWriter(stream))
{
await writer.WriteAsync(InvalidJsonCollection);
await writer.FlushAsync();
stream.Seek(0, SeekOrigin.Begin);
var collection = new ElementCollection();
await replacedert.ThrowsAsync<ArgumentException>(async () => await collection.LoadAsync(stream));
}
}
19
Source : FileSystemEventSink.cs
with Apache License 2.0
from awslabs
with Apache License 2.0
from awslabs
protected override async Task OnNextAsync(List<Envelope<InputLogEvent>> records, long batchBytes)
{
// If the sink has been stopped, don't keep trying to write to the file.
if (_isStopped) return;
// Obtain the fileLock semapreplaced to ensure that only a single process can call this method at any given time.
// This does not lock the file itself; we rely on the OS to manage file locking when we open the file stream.
await _fileLock.WaitAsync();
try
{
// Create a stream writer on a new FileStream object pointing to the target output file.
// This method will fail if the OS already has a lock on the file, which will trigger throttling behavior.
// This allows us to effectively reproduce throttling at the sink level, and also helps debug issues outside of the IDE.
using (var sw = new StreamWriter(new FileStream(FilePath, FileMode.Append, FileAccess.Write, FileShare.Read)))
{
foreach (var record in records)
{
await sw.WriteLineAsync(record.Data.Message);
}
await sw.FlushAsync();
}
await SaveBookmarks(records);
Throttle.SetSuccess();
}
catch (Exception)
{
// If the sink has been stopped, don't keep trying to write to the file.
if (_isStopped) return;
// This is the magic that reproduces the throttling behavior.
// We call the SetError method on the throttle object and requeue the events.
// This uses the same logic as the CloudWatchLogs sink.
Throttle.SetError();
_buffer.Requeue(records, Throttle.ConsecutiveErrorCount < _maxAttempts);
}
finally
{
// Release the semapreplaced. This doesn't release any locks on the file.
_fileLock.Release();
}
}
19
Source : LineCounterTest.cs
with Apache License 2.0
from awslabs
with Apache License 2.0
from awslabs
[Theory]
[InlineData(0, 5)]
[InlineData(5, 0)]
[InlineData(10, 11)]
public async Task CountToPosition(int linesBefore, int linesAfter)
{
var texts = new string[]
{
LineReaderTestData.FormatStringOneObject,
LineReaderTestData.FormatStringTwoObjects,
LineReaderTestData.FormatStringThreeObjects,
LineReaderTestData.FormatStringMultipleObjects
};
long position = 0;
var j = 0;
byte[] data;
using (var memStream = new MemoryStream())
using (var writer = new StreamWriter(memStream))
{
for (var i = 0; i < linesBefore; i++)
{
await writer.WriteLineAsync(texts[j++ % texts.Length]);
}
// remember the stream position at this point
await writer.FlushAsync();
position = memStream.Position;
for (var i = 0; i < linesAfter; i++)
{
await writer.WriteLineAsync(texts[j++ % texts.Length]);
}
await writer.FlushAsync();
data = memStream.ToArray();
}
using var readStream = new MemoryStream(data);
using var counter = new LineCounter(readStream, null);
var count = await counter.CountLinesAsync(position);
replacedert.Equal(linesBefore, count);
}
19
Source : W3SVCLogParserTest.cs
with Apache License 2.0
from awslabs
with Apache License 2.0
from awslabs
[Fact]
public async Task LogExpansionMark_ParserShouldRewind()
{
var parser = new AsyncW3SVCLogParser(NullLogger.Instance, "#Fields: date time key1", new DelimitedLogParserOptions());
var records = new List<IEnvelope<W3SVCRecord>>();
var context = new DelimitedTextLogContext
{
FilePath = _testFile
};
// write the initial file content
await File.WriteAllLinesAsync(_testFile, new string[]
{
"#Fields: field1 field2 field3 field4",
"before before before before"
});
var positionBeforeExpansionBlock = new FileInfo(_testFile).Length;
// write expansion block
await File.AppendAllLinesAsync(_testFile, new string[]
{
"\x00\x00\x00\x00\x00\x00\x00\x00"
});
// make sure we see only one record
await parser.ParseRecordsAsync(context, records, 10);
replacedert.Single(records);
// write the next record
using (var stream = File.OpenWrite(_testFile))
using (var writer = new StreamWriter(stream))
{
stream.Position = positionBeforeExpansionBlock;
await writer.WriteLineAsync("after after after after");
await writer.FlushAsync();
}
// make sure the parser catches this record
await parser.ParseRecordsAsync(context, records, 10);
replacedert.Equal(2, records.Count);
replacedert.Equal(3, (records[1] as LogEnvelope<W3SVCRecord>).LineNumber);
foreach (var kvp in records[1].Data)
{
replacedert.Equal("after", kvp.Value);
}
}
19
Source : FileSystemHelpers.cs
with Apache License 2.0
from Azure-App-Service
with Apache License 2.0
from Azure-App-Service
public static async Task WriteAllTextToFileAsync(string path, string content)
{
using (var fileStream = OpenFile(path, FileMode.Create, FileAccess.Write, FileShare.ReadWrite | FileShare.Delete))
using (var streamWriter = new StreamWriter(fileStream))
{
await streamWriter.WriteAsync(content);
await streamWriter.FlushAsync();
}
}
19
Source : FunctionManager.cs
with Apache License 2.0
from Azure-App-Service
with Apache License 2.0
from Azure-App-Service
private async Task<T> GetKeyObjectFromFile<T>(string name, IKeyJsonOps<T> keyOp)
{
var secretStorageType = System.Environment.GetEnvironmentVariable(Constants.AzureWebJobsSecretStorageType);
if (!string.IsNullOrEmpty(secretStorageType) &&
secretStorageType.Equals("Blob", StringComparison.OrdinalIgnoreCase))
{
throw new InvalidOperationException("Runtime keys are stored on blob storage. This API doesn't support this configuration.");
}
string keyPath = GetFunctionSecretsFilePath(name);
string key = null;
if (!FileSystemHelpers.FileExists(keyPath) || FileSystemHelpers.FileInfoFromFileName(keyPath).Length == 0)
{
FileSystemHelpers.EnsureDirectory(Path.GetDirectoryName(keyPath));
try
{
using (var fileStream = FileSystemHelpers.OpenFile(keyPath, FileMode.Create, FileAccess.Write, FileShare.None))
// getting the lock early (instead of acquire the lock at "new StreamWriter(fileStream)")
// so no redundant work is being done (generate secrets)
{
string jsonContent = keyOp.GenerateKeyJson(SecurityUtility.GenerateSecretStringsKeyPair(keyOp.NumberOfKeysInDefaultFormat), FunctionSiteExtensionVersion, out key);
using (var sw = new StringWriter())
using (var sr = new System.IO.StringReader(jsonContent))
{
// write json to memory
// since JsonConvert has no method to format a json string
new JsonTextWriter(sw) { Formatting = Formatting.Indented }.WriteToken(new JsonTextReader(sr));
using (var streamWriter = new StreamWriter(fileStream))
{
await streamWriter.WriteAsync(sw.ToString());
await streamWriter.FlushAsync();
}
}
}
return keyOp.GenerateKeyObject(key, name);
}
catch (IOException)
{
// failed to open file => function runtime has the handler
// fallback to read key files
}
}
string jsonStr = null;
int timeOut = 5;
while (true)
{
try
{
jsonStr = await FileSystemHelpers.ReadAllTextFromFileAsync(keyPath);
break;
}
catch (Exception)
{
if (timeOut == 0)
{
throw new TimeoutException($"Fail to read {keyPath}, the file is being held by another process");
}
timeOut--;
await Task.Delay(250);
}
}
bool isEncrypted;
key = keyOp.GetKeyValueFromJson(jsonStr, out isEncrypted);
if (isEncrypted)
{
key = SecurityUtility.DecryptSecretString(key);
}
return keyOp.GenerateKeyObject(key, name);
}
19
Source : ProcessInvoker.cs
with BSD 3-Clause "New" or "Revised" License
from balbarak
with BSD 3-Clause "New" or "Revised" License
from balbarak
public async Task WriteInputLine(string input, bool closeInput = false)
{
if (_proc == null)
throw new InvalidOperationException("Proccess not running");
await _inputWriter.WriteLineAsync(input);
await _inputWriter.FlushAsync();
if (closeInput)
_inputWriter.Close();
}
19
Source : HttpLoggerProcessor.cs
with MIT License
from Bishoymly
with MIT License
from Bishoymly
private async Task WriteLineAsync(string value)
{
await _writer.WriteLineAsync(value);
await _writer.FlushAsync();
}
19
Source : CLightningClient.cs
with MIT License
from btcpayserver
with MIT License
from btcpayserver
internal async Task<T> SendCommandAsync<T>(string command, object[] parameters = null, bool noReturn = false, bool isArray = false, CancellationToken cancellation = default(CancellationToken))
{
parameters = parameters ?? Array.Empty<string>();
using (Socket socket = await Connect())
{
using (var networkStream = new NetworkStream(socket))
{
using (var textWriter = new StreamWriter(networkStream, UTF8, 1024 * 10, true))
{
using (var jsonWriter = new JsonTextWriter(textWriter))
{
var req = new JObject();
req.Add("id", 0);
req.Add("method", command);
req.Add("params", new JArray(parameters));
await req.WriteToAsync(jsonWriter, cancellation);
await jsonWriter.FlushAsync(cancellation);
}
await textWriter.FlushAsync();
}
await networkStream.FlushAsync(cancellation);
using (var textReader = new StreamReader(networkStream, UTF8, false, 1024 * 10, true))
{
using (var jsonReader = new JsonTextReader(textReader))
{
var resultAsync = JObject.LoadAsync(jsonReader, cancellation);
// without this hack resultAsync is blocking even if cancellation happen
using (cancellation.Register(() =>
{
socket.Dispose();
}))
{
try
{
var result = await resultAsync;
var error = result.Property("error");
if (error != null)
{
throw new LightningRPCException(error.Value["message"].Value<string>(), error.Value["code"].Value<int>());
}
if (noReturn)
return default(T);
if (isArray)
{
return result["result"].Children().First().Children().First().ToObject<T>();
}
return result["result"].ToObject<T>();
}
catch when (cancellation.IsCancellationRequested)
{
cancellation.ThrowIfCancellationRequested();
throw new NotSupportedException(); // impossible
}
}
}
}
}
}
}
19
Source : Request.cs
with MIT License
from Celisuis
with MIT License
from Celisuis
public async Task Post(string url, IDictionary<string, string> data, WebHeaderCollection collection = null)
{
try
{
HttpWebRequest webRequest = (HttpWebRequest) WebRequest.Create(url);
webRequest.Method = "POST";
webRequest.UserAgent = User_Agent;
webRequest.ContentType = "application/json";
if (collection != null)
for (int i = 0; i < collection.Count; i++)
webRequest.Headers.Add(collection.Keys[i], collection.Get(i));
string post = JsonConvert.SerializeObject(data);
using (StreamWriter writer = new StreamWriter(webRequest.GetRequestStream()))
{
await writer.WriteAsync(post);
await writer.FlushAsync();
writer.Close();
}
HttpWebResponse webResponse = (HttpWebResponse) await webRequest.GetResponseAsync();
WebHeaderCollection header = webResponse.Headers;
ResponseStream = webResponse.GetResponseStream();
using (StreamReader reader = new StreamReader(webResponse.GetResponseStream()))
{
string response = await reader.ReadToEndAsync();
Response = response;
HeaderCollection = header;
URL = webResponse.ResponseUri.ToString();
}
}
catch (WebException e)
{
Status = (int) e.Status;
Response = $"{new StreamReader(e.Response.GetResponseStream()).ReadToEnd()}";
}
}
19
Source : DigestableSafeMutexIoManager.cs
with GNU General Public License v3.0
from chaincase-app
with GNU General Public License v3.0
from chaincase-app
public new async Task AppendAllLinesAsync(IEnumerable<string> lines, CancellationToken cancellationToken = default)
{
if (lines is null || !lines.Any())
{
return;
}
IoHelpers.EnsureContainingDirectoryExists(NewFilePath);
if (File.Exists(NewFilePath))
{
File.Delete(NewFilePath);
}
var byteArrayBuilder = new ByteArrayBuilder();
var linesArray = lines.ToArray();
var linesIndex = 0;
using (var sr = OpenText())
using (var fs = File.OpenWrite(NewFilePath))
using (var sw = new StreamWriter(fs, Encoding.ASCII, Constants.BigFileReadWriteBufferSize))
{
// 1. First copy.
if (!sr.EndOfStream)
{
var lineTask = sr.ReadLineAsync();
Task wTask = Task.CompletedTask;
string line = null;
while (lineTask != null)
{
if (line is null)
{
line = await lineTask.ConfigureAwait(false);
}
lineTask = sr.EndOfStream ? null : sr.ReadLineAsync();
if (linesArray[linesIndex] == line) // If the line is a line we want to write, then we know that someone else have worked into the file.
{
linesIndex++;
continue;
}
await wTask.ConfigureAwait(false);
wTask = sw.WriteLineAsync(line);
ContinueBuildHash(byteArrayBuilder, line);
cancellationToken.ThrowIfCancellationRequested();
line = null;
}
await wTask.ConfigureAwait(false);
}
await sw.FlushAsync().ConfigureAwait(false);
// 2. Then append.
foreach (var line in linesArray)
{
await sw.WriteLineAsync(line).ConfigureAwait(false);
ContinueBuildHash(byteArrayBuilder, line);
cancellationToken.ThrowIfCancellationRequested();
}
await sw.FlushAsync().ConfigureAwait(false);
}
var res = await WorkWithHashAsync(byteArrayBuilder, cancellationToken).ConfigureAwait(false);
if (res.same)
{
return;
}
SafeMoveNewToOriginal();
await WriteOutHashAsync(res.hash).ConfigureAwait(false);
}
19
Source : Startup.cs
with MIT License
from codenesium
with MIT License
from codenesium
public async Task Invoke(HttpContext context)
{
Exception ex = context.Features.Get<IExceptionHandlerFeature>()?.Error;
if (ex == null)
{
return;
}
else
{
this.logger.LogError(ex, null);
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
ApiError error = new ApiError();
if (this.env.IsDevelopment())
{
error.SetProperties(ex.Message, ex.Source, ex.StackTrace);
}
else
{
error.SetProperties("Internal Server Error", string.Empty, string.Empty);
}
context.Response.ContentType = "application/json";
using (var writer = new StreamWriter(context.Response.Body))
{
await writer.FlushAsync().ConfigureAwait(false);
}
}
}
19
Source : System_IO_StreamWriter_Binding.cs
with MIT License
from CragonGame
with MIT License
from CragonGame
static StackObject* FlushAsync_17(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
{
ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
StackObject* ptr_of_this_method;
StackObject* __ret = ILIntepreter.Minus(__esp, 1);
ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
System.IO.StreamWriter instance_of_this_method = (System.IO.StreamWriter)typeof(System.IO.StreamWriter).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
__intp.Free(ptr_of_this_method);
var result_of_this_method = instance_of_this_method.FlushAsync();
object obj_result_of_this_method = result_of_this_method;
if(obj_result_of_this_method is CrossBindingAdaptorType)
{
return ILIntepreter.PushObject(__ret, __mStack, ((CrossBindingAdaptorType)obj_result_of_this_method).ILInstance);
}
return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method);
}
19
Source : CsvOutputFormatter.cs
with Apache License 2.0
from crazyants
with Apache License 2.0
from crazyants
public async override Task WriteResponseBodyAsync(OutputFormatterWriteContext context)
{
var response = context.HttpContext.Response;
Type type = context.Object.GetType();
Type itemType;
if (type.GetGenericArguments().Length > 0)
{
itemType = type.GetGenericArguments()[0];
}
else
{
itemType = type.GetElementType();
}
StringWriter _stringWriter = new StringWriter();
if (_options.UseSingleLineHeaderInCsv)
{
_stringWriter.WriteLine(
string.Join<string>(
_options.CsvDelimiter, itemType.GetProperties().Select(x => x.Name)
)
);
}
foreach (var obj in (IEnumerable<object>)context.Object)
{
var vals = obj.GetType().GetProperties().Select(
pi => new {
Value = pi.GetValue(obj, null)
}
);
string _valueLine = string.Empty;
foreach (var val in vals)
{
if (val.Value != null)
{
var _val = val.Value.ToString();
//Check if the value contans a comma and place it in quotes if so
if (_val.Contains(","))
_val = string.Concat("\"", _val, "\"");
//Replace any \r or \n special characters from a new line with a space
if (_val.Contains("\r"))
_val = _val.Replace("\r", " ");
if (_val.Contains("\n"))
_val = _val.Replace("\n", " ");
_valueLine = string.Concat(_valueLine, _val, _options.CsvDelimiter);
}
else
{
_valueLine = string.Concat(_valueLine, string.Empty, _options.CsvDelimiter);
}
}
_stringWriter.WriteLine(_valueLine.TrimEnd(_options.CsvDelimiter.ToCharArray()));
}
var streamWriter = new StreamWriter(response.Body);
await streamWriter.WriteAsync(_stringWriter.ToString());
await streamWriter.FlushAsync();
}
19
Source : JsonRpcStreamsTests.cs
with Apache License 2.0
from CXuesong
with Apache License 2.0
from CXuesong
[Fact]
public async Task ServerHandlerTest()
{
var request = new RequestMessage(123, "add", JToken.FromObject(new {x = 20, y = 35}));
(var ss, var cs) = FullDuplexStream.CreatePair();
using (var clientReader = new StreamReader(cs))
using (var clientWriter = new StreamWriter(cs))
using (var serverReader = new ByLineTextMessageReader(ss))
using (var serverWriter = new ByLineTextMessageWriter(ss))
{
async Task<ResponseMessage> WaitForResponse()
{
var sw = Stopwatch.StartNew();
var content = await clientReader.ReadLineAsync();
Output.WriteLine($"Received response in {sw.Elapsed}.");
return (ResponseMessage) Message.LoadJson(content);
}
async Task<ResponseMessage> SendRequest(MessageId messageId)
{
request.Id = messageId;
request.WriteJson(clientWriter);
clientWriter.WriteLine();
await clientWriter.FlushAsync();
var response = await WaitForResponse();
replacedert.Equal(messageId, response.Id);
replacedert.Null(response.Error);
replacedert.Equal(55, (int) response.Result);
return response;
}
using (var server = new ServerTestHelper(this, serverReader, serverWriter,
StreamRpcServerHandlerOptions.None))
{
await SendRequest(123);
await SendRequest("abc");
}
}
}
19
Source : PartwiseStreamMessageWriter.cs
with Apache License 2.0
from CXuesong
with Apache License 2.0
from CXuesong
public override async Task WriteAsync(Message message, CancellationToken cancellationToken)
{
// Ensure that a message is either written completely or not at all.
if (message == null) throw new ArgumentNullException(nameof(message));
cancellationToken.ThrowIfCancellationRequested();
DisposalToken.ThrowIfCancellationRequested();
using (var linkedTokenSource =
CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, DisposalToken))
using (var ms = new MemoryStream())
{
try
{
#if BCL_FEATURE_ASYNC_DISPOSABLE
await
#endif
using (var writer = new StreamWriter(ms, Encoding, 4096, true)) message.WriteJson(writer);
linkedTokenSource.Token.ThrowIfCancellationRequested();
await streamSemapreplaced.WaitAsync(linkedTokenSource.Token).ConfigureAwait(false);
try
{
#if BCL_FEATURE_ASYNC_DISPOSABLE
await
#endif
using (var writer = new StreamWriter(Stream, Encoding, 4096, true))
{
await writer.WriteAsync("Content-Length: ").ConfigureAwait(false);
await writer.WriteAsync(ms.Length.ToString()).ConfigureAwait(false);
await writer.WriteAsync("\r\n").ConfigureAwait(false);
if (ContentType != null)
{
await writer.WriteAsync("Content-Type: ").ConfigureAwait(false);
await writer.WriteAsync(ContentType).ConfigureAwait(false);
if (EmitContentCharset)
{
await writer.WriteAsync(";charset=").ConfigureAwait(false);
await writer.WriteAsync(Encoding.WebName).ConfigureAwait(false);
}
await writer.WriteAsync("\r\n").ConfigureAwait(false);
}
await writer.WriteAsync("\r\n").ConfigureAwait(false);
await writer.FlushAsync().ConfigureAwait(false);
}
ms.Seek(0, SeekOrigin.Begin);
// ReSharper disable once MethodSupportsCancellation
await ms.CopyToAsync(Stream, 81920 /*, linkedTokenSource.Token*/).ConfigureAwait(false);
}
finally
{
streamSemapreplaced.Release();
}
}
catch (ObjectDisposedException)
{
// Throws OperationCanceledException if the cancellation has already been requested.
linkedTokenSource.Token.ThrowIfCancellationRequested();
throw;
}
}
}
19
Source : MailDemonService_MessageHandler.cs
with MIT License
from DigitalRuby
with MIT License
from DigitalRuby
private async Task HandleEhlo(StreamWriter writer, string line, SslStream sslStream, X509Certificate2 sslCertificate, IPEndPoint endPoint)
{
await ValidateGreeting("EHLO", line, endPoint);
await writer.WriteLineAsync($"250-SIZE {maxMessageSize}");
await writer.WriteLineAsync($"250-8BITMIME");
await writer.WriteLineAsync($"250-AUTH LOGIN PLAIN");
await writer.WriteLineAsync($"250-PIPELINING");
await writer.WriteLineAsync($"250-ENHANCEDSTATUSCODES");
await writer.WriteLineAsync($"250-BINARYMIME");
await writer.WriteLineAsync($"250-CHUNKING");
var cert = await CertificateCache.Instance.LoadSslCertificateAsync(sslCertificateFile, sslCertificatePrivateKeyFile, sslCertificatePreplacedword);
if (cert != null && sslStream == null && port != 465 && port != 587)
{
await writer.WriteLineAsync($"250-STARTTLS");
}
await writer.WriteLineAsync($"250 SMTPUTF8");
await writer.FlushAsync();
}
19
Source : MailDemonService_MessageHandler.cs
with MIT License
from DigitalRuby
with MIT License
from DigitalRuby
private async Task HandleHelo(StreamWriter writer, string line, IPEndPoint endPoint)
{
string clientDomain = await ValidateGreeting("HELO", line, endPoint);
await writer.WriteLineAsync($"220 {Domain} Hello {clientDomain}");
await writer.FlushAsync();
}
19
Source : MailDemonService_MessageHandler.cs
with MIT License
from DigitalRuby
with MIT License
from DigitalRuby
private async Task<MailDemonUser> AuthenticatePlain(Stream reader, StreamWriter writer, string line)
{
if (line == "AUTH PLAIN")
{
await writer.WriteLineAsync($"334 ok");
await writer.FlushAsync();
line = await ReadLineAsync(reader) ?? string.Empty;
}
else
{
line = line.Substring(11);
}
string sentAuth = Encoding.UTF8.GetString(Convert.FromBase64String(line)).Replace("\0", ":").Trim(':');
string userName = sentAuth;
string preplacedword = null;
int pos = sentAuth.IndexOf(':');
if (pos >= 0)
{
userName = sentAuth.Substring(0, pos).Trim();
preplacedword = sentAuth.Substring(++pos);
}
foreach (MailDemonUser user in users)
{
if (user.Authenticate(userName, preplacedword))
{
MailDemonLog.Info("User {0} authenticated", user.UserName);
await writer.WriteLineAsync($"235 2.7.0 Accepted");
await writer.FlushAsync();
return user;
}
}
// fail
MailDemonLog.Warn("Authentication failed: {0}", sentAuth);
await writer.WriteLineAsync($"535 authentication failed");
await writer.FlushAsync();
return new MailDemonUser(userName, userName, preplacedword, userName, null, false, false);
}
19
Source : MailDemonService_MessageHandler.cs
with MIT License
from DigitalRuby
with MIT License
from DigitalRuby
private async Task<MailDemonUser> AuthenticateLogin(Stream reader, StreamWriter writer, string line)
{
MailDemonUser foundUser = null;
await writer.WriteLineAsync("334 VXNlcm5hbWU6"); // user
await writer.FlushAsync();
string userName = await ReadLineAsync(reader) ?? string.Empty;
await writer.WriteLineAsync("334 UGFzc3dvcmQ6"); // pwd
await writer.FlushAsync();
string preplacedword = await ReadLineAsync(reader) ?? string.Empty;
userName = Encoding.UTF8.GetString(Convert.FromBase64String(userName)).Trim();
preplacedword = Encoding.UTF8.GetString(Convert.FromBase64String(preplacedword));
string sentAuth = userName + ":" + preplacedword;
foreach (MailDemonUser user in users)
{
if (user.Authenticate(userName, preplacedword))
{
foundUser = user;
break;
}
}
if (foundUser != null)
{
MailDemonLog.Info("User {0} authenticated", foundUser.UserName);
await writer.WriteLineAsync($"235 2.7.0 Accepted");
await writer.FlushAsync();
return foundUser;
}
// fail
MailDemonLog.Warn("Authentication failed: {0}", sentAuth);
await writer.WriteLineAsync($"535 authentication failed");
await writer.FlushAsync();
return new MailDemonUser(userName, userName, preplacedword, userName, null, false, false);
}
19
Source : MailDemonService_MessageHandler.cs
with MIT License
from DigitalRuby
with MIT License
from DigitalRuby
private async Task HandleClientConnectionAsync(TcpClient tcpClient)
{
if (tcpClient is null || tcpClient.Client is null || !tcpClient.Client.Connected)
{
return;
}
DateTime start = DateTime.UtcNow;
string ipAddress = (tcpClient.Client.RemoteEndPoint as IPEndPoint).Address.ToString();
MailDemonUser authenticatedUser = null;
NetworkStream clientStream = null;
X509Certificate2 sslCert = null;
SslStream sslStream = null;
bool helo = false;
try
{
tcpClient.ReceiveTimeout = tcpClient.SendTimeout = streamTimeoutMilliseconds;
MailDemonLog.Info("Connection from {0}", ipAddress);
// immediately drop if client is blocked
if (CheckBlocked(ipAddress))
{
MailDemonLog.Warn("Blocked {0}", ipAddress);
return;
}
clientStream = tcpClient.GetStream();
// create comm streams
clientStream.ReadTimeout = clientStream.WriteTimeout = streamTimeoutMilliseconds;
Stream reader = clientStream;
StreamWriter writer = new StreamWriter(clientStream, MailDemonExtensionMethods.Utf8EncodingNoByteMarker) { AutoFlush = true, NewLine = "\r\n" };
async Task StartSSL()
{
sslCert = await CertificateCache.Instance.LoadSslCertificateAsync(sslCertificateFile, sslCertificatePrivateKeyFile, sslCertificatePreplacedword);
Tuple <SslStream, Stream, StreamWriter> tls = await StartTls(tcpClient, ipAddress, reader, writer, true, sslCert);
if (tls == null)
{
await writer.WriteLineAsync("503 Failed to start TLS");
await writer.FlushAsync();
throw new IOException("Failed to start TLS, ssl certificate failed to load");
}
else
{
sslStream = tls.Item1;
reader = tls.Item2;
writer = tls.Item3;
}
}
if (port == 465 || port == 587)
{
await StartSSL();
}
MailDemonLog.Info("Connection accepted from {0}", ipAddress);
// send greeting
await writer.WriteLineAsync($"220 {Domain} {greeting}");
await writer.FlushAsync();
IPEndPoint endPoint = tcpClient.Client.RemoteEndPoint as IPEndPoint;
while (true)
{
if ((DateTime.UtcNow - start) > sessionTimeout)
{
throw new TimeoutException($"Session expired after {sessionTimeout.TotalMinutes:0.00} minutes");
}
string line = await ReadLineAsync(reader);
// these commands are allowed before HELO
if (string.IsNullOrWhiteSpace(line) || line.StartsWith("QUIT", StringComparison.OrdinalIgnoreCase))
{
await writer.WriteLineAsync("221 session terminated");
await writer.FlushAsync();
break;
}
else if (line.StartsWith("EHLO", StringComparison.OrdinalIgnoreCase))
{
await HandleEhlo(writer, line, sslStream, sslCert, endPoint);
helo = true;
}
else if (line.StartsWith("STARTTLS", StringComparison.OrdinalIgnoreCase))
{
if (sslStream != null)
{
await writer.WriteLineAsync("503 TLS already initiated");
await writer.FlushAsync();
}
else
{
await StartSSL();
}
}
else if (line.StartsWith("HELO", StringComparison.OrdinalIgnoreCase))
{
await HandleHelo(writer, line, endPoint);
helo = true;
}
else if (line.StartsWith("NOOP", StringComparison.OrdinalIgnoreCase))
{
await writer.WriteLineAsync("220 OK");
await writer.FlushAsync();
}
else if (line.StartsWith("HELP", StringComparison.OrdinalIgnoreCase))
{
await writer.WriteLineAsync("220 OK Please use EHLO command");
await writer.FlushAsync();
}
else if (!helo)
{
throw new InvalidOperationException("Client did not send greeting before line " + line);
}
// these commands may only appear after HELO/EHLO
else if (line.StartsWith("RSET", StringComparison.OrdinalIgnoreCase))
{
await writer.WriteLineAsync($"250 2.0.0 Resetting");
await writer.FlushAsync();
authenticatedUser = null;
}
else if (line.StartsWith("AUTH PLAIN", StringComparison.OrdinalIgnoreCase))
{
authenticatedUser = await AuthenticatePlain(reader, writer, line);
if (authenticatedUser.Authenticated && tcpClient.Client.RemoteEndPoint is IPEndPoint remoteEndPoint)
{
IPBan.IPBanPlugin.IPBanLoginSucceeded("SMTP", authenticatedUser.UserName, remoteEndPoint.Address.ToString());
}
else
{
throw new InvalidOperationException("Authentication failed");
}
}
else if (line.StartsWith("AUTH LOGIN", StringComparison.OrdinalIgnoreCase))
{
authenticatedUser = await AuthenticateLogin(reader, writer, line);
if (authenticatedUser.Authenticated && tcpClient.Client.RemoteEndPoint is IPEndPoint remoteEndPoint)
{
IPBan.IPBanPlugin.IPBanLoginSucceeded("SMTP", authenticatedUser.UserName, remoteEndPoint.Address.ToString());
}
else
{
throw new InvalidOperationException("Authentication failed");
}
}
// if authenticated, only valid line is MAIL FROM
// TODO: The mail from address is ignored, we replacedume only can send as yourself who you authenticated as
// consider error if from address doesn't match
// TODO: consider changing this
else if (authenticatedUser != null)
{
if (line.StartsWith("MAIL FROM:<", StringComparison.OrdinalIgnoreCase))
{
try
{
await SendMail(authenticatedUser, reader, writer, line, endPoint, true);
}
catch (Exception ex)
{
throw new ApplicationException("Error sending mail from " + endPoint, ex);
}
}
else
{
MailDemonLog.Warn("Ignoring client command: {0}", line);
}
}
else
{
if (line.StartsWith("MAIL FROM:<", StringComparison.OrdinalIgnoreCase))
{
// non-authenticated user, forward message on if possible, check settings
try
{
bool result = await ReceiveMail(reader, writer, line, endPoint);
if (!result)
{
await writer.WriteLineAsync("221 session terminated");
await writer.FlushAsync();
break;
}
}
catch (Exception ex)
{
throw new ApplicationException("Error receiving mail from " + endPoint, ex);
}
}
else
{
throw new InvalidOperationException("Invalid message: " + line + ", not authenticated");
}
}
}
}
catch (Exception ex)
{
if (!(ex is SocketException))
{
IncrementFailure(ipAddress, authenticatedUser?.UserName);
MailDemonLog.Error(ex, "{0} error", ipAddress);
}
}
finally
{
sslStream?.Dispose();
clientStream?.Dispose();
MailDemonLog.Info("{0} disconnected", ipAddress);
}
}
19
Source : MailDemonService_ParseMailFrom.cs
with MIT License
from DigitalRuby
with MIT License
from DigitalRuby
private async Task<MailFromResult> ParseMailFrom(MailDemonUser fromUser, Stream reader,
StreamWriter writer, string line, IPEndPoint endPoint)
{
string fromAddress = line.Substring(11);
int pos = fromAddress.IndexOf('>');
if (pos >= 0)
{
fromAddress = fromAddress.Substring(0, pos);
}
// if this is an anonymous user, ensure spf is a match
if (fromUser == null || !fromUser.Authenticated)
{
// validate spf
await ValidateSPF(writer, endPoint, fromAddress, fromAddress.Substring(fromAddress.IndexOf('@') + 1));
}
bool binaryMime = (line.Contains("BODY=BINARYMIME", StringComparison.OrdinalIgnoreCase));
if (!fromAddress.TryParseEmailAddress(out _))
{
await writer.WriteLineAsync($"500 invalid command - bad from address format");
await writer.FlushAsync();
throw new ArgumentException("Invalid format for from address: " + fromAddress);
}
if (fromUser != null && !fromUser.MailAddress.Address.Equals(fromAddress))
{
await writer.WriteLineAsync($"500 invalid command - bad from address");
await writer.FlushAsync();
throw new InvalidOperationException($"Invalid from address - bad from address '{fromAddress}' != '{fromUser.MailAddress.Address}'");
}
// denote success for sender and binarymime
string binaryMimeOk = (binaryMime ? " and BINARYMIME" : string.Empty);
string fromUserName = (fromUser == null ? fromAddress : fromUser.UserName);
await writer.WriteLineAsync($"250 2.1.0 sender {fromUserName}{binaryMimeOk} OK");
await writer.FlushAsync();
// read to addresses
line = await ReadLineAsync(reader);
if (line.Equals("QUIT", StringComparison.OrdinalIgnoreCase))
{
return null;
}
Dictionary<string, IEnumerable<MailboxAddress>> toAddressesByDomain = new Dictionary<string, IEnumerable<MailboxAddress>>(StringComparer.OrdinalIgnoreCase);
while (line.StartsWith("RCPT TO:<", StringComparison.OrdinalIgnoreCase))
{
string toAddress = line.Substring(9).Trim('>');
if (!toAddress.TryParseEmailAddress(out MailboxAddress toAddressMail))
{
await writer.WriteLineAsync($"500 invalid command - bad to address format for address '{toAddress}'");
await writer.FlushAsync();
throw new ArgumentException($"Invalid to address '{toAddress}'");
}
// if no authenticated user, the to address must match an existing user address
else if (fromUser == null && users.FirstOrDefault(u => u.MailAddress.Address.Equals(toAddress, StringComparison.OrdinalIgnoreCase)) == null)
{
await writer.WriteLineAsync($"500 invalid command - bad to address '{toAddress}'");
await writer.FlushAsync();
throw new InvalidOperationException($"Invalid to address '{toAddress}'");
}
// else user is authenticated, can send email to anyone
// group addresses by domain
pos = toAddress.LastIndexOf('@');
if (pos > 0)
{
string addressDomain = toAddress.Substring(++pos);
if (!toAddressesByDomain.TryGetValue(addressDomain, out IEnumerable<MailboxAddress> addressList))
{
toAddressesByDomain[addressDomain] = addressList = new List<MailboxAddress>();
}
(addressList as List<MailboxAddress>).Add(toAddressMail);
// denote success for recipient
await writer.WriteLineAsync($"250 2.1.0 recipient {toAddress} OK");
await writer.FlushAsync();
line = await ReadLineAsync(reader);
}
else
{
await writer.WriteLineAsync($"500 invalid command - bad to address '{toAddress}'");
await writer.FlushAsync();
throw new ArgumentException($"Invalid to address '{toAddress}'");
}
}
// if no to addresses, fail
if (toAddressesByDomain.Count == 0)
{
await writer.WriteLineAsync($"500 invalid command - no to address");
await writer.FlushAsync();
throw new InvalidOperationException("Invalid message: " + line);
}
if (line.StartsWith("DATA", StringComparison.OrdinalIgnoreCase))
{
if (binaryMime)
{
await writer.WriteLineAsync("503 5.5.1 Bad sequence of commands, BODY=BINARYMIME requires BDAT, not DATA");
await writer.FlushAsync();
throw new InvalidOperationException("Invalid message: " + line);
}
await writer.WriteLineAsync($"354 ok");
await writer.FlushAsync();
string tempFile = Path.Combine(AppContext.BaseDirectory, Guid.NewGuid().ToString("N") + ".msg");
int totalCount = 0;
try
{
using (Stream tempFileWriter = File.OpenWrite(tempFile))
{
int b;
int state = 0;
while (state != 5 && (b = reader.ReadByte()) >= 0)
{
if (b == (byte)'.')
{
if (state == 2)
{
// \r\n.
state = 3;
}
else
{
// reset
state = 0;
}
}
else if (b == (byte)'\r')
{
if (state == 3)
{
// \r\n.\r
state = 4;
}
else
{
// \r
state = 1;
}
}
else if (b == (byte)'\n')
{
if (state == 1)
{
// \r\n
state = 2;
}
else if (state == 4)
{
// \r\n.\r\n
state = 5;
}
else
{
// reset
state = 0;
}
}
else
{
// reset
state = 0;
}
totalCount++;
if (totalCount > maxMessageSize)
{
await writer.WriteLineAsync("552 message too large");
await writer.FlushAsync();
throw new InvalidOperationException("Invalid message: " + line);
}
tempFileWriter.WriteByte((byte)b);
}
}
// strip off the \r\n.\r\n, that is part of the protocol
using (FileStream tempFileStream = File.Open(tempFile, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
{
if (tempFileStream.Length >= 5)
{
tempFileStream.SetLength(tempFileStream.Length - 5);
}
}
return new MailFromResult
{
BackingFile = tempFile,
From = (fromUser == null ? MailboxAddress.Parse(fromAddress) : fromUser.MailAddress),
ToAddresses = toAddressesByDomain,
SuccessLine = "250 2.5.0 OK"
};
}
catch
{
File.Delete(tempFile);
throw;
}
}
else if (line.StartsWith("BDAT", StringComparison.OrdinalIgnoreCase))
{
// https://tools.ietf.org/html/rfc1830
string tempFile = Path.Combine(AppContext.BaseDirectory, Guid.NewGuid().ToString("N") + ".msg");
bool last = false;
int totalBytes = 0;
try
{
// send bdat to temp file to avoid memory issues
using (Stream stream = File.OpenWrite(tempFile))
{
do
{
int space = line.IndexOf(' ');
int space2 = line.IndexOf(' ', space + 1);
if (space2 < 0)
{
space2 = line.Length;
}
if (space < 0 || !int.TryParse(line.replacedpan(space, space2 - space),
NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, CultureInfo.InvariantCulture, out int size))
{
await writer.WriteLineAsync($"500 invalid command");
await writer.FlushAsync();
throw new InvalidOperationException("Invalid message: " + line);
}
last = line.Contains("LAST", StringComparison.OrdinalIgnoreCase);
totalBytes += size;
if (totalBytes > maxMessageSize)
{
await writer.WriteLineAsync("552 message too large");
await writer.FlushAsync();
throw new InvalidOperationException("Invalid message: " + line);
}
await ReadWriteAsync(reader, stream, size);
if (!last)
{
await writer.WriteLineAsync($"250 2.0.0 {size} bytes received OK");
await writer.FlushAsync();
}
}
while (!last && !cancelToken.IsCancellationRequested && (line = await ReadLineAsync(reader)) != null);
}
Stream fileStream = null;
try
{
fileStream = File.OpenRead(tempFile);
return new MailFromResult
{
BackingFile = tempFile,
From = (fromUser == null ? MailboxAddress.Parse(fromAddress) : fromUser.MailAddress),
ToAddresses = toAddressesByDomain,
SuccessLine = $"250 2.5.0 total {totalBytes} bytes received message OK"
};
}
catch
{
fileStream?.Dispose();
throw;
}
}
catch
{
File.Delete(tempFile);
throw;
}
}
else
{
await writer.WriteLineAsync($"500 invalid command");
await writer.FlushAsync();
throw new InvalidOperationException("Invalid line in mail from: " + line);
}
}
19
Source : MailDemonService_Receive.cs
with MIT License
from DigitalRuby
with MIT License
from DigitalRuby
public async Task ValidateSPF(StreamWriter writer, IPEndPoint connectionEndPoint, string fromAddress, string fromAddressDomain)
{
if (!requireSpfMatch)
{
return;
}
MailDemonLog.Info("Validating spf for end point {0}, from address: {1}, from domain: {2}", connectionEndPoint.Address, fromAddress, fromAddressDomain);
// example smtp host: mail-it1-f173.google.com
IPHostEntry entry = await Dns.GetHostEntryAsync(connectionEndPoint.Address);
var spfValidator = new ARSoft.Tools.Net.Spf.SpfValidator();
ARSoft.Tools.Net.Spf.ValidationResult result = await spfValidator.CheckHostAsync(connectionEndPoint.Address, fromAddressDomain, fromAddress);
if (result.Result == ARSoft.Tools.Net.Spf.SpfQualifier.Preplaced)
{
return;
}
else if (result.Result == ARSoft.Tools.Net.Spf.SpfQualifier.None)
{
// no spf record... what to do?
// TODO: Maybe email back to the address and tell them to setup SPF records...?
}
/*
LookupClient lookup = new LookupClient();
IDnsQueryResponse dnsQueryRoot = await lookup.QueryAsync(fromAddressDomain, QueryType.TXT);
foreach (var record in dnsQueryRoot.AllRecords)
{
MatchCollection ipMatches = ipRegex.Matches(record.ToString());
foreach (Match ipMatch in ipMatches)
{
if (IPAddressRange.TryParse(ipMatch.Groups["ip"].Value, out IPAddressRange testIp))
{
foreach (IPAddress ip in entry.AddressList)
{
if (testIp.Contains(ip))
{
// good
return;
}
}
}
}
MatchCollection matches = domainRegex.Matches(record.ToString());
foreach (Match match in matches)
{
string domainHost = match.Groups["domain"].Value;
IDnsQueryResponse dnsQuery = await lookup.QueryAsync(domainHost, QueryType.TXT);
foreach (var record2 in dnsQuery.AllRecords)
{
MatchCollection ipMatches2 = ipRegex.Matches(record2.ToString());
foreach (Match ipMatch in ipMatches2)
{
if (IPAddressRange.TryParse(ipMatch.Groups["ip"].Value, out IPAddressRange testIp))
{
foreach (IPAddress ip in entry.AddressList)
{
if (testIp.Contains(ip))
{
// good
return;
}
}
}
}
MatchCollection matches2 = domainRegex.Matches(record2.ToString());
foreach (Match match2 in matches2)
{
string domainHost2 = match2.Groups["domain"].Value;
IDnsQueryResponse dnsQuery3 = await lookup.QueryAsync(domainHost2, QueryType.TXT);
foreach (var record3 in dnsQuery3.AllRecords)
{
MatchCollection ipMatches3 = ipRegex.Matches(record3.ToString());
foreach (Match ipMatch in ipMatches3)
{
if (IPAddressRange.TryParse(ipMatch.Groups["ip"].Value, out IPAddressRange testIp))
{
foreach (IPAddress ip in entry.AddressList)
{
if (testIp.Contains(ip))
{
// good
return;
}
}
}
}
}
}
}
}
}
*/
if (writer != null)
{
await writer.WriteLineAsync($"500 invalid command - SPF records from mail domain '{fromAddressDomain}' do not match connection host '{entry.HostName}'");
await writer.FlushAsync();
}
throw new InvalidOperationException($"SPF validation failed for host '{entry.HostName}', address domain '{fromAddressDomain}'");
}
19
Source : MailDemonService_Receive.cs
with MIT License
from DigitalRuby
with MIT License
from DigitalRuby
private async Task<bool> ReceiveMail(Stream reader, StreamWriter writer, string line, IPEndPoint endPoint)
{
IPHostEntry entry = await Dns.GetHostEntryAsync(endPoint.Address);
MailFromResult result = await ParseMailFrom(null, reader, writer, line, endPoint);
if (result is null)
{
return false;
}
try
{
string subject;
MimeMessage msg;
using (Stream stream = File.OpenRead(result.BackingFile))
{
msg = await MimeMessage.LoadAsync(stream, true, cancelToken);
subject = msg.Subject;
}
subject = (subject ?? string.Empty).Trim();
if (subject.Equals("unsubscribe", StringComparison.OrdinalIgnoreCase))
{
UnsubscribeHandler?.Invoke(result.From.Address, subject, msg.HtmlBody);
return true;
}
// mail demon doesn't have an inbox yet, only forwarding, so see if any of the to addresses can be forwarded
foreach (var kv in result.ToAddresses)
{
foreach (MailboxAddress address in kv.Value)
{
MailDemonUser user = users.FirstOrDefault(u => u.MailAddress.Address.Equals(address.Address, StringComparison.OrdinalIgnoreCase));
// if no user or the forward address points to a user, fail
if (user == null || users.FirstOrDefault(u => u.MailAddress.Address.Equals(user.ForwardAddress.Address, StringComparison.Ordinal)) != null)
{
await writer.WriteLineAsync($"500 invalid command - user not found");
await writer.FlushAsync();
}
// setup forward headers
MailboxAddress forwardToAddress = (user.ForwardAddress ?? globalForwardAddress);
if (forwardToAddress == null)
{
await writer.WriteLineAsync($"500 invalid command - user not found 2");
await writer.FlushAsync();
}
else
{
string forwardDomain = forwardToAddress.Address.Substring(forwardToAddress.Address.IndexOf('@') + 1);
// create new object to forward on
MailFromResult newResult = new MailFromResult
{
BackingFile = result.BackingFile,
From = user.MailAddress,
ToAddresses = new Dictionary<string, IEnumerable<MailboxAddress>> { { forwardDomain, new List<MailboxAddress> { forwardToAddress } } }
};
// forward the message on and clear the forward headers
MailDemonLog.Info("Forwarding message, from: {0}, to: {1}, forward: {2}", result.From, address, forwardToAddress);
result.BackingFile = null; // we took ownership of the file
// send in background
SendMail(newResult, true, prepMsg =>
{
prepMsg.Subject = $"FW from {result.From}: {prepMsg.Subject}";
prepMsg.Cc.Clear();
prepMsg.Bcc.Clear();
string fromString = result.From.ToString();
if (prepMsg.ReplyTo.Count == 0)
{
prepMsg.ReplyTo.Add(result.From.Clone());
}
}, false).ConfigureAwait(false).GetAwaiter();
return true; // only forward to the first valid address
}
}
}
}
finally
{
result.Dispose();
}
return true;
}
19
Source : MailDemonService_Send.cs
with MIT License
from DigitalRuby
with MIT License
from DigitalRuby
private async Task SendMail(MailDemonUser foundUser, Stream reader, StreamWriter writer,
string line, IPEndPoint endPoint, bool synchronous)
{
MailFromResult result = await ParseMailFrom(foundUser, reader, writer, line, endPoint);
if (result is null)
{
return;
}
string origSuccessLine = result.SuccessLine;
int maxCount = (synchronous ? 2 : 1);
try
{
for (int i = 0; i < maxCount; i++)
{
try
{
// wait for call to complete, exception will be propagated to the caller if synchronous
result.SuccessLine = origSuccessLine;
await SendMail(result, false, null, synchronous);
break;
}
catch (Exception ex)
{
if (ex is AggregateException aggEx)
{
ex = aggEx.InnerExceptions.FirstOrDefault();
}
// denote failure to the caller
if (ex is SmtpCommandException smtpEx)
{
result.SuccessLine = (int)smtpEx.StatusCode + " " + ex.Message;
}
else
{
result.SuccessLine = "455 Internal Error: " + ex.Message;
}
if (i == 0 && maxCount > 1)
{
// wait a bit and retry
await Task.Delay(10000);
}
}
}
}
finally
{
result.Dispose();
}
// denote to caller that we have sent the message successfully
result.SuccessLine ??= $"250 2.1.0 OK";
await writer.WriteLineAsync(result.SuccessLine);
await writer.FlushAsync();
}
19
Source : MailDemonService_Tls.cs
with MIT License
from DigitalRuby
with MIT License
from DigitalRuby
private async Task<Tuple<SslStream, Stream, StreamWriter>> StartTls
(
TcpClient tcpClient,
string clientIPAddress,
Stream reader,
StreamWriter writer,
bool sendReadyCommand,
X509Certificate2 sslCertificate)
{
if (sslCertificate == null)
{
await writer.WriteLineAsync("501 Syntax error (no parameters allowed)");
await writer.FlushAsync();
return null;
}
else if (sendReadyCommand)
{
// upgrade to ssl
await writer.WriteLineAsync($"220 Ready to start TLS");
await writer.FlushAsync();
}
// create ssl stream and ensure encryption is required
SslStream sslStream = new SslStream(reader, false, null, null, EncryptionPolicy.RequireEncryption);
try
{
bool sslServerEnabled = false;
// shut everything down after 5 seconds if not success
Task.Run(async () =>
{
await Task.Delay(TimeSpan.FromSeconds(5));
if (!sslServerEnabled)
{
try
{
sslStream.Close();
tcpClient.Close();
}
catch
{
}
}
}).ConfigureAwait(false).GetAwaiter();
MailDemonLog.Info($"Starting ssl connection from client {clientIPAddress}");
await sslStream.AuthenticatereplacederverAsync(sslCertificate, false, System.Security.Authentication.SslProtocols.Tls12 |
System.Security.Authentication.SslProtocols.Tls11 | System.Security.Authentication.SslProtocols.Tls, true);
sslServerEnabled = true;
}
catch (Exception ex)
{
throw new InvalidOperationException($"Unable to negotiate ssl from client {clientIPAddress}, error: {ex}");
}
// create comm streams on top of ssl stream
Stream sslReader = sslStream;
StreamWriter sslWriter = new StreamWriter(sslStream, MailDemonExtensionMethods.Utf8EncodingNoByteMarker) { AutoFlush = true, NewLine = "\r\n" };
return new Tuple<SslStream, Stream, StreamWriter>(sslStream, sslReader, sslWriter);
}
19
Source : SynchronousTester.cs
with MIT License
from electricessence
with MIT License
from electricessence
public static Task TestAsyncFileStreamSingleThread()
{
Console.WriteLine($"File stream async benchmark.");
var sw = new Stopwatch();
return new SynchronousTester().Run((filePath, handler) =>
{
// Reuse testing method.
var queue = new ConcurrentQueue<string>();
handler(s => queue.Enqueue(s));
var a = queue.ToArray();
var len = a.Length;
queue.Clear();
Task.Run(async () =>
{
sw.Start();
using (var fs = new FileStream(filePath, FileMode.Append, FileAccess.Write, FileShare.None, 4096, true))
using (var writer = new StreamWriter(fs))
{
for (var i = 0; i < len; i++)
await writer.WriteAsync(a[i]).ConfigureAwait(false);
await writer.FlushAsync().ConfigureAwait(false);
await fs.FlushAsync().ConfigureAwait(false);
}
sw.Stop();
}).Wait();
})
.ContinueWith(t =>
{
Console.WriteLine("Total Elapsed Time: {0} seconds", sw.Elapsed.TotalSeconds);
Console.WriteLine("------------------------");
Console.WriteLine();
});
}
19
Source : Lang.SaveLang.cs
with Apache License 2.0
from Elepover
with Apache License 2.0
from Elepover
public static async Task<bool> SaveLang(bool isInvalid = false)
{ // DO NOT HANDLE ERRORS HERE.
var text = JsonConvert.SerializeObject(Vars.CurrentLang, Formatting.Indented);
var writer = new StreamWriter(File.Create(Vars.LangFile), System.Text.Encoding.UTF8);
await writer.WriteAsync(text).ConfigureAwait(false);
await writer.FlushAsync().ConfigureAwait(false);
writer.Close();
if (isInvalid)
{
Log("We've detected an invalid language file and have reset it.", "LANG", LogLevel.Warning);
Log("Please reconfigure it and try to start pmcenter again.", "LANG", LogLevel.Warning);
Vars.RestartRequired = true;
}
return true;
}
19
Source : CompanionCubeConfigLoader.cs
with GNU Affero General Public License v3.0
from Emzi0767
with GNU Affero General Public License v3.0
from Emzi0767
public async Task SaveConfigurationAsync(CompanionCubeConfig config, FileInfo file)
{
// validate the config first
this.ValidateConfiguration(config);
// serialize the config
var json = JsonConvert.SerializeObject(config, Formatting.Indented);
// write the config to a file
using (var fs = file.Create())
using (var sr = new StreamWriter(fs, CompanionCubeUtilities.UTF8))
{
await sr.WriteLineAsync(json);
await sr.FlushAsync();
}
}
19
Source : TurretConfigLoader.cs
with GNU Affero General Public License v3.0
from Emzi0767
with GNU Affero General Public License v3.0
from Emzi0767
public async Task SaveConfigurationAsync(TurretConfig config, FileInfo file)
{
// validate the config first
this.ValidateConfiguration(config);
// serialize the config
var json = JsonConvert.SerializeObject(config, Formatting.Indented);
// write the config to a file
using (var fs = file.Create())
using (var sr = new StreamWriter(fs, TurretUtilities.UTF8))
{
await sr.WriteLineAsync(json);
await sr.FlushAsync();
}
}
19
Source : FileGeneratorHelper.cs
with GNU General Public License v3.0
from fdonnet
with GNU General Public License v3.0
from fdonnet
public static async Task WriteSqlScriptsFileAsync(TSqlModel model, GeneratorSettings generatorSettings, Action<double> progressHandler = null)
{
var fileName = generatorSettings.OutputPath_SqlScripts;
var tables = model.GetAllTables().ToDictionary(currTable => currTable.Name.Parts[1].ToLower());
double progress = 0.0;
var fileStream = File.Open(fileName, FileMode.Create, FileAccess.Write);
var bufferSize = 5 * 1024 * 1024; // 5 MB
using (StreamWriter writer = new StreamWriter(fileStream, Encoding.UTF8, bufferSize))
{
// Flush stream after every table loop, manually
writer.AutoFlush = false;
// Loop only on selected tables, or on every table in model if GenerateForAllTables == true
IEnumerable<string> tableNames;
if (generatorSettings.RunGeneratorForAllTables)
tableNames = tables.Keys;
else
tableNames = (IEnumerable<string>)generatorSettings.RunGeneratorForSelectedTables ?? new string[0];
var tablesCount = tableNames.Count();
foreach (var currTableName in tableNames)
{
string sql = "";
var currTable = tables.ContainsKey(currTableName.ToLower()) ? tables[currTableName.ToLower()] : null;
if (currTable != null)
{
sql = new SqlInsertGenerator(generatorSettings, currTable).Generate();
if (sql != string.Empty) writer.WriteLine(sql);
sql = new SqlTableTypeGenerator(generatorSettings, currTable).Generate();
if (sql != string.Empty) writer.WriteLine(sql);
sql = new SqlBulkInsertGenerator(generatorSettings, currTable).Generate();
if (sql != string.Empty) writer.WriteLine(sql);
sql = new SqlBulkUpdateGenerator(generatorSettings, currTable).Generate();
if (sql != string.Empty) writer.WriteLine(sql);
sql = new SqlUpdateGenerator(generatorSettings, currTable).Generate();
if (sql != string.Empty) writer.WriteLine(sql);
sql = new SqlDeleteGenerator(generatorSettings, currTable).Generate();
if (sql != string.Empty) writer.WriteLine(sql);
sql = new SqlSelectAllGenerator(generatorSettings, currTable).Generate();
if (sql != string.Empty) writer.WriteLine(sql);
sql = new SqlSelectByPKGenerator(generatorSettings, currTable).Generate();
if (sql != string.Empty) writer.WriteLine(sql);
sql = new SqlSelectByPKListGenerator(generatorSettings, currTable).Generate();
if (sql != string.Empty) writer.WriteLine(sql);
sql = new SqlSelectByUKGenerator(generatorSettings, currTable).Generate();
if (sql != string.Empty) writer.WriteLine(sql);
await writer.FlushAsync();
progress += 100.0 / tablesCount;
progressHandler?.Invoke((int)progress);
}
}
}
return;
}
19
Source : FileGeneratorHelper.cs
with GNU General Public License v3.0
from fdonnet
with GNU General Public License v3.0
from fdonnet
public static async Task WriteCsEnreplacedyClreplacedesFileAsync(TSqlModel model, GeneratorSettings generatorSettings, Action<double> progressHandler = null)
{
var fileName = generatorSettings.OutputPath_CsEnreplacedyClreplacedes;
var tables = model.GetAllTables().ToDictionary(currTable => currTable.Name.Parts[1].ToLower());
double progress = 0.0;
var fileStream = File.Open(fileName, FileMode.Create, FileAccess.Write);
var bufferSize = 5 * 1024 * 1024; // 5 MB
using (StreamWriter writer = new StreamWriter(fileStream, Encoding.UTF8, bufferSize))
{
// Flush stream after every table loop, manually
writer.AutoFlush = false;
// Loop only on selected tables, or on every table in model if GenerateForAllTables == true
IEnumerable<string> tableNames;
if (generatorSettings.RunGeneratorForAllTables)
tableNames = tables.Keys;
else
tableNames = (IEnumerable<string>)generatorSettings.RunGeneratorForSelectedTables ?? new string[0];
var tablesCount = tableNames.Count();
foreach (var currTableName in tableNames)
{
string cs = "";
var currTable = tables.ContainsKey(currTableName.ToLower()) ? tables[currTableName.ToLower()] : null;
if (currTable != null)
{
cs = new CsEnreplacedyClreplacedGenerator(generatorSettings, currTable).Generate();
if (cs != string.Empty) writer.WriteLine(cs);
await writer.FlushAsync();
progress += 100.0 / tablesCount;
progressHandler?.Invoke((int)progress);
}
}
}
return;
}
19
Source : FileGeneratorHelper.cs
with GNU General Public License v3.0
from fdonnet
with GNU General Public License v3.0
from fdonnet
public static async Task WriteCsRepositoryClreplacedesFileAsync(TSqlModel model, GeneratorSettings generatorSettings, Action<double> progressHandler = null)
{
var fileName = generatorSettings.OutputPath_CsRepositoryClreplacedes;
var tables = model.GetAllTables().ToDictionary(currTable => currTable.Name.Parts[1].ToLower());
double progress = 0.0;
var fileStream = File.Open(fileName, FileMode.Create, FileAccess.Write);
var bufferSize = 5 * 1024 * 1024; // 5 MB
using (StreamWriter writer = new StreamWriter(fileStream, Encoding.UTF8, bufferSize))
{
// Flush stream after every table
writer.AutoFlush = false;
string cs = "";
// Loop only on selected tables, or on every table in model if GenerateForAllTables == true
IEnumerable<string> tableNames;
if (generatorSettings.RunGeneratorForAllTables)
tableNames = tables.Keys;
else
tableNames = (IEnumerable<string>)generatorSettings.RunGeneratorForSelectedTables ?? new string[0];
var tablesCount = tableNames.Count();
cs = new CsDbContextGenerator(generatorSettings, model).Generate();
writer.WriteLine(cs);
await writer.FlushAsync();
foreach (var currTableName in tableNames)
{
var currTable = tables.ContainsKey(currTableName.ToLower()) ? tables[currTableName.ToLower()] : null;
if (currTable != null)
{
cs = new CsRepositoryClreplacedGenerator(generatorSettings, currTable).Generate();
if (cs != string.Empty) writer.WriteLine(cs);
await writer.FlushAsync();
progress += 100.0 / tablesCount;
progressHandler?.Invoke((int)progress);
}
}
}
return;
}
19
Source : DictionaryFile_Helper.cs
with GNU General Public License v3.0
from flier268
with GNU General Public License v3.0
from flier268
public static async Task Save(string CSV_Filename, List<Line> lines)
{
try
{
using (StreamWriter streamWriter = new StreamWriter(CSV_Filename, false, Encoding.UTF8))
{
streamWriter.AutoFlush = false;
Line line = new Line();
lines.ForEach(x =>
{
Line temp = x.Clone();
if (temp.SimplifiedChinese_Length + temp.TraditionalChinese_Length > 0)
{
if (temp.Type.Contains("\""))
temp.Type = $"\"{temp.Type.Replace("\"", "\"\"")}\"";
if (temp.SimplifiedChinese.Contains("\""))
temp.SimplifiedChinese = $"\"{temp.SimplifiedChinese.Replace("\"", "\"\"")}\"";
if (temp.TraditionalChinese.Contains("\""))
temp.TraditionalChinese = $"\"{temp.TraditionalChinese.Replace("\"", "\"\"")}\"";
streamWriter.WriteLine($"{temp.Enable}\t{temp.Type}\t{temp.SimplifiedChinese}\t{temp.SimplifiedChinese_Priority}\t{temp.TraditionalChinese}\t{temp.TraditionalChinese_Priority}");
}
});
await streamWriter.FlushAsync();
}
}
catch (Exception e) { throw e; }
}
19
Source : TextReaderExtensionsTest.cs
with MIT License
from gimlichael
with MIT License
from gimlichael
[Fact]
public async Task CopyToAsync_ShouldCopyContentOfReaderToWriter()
{
var sut1 = $"This is a string that will be converted back and forth. Lets add some foreign characters: æøå and some punctuations as well: {Alphanumeric.PunctuationMarks}.";
var sut2 = sut1.ToTextReader();
var sut3 = new MemoryStream();
var sut4 = new StreamWriter(sut3);
await sut2.CopyToAsync(sut4);
await sut4.FlushAsync();
var sut5 = await sut3.ToEncodedStringAsync();
sut2.Dispose();
await sut3.DisposeAsync();
await sut4.DisposeAsync();
replacedert.Equal(sut1, sut5);
}
19
Source : TextHookHandle.cs
with GNU General Public License v3.0
from hanmin0822
with GNU General Public License v3.0
from hanmin0822
public async Task AttachProcess(int pid) {
await ProcessTextractor.StandardInput.WriteLineAsync("attach -P" + pid);
await ProcessTextractor.StandardInput.FlushAsync();
}
19
Source : TextHookHandle.cs
with GNU General Public License v3.0
from hanmin0822
with GNU General Public License v3.0
from hanmin0822
public async Task DetachProcess(int pid) {
await ProcessTextractor.StandardInput.WriteLineAsync("detach -P" + pid);
await ProcessTextractor.StandardInput.FlushAsync();
}
19
Source : TextHookHandle.cs
with GNU General Public License v3.0
from hanmin0822
with GNU General Public License v3.0
from hanmin0822
public async Task AttachProcessByHookCode(int pid, string HookCode) {
await ProcessTextractor.StandardInput.WriteLineAsync(HookCode + " -P" + pid);
await ProcessTextractor.StandardInput.FlushAsync();
}
19
Source : TextHookHandle.cs
with GNU General Public License v3.0
from hanmin0822
with GNU General Public License v3.0
from hanmin0822
public async Task DetachProcessByHookAddress(int pid, string HookAddress) {
//这个方法的原理是注入一个用户给定的钩子,给定一个Hook地址,由于hook地址存在,Textractor会自动卸载掉之前的
//但是后续给定的模块并不存在,于是Textractor再卸载掉这个用户自定义钩子,达到卸载一个指定Hook办法
await ProcessTextractor.StandardInput.WriteLineAsync("HW0@" + HookAddress + ":module_which_never_exists" + " -P" + pid);
await ProcessTextractor.StandardInput.FlushAsync();
}
19
Source : ProcessAbstractions.cs
with MIT License
from hasan-hasanov
with MIT License
from hasan-hasanov
public static async Task StartCmdWithInput(string input)
{
var process = new Process()
{
StartInfo = new ProcessStartInfo()
{
FileName = "cmd.exe",
RedirectStandardInput = true,
RedirectStandardOutput = true,
CreateNoWindow = false,
WindowStyle = ProcessWindowStyle.Hidden,
UseShellExecute = false,
}
};
process.Start();
await process.StandardInput.WriteLineAsync($"\"{input}\"");
await process.StandardInput.FlushAsync();
process.StandardInput.Close();
process.WaitForExit();
}
19
Source : AutoGrader.cs
with MIT License
from ianhorswill
with MIT License
from ianhorswill
public static IEnumerator Gradereplacedignment(string replacedignmentName)
{
var dir = Combine(ConfigurationFiles.GradingDirectory, replacedignmentName);
// Get the grades spreadsheet from Canvas and find the column header for the grades for this replacedignment
var canvasGrades = new Spreadsheet(Combine(dir,"canvas grades.csv"), "ID");
var replacedignmentColumn = 0;
foreach (var cName in canvasGrades.Header)
if (cName.StartsWith(replacedignmentName + " ("))
break;
else
replacedignmentColumn++;
if (replacedignmentColumn == canvasGrades.Header.Length)
{
Driver.SetOutputWindow($"No column found in canvas grades spreadsheet starting with '{replacedignmentName}'; grading aborted.");
}
var replacedignmentColumnName = canvasGrades.Header[replacedignmentColumn];
Debug.Log($"Grades are in column {replacedignmentColumnName}");
Debug.Log($"Starting grading of replacedignments in {dir}");
yield return null;
using (var results = new StreamWriter(Combine(dir, "Scores.csv")))
{
results.WriteLine("Student,Score,Errors");
foreach (var submission in Directory.GetDirectories(dir))
{
var submissionName = GetFileNameWithoutExtension(submission);
System.Diagnostics.Debug.replacedert(submissionName != null, nameof(submissionName) + " != null");
var firstUnderscore = submissionName.IndexOf('_');
var secondUnderscore = submissionName.IndexOf('_', firstUnderscore+1);
var studentName = submissionName.Substring(0, firstUnderscore);
var studentId = submissionName.Substring(firstUnderscore + 1, secondUnderscore - (firstUnderscore + 1));
Debug.Log(studentName);
Driver.SetOutputWindow($"Starting grading of {studentName}");
yield return null;
var generator = FindGeneratorDirectory(submission);
if (generator != null)
yield return Object.FindObjectOfType<UIDriver>().StartCoroutine(GradeSubmission(studentName, generator, dir, results, canvasGrades, studentId, replacedignmentColumnName));
else
{
results.WriteLine($"{studentName},0,No .gen files found");
Debug.Log("No generator found");
Driver.SetOutputWindow($"{studentName}: no .gen files found");
}
results.FlushAsync();
yield return null;
}
}
canvasGrades.Save();
Debug.Log("Grading finished");
Driver.SetOutputWindow("Grading complete");
}
19
Source : WriterAsOutputStream.cs
with MIT License
from icarus-consulting
with MIT License
from icarus-consulting
private async Task<int> NextAsync(byte[] buffer, int offset, int length)
{
var charCount = this._decoder.Value().GetCharCount(buffer, 0, length);
char[] chars = new char[charCount];
this._decoder.Value().GetChars(buffer, 0, charCount, chars, 0);
long max = Math.Min((long)length, charCount);
await this._writer.WriteAsync(chars);
await this._writer.FlushAsync();
return (int)Math.Min((long)length, charCount);
}
19
Source : JsonTemplateMapper.cs
with Apache License 2.0
from ILMTitan
with Apache License 2.0
from ILMTitan
public static async Task WriteToAsync(object template, Stream stream)
{
var jsonString = JsonConvert.SerializeObject(template);
Debug.WriteLine(jsonString);
using (var writer = new StreamWriter(stream))
{
await writer.WriteAsync(jsonString).ConfigureAwait(false);
await writer.FlushAsync().ConfigureAwait(false);
}
}
19
Source : ChatWindowViewModel.cs
with GNU General Public License v3.0
from immense
with GNU General Public License v3.0
from immense
public async Task SendChatMessage()
{
if (string.IsNullOrWhiteSpace(InputText))
{
return;
}
var chatMessage = new ChatMessage(string.Empty, InputText);
InputText = string.Empty;
await PipeStreamWriter.WriteLineAsync(JsonSerializer.Serialize(chatMessage));
await PipeStreamWriter.FlushAsync();
chatMessage.SenderName = "You";
ChatMessages.Add(chatMessage);
}
19
Source : TextHookHandler.cs
with GNU General Public License v3.0
from Isayama-Kagura
with GNU General Public License v3.0
from Isayama-Kagura
public async Task AttachProcess()
{
//ProcessTextractor.StandardInput.WriteLine("attach -P" + GamePID);
//Console.Write("attach -P" + GamePID);
//适用多个同名进程的情况,只在通过进程启动有效。
Process[] processes = Process.GetProcessesByName(ProcessGame.ProcessName);
foreach (Process process in processes)
{
await ProcessTextractor.StandardInput.WriteLineAsync("attach -P" + process.Id);
await ProcessTextractor.StandardInput.FlushAsync();
}
}
19
Source : TextHookHandler.cs
with GNU General Public License v3.0
from Isayama-Kagura
with GNU General Public License v3.0
from Isayama-Kagura
public async Task DetachProcess()
{
//适用多个同名进程的情况,只在通过进程启动有效。
Process[] processes = Process.GetProcessesByName(ProcessGame.ProcessName);
foreach (Process process in processes)
{
await ProcessTextractor.StandardInput.WriteLineAsync("detach -P" + process.Id);
await ProcessTextractor.StandardInput.FlushAsync();
}
}
See More Examples