Here are the examples of the csharp api System.IO.StreamWriter.Flush() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1402 Examples
19
Source : Log.cs
with MIT License
from 13xforever
with MIT License
from 13xforever
private static void LogInternal(Exception e, string message, LogLevel level, ConsoleColor foregroundColor, ConsoleColor? backgroundColor = null)
{
try
{
#if DEBUG
const LogLevel minLevel = LogLevel.TRACE;
#else
const LogLevel minLevel = LogLevel.DEBUG;
#endif
if (level >= minLevel && message != null)
{
Console.ForegroundColor = foregroundColor;
if (backgroundColor is ConsoleColor bg)
Console.BackgroundColor = bg;
Console.WriteLine(DateTime.Now.ToString("hh:mm:ss ") + message);
Console.ResetColor();
}
if (FileLog != null)
{
if (message != null)
FileLog.WriteLine($"{DateTime.Now:yyyy-MM-dd hh:mm:ss}\t{(long)Timer.Elapsed.TotalMilliseconds}\t{level}\t{message}");
if (e != null)
FileLog.WriteLine(e.ToString());
FileLog.Flush();
}
}
catch { }
}
19
Source : Utils.cs
with GNU General Public License v3.0
from 2dust
with GNU General Public License v3.0
from 2dust
public static void SaveLog(string strreplacedle, Exception ex)
{
try
{
string path = Path.Combine(StartupPath(), "guiLogs");
string FilePath = Path.Combine(path, DateTime.Now.ToString("yyyyMMdd") + ".txt");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
if (!File.Exists(FilePath))
{
FileStream FsCreate = new FileStream(FilePath, FileMode.Create);
FsCreate.Close();
FsCreate.Dispose();
}
FileStream FsWrite = new FileStream(FilePath, FileMode.Append, FileAccess.Write);
StreamWriter SwWrite = new StreamWriter(FsWrite);
string strContent = ex.ToString();
SwWrite.WriteLine(string.Format("{0}{1}[{2}]{3}", "--------------------------------", strreplacedle, DateTime.Now.ToString("HH:mm:ss"), "--------------------------------"));
SwWrite.Write(strContent);
SwWrite.WriteLine(Environment.NewLine);
SwWrite.WriteLine(" ");
SwWrite.Flush();
SwWrite.Close();
}
catch { }
}
19
Source : Machine.cs
with MIT License
from 3RD-Dimension
with MIT License
from 3RD-Dimension
private void Work()
{
try
{
StreamReader reader = new StreamReader(Connection);
StreamWriter writer = new StreamWriter(Connection);
int StatusPollInterval = Properties.Settings.Default.StatusPollInterval;
int ControllerBufferSize = Properties.Settings.Default.ControllerBufferSize;
BufferState = 0;
TimeSpan WaitTime = TimeSpan.FromMilliseconds(0.5);
DateTime LastStatusPoll = DateTime.Now + TimeSpan.FromSeconds(0.5);
DateTime StartTime = DateTime.Now;
DateTime LastFilePosUpdate = DateTime.Now;
bool filePosChanged = false;
bool SendMacroStatusReceived = false;
writer.Write("\n$G\n");
writer.Write("\n$#\n");
writer.Flush();
while (true)
{
Task<string> lineTask = reader.ReadLineAsync();
while (!lineTask.IsCompleted)
{
if (!Connected)
{
return;
}
while (ToSendPriority.Count > 0)
{
writer.Write((char)ToSendPriority.Dequeue());
writer.Flush();
}
if (Mode == OperatingMode.SendFile)
{
if (File.Count > FilePosition && (File[FilePosition].Length + 1) < (ControllerBufferSize - BufferState))
{
string send_line = File[FilePosition].Replace(" ", ""); // don't send whitespace to machine
writer.Write(send_line);
writer.Write('\n');
writer.Flush();
RecordLog("> " + send_line);
RaiseEvent(UpdateStatus, send_line);
RaiseEvent(LineSent, send_line);
BufferState += send_line.Length + 1;
Sent.Enqueue(send_line);
if (PauseLines[FilePosition] && Properties.Settings.Default.PauseFileOnHold)
{
Mode = OperatingMode.Manual;
}
if (++FilePosition >= File.Count)
{
Mode = OperatingMode.Manual;
}
filePosChanged = true;
}
}
else if (Mode == OperatingMode.SendMacro)
{
switch (Status)
{
case "Idle":
if (BufferState == 0 && SendMacroStatusReceived)
{
SendMacroStatusReceived = false;
string send_line = (string)ToSendMacro.Dequeue();
send_line = Calculator.Evaluate(send_line, out bool success);
if (!success)
{
ReportError("Error while evaluating macro!");
ReportError(send_line);
ToSendMacro.Clear();
}
else
{
send_line = send_line.Replace(" ", "");
writer.Write(send_line);
writer.Write('\n');
writer.Flush();
RecordLog("> " + send_line);
RaiseEvent(UpdateStatus, send_line);
RaiseEvent(LineSent, send_line);
BufferState += send_line.Length + 1;
Sent.Enqueue(send_line);
}
}
break;
case "Run":
case "Hold":
break;
default: // grbl is in some kind of alarm state
ToSendMacro.Clear();
break;
}
if (ToSendMacro.Count == 0)
Mode = OperatingMode.Manual;
}
else if (ToSend.Count > 0 && (((string)ToSend.Peek()).Length + 1) < (ControllerBufferSize - BufferState))
{
string send_line = ((string)ToSend.Dequeue()).Replace(" ", "");
writer.Write(send_line);
writer.Write('\n');
writer.Flush();
RecordLog("> " + send_line);
RaiseEvent(UpdateStatus, send_line);
RaiseEvent(LineSent, send_line);
BufferState += send_line.Length + 1;
Sent.Enqueue(send_line);
}
DateTime Now = DateTime.Now;
if ((Now - LastStatusPoll).TotalMilliseconds > StatusPollInterval)
{
writer.Write('?');
writer.Flush();
LastStatusPoll = Now;
}
//only update file pos every X ms
if (filePosChanged && (Now - LastFilePosUpdate).TotalMilliseconds > 500)
{
RaiseEvent(FilePositionChanged);
LastFilePosUpdate = Now;
filePosChanged = false;
}
Thread.Sleep(WaitTime);
}
string line = lineTask.Result;
RecordLog("< " + line);
if (line == "ok")
{
if (Sent.Count != 0)
{
BufferState -= ((string)Sent.Dequeue()).Length + 1;
}
else
{
MainWindow.Logger.Info("Received OK without anything in the Sent Buffer");
BufferState = 0;
}
}
else
{
if (line.StartsWith("error:"))
{
if (Sent.Count != 0)
{
string errorline = (string)Sent.Dequeue();
RaiseEvent(ReportError, $"{line}: {errorline}");
BufferState -= errorline.Length + 1;
}
else
{
if ((DateTime.Now - StartTime).TotalMilliseconds > 200)
RaiseEvent(ReportError, $"Received <{line}> without anything in the Sent Buffer");
BufferState = 0;
}
Mode = OperatingMode.Manual;
}
else if (line.StartsWith("<"))
{
RaiseEvent(ParseStatus, line);
SendMacroStatusReceived = true;
}
else if (line.StartsWith("[PRB:"))
{
RaiseEvent(ParseProbe, line);
RaiseEvent(LineReceived, line);
}
else if (line.StartsWith("["))
{
RaiseEvent(UpdateStatus, line);
RaiseEvent(LineReceived, line);
}
else if (line.StartsWith("ALARM"))
{
RaiseEvent(ReportError, line);
Mode = OperatingMode.Manual;
ToSend.Clear();
ToSendMacro.Clear();
}
else if (line.Length > 0)
RaiseEvent(LineReceived, line);
}
}
}
catch (Exception ex)
{
RaiseEvent(ReportError, $"Fatal Error in Work Loop: {ex.Message}");
RaiseEvent(() => Disconnect());
}
}
19
Source : TextEditor.cs
with MIT License
from Abdesol
with MIT License
from Abdesol
public void Save(Stream stream)
{
if (stream == null)
throw new ArgumentNullException("stream");
var encoding = this.Encoding;
var doreplacedent = this.Doreplacedent;
StreamWriter writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream);
if (doreplacedent != null)
doreplacedent.WriteTextTo(writer);
writer.Flush();
// do not close the stream
SetCurrentValue(IsModifiedProperty, Boxes.False);
}
19
Source : SoapSearch.cs
with MIT License
from ABN-SFLookupTechnicalSupport
with MIT License
from ABN-SFLookupTechnicalSupport
private static void Send(HttpWebRequest webRequest, string soapMessage) {
StreamWriter StreamWriter;
StreamWriter = new StreamWriter(webRequest.GetRequestStream());
StreamWriter.Write(soapMessage);
StreamWriter.Flush();
StreamWriter.Close();
}
19
Source : Logging.cs
with MIT License
from actions
with MIT License
from actions
private void EndPage()
{
if (_pageWriter != null)
{
_pageWriter.Flush();
_pageData.Flush();
//The StreamWriter object calls Dispose() on the provided Stream object when StreamWriter.Dispose is called.
_pageWriter.Dispose();
_pageWriter = null;
_pageData = null;
_jobServerQueue.QueueFileUpload(_timelineId, _timelineRecordId, "DistributedTask.Core.Log", "CustomToolLog", _dataFileName, true);
}
}
19
Source : ProcessInvoker.cs
with MIT License
from actions
with MIT License
from actions
private void StartWriteStream(Channel<string> redirectStandardIn, StreamWriter standardIn, bool keepStandardInOpen)
{
Task.Run(async () =>
{
// Write the contents as UTF8 to handle all characters.
var utf8Writer = new StreamWriter(standardIn.BaseStream, new UTF8Encoding(false));
while (!_processExitedCompletionSource.Task.IsCompleted)
{
ValueTask<string> dequeueTask = redirectStandardIn.Reader.ReadAsync(_processStandardInWriteCancellationTokenSource.Token);
string input = await dequeueTask;
if (input != null)
{
utf8Writer.WriteLine(input);
utf8Writer.Flush();
if (!keepStandardInOpen)
{
Trace.Info("Close STDIN after the first redirect finished.");
standardIn.Close();
break;
}
}
}
Trace.Info("STDIN stream write finished.");
});
}
19
Source : RichTextBoxExtended.cs
with MIT License
from Actipro
with MIT License
from Actipro
public void LoadDoreplacedent(string text) {
MemoryStream stream = new MemoryStream();
StreamWriter writer = new StreamWriter(stream);
writer.Write(text);
writer.Flush();
stream.Position = 0;
TextRange range = new TextRange(this.Doreplacedent.ContentStart, this.Doreplacedent.ContentEnd);
range.Load(stream, DataFormats.Rtf);
stream.Close();
}
19
Source : MainControl.xaml.cs
with MIT License
from Actipro
with MIT License
from Actipro
private void LoadRtf(string rtf) {
if (string.IsNullOrEmpty(rtf))
return;
TextRange textRange = new TextRange(previewRichTextBox.Doreplacedent.ContentStart, previewRichTextBox.Doreplacedent.ContentEnd);
using (MemoryStream stream = new MemoryStream()) {
using (StreamWriter writer = new StreamWriter(stream)) {
writer.Write(rtf);
writer.Flush();
stream.Seek(0, SeekOrigin.Begin);
textRange.Load(stream, DataFormats.Rtf);
}
}
}
19
Source : APIConsumerHelper.cs
with BSD 3-Clause "New" or "Revised" License
from ActuarialIntelligence
with BSD 3-Clause "New" or "Revised" License
from ActuarialIntelligence
public static ReturnType ReceiveHTTPObjectPointer<ParameterType,ReturnType>
(ParameterType parameterLObject,
string url,
RESTMethodType methodType)
{
HttpWebRequest request = (HttpWebRequest)WebRequest
.Create(url);
request.Method = methodType.ToString();
request.ContentType = "application/json";
JavaScriptSerializer serializer = new JavaScriptSerializer();
using (var sw = new StreamWriter(request.GetRequestStream()))
{
string json = serializer.Serialize(parameterLObject);
sw.Write(json);
sw.Flush();
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream receiveStream = response.GetResponseStream();
string strP = ReadResponseStream(receiveStream);
var result = JsonConvert.DeserializeObject<ReturnType>(strP);
return result;
}
19
Source : MemoryFileProvider.cs
with MIT License
from adams85
with MIT License
from adams85
public void WriteContent(string path, string content, Encoding encoding = null, bool append = false)
{
path = NormalizePath(path);
CancellationTokenSource changeTokenSource = null;
lock (_catalog)
using (MemoryStream stream = GetStreamCore(path, out File file))
{
if (content.Length == 0)
return;
if (!append)
stream.SetLength(0);
else
stream.Seek(0, SeekOrigin.End);
var writer = new StreamWriter(stream, encoding ?? Encoding.UTF8);
writer.Write(content);
writer.Flush();
if (file.ChangeTokenSource != null)
{
changeTokenSource = file.ChangeTokenSource;
file.ChangeTokenSource = new CancellationTokenSource();
}
}
changeTokenSource?.Cancel();
}
19
Source : MemoryFileProvider.cs
with MIT License
from adams85
with MIT License
from adams85
public void CreateFile(string path, string content = null, Encoding encoding = null)
{
path = NormalizePath(path);
lock (_catalog)
{
CheckPath(path);
var file = new File();
file.Content = new File.Stream(this, file);
if (content != null)
{
var writer = new StreamWriter(file.Content, encoding ?? Encoding.UTF8);
writer.Write(content);
writer.Flush();
}
_catalog.Add(path, file);
}
}
19
Source : POGenerator.cs
with MIT License
from adams85
with MIT License
from adams85
public static void Generate(this POGenerator generator, Stream output, POCatalog catalog)
{
if (generator == null)
throw new ArgumentNullException(nameof(generator));
if (output == null)
throw new ArgumentNullException(nameof(output));
var writer = new StreamWriter(output);
generator.Generate(writer, catalog);
writer.Flush();
}
19
Source : POGenerator.cs
with MIT License
from adams85
with MIT License
from adams85
public static void Generate(this POGenerator generator, Stream output, POCatalog catalog, Encoding encoding)
{
if (generator == null)
throw new ArgumentNullException(nameof(generator));
if (output == null)
throw new ArgumentNullException(nameof(output));
var writer = new StreamWriter(output, encoding);
generator.Generate(writer, catalog);
writer.Flush();
}
19
Source : Requestor.cs
with MIT License
from adoprog
with MIT License
from adoprog
public void PostRequest(string url, string json)
{
try
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
}
catch (Exception ex)
{
Log.Error("PostToFlow: Action failed to execute", ex);
}
}
19
Source : SendToFlow.cs
with MIT License
from adoprog
with MIT License
from adoprog
public void PostRequest(string url, string json)
{
try
{
var httpWebRequest = (HttpWebRequest) WebRequest.Create(url);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse) httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
}
catch
{
// TODO: Use MA logging API to log error
}
}
19
Source : FileLogger.cs
with MIT License
from adrianmteo
with MIT License
from adrianmteo
internal override void WriteMessage(string message)
{
ReaderWriterLockSlim currentLock = _allLocks[Path];
try
{
currentLock.EnterWriteLock();
using (StreamWriter writer = File.AppendText(Path))
{
writer.WriteLine(message);
writer.Flush();
}
}
catch (Exception ex)
{
Console.WriteLine("Error while writing log to file: {1}", ex.Message);
}
finally
{
currentLock.ExitWriteLock();
}
}
19
Source : HttpURLConnectionClient.cs
with MIT License
from Adyen
with MIT License
from Adyen
public string Request(string endpoint, string json, Config config, bool isApiKeyRequired, RequestOptions requestOptions = null )
{
string responseText = null;
_environment = config.Environment;
var httpWebRequest = GetHttpWebRequest(endpoint, config, isApiKeyRequired, requestOptions );
if (config.HttpRequestTimeout > 0)
{
httpWebRequest.Timeout = config.HttpRequestTimeout;
}
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
try
{
using (var response = (HttpWebResponse) httpWebRequest.GetResponse())
{
using (var reader = new StreamReader(response.GetResponseStream(), _encoding))
{
responseText = reader.ReadToEnd();
}
}
}
catch (WebException e)
{
HandleWebException(e);
}
return responseText;
}
19
Source : HttpURLConnectionClient.cs
with MIT License
from Adyen
with MIT License
from Adyen
public async Task<string> RequestAsync(string endpoint, string json, Config config, bool isApiKeyRequired, RequestOptions requestOptions = null)
{
string responseText = null;
//Set security protocol. Only TLS1.2
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var httpWebRequest = GetHttpWebRequest(endpoint, config, isApiKeyRequired, requestOptions);
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
try
{
using (var response = (HttpWebResponse)await httpWebRequest.GetResponseAsync())
{
using (var reader = new StreamReader(response.GetResponseStream(), _encoding))
{
responseText = await reader.ReadToEndAsync();
}
}
}
catch (WebException e)
{
HandleWebException(e);
}
return responseText;
}
19
Source : AElfKeyStore.cs
with MIT License
from AElfProject
with MIT License
from AElfProject
private async Task<bool> WriteKeyPairAsync(ECKeyPair keyPair, string preplacedword)
{
if (keyPair?.PrivateKey == null || keyPair.PublicKey == null)
throw new InvalidKeyPairException("Invalid keypair (null reference).", null);
// Ensure path exists
CreateKeystoreDirectory();
var address = Address.FromPublicKey(keyPair.PublicKey);
var fullPath = GetKeyFileFullPath(address.ToBase58());
await Task.Run(() =>
{
using (var writer = File.CreateText(fullPath))
{
var scryptResult = _keyStoreService.EncryptAndGenerateDefaultKeyStoreAsJson(preplacedword,
keyPair.PrivateKey,
address.ToBase58());
writer.Write(scryptResult);
writer.Flush();
}
});
return true;
}
19
Source : ExportDialog.cs
with GNU General Public License v2.0
from afrantzis
with GNU General Public License v2.0
from afrantzis
private void UpdatePatternFile(ListStore ls)
{
StreamWriter writer;
try {
FileStream fs = GetPatternFile(FileMode.Create, FileAccess.Write);
writer = new StreamWriter(fs);
}
catch (Exception e) {
System.Console.WriteLine(e.Message);
return;
}
foreach (object[] row in ls)
writer.WriteLine(row[0] as string);
writer.Flush();
writer.BaseStream.Close();
}
19
Source : TextExportBuilder.cs
with GNU General Public License v2.0
from afrantzis
with GNU General Public License v2.0
from afrantzis
public virtual int BuildBytes(IBuffer buffer, long offset, BuildBytesInfo info)
{
int nwritten = 0;
int count = info.Count;
count -= MatchAlignment(offset, info);
// emit the bytes (eg "__ __ 00 00")
for (int i = 0; i < count; i++) {
if (i != 0)
BuildSeparator(info.Separator);
nwritten += BuildByte(buffer, offset + i, info, false);
}
writer.Flush();
return nwritten;
}
19
Source : TextExportBuilder.cs
with GNU General Public License v2.0
from afrantzis
with GNU General Public License v2.0
from afrantzis
public virtual void BuildString(string str)
{
writer.Write(str);
writer.Flush();
}
19
Source : TextExportBuilder.cs
with GNU General Public License v2.0
from afrantzis
with GNU General Public License v2.0
from afrantzis
public virtual void BuildCharacter(char c)
{
writer.Write(c);
writer.Flush();
}
19
Source : IOHelper.cs
with Mozilla Public License 2.0
from agebullhu
with Mozilla Public License 2.0
from agebullhu
public static T XMLDeSerializer<T>(string args)
{
if (string.IsNullOrWhiteSpace(args) || args[0] != '<')
{
return default(T);
}
byte[] buffers;
long len;
using (var ms = new MemoryStream())
{
var sw = new StreamWriter(ms);
sw.Write(args);
sw.Flush();
len = ms.Position;
buffers = ms.GetBuffer();
}
using (var reader = XmlDictionaryReader.CreateTextReader(buffers, 0, (int)len, new XmlDictionaryReaderQuotas()))
{
var ds = new DataContractSerializer(typeof(T));
var re = (T)ds.ReadObject(reader, false);
return re;
}
}
19
Source : TxtRecorder.cs
with Mozilla Public License 2.0
from agebullhu
with Mozilla Public License 2.0
from agebullhu
private void DisposeWriters()
{
foreach (var info in _writers)
{
if (info.Value.Stream == null)
continue;
info.Value.Stream.Flush();
info.Value.Stream.Dispose();
}
_writers.Clear();
}
19
Source : IdentityBuilderExtensions.cs
with Apache License 2.0
from Aguafrommars
with Apache License 2.0
from Aguafrommars
private static IOptions<OAuthServiceAccountKey> StoreAuthFile(IServiceProvider provider, string authFilePath)
{
var authOptions = provider.GetRequiredService<IOptions<OAuthServiceAccountKey>>();
var json = JsonConvert.SerializeObject(authOptions.Value);
using (var writer = File.CreateText(authFilePath))
{
writer.Write(json);
writer.Flush();
writer.Close();
}
Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", authFilePath);
return authOptions;
}
19
Source : Program.cs
with GNU General Public License v3.0
from ahmed605
with GNU General Public License v3.0
from ahmed605
static int Main(string[] args)
{
string gtaPath = KeyUtil.FindGTADirectory();
while (gtaPath == null)
{
Console.Error.WriteLine("ERROR");
Console.Error.WriteLine("Could not find GTAIV directory. Please install GTAIV or copy EFLC.exe\n" +
"to the same path as Scruff.");
return 1;
}
byte[] key = KeyUtil.FindKey(gtaPath);
if (key == null)
{
Console.Error.WriteLine("ERROR");
Console.Error.WriteLine("Your EFLC.exe seems to be modified or is a newer version than this tool\n" +
"supports. If it is a newer version, please check for an update of Scruff.\n" +
"Scruff can not run without a supported EFLC.exe file.");
return 1;
}
KeyStore.SetKeyLoader(() => key);
CodeFormatOptions[] formats =
{
new CodeFormatOptions("d", CodeFormat.ScruffDecompile, "Default Scruff disreplacedembly format"),
new CodeFormatOptions("h", CodeFormat.ScruffHeader, "Default Scruff header/local varibles/etc format"),
new CodeFormatOptions("hl", CodeFormat.FullDecompile, "High level C-like format"),
new CodeFormatOptions("hla", CodeFormat.FullDecompileAnnotate, "High level C-like format (annotated)"),
new CodeFormatOptions("ll", CodeFormat.Disreplacedemble, "Low level raw replacedembly format"),
new CodeFormatOptions("cp", CodeFormat.CodePath, "Code path for the control-flow-replacedyzer (for debugging)"),
};
CodeFormat customFormat = CodeFormat.ScruffDecompile;
bool defaultMode = true;
string filename = null;
string outputFilename = null;
if (args.Length > 0)
{
var argsQueue = new Queue<string>(args);
while (argsQueue.Count > 0)
{
var arg = argsQueue.Dequeue();
if (arg.StartsWith("-"))
{
if (arg == "-o")
{
defaultMode = false;
outputFilename = argsQueue.Dequeue();
}
else
{
foreach (var format in formats)
{
if (arg == "-" + format.Param)
{
defaultMode = false;
customFormat = format.Format;
break;
}
}
}
}
else
{
if (argsQueue.Count > 0)
{
break;
}
filename = arg;
}
}
}
if (filename == null)
{
var formatParams = new StringBuilder();
foreach (var format in formats)
{
if (formatParams.Length > 0)
{
formatParams.Append("|");
}
formatParams.Append("-");
formatParams.Append(format.Param);
}
Console.Error.WriteLine("Scruff - A RAGE Script File Decompiler/Disreplacedembler");
Console.Error.WriteLine("v" + Version + " -- (c) 2008-2009, Aru <oneforaru at gmail dot com>");
Console.Error.WriteLine();
Console.Error.WriteLine(string.Format("Usage: scruff [{0}] [-o filename.sca] filename.sco", formatParams));
Console.Error.WriteLine();
Console.Error.WriteLine("By default, will generate filename.sca (-d) and filename.sch (-h)");
Console.Error.WriteLine("If output file is specified, only filename.sca will be generated.");
Console.Error.WriteLine("If format specified without output filename, will dump to console (stdout).");
Console.Error.WriteLine();
Console.Error.WriteLine("For custom options, use:");
Console.Error.WriteLine(" -{0,-5} {1}", "o", "Saves the result to a specified file.");
foreach (var format in formats)
{
Console.Error.WriteLine(" -{0,-5} {1}", format.Param, format.Description);
}
Console.Error.WriteLine();
/*
Console.Error.WriteLine("Press any key to exit");
Console.ReadKey();
*/
return 1;
}
var file = new ScriptFile();
try
{
file.Open(filename);
}
catch
{
Console.Error.WriteLine("Invalid input file -- not a valid script.");
/*
Console.ReadKey();
*/
return 1;
}
if (defaultMode)
{
using (var fs = File.OpenWrite(Path.ChangeExtension(filename, "sca")))
{
var sw = new StreamWriter(fs);
OutputCode(file, CodeFormat.ScruffDecompile, sw);
sw.Flush();
}
using (var fs = File.OpenWrite(Path.ChangeExtension(filename, "sch")))
{
var sw = new StreamWriter(fs);
OutputCode(file, CodeFormat.ScruffHeader, sw);
sw.Flush();
}
}
else
{
if (outputFilename != null)
{
using(var fs = File.OpenWrite(outputFilename))
{
var sw = new StreamWriter(fs);
OutputCode(file, customFormat, sw);
sw.Flush();
}
}
else
{
OutputCode(file, customFormat, Console.Out);
}
}
#if DEBUG
Console.ReadLine();
#endif
return 0;
}
19
Source : Program.cs
with GNU Affero General Public License v3.0
from aianlinb
with GNU Affero General Public License v3.0
from aianlinb
static void Main(string[] args)
{
string path = args.Length > 0 && Path.GetFileName(args[0]) == "_.index.bin" ? args[0] : "_.index.bin";
if (!File.Exists(path))
{
Console.WriteLine("File not found: " + path);
Console.WriteLine("Click enter to exit . . .");
Console.ReadLine();
return;
}
Console.WriteLine("Loading . . .");
var ic = new IndexContainer(path);
Console.WriteLine("Found:");
Console.WriteLine(ic.Bundles.Length.ToString() + " BundleRecords");
Console.WriteLine(ic.Files.Length.ToString() + " FileRecords");
Console.WriteLine(ic.Directorys.Length.ToString() + " DirectoryRecords");
Console.WriteLine(Environment.NewLine + "Generating FileList . . .");
var sw = File.CreateText("FileList.yml");
foreach (var b in ic.Bundles)
{
sw.WriteLine(b.Name + ":");
foreach (var f in b.Files)
sw.WriteLine("- " + f.path);
}
sw.Flush();
sw.Close();
Console.WriteLine("Done!");
Console.WriteLine(Environment.NewLine + "Click enter to exit . . .");
Console.ReadLine();
}
19
Source : NodeParamGenerator.cs
with MIT License
from aillieo
with MIT License
from aillieo
internal static void CreateNodeDefine(string folder, IList<NodeParamConfigEntry> entries)
{
StringBuilder stringBuilder1 = new StringBuilder();
StringBuilder stringBuilder2 = new StringBuilder();
foreach (var entry in entries)
{
if (IsTypeNameValid(entry.typeName) && entry.willGenerate)
{
string str0 = entry.safeParamTypeName;
string str1 = "m" + entry.safeParamTypeName;
stringBuilder1.AppendFormat(CodeTemplate.nodeDefineTemplate1, str0, str1);
stringBuilder2.AppendFormat(CodeTemplate.nodeDefineTemplate2, str0, str1, entry.typeName);
if (entry.includeArrayType)
{
NodeParamConfigEntry arrayEntry = entry.MakeArrayTypeEntry();
str0 = arrayEntry.safeParamTypeName;
str1 = "m" + arrayEntry.safeParamTypeName;
stringBuilder1.AppendFormat(CodeTemplate.nodeDefineTemplate1, str0, str1);
stringBuilder2.AppendFormat(CodeTemplate.nodeDefineTemplate2, str0, str1, arrayEntry.typeName);
}
}
}
string filePath = Path.Combine(folder, "NodeDefineGen.cs");
using (FileStream fs = new FileStream(filePath, FileMode.Create))
{
using (StreamWriter sw = new StreamWriter(fs))
{
sw.Write(CodeTemplate.head);
sw.Write(CodeTemplate.nodeDefineTemplate0, stringBuilder1.ToString(), stringBuilder2.ToString());
sw.Flush();
}
}
}
19
Source : NodeParamGenerator.cs
with MIT License
from aillieo
with MIT License
from aillieo
internal static void CreateOneFile(string folder, NodeParamConfigEntry nodeParamConfigEntry)
{
string str0 = nodeParamConfigEntry.typeName;
string str1 = nodeParamConfigEntry.safeParamTypeName;
string filePath = Path.Combine(folder, string.Format(CodeTemplate.filename, str1));
using (FileStream fs = new FileStream(filePath, FileMode.Create))
{
using (StreamWriter sw = new StreamWriter(fs))
{
sw.Write(CodeTemplate.head);
sw.Write(CodeTemplate.nodeParamTempate, str0, str1);
sw.Flush();
}
}
}
19
Source : Encryption.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
private static string Encrypt(string data, Byte[] key, Byte[] iv)
{
Byte[] tmp = null;
System.Security.Cryptography.TripleDES tripleDes = System.Security.Cryptography.TripleDES.Create();
ICryptoTransform encryptor = tripleDes.CreateEncryptor(key, iv);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
{
StreamWriter writer = new StreamWriter(cs);
writer.Write(data);
writer.Flush();
}
tmp = ms.ToArray();
}
return Convert.ToBase64String(tmp);
}
19
Source : MixtureDocumentationWindow.cs
with MIT License
from alelievr
with MIT License
from alelievr
void GenerateNodeMarkdownDoc(BaseNodeView view)
{
using (var fs = new FileStream(nodeManualDir + view.nodeTarget.GetType().ToString() + ".md", FileMode.OpenOrCreate))
{
fs.SetLength(0);
using (var sw = new StreamWriter(fs))
{
// Append replacedle
sw.WriteLine($"# {view.nodeTarget.name}");
// Add link to node image
sw.WriteLine($"![{view.nodeTarget.GetType()}]({GetImageLink(view.nodeTarget)})");
// Add node input tooltips
if (view.inputPortViews.Count > 0)
{
sw.WriteLine($"## Inputs");
sw.WriteLine("Port Name | Description");
sw.WriteLine("--- | ---");
foreach (var pv in view.inputPortViews)
sw.WriteLine($"{pv.portData.displayName} | {pv.portData.tooltip ?? ""}");
}
// Empty line to end the table
sw.WriteLine();
// Add node output tooltips
if (view.outputPortViews.Count > 0)
{
sw.WriteLine($"## Output");
sw.WriteLine("Port Name | Description");
sw.WriteLine("--- | ---");
foreach (var pv in view.outputPortViews)
sw.WriteLine($"{pv.portData.displayName} | {pv.portData.tooltip ?? ""}");
}
// Empty line to end the table
sw.WriteLine();
sw.WriteLine("## Description");
// Add node doreplacedentation if any
var docAttr = view.nodeTarget.GetType().GetCustomAttribute<DoreplacedentationAttribute>();
if (docAttr != null)
{
sw.WriteLine(docAttr.markdown.Trim());
}
sw.WriteLine();
if (view.nodeTarget is ShaderNode s)
{
// In case a node doesn't support all dimensions:
if (s.supportedDimensions.Count != 3)
{
sw.WriteLine("Please note that this node only support " + string.Join(" and ", s.supportedDimensions) + " dimension(s).");
}
}
sw.Flush();
}
}
}
19
Source : MixtureDocumentationWindow.cs
with MIT License
from alelievr
with MIT License
from alelievr
void GenerateNodeIndexFiles(List<BaseNodeView> nodeViews)
{
using (var fs = new FileStream(nodeManualDir + nodeIndexFile, FileMode.OpenOrCreate))
{
fs.SetLength(0);
using (var sw = new StreamWriter(fs))
{
foreach (var nodeView in nodeViews)
{
sw.WriteLine($"[{GetNodeName(nodeView)}]({nodeView.nodeTarget.GetType()}.md) ");
sw.WriteLine();
}
sw.Flush();
}
}
// We also generate toc.yml in the nodes folder
using (var fs = new FileStream(nodeManualDir + "toc.yml", FileMode.OpenOrCreate))
{
fs.SetLength(0);
using (var sw = new StreamWriter(fs))
{
foreach (var nodeView in nodeViews)
{
sw.WriteLine($"- name: {GetNodeName(nodeView)}");
sw.WriteLine($" href: {nodeView.nodeTarget.GetType().ToString()}.md");
}
}
}
}
19
Source : PerformanceTestsRunner.cs
with MIT License
from alelievr
with MIT License
from alelievr
[MenuItem("Window/Procedural Worlds/Run performance tests", priority = 10)]
public static void Run()
{
string[] performanceGraphGUIDs = replacedetDatabase.Findreplacedets("performance* t:WorldGraph");
//empty log file:
File.WriteAllText(logFilePath, string.Empty);
logFile = new StreamWriter(File.OpenWrite(logFilePath));
var resultsList = new List< PerformanceResultMulti >();
ProfilerDriver.ClearAllFrames();
ProfilerDriver.deepProfiling = true;
Profiler.logFile = tmpProfilerLogFile;
Profiler.enabled = true;
foreach (var performanceGraphGUID in performanceGraphGUIDs)
{
string path = replacedetDatabase.GUIDToreplacedetPath(performanceGraphGUID);
WorldGraph graph = replacedetDatabase.LoadreplacedetAtPath(path, typeof(WorldGraph)) as WorldGraph;
var results = new PerformanceResultMulti(tesreplacederationCount);
for (int i = 0; i < tesreplacederationCount; i++)
results.results[i] = RunTestForGraph(graph);
resultsList.Add(results);
}
Profiler.enabled = false;
ProfilerDriver.deepProfiling = false;
//this is totally broken in 2017.3 ...
#if !UNITY_2017_3
ProfilerDriver.LoadProfile(tmpProfilerLogFile, false);
ProfilerDriver.SaveProfile(profilerDataFile);
#endif
string text = SerializeResults(resultsList);
string reportPerfs = Environment.GetEnvironmentVariable("PW_REPORT_PERFORMANCES");
if (reportPerfs == "ON")
{
ReportPerformaces(resultsList);
}
logFile.Write(text);
logFile.Flush();
}
19
Source : BlockMining.cs
with MIT License
from alexanderdna
with MIT License
from alexanderdna
public bool Attempt()
{
int nonceRange = int.MaxValue - _startingNonce;
if (nonceRange > _nonceRange) nonceRange = _nonceRange;
for (int n = _startingNonce, c = _startingNonce + nonceRange; n < c; ++n)
{
HexUtils.AppendHexFromInt(_headerStreamWriter, n);
_headerStreamWriter.Flush();
var hash = Pow.Hash(_headerStream);
if (Pow.IsValidHash(hash, _difficulty))
{
Block.Nonce = n;
Block.Hash = HexUtils.HexFromByteArray(hash);
return true;
}
_headerStream.Seek(_streamOrgPosition, SeekOrigin.Begin);
}
_startingNonce += nonceRange;
if (_startingNonce == int.MaxValue)
_maxNonceReached = true;
return false;
}
19
Source : DataService.cs
with MIT License
from AliakseiFutryn
with MIT License
from AliakseiFutryn
public Stream GetData()
{
MemoryStream stream = new MemoryStream();
StreamWriter writer = new StreamWriter(stream);
writer.Write("This is data from the server.");
writer.Flush();
stream.Position = 0;
return stream;
}
19
Source : OSSEventHandler.cs
with MIT License
from aliyun
with MIT License
from aliyun
public Stream HandlePoco(OSSEvent ossEvent, IFcContext context)
{
MemoryStream output = new MemoryStream();
StreamWriter writer = new StreamWriter(output);
foreach (OSSEvent.Event evnt in ossEvent.events)
{
writer.Write(string.Format("received {0} from {1} @ {2}", evnt.eventName, evnt.eventSource, evnt.region));
writer.Write(string.Format("received bucket {0}", evnt.oss.bucket.arn));
writer.Write(string.Format("received object {0} and it's size is {1}", evnt.oss.obj.key, evnt.oss.obj.size));
}
writer.Flush();
return output;
}
19
Source : FileLogger.cs
with GNU General Public License v3.0
from Alois-xx
with GNU General Public License v3.0
from Alois-xx
public void Log(string message)
{
lock (myLock)
{
if (myFile.Position > myMaxFileSizeInBytes)
{
RollOver();
}
myLog.WriteLine(message);
myLog.Flush(); // ensure that even in case of crash we get our data written to disk and out of StreamWriter buffer
}
}
19
Source : ModelDeserializerTests.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn
with BSD 3-Clause "New" or "Revised" License
from Altinn
private static Stream CreateStream(string text)
{
MemoryStream stream = new MemoryStream();
StreamWriter writer = new StreamWriter(stream);
writer.Write(text);
writer.Flush();
stream.Position = 0;
return stream;
}
19
Source : BlobService.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn
with BSD 3-Clause "New" or "Revised" License
from Altinn
public static async Task SaveBlob(IConfiguration config, string name, string data)
{
BlobClient client;
StorageSharedKeyCredential storageCredentials = new StorageSharedKeyCredential(config["AccountName"], config["AccountKey"]);
BlobServiceClient serviceClient = new BlobServiceClient(new Uri(config["BlobEndPoint"]), storageCredentials);
BlobContainerClient blobContainerClient = serviceClient.GetBlobContainerClient(config["StorageContainer"]);
client = blobContainerClient.GetBlobClient(name);
Stream stream = new MemoryStream();
StreamWriter writer = new StreamWriter(stream);
writer.Write(data);
writer.Flush();
stream.Position = 0;
await client.UploadAsync(stream, true);
stream.Dispose();
}
19
Source : lyricPoster.cs
with GNU General Public License v2.0
from AmanoTooko
with GNU General Public License v2.0
from AmanoTooko
public static void PostJson(string text)
{
try
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create($"http://127.0.0.1:{port}/command");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write($"/s ♪ {text} ♪");
streamWriter.Flush();
streamWriter.Close();
}
httpWebRequest.GetResponse();
}
catch (Exception ex)
{
}
}
19
Source : UnifiedDiffCommand.cs
with Apache License 2.0
from AmpScm
with Apache License 2.0
from AmpScm
public override void OnExecute(CommandEventArgs e)
{
List<string> toAdd = new List<string>();
List<SvnItem> items = new List<SvnItem>();
foreach (SvnItem item in e.Selection.GetSelectedSvnItems(true))
{
if (item.IsVersioned)
{
items.Add(item);
}
else if (item.IsFile && item.IsVersionable && item.InSolution && !item.IsIgnored && !item.IsSccExcluded)
{
toAdd.Add(item.FullPath); // Add new files ### Alternative: Show them as added
items.Add(item);
}
}
if (items.Count == 0)
return;
SvnRevision start = SvnRevision.Base;
SvnRevision end = SvnRevision.Working;
// should we show the path selector?
if (e.ShouldPrompt(true))
{
using (CommonFileSelectorDialog dlg = new CommonFileSelectorDialog())
{
dlg.Text = CommandStrings.UnifiedDiffreplacedle;
dlg.Items = items;
dlg.RevisionStart = start;
dlg.RevisionEnd = end;
if (dlg.ShowDialog(e.Context) != DialogResult.OK)
return;
items.Clear();
items.AddRange(dlg.GetCheckedItems());
start = dlg.RevisionStart;
end = dlg.RevisionEnd;
}
}
if (items.Count == 0)
return;
SvnRevisionRange revRange = new SvnRevisionRange(start, end);
IAnkhTempFileManager tempfiles = e.GetService<IAnkhTempFileManager>();
string tempFile = tempfiles.GetTempFile(".patch");
IAnkhSolutionSettings ss = e.GetService<IAnkhSolutionSettings>();
string slndir = ss.ProjectRoot;
using (MemoryStream stream = new MemoryStream())
{
e.Context.GetService<IProgressRunner>().RunModal(CommandStrings.RunningDiff,
delegate(object sender, ProgressWorkerArgs ee)
{
SvnAddArgs aa = new SvnAddArgs();
aa.ThrowOnError = false;
aa.AddParents = false;
foreach (string item in toAdd)
{
ee.Client.Add(item, aa);
}
SvnDiffArgs diffArgs = new SvnDiffArgs();
diffArgs.IgnoreAncestry = true;
diffArgs.NoDeleted = false;
diffArgs.ThrowOnError = false;
foreach (SvnItem item in items)
{
SvnWorkingCopy wc;
if (!string.IsNullOrEmpty(slndir) && item.IsBelowPath(slndir))
diffArgs.RelativeToPath = slndir;
else if ((wc = item.WorkingCopy) != null)
diffArgs.RelativeToPath = wc.FullPath;
else
diffArgs.RelativeToPath = null;
if (!ee.Client.Diff(item.FullPath, revRange, diffArgs, stream))
{
if (diffArgs.LastException != null)
{
StreamWriter sw = new StreamWriter(stream);
sw.WriteLine();
sw.WriteLine(string.Format("# {0}: {1}", item.FullPath, diffArgs.LastException.Message));
sw.Flush();
// Don't dispose the writer as that might close the stream
}
if (diffArgs.IsLastInvocationCanceled)
break;
}
}
stream.Flush();
});
stream.Position = 0;
using (StreamReader sr = new StreamReader(stream))
{
File.WriteAllText(tempFile, sr.ReadToEnd(), Encoding.UTF8);
VsShellUtilities.OpenDoreplacedent(e.Context, tempFile);
}
}
}
19
Source : MainForm.cs
with Mozilla Public License 2.0
from amrali-eg
with Mozilla Public License 2.0
from amrali-eg
private void OnConvert(object sender, EventArgs e)
{
if (lstResults.CheckedItems.Count == 0)
{
ShowWarning("Select one or more files to convert");
return;
}
// stop drawing of the results list view control
lstResults.BeginUpdate();
lstResults.ItemChecked -= OnResulreplacedemChecked;
foreach (ListViewItem item in lstResults.CheckedItems)
{
string charset = item.SubItems[RESULTS_COLUMN_CHARSET].Text;
if (charset == "(Unknown)")
continue;
string fileName = item.SubItems[RESULTS_COLUMN_FILE_NAME].Text;
string directory = item.SubItems[RESULTS_COLUMN_DIRECTORY].Text;
string filePath = Path.Combine(directory, fileName);
FileAttributes attributes = File.GetAttributes(filePath);
if ((attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
{
attributes ^= FileAttributes.ReadOnly;
File.SetAttributes(filePath, attributes);
}
if (!Encoding.GetEncoding(charset).Validate(File.ReadAllBytes(filePath)))
{
Debug.WriteLine("Decoding error. " + filePath);
continue;
}
string content;
using (StreamReader reader = new StreamReader(filePath, Encoding.GetEncoding(charset)))
content = reader.ReadToEnd();
string targetCharset = (string)lstConvert.SelectedItem;
Encoding encoding;
// handle UTF-8 and UTF-8 with BOM
if (targetCharset == "utf-8")
{
encoding = new UTF8Encoding(false);
}
else if (targetCharset == "utf-8-bom")
{
encoding = new UTF8Encoding(true);
}
else
{
encoding = Encoding.GetEncoding(targetCharset);
}
using (StreamWriter writer = new StreamWriter(filePath, append: false, encoding))
{
// TODO: catch exceptions
writer.Write(content);
writer.Flush();
}
item.Checked = false;
item.ImageIndex = 0;
item.SubItems[RESULTS_COLUMN_CHARSET].Text = targetCharset;
}
// resume drawing of the results list view control
lstResults.ItemChecked += OnResulreplacedemChecked;
lstResults.EndUpdate();
// execute handler of the 'ItemChecked' event
OnResulreplacedemChecked(lstResults, new ItemCheckedEventArgs(lstResults.Items[0]));
}
19
Source : FileLogger.cs
with GNU General Public License v3.0
from AndreiFedarets
with GNU General Public License v3.0
from AndreiFedarets
protected override void LogInternal(TraceEventType eventType, string source, string message)
{
StringBuilder builder = new StringBuilder();
builder.AppendFormat("EventType: {0}{1}", eventType, Environment.NewLine);
builder.AppendFormat("Source: {0}{1}", source, Environment.NewLine);
builder.AppendFormat("Message: {0}{1}", message, Environment.NewLine);
builder.AppendLine("====================================================================================");
StreamWriter writer = GetWriter();
writer.Write(builder);
writer.Flush();
}
19
Source : JsonSerializer.cs
with MIT License
from AndreiMisiukevich
with MIT License
from AndreiMisiukevich
public T Deserialize<T>(string serializedString)
{
var serializer = new DataContractJsonSerializer(typeof(T));
var memoryStream = new MemoryStream();
var writer = new StreamWriter(memoryStream);
writer.Write(serializedString);
writer.Flush();
memoryStream.Position = 0;
using (memoryStream)
{
return (T) serializer.ReadObject(memoryStream);
}
}
19
Source : Rqq.cs
with MIT License
from AndreyAkinshin
with MIT License
from AndreyAkinshin
public void DumpTreeAscii([NotNull] StreamWriter writer, bool details = false)
{
var valuesStr = values.Select(v => v.ToString(CultureInfo.InvariantCulture)).ToArray(); // TODO: precision
// Calculate width for each node
var width = new int[nodeCount];
for (int node = 0; node < nodeCount; node++)
{
width[node] += rangeRight[node] - rangeLeft[node] + 2; // result += <widths of spaces>
if (kinds[node] != NodeKind.Fake)
for (int i = rangeLeft[node]; i <= rangeRight[node]; i++)
width[node] += valuesStr[i].Length; // result += <widths of values>
width[node] += 2; // result += <widths of borders>
}
// Calculate padding for each node and connector-with-child positions
var paddingLeft = new int[nodeCount];
var paddingRight = new int[nodeCount];
var connectorDownLeft = new int[nodeCount];
var connectorDownRight = new int[nodeCount];
var connectorUp = new int[nodeCount];
for (int node = nodeCount - 1; node >= 0; node--)
{
if (kinds[node] == NodeKind.Parent)
{
int child1 = node * 2 + 1;
int child2 = node * 2 + 2;
int totalWidth1 = paddingLeft[child1] + width[child1] + paddingRight[child1];
int totalWidth2 = paddingLeft[child2] + width[child2] + paddingRight[child2];
int childrenWidth = totalWidth1 + 1 + totalWidth2;
int padding = Math.Max(0, childrenWidth - width[node]);
paddingLeft[node] = paddingLeft[child1] + width[child1] +
(paddingRight[child1] + 1 + paddingLeft[child2]) / 2 -
width[node] / 2;
paddingRight[node] = padding - paddingLeft[node];
connectorDownLeft[node] = 1;
connectorDownRight[node] = width[node] - 2;
connectorUp[child1] = paddingLeft[node] + connectorDownLeft[node] - paddingLeft[child1];
connectorUp[child2] = paddingLeft[node] + connectorDownRight[node] -
(totalWidth1 + 1) - paddingLeft[child2];
}
}
int layer = -1;
while (true)
{
layer++;
int node2 = (1 << (layer + 1)) - 2;
int node1 = node2 - (1 << layer) + 1;
if (node1 >= nodeCount)
break;
void DumpLine(char leftBorder, char separator, char rightBorder, Func<int, string> element,
char? down = null, char? up = null)
{
for (int node = node1; node <= node2; node++)
{
if (kinds[node] == NodeKind.Fake)
{
if (node % 2 == 1) // It's a left child
{
int parentIndex = (node - 1) / 2;
int parentWidth = 1 + paddingLeft[parentIndex] + width[parentIndex] +
paddingRight[parentIndex];
for (int j = 0; j < parentWidth; j++)
writer.Write(' ');
}
continue;
}
int position = -paddingLeft[node];
void PrintChar(char c)
{
if (kinds[node] == NodeKind.Parent && down.HasValue &&
(position == connectorDownLeft[node] ||
position == connectorDownRight[node]))
writer.Write(down.Value);
else if (position == connectorUp[node] && node > 0 && up.HasValue)
writer.Write(up.Value);
else
writer.Write(c);
position++;
}
void PrintString(string s)
{
foreach (var c in s)
PrintChar(c);
}
for (int j = 0; j < paddingLeft[node]; j++)
PrintChar(' ');
PrintChar(leftBorder);
PrintChar(separator);
for (int i = rangeLeft[node]; i <= rangeRight[node]; i++)
{
string elementStr = element(i);
int elementPadding = Math.Max(0, valuesStr[i].Length - elementStr.Length);
for (int j = 0; j < elementPadding; j++)
PrintChar(separator);
PrintString(elementStr);
if (i != rangeRight[node])
PrintChar(separator);
}
PrintChar(separator);
PrintChar(rightBorder);
for (int j = 0; j < paddingRight[node]; j++)
PrintChar(' ');
if (node != node2)
PrintChar(' ');
}
writer.WriteLine();
}
DumpLine('┌', '─', '┐', i => "─", up: '┴');
DumpLine('│', ' ', '│', i => valuesStr[i]);
DumpLine('│', ' ', '│', i => b[i] == BinaryFlag.NotDefined ? " " : ((int) b[i]).ToString());
DumpLine('└', '─', '┘', i => "─", down: '┬');
DumpLine(' ', ' ', ' ', i => "", down: '│');
}
writer.WriteLine();
if (details)
{
for (int node = 0; node < nodeCount; node++)
{
writer.Write('#');
writer.Write(node.ToString());
writer.Write(": ");
switch (kinds[node])
{
case NodeKind.Parent:
writer.Write("NODE(");
for (int i = rangeLeft[node]; i <= rangeRight[node]; i++)
{
writer.Write(valuesStr[i]);
if (i != rangeRight[node])
writer.Write(',');
}
writer.Write("); Children = { #");
writer.Write(node * 2 + 1);
writer.Write(", #");
writer.Write(node * 2 + 2);
writer.WriteLine(" }");
break;
case NodeKind.Leaf:
writer.Write("LEAF(");
writer.Write(valuesStr[rangeLeft[node]]);
writer.WriteLine(")");
break;
case NodeKind.Fake:
writer.WriteLine("FAKE");
break;
default:
throw new ArgumentOutOfRangeException();
}
}
writer.WriteLine();
writer.WriteLine("Allocated values : " + values.Length);
writer.WriteLine("Used values : " + usedValues);
}
writer.Flush();
}
19
Source : HttpListenerResponse.cs
with MIT License
from andruzzzhka
with MIT License
from andruzzzhka
internal WebHeaderCollection WriteHeadersTo (MemoryStream destination)
{
var headers = new WebHeaderCollection (HttpHeaderType.Response, true);
if (_headers != null)
headers.Add (_headers);
if (_contentType != null) {
var type = _contentType.IndexOf ("charset=", StringComparison.Ordinal) == -1 &&
_contentEncoding != null
? String.Format ("{0}; charset={1}", _contentType, _contentEncoding.WebName)
: _contentType;
headers.InternalSet ("Content-Type", type, true);
}
if (headers["Server"] == null)
headers.InternalSet ("Server", "websocket-sharp/1.0", true);
var prov = CultureInfo.InvariantCulture;
if (headers["Date"] == null)
headers.InternalSet ("Date", DateTime.UtcNow.ToString ("r", prov), true);
if (!_sendChunked)
headers.InternalSet ("Content-Length", _contentLength.ToString (prov), true);
else
headers.InternalSet ("Transfer-Encoding", "chunked", true);
/*
* Apache forces closing the connection for these status codes:
* - 400 Bad Request
* - 408 Request Timeout
* - 411 Length Required
* - 413 Request Enreplacedy Too Large
* - 414 Request-Uri Too Long
* - 500 Internal Server Error
* - 503 Service Unavailable
*/
var closeConn = !_context.Request.KeepAlive ||
!_keepAlive ||
_statusCode == 400 ||
_statusCode == 408 ||
_statusCode == 411 ||
_statusCode == 413 ||
_statusCode == 414 ||
_statusCode == 500 ||
_statusCode == 503;
var reuses = _context.Connection.Reuses;
if (closeConn || reuses >= 100) {
headers.InternalSet ("Connection", "close", true);
}
else {
headers.InternalSet (
"Keep-Alive", String.Format ("timeout=15,max={0}", 100 - reuses), true);
if (_context.Request.ProtocolVersion < HttpVersion.Version11)
headers.InternalSet ("Connection", "keep-alive", true);
}
if (_location != null)
headers.InternalSet ("Location", _location, true);
if (_cookies != null)
foreach (Cookie cookie in _cookies)
headers.InternalSet ("Set-Cookie", cookie.ToResponseString (), true);
var enc = _contentEncoding ?? Encoding.Default;
var writer = new StreamWriter (destination, enc, 256);
writer.Write ("HTTP/{0} {1} {2}\r\n", _version, _statusCode, _statusDescription);
writer.Write (headers.ToStringMultiValue (true));
writer.Flush ();
// replacedumes that the destination was at position 0.
destination.Position = enc.GetPreamble ().Length;
return headers;
}
19
Source : Logger.cs
with MIT License
from andruzzzhka
with MIT License
from andruzzzhka
public void Dispose()
{
LogWriter.Flush();
LogWriter.Close();
}
19
Source : CsvOutputFormatter.cs
with GNU General Public License v3.0
from andysal
with GNU General Public License v3.0
from andysal
private void writeStream(Type type, object value, Stream stream)
{
Type itemType = type.GetGenericArguments()[0];
StringWriter _stringWriter = new StringWriter();
_stringWriter.WriteLine(
string.Join<string>(
";", itemType.GetProperties().Select(x => x.Name)
)
);
foreach (var obj in (IEnumerable<object>)value)
{
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, ";");
}
else
{
_valueLine = string.Concat(string.Empty, ";");
}
}
_stringWriter.WriteLine(_valueLine.TrimEnd(';'));
}
var streamWriter = new StreamWriter(stream);
streamWriter.Write(_stringWriter.ToString());
streamWriter.Flush();
}
See More Examples