Here are the examples of the csharp api System.IO.TextWriter.Write(string, params object[]) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1383 Examples
19
View Source File : LogWriter.cs
License : MIT License
Project Creator : 0x0ade
License : MIT License
Project Creator : 0x0ade
public override void Write(string? value) {
STDOUT?.Write(value);
File?.Write(value);
File?.Flush();
}
19
View Source File : Disassembler.cs
License : MIT License
Project Creator : 0xd4d
License : MIT License
Project Creator : 0xd4d
public void Disreplacedemble(Formatter formatter, TextWriter output, DisasmInfo method) {
formatterOutput.writer = output;
targets.Clear();
sortedTargets.Clear();
bool uppercaseHex = formatter.Options.UppercaseHex;
output.Write(commentPrefix);
output.WriteLine("================================================================================");
output.Write(commentPrefix);
output.WriteLine(method.MethodFullName);
uint codeSize = 0;
foreach (var info in method.Code)
codeSize += (uint)info.Code.Length;
var codeSizeHexText = codeSize.ToString(uppercaseHex ? "X" : "x");
output.WriteLine($"{commentPrefix}{codeSize} (0x{codeSizeHexText}) bytes");
var instrCount = method.Instructions.Count;
var instrCountHexText = instrCount.ToString(uppercaseHex ? "X" : "x");
output.WriteLine($"{commentPrefix}{instrCount} (0x{instrCountHexText}) instructions");
void Add(ulong address, TargetKind kind) {
if (!targets.TryGetValue(address, out var addrInfo))
targets[address] = new AddressInfo(kind);
else if (addrInfo.Kind < kind)
addrInfo.Kind = kind;
}
if (method.Instructions.Count > 0)
Add(method.Instructions[0].IP, TargetKind.Unknown);
foreach (ref var instr in method.Instructions) {
switch (instr.FlowControl) {
case FlowControl.Next:
case FlowControl.Interrupt:
break;
case FlowControl.UnconditionalBranch:
Add(instr.NextIP, TargetKind.Unknown);
if (instr.Op0Kind == OpKind.NearBranch16 || instr.Op0Kind == OpKind.NearBranch32 || instr.Op0Kind == OpKind.NearBranch64)
Add(instr.NearBranchTarget, TargetKind.Branch);
break;
case FlowControl.ConditionalBranch:
case FlowControl.XbeginXabortXend:
if (instr.Op0Kind == OpKind.NearBranch16 || instr.Op0Kind == OpKind.NearBranch32 || instr.Op0Kind == OpKind.NearBranch64)
Add(instr.NearBranchTarget, TargetKind.Branch);
break;
case FlowControl.Call:
if (instr.Op0Kind == OpKind.NearBranch16 || instr.Op0Kind == OpKind.NearBranch32 || instr.Op0Kind == OpKind.NearBranch64)
Add(instr.NearBranchTarget, TargetKind.Call);
break;
case FlowControl.IndirectBranch:
Add(instr.NextIP, TargetKind.Unknown);
// Unknown target
break;
case FlowControl.IndirectCall:
// Unknown target
break;
case FlowControl.Return:
case FlowControl.Exception:
Add(instr.NextIP, TargetKind.Unknown);
break;
default:
Debug.Fail($"Unknown flow control: {instr.FlowControl}");
break;
}
var baseReg = instr.MemoryBase;
if (baseReg == Register.RIP || baseReg == Register.EIP) {
int opCount = instr.OpCount;
for (int i = 0; i < opCount; i++) {
if (instr.GetOpKind(i) == OpKind.Memory) {
if (method.Contains(instr.IPRelativeMemoryAddress))
Add(instr.IPRelativeMemoryAddress, TargetKind.Branch);
break;
}
}
}
else if (instr.MemoryDisplSize >= 2) {
ulong displ;
switch (instr.MemoryDisplSize) {
case 2:
case 4: displ = instr.MemoryDisplacement; break;
case 8: displ = (ulong)(int)instr.MemoryDisplacement; break;
default:
Debug.Fail($"Unknown mem displ size: {instr.MemoryDisplSize}");
goto case 8;
}
if (method.Contains(displ))
Add(displ, TargetKind.Branch);
}
}
foreach (var map in method.ILMap) {
if (targets.TryGetValue(map.nativeStartAddress, out var info)) {
if (info.Kind < TargetKind.BlockStart && info.Kind != TargetKind.Unknown)
info.Kind = TargetKind.BlockStart;
}
else
targets.Add(map.nativeStartAddress, info = new AddressInfo(TargetKind.Unknown));
if (info.ILOffset < 0)
info.ILOffset = map.ilOffset;
}
int labelIndex = 0, methodIndex = 0;
string GetLabel(int index) => LABEL_PREFIX + index.ToString();
string GetFunc(int index) => FUNC_PREFIX + index.ToString();
foreach (var kv in targets) {
if (method.Contains(kv.Key))
sortedTargets.Add(kv);
}
sortedTargets.Sort((a, b) => a.Key.CompareTo(b.Key));
foreach (var kv in sortedTargets) {
var address = kv.Key;
var info = kv.Value;
switch (info.Kind) {
case TargetKind.Unknown:
info.Name = null;
break;
case TargetKind.Data:
info.Name = GetLabel(labelIndex++);
break;
case TargetKind.BlockStart:
case TargetKind.Branch:
info.Name = GetLabel(labelIndex++);
break;
case TargetKind.Call:
info.Name = GetFunc(methodIndex++);
break;
default:
throw new InvalidOperationException();
}
}
foreach (ref var instr in method.Instructions) {
ulong ip = instr.IP;
if (targets.TryGetValue(ip, out var lblInfo)) {
output.WriteLine();
if (!(lblInfo.Name is null)) {
output.Write(lblInfo.Name);
output.Write(':');
output.WriteLine();
}
if (lblInfo.ILOffset >= 0) {
if (ShowSourceCode) {
foreach (var info in sourceCodeProvider.GetStatementLines(method, lblInfo.ILOffset)) {
output.Write(commentPrefix);
var line = info.Line;
int column = commentPrefix.Length;
WriteWithTabs(output, line, 0, line.Length, '\0', ref column);
output.WriteLine();
if (info.Partial) {
output.Write(commentPrefix);
column = commentPrefix.Length;
WriteWithTabs(output, line, 0, info.Span.Start, ' ', ref column);
output.WriteLine(new string('^', info.Span.Length));
}
}
}
}
}
if (ShowAddresses) {
var address = FormatAddress(bitness, ip, uppercaseHex);
output.Write(address);
output.Write(" ");
}
else
output.Write(formatter.Options.TabSize > 0 ? "\t\t" : " ");
if (ShowHexBytes) {
if (!method.TryGetCode(ip, out var nativeCode))
throw new InvalidOperationException();
var codeBytes = nativeCode.Code;
int index = (int)(ip - nativeCode.IP);
int instrLen = instr.Length;
for (int i = 0; i < instrLen; i++) {
byte b = codeBytes[index + i];
output.Write(b.ToString(uppercaseHex ? "X2" : "x2"));
}
int missingBytes = HEXBYTES_COLUMN_BYTE_LENGTH - instrLen;
for (int i = 0; i < missingBytes; i++)
output.Write(" ");
output.Write(" ");
}
formatter.Format(instr, formatterOutput);
output.WriteLine();
}
}
19
View Source File : Program.cs
License : MIT License
Project Creator : 13xforever
License : MIT License
Project Creator : 13xforever
static void Main(string[] args)
{
if (args.Length != 1)
{
Console.WriteLine("Usage:");
Console.WriteLine(" gvas-converter path_to_save_file|path_to_json");
return;
}
var ext = Path.GetExtension(args[0]).ToLower();
if (ext == ".json")
{
Console.WriteLine("Not implemented atm");
}
else
{
Console.WriteLine("Parsing UE4 save file structure...");
Gvas save;
using (var stream = File.Open(args[0], FileMode.Open, FileAccess.Read, FileShare.Read))
save = UESerializer.Read(stream);
Console.WriteLine("Converting to json...");
var json = JsonConvert.SerializeObject(save, new JsonSerializerSettings{Formatting = Formatting.Indented});
Console.WriteLine("Saving json...");
using (var stream = File.Open(args[0] + ".json", FileMode.Create, FileAccess.Write, FileShare.Read))
using (var writer = new StreamWriter(stream, new UTF8Encoding(false)))
writer.Write(json);
}
Console.WriteLine("Done.");
Console.ReadKey(true);
}
19
View Source File : FrmMain.cs
License : MIT License
Project Creator : A-Tabeshfard
License : MIT License
Project Creator : A-Tabeshfard
private void MnuFileSave_Click(object sender, EventArgs e)
{
try
{
if (!((FrmContent)ActiveMdiChild).NameCondition)
MnuFileSaveAs_Click(sender, e);
else
{
_streamWriter = new StreamWriter(ActiveMdiChild.Text);
_streamWriter.Write(((FrmContent)ActiveMdiChild).textBox.Text);
((FrmContent)ActiveMdiChild).SaveCondition = false;
ActiveMdiChild.Text = _saveFileDialog.FileName;
((FrmContent)ActiveMdiChild).NameCondition = true;
((FrmContent)ActiveMdiChild).SaveCondition = false;
}
}
catch (Exception Ex)
{
MessageBox.Show(Ex.Message, "Note Pad", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
if (_streamWriter != null)
_streamWriter.Close();
}
}
19
View Source File : FrmMain.cs
License : MIT License
Project Creator : A-Tabeshfard
License : MIT License
Project Creator : A-Tabeshfard
internal void MnuFileSaveAs_Click(object sender, EventArgs e)
{
try
{
_saveFileDialog.FileName = ActiveMdiChild.Text;
if (_saveFileDialog.ShowDialog() == DialogResult.OK)
{
_streamWriter = new StreamWriter(_saveFileDialog.OpenFile());
_streamWriter.Write(((FrmContent)ActiveMdiChild).textBox.Text);
ActiveMdiChild.Text = _saveFileDialog.FileName;
((FrmContent)ActiveMdiChild).NameCondition = true;
((FrmContent)ActiveMdiChild).SaveCondition = false;
}
}
catch (Exception Ex)
{
MessageBox.Show(Ex.Message, "Note Pad", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
if (_streamWriter != null)
_streamWriter.Close();
}
}
19
View Source File : ZUART.cs
License : MIT License
Project Creator : a2633063
License : MIT License
Project Creator : a2633063
private void lkbSaveRev_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
//if (txtShowData.Text.Length < 1)
//{
// MessageBox("");
// return;
//}
StreamWriter myStream;
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "文本文档(*.txt)|*.txt|所有文件(*.*)|*.*";
saveFileDialog1.RestoreDirectory = true;
saveFileDialog1.replacedle = "保存接受区数据";
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
myStream = new StreamWriter(saveFileDialog1.FileName);
myStream.Write(txtShowData.Text); //写入
myStream.Close();//关闭流
}
}
19
View Source File : SerializeHelper.cs
License : GNU General Public License v3.0
Project Creator : a2659802
License : GNU General Public License v3.0
Project Creator : a2659802
public static void SaveGlobalSettings(object data)
{
var settings = data;
if (settings is null)
return;
//Log("Saving Global Settings");
if (File.Exists(GLOBAL_FILE_DIR + ".bak"))
{
File.Delete(GLOBAL_FILE_DIR + ".bak");
}
if (File.Exists(GLOBAL_FILE_DIR))
{
File.Move(GLOBAL_FILE_DIR, GLOBAL_FILE_DIR + ".bak");
}
using (FileStream fileStream = File.Create(GLOBAL_FILE_DIR))
{
using (var writer = new StreamWriter(fileStream))
{
try
{
writer.Write
(
JsonConvert.SerializeObject
(
settings,
Formatting.Indented,
new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.Auto,
}
)
);
}
catch (Exception e)
{
LogError(e);
}
}
}
}
19
View Source File : SerializeHelper.cs
License : GNU General Public License v3.0
Project Creator : a2659802
License : GNU General Public License v3.0
Project Creator : a2659802
public static void SaveSceneSettings(object data,string sceneName)
{
string dir = Path.Combine(DATA_DIR, sceneName+".json");
using (FileStream fileStream = File.Create(dir))
{
using (var writer = new StreamWriter(fileStream))
{
try
{
writer.Write
(
JsonConvert.SerializeObject
(
data,
Formatting.Indented,
new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.Auto,
}
)
);
}
catch (Exception e)
{
LogError(e);
}
}
}
}
19
View Source File : CharRope.cs
License : MIT License
Project Creator : Abdesol
License : MIT License
Project Creator : Abdesol
internal static void WriteTo(this RopeNode<char> node, int index, TextWriter output, int count)
{
if (node.height == 0) {
if (node.contents == null) {
// function node
node.GetContentNode().WriteTo(index, output, count);
} else {
// leaf node: append data
output.Write(node.contents, index, count);
}
} else {
// concat node: do recursive calls
if (index + count <= node.left.length) {
node.left.WriteTo(index, output, count);
} else if (index >= node.left.length) {
node.right.WriteTo(index - node.left.length, output, count);
} else {
int amountInLeft = node.left.length - index;
node.left.WriteTo(index, output, amountInLeft);
node.right.WriteTo(0, output, count - amountInLeft);
}
}
}
19
View Source File : RichTextWriter.cs
License : MIT License
Project Creator : Abdesol
License : MIT License
Project Creator : Abdesol
public void Write(RichText richText)
{
Write(richText, 0, richText.Length);
}
19
View Source File : RichTextWriter.cs
License : MIT License
Project Creator : Abdesol
License : MIT License
Project Creator : Abdesol
public virtual void Write(RichText richText, int offset, int length)
{
foreach (var section in richText.GetHighlightedSections(offset, length)) {
BeginSpan(section.Color);
Write(richText.Text.Substring(section.Offset, section.Length));
EndSpan();
}
}
19
View Source File : AssemblyDefinition.cs
License : Apache License 2.0
Project Creator : abist-co-ltd
License : Apache License 2.0
Project Creator : abist-co-ltd
public void Save(string fileName)
{
if (string.IsNullOrWhiteSpace(fileName))
{
Debug.LogError("A name for the replacedembly definition file must be specified.");
return;
}
FileInfo file = new FileInfo(fileName);
bool readOnly = (file.Exists) ? file.IsReadOnly : false;
if (readOnly)
{
file.IsReadOnly = false;
}
Debug.Log($"Saving {fileName}");
using (StreamWriter writer = new StreamWriter(fileName, false))
{
writer.Write(JsonUtility.ToJson(this, true));
}
if (readOnly)
{
file.IsReadOnly = true;
}
}
19
View Source File : LiquidExtensions.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
private static void InternalRenderLiquid(string source, string sourceIdentifier, TextWriter output, Context context)
{
Template template;
if (!string.IsNullOrEmpty(sourceIdentifier))
{
sourceIdentifier = string.Format(" ({0})", sourceIdentifier);
}
try
{
using (PerformanceProfiler.Instance.StartMarker(PerformanceMarkerName.LiquidExtension, PerformanceMarkerArea.Liquid, PerformanceMarkerTagName.LiquidSourceParsed))
{
template = Template.Parse(source);
}
}
catch (SyntaxException e)
{
ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format("Liquid parse error{0}: {1}", sourceIdentifier, e.ToString()));
output.Write(e.Message);
return;
}
ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Rendering Liquid{0}", sourceIdentifier));
using (PerformanceProfiler.Instance.StartMarker(PerformanceMarkerName.LiquidExtension, PerformanceMarkerArea.Liquid, PerformanceMarkerTagName.RenderLiquid))
{
template.Render(output, RenderParameters.FromContext(context));
}
foreach (var error in template.Errors)
{
ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format("Liquid rendering error{0}: {1}", sourceIdentifier, error.ToString()));
}
}
19
View Source File : Rating.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public override void Render(Context context, TextWriter result)
{
IPortalLiquidContext portalLiquidContext;
if (!context.TryGetPortalLiquidContext(out portalLiquidContext))
{
return;
}
string id;
Guid parsedId;
if (!this.TryGetAttributeValue(context, "id", out id) || !Guid.TryParse(id, out parsedId))
{
throw new SyntaxException("Syntax Error in 'rating' tag. Missing required attribute 'id:[string]'");
}
string enreplacedy;
if (!this.TryGetAttributeValue(context, "enreplacedy", out enreplacedy) || string.IsNullOrWhiteSpace(enreplacedy))
{
enreplacedy = "adx_webpage";
}
string readonlyString;
var parsedReadonly = false;
if (this.TryGetAttributeValue(context, "readonly", out readonlyString))
{
bool.TryParse(readonlyString, out parsedReadonly);
}
string panel;
var parsedPanel = false;
if (this.TryGetAttributeValue(context, "panel", out panel))
{
bool.TryParse(panel, out parsedPanel);
}
string panelSnippet;
this.TryGetAttributeValue(context, "snippet", out panelSnippet);
string step;
this.TryGetAttributeValue(context, "step", out step);
string min;
this.TryGetAttributeValue(context, "min", out min);
string max;
this.TryGetAttributeValue(context, "max", out max);
string round;
var parsedRound = true;
if (this.TryGetAttributeValue(context, "round", out round))
{
bool.TryParse(round, out parsedRound);
}
var enreplacedyReference = new EnreplacedyReference(enreplacedy, parsedId);
var html = portalLiquidContext.Html.Rating(enreplacedyReference, panel: parsedPanel, panelreplacedleSnippetName: panelSnippet, isReadonly: parsedReadonly, step: step, min: min, max: max, roundNearestHalf: parsedRound);
result.Write(html);
}
19
View Source File : Chart.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public override void Render(Context context, TextWriter result)
{
IPortalLiquidContext portalLiquidContext;
if (!context.TryGetPortalLiquidContext(out portalLiquidContext))
{
return;
}
string chartId;
Guid parsedChartId;
if (!this.TryGetAttributeValue(context, "id", out chartId) || !Guid.TryParse(chartId, out parsedChartId))
{
throw new SyntaxException("Syntax Error in 'chart' tag. Missing required attribute 'id:[string]'");
}
string viewId;
var parsedViewId = Guid.Empty;
Guid? outViewId = null;
var hasView = this.TryGetAttributeValue(context, "viewid", out viewId) && Guid.TryParse(viewId, out parsedViewId);
if (hasView)
{
outViewId = parsedViewId;
}
string serviceUrl;
if (!this.TryGetAttributeValue(context, "serviceurl", out serviceUrl))
{
serviceUrl = GetLazyServiceUrl(portalLiquidContext).Value;
}
var html = portalLiquidContext.Html.CrmChart(serviceUrl, parsedChartId, outViewId);
result.Write(html);
}
19
View Source File : Editable.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public override void Render(Context context, TextWriter result)
{
var attributes = _attributes.ToDictionary(e => e.Key, e => context[e.Value]);
var key = context[_key] as string;
if (string.IsNullOrEmpty(key))
{
var editable = context[_editable] as IEditable;
if (editable == null)
{
return;
}
result.Write(editable.GetEditable(context, new EditableOptions(attributes)) ?? string.Empty);
}
else
{
var editable = context[_editable] as IEditableCollection;
if (editable == null)
{
return;
}
result.Write(editable.GetEditable(context, key, new EditableOptions(attributes)) ?? string.Empty);
}
}
19
View Source File : Substitution.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public override void Render(Context context, TextWriter result)
{
var html = context.Registers["htmlHelper"] as HtmlHelper;
if (html == null)
{
return;
}
var source = NodeList.Cast<string>().Aggregate(new StringBuilder(), (sb, token) => sb.Append(token));
var viewSupportsDonuts = context.ViewSupportsDonuts();
context.Stack(() =>
{
// If donuts are supported then call the LiquidSubsreplacedution action, otherwise render the liquid code directly.
if (viewSupportsDonuts)
{
var encodedSource = Convert.ToBase64String(Encoding.UTF8.GetBytes(source.ToString()));
result.Write(html.Action("LiquidSubsreplacedution", "Layout", new { encodedSource }, viewSupportsDonuts));
}
else
{
html.RenderLiquid(source.ToString(), "Subsreplacedution string, but donuts not supported", result);
}
});
}
19
View Source File : Formatter.cs
License : MIT License
Project Creator : adrianoc
License : MIT License
Project Creator : adrianoc
private static void WriteVariables(TextWriter writer, MethodBody body)
{
var variables = body.Variables;
writer.Write('\t');
writer.Write(".locals {0}(", body.InitLocals ? "init " : string.Empty);
for (var i = 0; i < variables.Count; i++)
{
if (i > 0)
{
writer.Write(", ");
}
var variable = variables[i];
writer.Write("{0} {1}", variable.VariableType, variable);
}
writer.WriteLine(")");
}
19
View Source File : Formatter.cs
License : MIT License
Project Creator : adrianoc
License : MIT License
Project Creator : adrianoc
private static void WriteInstruction(TextWriter writer, Instruction instruction)
{
writer.Write(FormatLabel(instruction.Offset));
writer.Write(": ");
writer.Write(instruction.OpCode.Name);
if (null != instruction.Operand)
{
writer.Write(' ');
WriteOperand(writer, instruction.Operand);
}
}
19
View Source File : Formatter.cs
License : MIT License
Project Creator : adrianoc
License : MIT License
Project Creator : adrianoc
private static void WriteSequencePoint(TextWriter writer, SequencePoint sequence_point)
{
writer.Write(".line {0},{1}:{2},{3} '{4}'",
sequence_point.StartLine,
sequence_point.EndLine,
sequence_point.StartColumn,
sequence_point.EndColumn,
sequence_point.Doreplacedent.Url);
}
19
View Source File : SettingsManager.cs
License : MIT License
Project Creator : Adsito
License : MIT License
Project Creator : Adsito
[InitializeOnLoadMethod]
private static void Init()
{
if (!File.Exists(SettingsPath))
using (StreamWriter write = new StreamWriter(SettingsPath, false))
write.Write(JsonUtility.ToJson(new EditorSettings(), true));
LoadSettings();
}
19
View Source File : SettingsManager.cs
License : MIT License
Project Creator : Adsito
License : MIT License
Project Creator : Adsito
public static void SaveSettings()
{
using (StreamWriter write = new StreamWriter(SettingsPath, false))
{
EditorSettings editorSettings = new EditorSettings
(
RustDirectory, PrefabRenderDistance, PathRenderDistance, WaterTransparency, LoadBundleOnLaunch
);
write.Write(JsonUtility.ToJson(editorSettings, true));
Debug.Log("Saved Settings.");
}
}
19
View Source File : AElfKeyStore.cs
License : MIT License
Project Creator : AElfProject
License : MIT License
Project Creator : 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
View Source File : BadContract.cs
License : MIT License
Project Creator : AElfProject
License : MIT License
Project Creator : AElfProject
public override Empty WriteFileToNode(FileInfoInput input)
{
using (var writer = new StreamWriter(input.FilePath))
{
writer.Write(input.FileContent);
}
return new Empty();
}
19
View Source File : TextExportBuilder.cs
License : GNU General Public License v2.0
Project Creator : afrantzis
License : GNU General Public License v2.0
Project Creator : afrantzis
protected virtual int MatchAlignment(long offset, BuildBytesInfo info)
{
int count = 0;
// match alignment
// find lower alignment offset
long lowAlign = (offset / alignment) * alignment;
// fill with blanks (eg "__ __")
for (long i = lowAlign; i < offset; i++) {
if (i != lowAlign)
BuildSeparator(info.Separator);
BuildByte(null, 0, info, true);
count++;
}
// if alignment adjustments had to be made
// emit one more separator (eg "__ __ " <-- notice last space)
if (lowAlign != offset)
writer.Write(info.Separator);
return count;
}
19
View Source File : IdentityBuilderExtensions.cs
License : Apache License 2.0
Project Creator : Aguafrommars
License : Apache License 2.0
Project Creator : 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
View Source File : DecompileFullOutput.cs
License : GNU General Public License v3.0
Project Creator : ahmed605
License : GNU General Public License v3.0
Project Creator : ahmed605
public void Process(File file, TextWriter writer)
{
var decoder = new Decoder(file);
var program = new ScriptProgram(decoder);
var replacedyzer = new ControlFlowreplacedyzer(program);
replacedyzer.replacedyze();
var stackreplacedyzer = new StackUsereplacedyzer(program);
stackreplacedyzer.replacedyze();
foreach (Function function in program.Functions)
{
var sb = new StringBuilder();
for (int i = 0; i < function.ParameterCount; i++)
{
if (i != 0)
{
sb.Append(", ");
}
sb.Append("var");
sb.Append(i);
}
writer.WriteLine(string.Format("{0} {1}({2})", function.ReturnCount > 0 ? "function" : "void",
function.Name, sb));
writer.WriteLine("{");
if (function.VariableCount > 2)
{
writer.Write(" auto ");
for (int i = 2; i < function.VariableCount; i++)
{
if (i != 2)
{
writer.Write(", ");
}
writer.Write("var" + (i + function.ParameterCount));
}
writer.WriteLine(";");
}
if (function.TemporaryCount > 0)
{
writer.Write(" auto ");
for (int i = 0; i < function.TemporaryCount; i++)
{
if (i != 0)
{
writer.Write(", ");
}
writer.Write("temp" + i);
}
writer.WriteLine(";");
}
if (function.TemporaryCount > 0 || function.VariableCount > 2)
{
writer.WriteLine();
}
ProcessCodePath(writer, function.MainCodePath, " ");
writer.WriteLine("}");
writer.WriteLine();
}
}
19
View Source File : NodeParamGenerator.cs
License : MIT License
Project Creator : aillieo
License : MIT License
Project Creator : 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
View Source File : NodeParamGenerator.cs
License : MIT License
Project Creator : aillieo
License : MIT License
Project Creator : 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
View Source File : AboutDialog.xaml.cs
License : GNU Affero General Public License v3.0
Project Creator : akshinmustafayev
License : GNU Affero General Public License v3.0
Project Creator : akshinmustafayev
private static void ConvertTo(HtmlNode node, TextWriter outText)
{
string html;
switch (node.NodeType)
{
case HtmlNodeType.Comment:
// don't output comments
break;
case HtmlNodeType.Doreplacedent:
ConvertContentTo(node, outText);
break;
case HtmlNodeType.Text:
// script and style must not be output
string parentName = node.ParentNode.Name;
if ((parentName == "script") || (parentName == "style"))
break;
// get text
html = ((HtmlTextNode)node).Text;
// is it in fact a special closing node output as text?
if (HtmlNode.IsOverlappedClosingElement(html))
break;
// check the text is meaningful and not a bunch of whitespaces
if (html.Trim().Length > 0)
{
outText.Write(HtmlEnreplacedy.DeEnreplacedize(html));
}
break;
case HtmlNodeType.Element:
switch (node.Name)
{
case "p":
// treat paragraphs as crlf
outText.Write("\r\n");
break;
case "br":
outText.Write("\r\n");
break;
}
if (node.HasChildNodes)
{
ConvertContentTo(node, outText);
}
break;
}
}
19
View Source File : ExperimentInstanceController.cs
License : MIT License
Project Creator : AlexanderFroemmgen
License : MIT License
Project Creator : AlexanderFroemmgen
private void PackPythonSpecifics(ZipArchive archive, List<ParameterValue> selectedParameterInstances)
{
var experiment = _context.Experiments.Single(s => s.Id == _currentExperimentInstance.ExperimentId);
var script = experiment.Script;
var scriptInstall = experiment.ScriptInstall;
var angularReplaced = new List<string>();
using (var file = new StreamWriter(archive.CreateEntry("experiment.py").Open()))
{
/* angular style for parameter */
foreach (var param in selectedParameterInstances)
{
var angularStyle = "{{" + param.Parameter.Name + "}}";
if (script.Contains(angularStyle))
{
/* angular style does not encapsulate strings in ' ' */
script = script.Replace(angularStyle, param.Value);
angularReplaced.Add(param.Parameter.Name);
}
}
file.Write(script);
}
if (!String.IsNullOrEmpty(scriptInstall))
{
using (var file = new StreamWriter(archive.CreateEntry("install.py").Open()))
{
file.Write(scriptInstall);
}
}
using (var file = new StreamWriter(archive.CreateEntry("parameters.py").Open()))
{
file.Write("params = {");
foreach (var param in selectedParameterInstances)
{
var value = param.Parameter.Type == ParameterType.String ? $"'{param.Value}'" : param.Value;
file.Write($"'{param.Parameter.Name}' : {value}");
if (!ReferenceEquals(param, selectedParameterInstances.Last()))
{
file.Write(", ");
}
}
file.Write("}\n");
file.Write("requestedParams = set(['simId', 'simInstanceId'");
foreach(var param in angularReplaced)
{
file.Write(", '" + param + "'");
}
file.Write("])\n");
}
}
19
View Source File : ScienceExportController.cs
License : MIT License
Project Creator : AlexanderFroemmgen
License : MIT License
Project Creator : AlexanderFroemmgen
[HttpPost("export")]
public IActionResult ExportTrigger([FromBody] ScienceExportDto scienceExport)
{
/*
* Stuff to export:
* - Database content (outstanding)
* - Exported folders
* - Experiment files
*/
string fileId = $"export{new Random().Next(10000, 99999):000000}";
using (var stream = new FileStream(_directoryOptions.DataLocation + "Exports/" + fileId + ".zip", FileMode.CreateNew)) {
using (var archive = new ZipArchive(stream, ZipArchiveMode.Create, true))
{
using (var file = new StreamWriter(archive.CreateEntry("readme.txt").Open()))
{
file.Write(scienceExport.Name + "\n\n" + scienceExport.Description + "\n\n");
file.Write("This export was generated with MACI version 0.9 at " + DateTime.Now.ToString());
}
foreach (int id in scienceExport.Experiments)
{
/* exported replacedysis files for this experiment id */
var tmp = _directoryOptions.DataLocation + $"/JupyterNotebook/sim{id:0000}";
foreach (var fileEntry in _directoryOptions.GetAllFilesRecursively(tmp))
{
archive.CreateEntryFromFile(fileEntry, $"JupyterNotebooks/sim{id:0000}/{fileEntry}");
}
// TODO copy experiment framework stuff to avoid overriding stuff
/* export experiment files */
var experiment = _context.Experiments.Where(s => id == s.Id).SingleOrDefault();
var tmp2 = _directoryOptions.DataLocation + $"/ExperimentFramework/" + experiment.FileName;
foreach (var fileEntry in _directoryOptions.GetAllFilesRecursively(tmp2))
{
archive.CreateEntryFromFile(fileEntry, $"ExperimentFramework/sim{id:0000}/{fileEntry}");
}
}
}
stream.Flush();
}
return Json(new
{
Name = fileId
});
}
19
View Source File : ExperimentInstanceController.cs
License : MIT License
Project Creator : AlexanderFroemmgen
License : MIT License
Project Creator : AlexanderFroemmgen
[HttpGet("experiment.zip")]
public IActionResult DownloadJobArchive()
{
var stream = new MemoryStream();
using (var archive = new ZipArchive(stream, ZipArchiveMode.Create, true))
{
copySnapshotFilesToArchive(archive);
var selectedParameterInstances = _context.ExperimentParameterreplacedignments
.Where(a => a.ExperimentInstanceId == _currentExperimentInstance.Id)
.Include(a => a.ParameterValue).ThenInclude(i => i.Parameter)
.ToList()
.Select(a => a.ParameterValue)
.ToList();
selectedParameterInstances.Add(getExperimentIdParameter());
selectedParameterInstances.Add(getExperimentInstanceIdParameter());
if (_currentExperimentInstance.Experiment.Language.ToLower() == "python")
{
PackPythonSpecifics(archive, selectedParameterInstances);
using (var file = new StreamWriter(archive.CreateEntry("config.json").Open()))
{
file.Write("{\"timeout\" : " + _currentExperimentInstance.Experiment.Timeout.ToString() + "}");
}
}
else
{
throw new Exception("Unexpected experiment language.");
}
}
return File(stream.ToArray(), "application/zip");
}
19
View Source File : CSharpTemplateSourceFileGenerator.cs
License : GNU General Public License v3.0
Project Creator : alexgracianoarj
License : GNU General Public License v3.0
Project Creator : alexgracianoarj
public List<string> GenerateFiles(string directory, bool perEnreplacedy)
{
List<string> files = new List<string>();
var tmpltsSettings = TemplatesSettings.Load();
if (!Directory.Exists(directory))
Directory.CreateDirectory(directory);
foreach (var group in tmpltsSettings.Groups.Where(x => x.Enabled))
{
foreach (var tmpltSettings in group.Templates.Where(x => x.Enabled && x.PerEnreplacedy == perEnreplacedy))
{
try
{
string fileName = null;
if (tmpltSettings.PerEnreplacedy)
{
var enreplacedyMeta = GenerateEnreplacedyMeta();
fileName = TemplateRender("enreplacedy", enreplacedyMeta, tmpltSettings.FileExt);
}
else
{
var modelMeta = GenerateModelMeta();
fileName = TemplateRender("model", modelMeta, tmpltSettings.FileExt);
}
fileName = Regex.Replace(fileName, @"\<(?<type>.+)\>", @"[${type}]");
string path = Path.Combine(directory, fileName);
if (WriteFileContent(tmpltSettings))
{
using (StreamWriter writer = new StreamWriter(path, false, Encoding.Unicode))
{
writer.Write(CodeBuilder.ToString());
}
files.Add(fileName);
}
}
catch (Exception ex)
{
throw new FileGenerationException(directory, ex);
}
}
}
return files;
}
19
View Source File : Logger.cs
License : MIT License
Project Creator : AlexGyver
License : MIT License
Project Creator : AlexGyver
private void CreateNewLogFile() {
IList<ISensor> list = new List<ISensor>();
SensorVisitor visitor = new SensorVisitor(sensor => {
list.Add(sensor);
});
visitor.VisitComputer(computer);
sensors = list.ToArray();
identifiers = sensors.Select(s => s.Identifier.ToString()).ToArray();
using (StreamWriter writer = new StreamWriter(fileName, false)) {
writer.Write(",");
for (int i = 0; i < sensors.Length; i++) {
writer.Write(sensors[i].Identifier);
if (i < sensors.Length - 1)
writer.Write(",");
else
writer.WriteLine();
}
writer.Write("Time,");
for (int i = 0; i < sensors.Length; i++) {
writer.Write('"');
writer.Write(sensors[i].Name);
writer.Write('"');
if (i < sensors.Length - 1)
writer.Write(",");
else
writer.WriteLine();
}
}
}
19
View Source File : MessagePackSerializer.Json.cs
License : Apache License 2.0
Project Creator : allenai
License : Apache License 2.0
Project Creator : allenai
private static void ToJsonCore(ref MessagePackReader reader, TextWriter writer, MessagePackSerializerOptions options)
{
MessagePackType type = reader.NextMessagePackType;
switch (type)
{
case MessagePackType.Integer:
if (MessagePackCode.IsSignedInteger(reader.NextCode))
{
writer.Write(reader.ReadInt64().ToString(CultureInfo.InvariantCulture));
}
else
{
writer.Write(reader.ReadUInt64().ToString(CultureInfo.InvariantCulture));
}
break;
case MessagePackType.Boolean:
writer.Write(reader.ReadBoolean() ? "true" : "false");
break;
case MessagePackType.Float:
if (reader.NextCode == MessagePackCode.Float32)
{
writer.Write(reader.ReadSingle().ToString(CultureInfo.InvariantCulture));
}
else
{
writer.Write(reader.ReadDouble().ToString(CultureInfo.InvariantCulture));
}
break;
case MessagePackType.String:
WriteJsonString(reader.ReadString(), writer);
break;
case MessagePackType.Binary:
ArraySegment<byte> segment = ByteArraySegmentFormatter.Instance.Deserialize(ref reader, DefaultOptions);
writer.Write("\"" + Convert.ToBase64String(segment.Array, segment.Offset, segment.Count) + "\"");
break;
case MessagePackType.Array:
{
int length = reader.ReadArrayHeader();
options.Security.DepthStep(ref reader);
try
{
writer.Write("[");
for (int i = 0; i < length; i++)
{
ToJsonCore(ref reader, writer, options);
if (i != length - 1)
{
writer.Write(",");
}
}
writer.Write("]");
}
finally
{
reader.Depth--;
}
return;
}
case MessagePackType.Map:
{
int length = reader.ReadMapHeader();
options.Security.DepthStep(ref reader);
try
{
writer.Write("{");
for (int i = 0; i < length; i++)
{
// write key
{
MessagePackType keyType = reader.NextMessagePackType;
if (keyType == MessagePackType.String || keyType == MessagePackType.Binary)
{
ToJsonCore(ref reader, writer, options);
}
else
{
writer.Write("\"");
ToJsonCore(ref reader, writer, options);
writer.Write("\"");
}
}
writer.Write(":");
// write body
{
ToJsonCore(ref reader, writer, options);
}
if (i != length - 1)
{
writer.Write(",");
}
}
writer.Write("}");
}
finally
{
reader.Depth--;
}
return;
}
case MessagePackType.Extension:
ExtensionHeader extHeader = reader.ReadExtensionFormatHeader();
if (extHeader.TypeCode == ReservedMessagePackExtensionTypeCode.DateTime)
{
DateTime dt = reader.ReadDateTime(extHeader);
writer.Write("\"");
writer.Write(dt.ToString("o", CultureInfo.InvariantCulture));
writer.Write("\"");
}
#if !UNITY_2018_3_OR_NEWER
else if (extHeader.TypeCode == ThisLibraryExtensionTypeCodes.TypelessFormatter)
{
// prepare type name token
var privateBuilder = new StringBuilder();
var typeNameTokenBuilder = new StringBuilder();
SequencePosition positionBeforeTypeNameRead = reader.Position;
ToJsonCore(ref reader, new StringWriter(typeNameTokenBuilder), options);
int typeNameReadSize = (int)reader.Sequence.Slice(positionBeforeTypeNameRead, reader.Position).Length;
if (extHeader.Length > typeNameReadSize)
{
// object map or array
MessagePackType typeInside = reader.NextMessagePackType;
if (typeInside != MessagePackType.Array && typeInside != MessagePackType.Map)
{
privateBuilder.Append("{");
}
ToJsonCore(ref reader, new StringWriter(privateBuilder), options);
// insert type name token to start of object map or array
if (typeInside != MessagePackType.Array)
{
typeNameTokenBuilder.Insert(0, "\"$type\":");
}
if (typeInside != MessagePackType.Array && typeInside != MessagePackType.Map)
{
privateBuilder.Append("}");
}
if (privateBuilder.Length > 2)
{
typeNameTokenBuilder.Append(",");
}
privateBuilder.Insert(1, typeNameTokenBuilder.ToString());
writer.Write(privateBuilder.ToString());
}
else
{
writer.Write("{\"$type\":\"" + typeNameTokenBuilder.ToString() + "}");
}
}
#endif
else
{
var data = reader.ReadRaw((long)extHeader.Length);
writer.Write("[");
writer.Write(extHeader.TypeCode);
writer.Write(",");
writer.Write("\"");
writer.Write(Convert.ToBase64String(data.ToArray()));
writer.Write("\"");
writer.Write("]");
}
break;
case MessagePackType.Nil:
reader.Skip();
writer.Write("null");
break;
default:
throw new MessagePackSerializationException($"code is invalid. code: {reader.NextCode} format: {MessagePackCode.ToFormatName(reader.NextCode)}");
}
}
19
View Source File : Program.cs
License : MIT License
Project Creator : altimesh
License : MIT License
Project Creator : altimesh
[EntryPoint]
public static void Run(int N, int[] a)
{
for (int i = threadIdx.x + blockDim.x * blockIdx.x; i < N; i += blockDim.x * gridDim.x)
{
Console.Out.Write("hello from thread = {0} in block = {1} a[i] = {2}\n", threadIdx.x, blockIdx.x, a[i]);
};
}
19
View Source File : Program.cs
License : MIT License
Project Creator : altimesh
License : MIT License
Project Creator : altimesh
[EntryPoint("run")]
public static void Run(int N, int[] a)
{
for (int i = threadIdx.x + blockDim.x * blockIdx.x; i < N; i += blockDim.x * gridDim.x)
{
Console.Out.Write("hello from thread = {0} in block = {1} a[i] = {2}\n", threadIdx.x, blockIdx.x, a[i]);
};
}
19
View Source File : OpenVPNSession.cs
License : GNU General Public License v3.0
Project Creator : Amebis
License : GNU General Public License v3.0
Project Creator : Amebis
protected override void DoRun()
{
Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => Wizard.TaskCount++));
try
{
try
{
// Start OpenVPN management interface on IPv4 loopack interface (any TCP free port).
var mgmtServer = new TcpListener(IPAddress.Loopback, 0);
mgmtServer.Start();
try
{
try
{
// Purge stale log files.
var timestamp = DateTime.UtcNow.Subtract(new TimeSpan(30, 0, 0, 0));
foreach (var f in Directory.EnumerateFiles(WorkingFolder, "*.txt", SearchOption.TopDirectoryOnly))
{
SessionAndWindowInProgress.Token.ThrowIfCancellationRequested();
if (File.GetLastWriteTimeUtc(f) <= timestamp)
{
try { File.Delete(LogPath); }
catch { }
}
}
}
catch (OperationCanceledException) { throw; }
catch (Exception) { /* Failure to remove stale log files is not fatal. */ }
try
{
// Save OpenVPN configuration file.
using (var fs = new FileStream(
ConfigurationPath,
FileMode.Create,
FileAccess.Write,
FileShare.Read,
1048576,
FileOptions.SequentialScan))
using (var sw = new StreamWriter(fs))
{
// Save profile's configuration to file.
if (Properties.SettingsEx.Default.OpenVPNRemoveOptions is StringCollection openVPNRemoveOptions)
{
// Remove options on the OpenVPNRemoveOptions list on the fly.
using (var sr = new StringReader(ProfileConfig))
{
string inlineTerm = null;
bool inlineRemove = false;
for (; ; )
{
var line = sr.ReadLine();
if (line == null)
break;
var trimmedLine = line.Trim();
if (!string.IsNullOrEmpty(trimmedLine))
{
// Not an empty line.
if (inlineTerm == null)
{
// Not inside an inline option block = Regular parsing mode.
if (!trimmedLine.StartsWith("#") &&
!trimmedLine.StartsWith(";"))
{
// Not a comment.
var option = eduOpenVPN.Configuration.ParseParams(trimmedLine);
if (option.Count > 0)
{
if (option[0].StartsWith("<") && !option[0].StartsWith("</") && option[0].EndsWith(">"))
{
// Start of an inline option.
var o = option[0].Substring(1, option[0].Length - 2);
inlineTerm = "</" + o + ">";
inlineRemove = openVPNRemoveOptions.Contains(o);
if (inlineRemove)
{
sw.WriteLine("# Commented by OpenVPNRemoveOptions setting:");
line = "# " + line;
}
}
else if (openVPNRemoveOptions.Contains(option[0]))
{
sw.WriteLine("# Commented by OpenVPNRemoveOptions setting:");
line = "# " + line;
}
}
}
}
else
{
// Inside an inline option block.
if (inlineRemove)
{
// Remove the inline option content.
line = "# " + line;
}
if (trimmedLine == inlineTerm)
{
// Inline option terminator found. Returning to regular parsing mode.
inlineTerm = null;
}
}
}
sw.WriteLine(line);
}
}
}
else
sw.Write(ProfileConfig);
// Append eduVPN Client specific configuration directives.
sw.WriteLine();
sw.WriteLine();
sw.WriteLine("# eduVPN Client for Windows");
// Introduce ourself (to OpenVPN server).
var replacedembly = replacedembly.GetExecutingreplacedembly();
var replacedemblyreplacedleAttribute = Attribute.GetCustomAttributes(replacedembly, typeof(replacedemblyreplacedleAttribute)).SingleOrDefault() as replacedemblyreplacedleAttribute;
var replacedemblyVersion = replacedembly?.GetName()?.Version;
sw.WriteLine("setenv IV_GUI_VER " + eduOpenVPN.Configuration.EscapeParamValue(replacedemblyreplacedleAttribute?.replacedle + " " + replacedemblyVersion?.ToString()));
// Configure log file (relative to WorkingFolder).
sw.WriteLine("log-append " + eduOpenVPN.Configuration.EscapeParamValue(ConnectionId + ".txt"));
// Configure interaction between us and openvpn.exe.
sw.WriteLine("management " + eduOpenVPN.Configuration.EscapeParamValue(((IPEndPoint)mgmtServer.LocalEndpoint).Address.ToString()) + " " + eduOpenVPN.Configuration.EscapeParamValue(((IPEndPoint)mgmtServer.LocalEndpoint).Port.ToString()) + " stdin");
sw.WriteLine("management-client");
sw.WriteLine("management-hold");
sw.WriteLine("management-query-preplacedwords");
sw.WriteLine("management-query-remote");
// Configure client certificate.
sw.WriteLine("cert " + eduOpenVPN.Configuration.EscapeParamValue(ConnectingProfile.Server.ClientCertificatePath));
sw.WriteLine("key " + eduOpenVPN.Configuration.EscapeParamValue(ConnectingProfile.Server.ClientCertificatePath));
// Ask when username/preplacedword is denied.
sw.WriteLine("auth-retry interact");
sw.WriteLine("auth-nocache");
// Set Wintun interface to be used.
sw.Write("windows-driver wintun\n");
sw.Write("dev-node " + eduOpenVPN.Configuration.EscapeParamValue(Properties.Settings.Default.Clientreplacedle) + "\n");
#if DEBUG
// Renegotiate data channel every 5 minutes in debug versions.
sw.WriteLine("reneg-sec 300");
#endif
if (Environment.OSVersion.Version < new Version(6, 2))
{
// Windows 7 is using tiny 8kB send/receive socket buffers by default.
// Increase to 64kB which is default from Windows 8 on.
sw.WriteLine("sndbuf 65536");
sw.WriteLine("rcvbuf 65536");
}
var openVPNAddOptions = Properties.SettingsEx.Default.OpenVPNAddOptions;
if (!string.IsNullOrWhiteSpace(openVPNAddOptions))
{
sw.WriteLine();
sw.WriteLine();
sw.WriteLine("# Added by OpenVPNAddOptions setting:");
sw.WriteLine(openVPNAddOptions);
}
}
}
catch (OperationCanceledException) { throw; }
catch (Exception ex) { throw new AggregateException(string.Format(Resources.Strings.ErrorSavingProfileConfiguration, ConfigurationPath), ex); }
bool retry;
do
{
retry = false;
// Connect to OpenVPN Interactive Service to launch the openvpn.exe.
using (var openvpnInteractiveServiceConnection = new eduOpenVPN.InteractiveService.Session())
{
var mgmtPreplacedword = Membership.GeneratePreplacedword(16, 6);
try
{
openvpnInteractiveServiceConnection.Connect(
string.Format("openvpn{0}\\service", InstanceName),
WorkingFolder,
new string[] { "--config", ConnectionId + ".conf", },
mgmtPreplacedword + "\n",
3000,
SessionAndWindowInProgress.Token);
}
catch (OperationCanceledException) { throw; }
catch (Exception ex) { throw new AggregateException(Resources.Strings.ErrorInteractiveService, ex); }
try
{
// Wait and accept the openvpn.exe on our management interface (--management-client parameter).
var mgmtClientTask = mgmtServer.AcceptTcpClientAsync();
try { mgmtClientTask.Wait(30000, SessionAndWindowInProgress.Token); }
catch (AggregateException ex) { throw ex.InnerException; }
var mgmtClient = mgmtClientTask.Result;
try
{
// Start the management session.
ManagementSession.Start(mgmtClient.GetStream(), mgmtPreplacedword, SessionAndWindowInProgress.Token);
// Initialize session and release openvpn.exe to get started.
ManagementSession.SetVersion(3, SessionAndWindowInProgress.Token);
ManagementSession.ReplayAndEnableState(SessionAndWindowInProgress.Token);
ManagementSession.ReplayAndEnableEcho(SessionAndWindowInProgress.Token);
ManagementSession.SetByteCount(5, SessionAndWindowInProgress.Token);
ManagementSession.ReleaseHold(SessionAndWindowInProgress.Token);
Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => Wizard.TaskCount--));
try
{
// Wait for the session to end gracefully.
ManagementSession.Monitor.Join();
if (ManagementSession.Error != null && !(ManagementSession.Error is OperationCanceledException))
{
// Session reported an error. Retry.
retry = true;
}
}
finally { Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => Wizard.TaskCount++)); }
}
finally { mgmtClient.Close(); }
}
finally
{
Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(
() =>
{
// Cleanup status properties.
State = SessionStatusType.Disconnecting;
StateDescription = Resources.Strings.OpenVPNStateTypeExiting;
TunnelAddress = null;
IPv6TunnelAddress = null;
ConnectedAt = null;
BytesIn = null;
BytesOut = null;
}));
// Wait for openvpn.exe to finish. Maximum 30s.
try { Process.GetProcessById(openvpnInteractiveServiceConnection.ProcessId)?.WaitForExit(30000); }
catch (ArgumentException) { }
}
}
} while (retry);
}
finally
{
mgmtServer.Stop();
}
}
finally
{
// Delete profile configuration file. If possible.
try { File.Delete(ConfigurationPath); }
catch { }
}
}
finally
{
Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(
() =>
{
// Cleanup status properties.
State = SessionStatusType.Disconnected;
StateDescription = "";
Wizard.TaskCount--;
}));
PropertyUpdater.Stop();
}
}
19
View Source File : Server.cs
License : GNU General Public License v3.0
Project Creator : Amebis
License : GNU General Public License v3.0
Project Creator : Amebis
public X509Certificate2 GetClientCertificate(Server authenticatingServer, bool forceRefresh = false, CancellationToken ct = default)
{
lock (ClientCertificateLock)
{
var path = ClientCertificatePath;
// Get API endpoints.
var api = GetEndpoints(ct);
var e = new RequestAuthorizationEventArgs("config");
if (forceRefresh)
e.SourcePolicy = RequestAuthorizationEventArgs.SourcePolicyType.ForceAuthorization;
retry:
// Request authentication token.
OnRequestAuthorization(authenticatingServer, e);
if (!forceRefresh && File.Exists(path))
{
// Perform an optional certificate check.
try
{
// Load certificate.
var cert = new X509Certificate2(
Certificate.GetBytesFromPEM(
File.ReadAllText(path),
"CERTIFICATE"),
(string)null,
X509KeyStorageFlags.PersistKeySet);
// Check certificate.
var uriBuilder = new UriBuilder(api.CheckCertificate);
var query = HttpUtility.ParseQueryString(uriBuilder.Query);
query["common_name"] = cert.GetNameInfo(X509NameType.SimpleName, false);
uriBuilder.Query = query.ToString();
var certCheck = new CertificateCheck();
certCheck.LoadJSONAPIResponse(Xml.Response.Get(
uri: uriBuilder.Uri,
token: e.AccessToken,
ct: ct).Value, "check_certificate", ct);
switch (certCheck.Result)
{
case CertificateCheck.ReasonType.Valid:
// Certificate is valid.
return cert;
case CertificateCheck.ReasonType.UserDisabled:
throw new CertificateCheckException(Resources.Strings.ErrorUserDisabled);
case CertificateCheck.ReasonType.CertificateDisabled:
throw new CertificateCheckException(Resources.Strings.ErrorCertificateDisabled);
default:
// Server reported it will not accept this certificate.
break;
}
}
catch (OperationCanceledException) { throw; }
catch (CertificateCheckException) { throw; }
catch (WebException ex)
{
if (ex.Response is HttpWebResponse response && response.StatusCode == HttpStatusCode.Unauthorized)
{
// Access token was rejected (401 Unauthorized).
if (e.TokenOrigin == RequestAuthorizationEventArgs.TokenOriginType.Saved)
{
// Access token loaded from the settings was rejected.
// This might happen when ill-clocked client thinks the token is still valid, but the server expired it already.
// Retry with forced access token refresh.
e.ForceRefresh = true;
goto retry;
}
}
}
catch (Exception) { }
}
try
{
// Get certificate and save it.
var cert = new Certificate();
cert.LoadJSONAPIResponse(Xml.Response.Get(
uri: api.CreateCertificate,
param: new NameValueCollection
{
{ "display_name", string.Format("{0} Client for Windows", Properties.Settings.Default.Clientreplacedle) } // Always use English display_name
},
token: e.AccessToken,
ct: ct).Value, "create_keypair", ct);
Directory.CreateDirectory(Path.GetDirectoryName(path));
using (StreamWriter file = new StreamWriter(path))
{
file.Write(cert.Cert);
file.Write("\n");
file.Write(new NetworkCredential("", cert.PrivateKey).Preplacedword);
file.Write("\n");
}
var certX509 = new X509Certificate2(
Certificate.GetBytesFromPEM(
cert.Cert,
"CERTIFICATE"),
(string)null,
X509KeyStorageFlags.PersistKeySet);
return certX509;
}
catch (OperationCanceledException) { throw; }
catch (WebException ex)
{
if (ex.Response is HttpWebResponse response && response.StatusCode == HttpStatusCode.Unauthorized)
{
// Access token was rejected (401 Unauthorized).
if (e.TokenOrigin == RequestAuthorizationEventArgs.TokenOriginType.Saved)
{
// Access token loaded from the settings was rejected.
// This might happen when ill-clocked client thinks the token is still valid, but the server expired it already.
// Retry with forced access token refresh.
e.ForceRefresh = true;
goto retry;
}
}
throw new AggregateException(Resources.Strings.ErrorClientCertificateLoad, ex);
}
catch (Exception ex) { throw new AggregateException(Resources.Strings.ErrorClientCertificateLoad, ex); }
}
}
19
View Source File : ControlPanel.cs
License : MIT License
Project Creator : AmigoCap
License : MIT License
Project Creator : AmigoCap
void ExportJson() {
UpdateDataFromUI();
string path = "";
try {
dataInfo.Directory.Create();
path = System.IO.Path.Combine(workingDirectory, "export.json");
using (StreamWriter w = new StreamWriter(path)) {
JsonSerializerSettings settings = new JsonSerializerSettings();
settings.FloatFormatHandling = FloatFormatHandling.String;
settings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter());
w.Write(JsonConvert.SerializeObject(data, Formatting.Indented, settings));
}
}
catch (System.Exception e) {
MakeErrorWindow("Error exporting .json: ensure export.json is not being used by another process\n\n" + e.Message);
}
MakeMessageWindow(".json export", "Succesfully exported configuration to " + path);
}
19
View Source File : PerformContextValue.cs
License : MIT License
Project Creator : AnderssonPeter
License : MIT License
Project Creator : AnderssonPeter
public override void Render(TextWriter output, string format = null, IFormatProvider formatProvider = null)
{
// How the value will be rendered in Json output, etc.
// Not important for the function of this code..
output.Write(PerformContext.BackgroundJob.Id);
}
19
View Source File : TokenWriter.cs
License : MIT License
Project Creator : AndresTraks
License : MIT License
Project Creator : AndresTraks
private void WriteToken(IToken token, IToken precedingToken)
{
switch (token)
{
case StringToken @string:
if (token is WordToken && precedingToken != null)
{
_writer.Write(' ');
}
_writer.Write(@string.Value);
break;
case LineToken line:
WriteLine(line);
break;
case BlockToken block:
if (precedingToken != null)
{
_writer.WriteLine();
}
WriteBlock(block);
break;
case ExpressionBodyToken body:
if (precedingToken != null)
{
_writer.WriteLine();
}
WriteLine(body.Line);
break;
case LinesToken lines:
{
foreach (LineToken lineToken in lines.Lines)
{
WriteLine(lineToken);
}
break;
}
case ListToken list:
WriteList(list);
break;
}
}
19
View Source File : LowlandModalityDiagnosticsData.cs
License : MIT License
Project Creator : AndreyAkinshin
License : MIT License
Project Creator : AndreyAkinshin
public void DumpAsCsv(StreamWriter writer, CultureInfo cultureInfo = null)
{
cultureInfo ??= DefaultCultureInfo.Instance;
writer.WriteLine("index,left,right,height,water,isMode,isPeak,isLowland");
for (int i = 0; i < Bins.Count; i++)
{
var bin = Bins[i];
writer.Write(i);
writer.Write(",");
writer.Write(bin.HistogramBin.Lower.ToString("N7", cultureInfo));
writer.Write(",");
writer.Write(bin.HistogramBin.Upper.ToString("N7", cultureInfo));
writer.Write(",");
writer.Write(bin.HistogramBin.Height.ToString("N5", cultureInfo));
writer.Write(",");
writer.Write(bin.WaterLevel.ToString("N5", cultureInfo));
writer.Write(",");
writer.Write(bin.IsMode.ToString().ToLowerInvariant());
writer.Write(",");
writer.Write(bin.IsPeak.ToString().ToLowerInvariant());
writer.Write(",");
writer.Write(bin.IsLowland.ToString().ToLowerInvariant());
writer.WriteLine();
}
writer.WriteLine();
}
19
View Source File : Config.cs
License : MIT License
Project Creator : andruzzzhka
License : MIT License
Project Creator : andruzzzhka
public bool Save() {
if (!IsDirty) return false;
try {
using (var f = new StreamWriter(FileLocation.FullName)) {
Plugin.log.Debug($"Writing to File @ {FileLocation.FullName}");
var json = JsonUtility.ToJson(this, true);
f.Write(json);
}
MarkClean();
return true;
}
catch (Exception ex) {
Plugin.log.Critical(ex);
return false;
}
}
19
View Source File : HttpListenerResponse.cs
License : MIT License
Project Creator : andruzzzhka
License : MIT License
Project Creator : 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
View Source File : RequestWriter.cs
License : MIT License
Project Creator : angelobreuer
License : MIT License
Project Creator : angelobreuer
public static void WriteRequest(TextWriter writer, HttpRequestMessage request, long contentLength, NameValueCollection contentHeaders)
{
// status line
writer.Write(request.Method);
writer.Write(' ');
writer.Write(request.RequestUri!.PathAndQuery);
writer.Write(" HTTP/1.1");
writer.Write(HTTP_EOL);
WriteHeader(writer, "Content-Length", contentLength.ToString());
// ---------------------------------------------------------- Shahid Changes
// ------------------------------------------------------------ Content headers were
// missing, and if they are not present and parsed, they will not be forwarded ahead
// leading to errors
foreach (string key in contentHeaders)
{
WriteHeader(writer, key, contentHeaders[key]);
}
// headers
foreach (var (key, value) in request.Headers)
{
WriteHeader(writer, key, string.Join(",", value));
}
writer.Write(HTTP_EOL);
}
19
View Source File : RequestWriter.cs
License : MIT License
Project Creator : angelobreuer
License : MIT License
Project Creator : angelobreuer
public static void WriteHeader(TextWriter writer, string key, string? encodedValues)
{
if (encodedValues is not null && encodedValues != "")
{
writer.Write(key);
writer.Write(": ");
writer.Write(encodedValues);
writer.Write(HTTP_EOL);
}
}
19
View Source File : EgsPhantomCreator.cs
License : Apache License 2.0
Project Creator : anmcgrath
License : Apache License 2.0
Project Creator : anmcgrath
private void WriteVoxelValues(EgsPhantomCreatorOptions options, StreamWriter sw)
{
for (double z = options.ZRange.Minimum; z < options.ZRange.Maximum; z += options.Dz)
{
for (double y = options.YRange.Minimum; y < options.YRange.Maximum; y += options.Dy)
{
for (double x = options.XRange.Minimum; x < options.XRange.Maximum; x += options.Dx)
{
sw.Write("{0}\t",options.Grid.Interpolate(x,y,z).Value*options.Grid.Scaling);
}
sw.Write('\n');
}
}
}
19
View Source File : NavMeshExporter.cs
License : MIT License
Project Creator : AnotherEnd15
License : MIT License
Project Creator : AnotherEnd15
private static void WriteRecastObjFile()
{
if (!System.IO.Directory.Exists(outputClientFolder))
{
System.IO.Directory.CreateDirectory(outputClientFolder);
}
var filename = SceneManager.GetActiveScene().name;
var path = outputClientFolder + filename + ".obj";
StreamWriter sw = new StreamWriter(path);
Dictionary<string, ObjMaterial> materialList = PrepareFileWrite();
List<MeshFilter> meshes = Collect();
int count = 0;
foreach (MeshFilter mf in meshes)
{
sw.Write("mtllib ./" + filename + ".mtl\n");
string strMes = MeshToString(mf, materialList);
sw.Write(strMes);
EditorUtility.DisplayProgressBar("Exporting objects...", mf.name, count++ / (float) meshes.Count);
}
sw.Flush();
sw.Close();
EditorUtility.ClearProgressBar();
replacedetDatabase.Refresh();
}
See More Examples