Here are the examples of the csharp api System.IO.StreamWriter.Write(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
2171 Examples
19
Source : Program.cs
with GNU Affero General Public License v3.0
from arklumpus
with GNU Affero General Public License v3.0
from arklumpus
static int Main(string[] args)
{
bool showHelp = false;
bool showUsage = false;
string rootPath = null;
string privateKeyFile = null;
OptionSet argParser = new OptionSet()
{
{ "h|help", "Print this message and exit.", v => { showHelp = v != null; } },
{ "r|root=", "The path to the root of the repository. Required.", v => { rootPath = v; } },
{ "k|key=", "Provide the path to the private key file that will be used to sign the modules. Required.", v => { privateKeyFile = v; } },
};
List<string> unrecognised = argParser.Parse(args);
if (unrecognised.Count > 0)
{
Console.WriteLine();
Console.WriteLine("Unrecognised argument" + (unrecognised.Count > 1 ? "s" : "") + ": " + unrecognised.Aggregate((a, b) => a + " " + b));
showUsage = true;
}
if (string.IsNullOrEmpty(rootPath) && !showHelp)
{
Console.WriteLine();
Console.WriteLine("The root path is required!");
showUsage = true;
}
if (string.IsNullOrEmpty(privateKeyFile) && !showHelp)
{
Console.WriteLine();
Console.WriteLine("The private key file is required!");
showUsage = true;
}
if (showUsage || showHelp)
{
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("BuildRepositoryModuleDatabase");
Console.WriteLine();
Console.WriteLine("Usage:");
Console.WriteLine();
Console.WriteLine(" BuildRepositoryModuleDatabase {-h|--help}");
Console.WriteLine(" BuildRepositoryModuleDatabase --root <root_path> --key <key_file>");
}
if (showHelp)
{
Console.WriteLine();
Console.WriteLine("Options:");
Console.WriteLine();
argParser.WriteOptionDescriptions(Console.Out);
return 0;
}
if (showUsage)
{
return 64;
}
System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.InvariantCulture;
System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture;
Directory.SetCurrentDirectory(Path.GetDirectoryName(replacedembly.GetExecutingreplacedembly().Location));
string[] files = Directory.GetFiles(Path.Combine(rootPath, "src", "Modules"), "*.cs");
VectSharp.SVG.Parser.ParseImageURI = VectSharp.MuPDFUtils.ImageURIParser.Parser(VectSharp.SVG.Parser.ParseSVGURI);
File.Delete(Modules.ModuleListPath);
TreeViewer.ModuleMetadata[] modules = new TreeViewer.ModuleMetadata[files.Length];
if (!Directory.Exists("references"))
{
Directory.CreateDirectory("references");
}
Console.ForegroundColor = ConsoleColor.Blue;
Console.WriteLine();
Console.WriteLine("Compiling modules...");
Console.WriteLine();
Console.ForegroundColor = ConsoleColor.Gray;
for (int i = 0; i < files.Length; i++)
{
Console.WriteLine(Path.GetFileName(files[i]));
if (!File.Exists(Path.Combine(rootPath, "src", "Modules", "references", Path.GetFileName(files[i]) + ".references")))
{
References[Path.GetFileName(files[i])] = new List<string>(baseReferences);
}
else
{
References[Path.GetFileName(files[i])] = new List<string>(File.ReadAllLines(Path.Combine(rootPath, "src", "Modules", "references", Path.GetFileName(files[i]) + ".references")));
}
bool compiledWithoutErrors = false;
while (!compiledWithoutErrors)
{
try
{
modules[i] = TreeViewer.ModuleMetadata.CreateFromSource(File.ReadAllText(files[i]), References[Path.GetFileName(files[i])].ToArray());
compiledWithoutErrors = true;
}
catch (Exception e)
{
HashSet<string> newReferences = new HashSet<string>();
string msg = e.Message;
while (msg.Contains("You must add a reference to replacedembly '"))
{
msg = msg.Substring(msg.IndexOf("You must add a reference to replacedembly '") + "You must add a reference to replacedembly '".Length);
newReferences.Add(msg.Substring(0, msg.IndexOf(",")));
}
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine();
Console.WriteLine(e.Message);
Console.WriteLine();
Console.ForegroundColor = ConsoleColor.Gray;
if (newReferences.Count == 0)
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.Write("Which references should I add? ");
Console.ForegroundColor = ConsoleColor.Gray;
string[] newRefs = Console.ReadLine().Split(',');
foreach (string sr in newRefs)
{
string refName = sr.Trim();
if (refName.EndsWith(".dll"))
{
refName = refName.Substring(0, refName.Length - 4);
}
newReferences.Add(refName);
}
Console.WriteLine();
}
Console.WriteLine("Adding references: ");
foreach (string sr in newReferences)
{
References[Path.GetFileName(files[i])].Add(sr + ".dll");
Console.WriteLine("\t" + sr + ".dll");
}
}
}
File.WriteAllLines(Path.Combine(rootPath, "src", "Modules", "references", Path.GetFileName(files[i]) + ".references"), References[Path.GetFileName(files[i])]);
}
Console.ForegroundColor = ConsoleColor.Blue;
Console.WriteLine();
Console.WriteLine("Checking for unnecessary references...");
Console.WriteLine();
Console.ForegroundColor = ConsoleColor.Gray;
for (int i = 0; i < files.Length; i++)
{
Console.WriteLine(Path.GetFileName(files[i]));
List<string> toBeRemoved = new List<string>();
List<string> originalReferences = References[Path.GetFileName(files[i])];
for (int j = 0; j < originalReferences.Count; j++)
{
List<string> currentReferences = new List<string>(originalReferences);
currentReferences.Remove(originalReferences[j]);
try
{
TreeViewer.ModuleMetadata.CreateFromSource(File.ReadAllText(files[i]), currentReferences.ToArray());
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("\tRemoving " + originalReferences[j]);
Console.ForegroundColor = ConsoleColor.Gray;
toBeRemoved.Add(originalReferences[j]);
}
catch
{
}
}
for (int j = 0; j < toBeRemoved.Count; j++)
{
References[Path.GetFileName(files[i])].Remove(toBeRemoved[j]);
}
File.WriteAllLines(Path.Combine(rootPath, "src", "Modules", "references", Path.GetFileName(files[i]) + ".references"), References[Path.GetFileName(files[i])]);
}
Console.ForegroundColor = ConsoleColor.Blue;
Console.WriteLine();
Console.WriteLine("Exporting modules and rendering manuals...");
Console.WriteLine();
Console.ForegroundColor = ConsoleColor.Gray;
Directory.CreateDirectory(Path.Combine(rootPath, "Modules"));
VectSharp.Markdown.MarkdownRenderer renderer = new VectSharp.Markdown.MarkdownRenderer() { BaseFontSize = 12 };
Func<string, string, (string, bool)> imageUriResolver = renderer.ImageUriResolver;
List<string> imagesToDelete = new List<string>();
Dictionary<string, string> imageCache = new Dictionary<string, string>();
renderer.ImageUriResolver = (imageUri, baseUri) =>
{
if (!imageCache.TryGetValue(baseUri + "|||" + imageUri, out string cachedImage))
{
if (!imageUri.StartsWith("data:"))
{
bool wasDownloaded;
(cachedImage, wasDownloaded) = imageUriResolver(imageUri, baseUri);
if (wasDownloaded)
{
imagesToDelete.Add(cachedImage);
}
imageCache.Add(baseUri + "|||" + imageUri, cachedImage);
}
else
{
string tempFile = Path.GetTempFileName();
if (File.Exists(tempFile))
{
File.Delete(tempFile);
}
Directory.CreateDirectory(tempFile);
string uri = imageUri;
string mimeType = uri.Substring(uri.IndexOf(":") + 1, uri.IndexOf(";") - uri.IndexOf(":") - 1);
string type = uri.Substring(uri.IndexOf(";") + 1, uri.IndexOf(",") - uri.IndexOf(";") - 1);
if (mimeType == "image/svg+xml")
{
int offset = uri.IndexOf(",") + 1;
string data;
switch (type)
{
case "base64":
data = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(uri.Substring(offset)));
break;
}
}
VectSharp.Page pag = VectSharp.SVG.Parser.ParseImageURI(imageUri, true);
VectSharp.SVG.SVGContextInterpreter.SavereplacedVG(pag, Path.Combine(tempFile, "temp.svg"));
imagesToDelete.Add(Path.Combine(tempFile, "temp.svg"));
cachedImage = Path.Combine(tempFile, "temp.svg");
imageCache.Add(baseUri + "|||" + imageUri, cachedImage);
}
}
else
{
Console.WriteLine("Fetching {0} from cache.", imageUri);
}
return (cachedImage, false);
};
List<ModuleHeader> moduleHeaders = new List<ModuleHeader>();
foreach (TreeViewer.ModuleMetadata module in modules)
{
Directory.CreateDirectory(Path.Combine(rootPath, "Modules", module.Id));
string modulePath = Path.Combine(rootPath, "Modules", module.Id, module.Id + ".v" + module.Version.ToString() + ".json.zip");
module.Sign(privateKeyFile);
module.Export(modulePath, true, true, true);
string markdownSource = module.BuildReadmeMarkdown();
Console.WriteLine("Rendering {0} - {1}", module.Name, module.Id);
Markdig.Syntax.MarkdownDoreplacedent markdownDoreplacedent = Markdig.Markdown.Parse(markdownSource, new Markdig.MarkdownPipelineBuilder().UseGridTables().UsePipeTables().UseEmphasisExtras().UseGenericAttributes().UseAutoIdentifiers().UseAutoLinks().UseTaskLists().UseListExtras().UseCitations().UseMathematics().Build());
VectSharp.Doreplacedent doc = renderer.Render(markdownDoreplacedent, out Dictionary<string, string> linkDestinations);
VectSharp.PDF.PDFContextInterpreter.SaveAsPDF(doc, Path.Combine(rootPath, "Modules", module.Id, "Readme.pdf"), linkDestinations: linkDestinations);
TreeViewer.ModuleMetadata.Install(modulePath, true, false);
ModuleHeader header = new ModuleHeader(module);
moduleHeaders.Add(header);
}
foreach (string imageFile in imagesToDelete)
{
System.IO.File.Delete(imageFile);
System.IO.Directory.Delete(System.IO.Path.GetDirectoryName(imageFile));
}
string serializedModuleHeaders = System.Text.Json.JsonSerializer.Serialize(moduleHeaders, Modules.DefaultSerializationOptions);
using (FileStream fs = new FileStream(Path.Combine(rootPath, "Modules", "modules.json.gz"), FileMode.Create))
{
using (GZipStream compressionStream = new GZipStream(fs, CompressionLevel.Optimal))
{
using (StreamWriter sw = new StreamWriter(compressionStream))
{
sw.Write(serializedModuleHeaders);
}
}
}
using (StreamWriter sw = new StreamWriter(Path.Combine(rootPath, "Modules", "Readme.md")))
{
sw.WriteLine("# Module repository");
sw.WriteLine();
sw.WriteLine("This folder contains a collection of modules maintained by the developer(s) of TreeViewer. All the modules are signed and tested before being included in this repository.");
sw.WriteLine();
sw.WriteLine("The modules can be loaded or installed by using the `Load from repository...` or `Install from repository...` options in the module manager window.");
sw.WriteLine("Alternatively, the module `json.zip` files can be downloaded and loaded or installed manually using the `Load...` or `Install...` options.");
sw.WriteLine();
sw.WriteLine("Click on the name of any module to open the folder containing the module's manual and `json.zip` file.");
sw.WriteLine();
sw.WriteLine("## List of currently available modules");
sw.WriteLine();
foreach (ModuleHeader header in moduleHeaders)
{
sw.WriteLine("<br />");
sw.WriteLine();
sw.WriteLine("### [" + header.Name + "](" + header.Id + ")");
sw.WriteLine();
sw.WriteLine("_Version " + header.Version.ToString() + ", by " + header.Author + "_");
sw.WriteLine();
sw.WriteLine("**Description**: " + header.HelpText);
sw.WriteLine();
sw.WriteLine("**Module type**: " + header.ModuleType.ToString());
sw.WriteLine();
sw.WriteLine("**Module ID**: `" + header.Id + "`");
sw.WriteLine();
}
}
return 0;
}
19
Source : Attachments.cs
with GNU Affero General Public License v3.0
from arklumpus
with GNU Affero General Public License v3.0
from arklumpus
public void WriteBase64Encoded(StreamWriter writer)
{
this.Stream.Seek(this.StreamStart, SeekOrigin.Begin);
byte[] buffer = new byte[8193];
int bytesWritten = 0;
int bufferShift = 0;
while (bytesWritten < this.StreamLength)
{
int read = this.Stream.Read(buffer, bufferShift, Math.Min(8193 - bufferShift, this.StreamLength - bytesWritten)) + bufferShift;
byte[] readBytes;
if (read == 8193)
{
readBytes = buffer;
bufferShift = 0;
}
else
{
if (read - bufferShift > 0)
{
readBytes = new byte[(read / 3) * 3];
for (int i = 0; i < readBytes.Length; i++)
{
readBytes[i] = buffer[i];
}
if (readBytes.Length < read)
{
byte[] tempBuffer = new byte[read - readBytes.Length];
for (int i = 0; i < tempBuffer.Length; i++)
{
tempBuffer[i] = buffer[i + readBytes.Length];
}
for (int i = 0; i < tempBuffer.Length; i++)
{
buffer[i] = tempBuffer[i];
}
bufferShift = tempBuffer.Length;
}
else
{
bufferShift = 0;
}
}
else
{
readBytes = new byte[bufferShift];
for (int i = 0; i < readBytes.Length; i++)
{
readBytes[i] = buffer[i];
}
bufferShift = 0;
}
}
string encoded = Convert.ToBase64String(readBytes);
writer.Write(encoded);
bytesWritten += readBytes.Length;
}
}
19
Source : Autosave.cs
with GNU Affero General Public License v3.0
from arklumpus
with GNU Affero General Public License v3.0
from arklumpus
private void Autosave(object sender, EventArgs e)
{
lock (AutosaveLock)
{
if (this.IsTreeOpened)
{
try
{
string autosavePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), replacedembly.GetEntryreplacedembly().GetName().Name, "Autosave", DateTime.Now.ToString("yyyy_MM_dd"), WindowGuid);
if (!Directory.Exists(autosavePath))
{
Directory.CreateDirectory(autosavePath);
}
AutosaveData saveData = new AutosaveData(this.OriginalFileName, DateTime.Now);
string autosaveFile = Path.Combine(autosavePath, WindowGuid + ".nex-2");
using (System.IO.StreamWriter sw = new System.IO.StreamWriter(autosaveFile))
{
sw.WriteLine("#NEXUS");
sw.WriteLine();
sw.WriteLine("Begin Trees;");
int count = 0;
foreach (TreeNode tree in this.Trees)
{
if (tree.Attributes.ContainsKey("TreeName"))
{
sw.Write("\tTree " + tree.Attributes["TreeName"].ToString() + " = ");
}
else
{
sw.Write("\tTree tree" + count.ToString() + " = ");
}
sw.Write(NWKA.WriteTree(tree, true));
sw.WriteLine();
count++;
}
sw.WriteLine("End;");
sw.WriteLine();
sw.WriteLine("Begin TreeViewer;");
string serializedModules = this.SerializeAllModules(MainWindow.ModuleTarget.AllModules, true);
sw.WriteLine("\tLength: " + serializedModules.Length + ";");
sw.WriteLine(serializedModules);
sw.WriteLine("End;");
foreach (KeyValuePair<string, Attachment> kvp in this.StateData.Attachments)
{
sw.WriteLine();
sw.WriteLine("Begin Attachment;");
sw.WriteLine("\tName: " + kvp.Key + ";");
sw.WriteLine("\tFlags: " + (kvp.Value.StoreInMemory ? "1" : "0") + (kvp.Value.CacheResults ? "1" : "0") + ";");
sw.WriteLine("\tLength: " + kvp.Value.StreamLength + ";");
kvp.Value.WriteBase64Encoded(sw);
sw.WriteLine();
sw.WriteLine("End;");
}
}
if (File.Exists(Path.Combine(autosavePath, WindowGuid + ".nex")))
{
File.Delete(Path.Combine(autosavePath, WindowGuid + ".nex"));
}
File.Move(Path.Combine(autosavePath, WindowGuid + ".nex-2"), Path.Combine(autosavePath, WindowGuid + ".nex"), true);
File.WriteAllText(Path.Combine(autosavePath, "autosave.json"), System.Text.Json.JsonSerializer.Serialize(saveData, Modules.DefaultSerializationOptions));
}
catch
{
}
}
}
}
19
Source : CryptoUtils.cs
with GNU Affero General Public License v3.0
from arklumpus
with GNU Affero General Public License v3.0
from arklumpus
public static bool VerifyStringSignature(string subject, string signature, IEnumerable<RSACryptoServiceProvider> rsaDecrypters)
{
if (string.IsNullOrEmpty(signature))
{
return false;
}
using (MemoryStream codeStream = new MemoryStream())
using (StreamWriter memoryWriter = new StreamWriter(codeStream, Encoding.UTF8))
{
memoryWriter.Write(subject);
byte[] byteSignature = Convert.FromBase64String(signature);
foreach (RSACryptoServiceProvider provider in rsaDecrypters)
{
codeStream.Seek(0, SeekOrigin.Begin);
if (provider.VerifyData(codeStream, byteSignature, HashAlgorithmName.SHA512, RSASignaturePadding.Pkcs1))
{
return true;
}
}
}
return false;
}
19
Source : CryptoUtils.cs
with GNU Affero General Public License v3.0
from arklumpus
with GNU Affero General Public License v3.0
from arklumpus
public static string SignString(string subject, RSACryptoServiceProvider rsaEncrypter)
{
using (MemoryStream codeStream = new MemoryStream())
using (StreamWriter memoryWriter = new StreamWriter(codeStream, Encoding.UTF8))
{
memoryWriter.Write(subject);
codeStream.Seek(0, SeekOrigin.Begin);
byte[] byteSignature = rsaEncrypter.SignData(codeStream, HashAlgorithmName.SHA512, RSASignaturePadding.Pkcs1);
return Convert.ToBase64String(byteSignature);
}
}
19
Source : NexusCommand.cs
with GNU Affero General Public License v3.0
from arklumpus
with GNU Affero General Public License v3.0
from arklumpus
void ExportToStream(Stream stream, int subject, bool modules, bool addSignature, bool includeAttachments)
{
using (StreamWriter sw = new StreamWriter(stream))
{
if (subject == 0)
{
sw.WriteLine("#NEXUS");
sw.WriteLine();
sw.WriteLine("Begin Trees;");
int count = 0;
foreach (TreeNode tree in Program.Trees)
{
if (tree.Attributes.ContainsKey("TreeName"))
{
sw.Write("\tTree " + tree.Attributes["TreeName"].ToString() + " = ");
}
else
{
sw.Write("\tTree tree" + count.ToString() + " = ");
}
sw.Write(NWKA.WriteTree(tree, true));
sw.WriteLine();
count++;
}
sw.WriteLine("End;");
if (modules)
{
sw.WriteLine();
sw.WriteLine("Begin TreeViewer;");
string serializedModules = Program.SerializeAllModules(TreeViewer.MainWindow.ModuleTarget.AllModules, addSignature);
sw.WriteLine("\tLength: " + serializedModules.Length + ";");
sw.WriteLine(serializedModules);
sw.WriteLine("End;");
}
}
else if (subject == 1)
{
sw.WriteLine("#NEXUS");
sw.WriteLine();
sw.WriteLine("Begin Trees;");
if (Program.FirstTransformedTree.Attributes.ContainsKey("TreeName"))
{
sw.Write("\tTree " + Program.FirstTransformedTree.Attributes["TreeName"].ToString() + " = ");
}
else
{
sw.Write("\tTree tree = ");
}
sw.Write(NWKA.WriteTree(Program.FirstTransformedTree, true));
sw.WriteLine();
sw.WriteLine("End;");
if (modules)
{
sw.WriteLine();
sw.WriteLine("Begin TreeViewer;");
string serializedModules = Program.SerializeAllModules(TreeViewer.MainWindow.ModuleTarget.ExcludeTransform, addSignature);
sw.WriteLine("\tLength: " + serializedModules.Length + ";");
sw.WriteLine(serializedModules);
sw.WriteLine("End;");
}
}
else if (subject == 2)
{
sw.WriteLine("#NEXUS");
sw.WriteLine();
sw.WriteLine("Begin Trees;");
if (Program.TransformedTree.Attributes.ContainsKey("TreeName"))
{
sw.Write("\tTree " + Program.TransformedTree.Attributes["TreeName"].ToString() + " = ");
}
else
{
sw.Write("\tTree tree = ");
}
sw.Write(NWKA.WriteTree(Program.TransformedTree, true));
sw.WriteLine();
sw.WriteLine("End;");
if (modules)
{
sw.WriteLine();
sw.WriteLine("Begin TreeViewer;");
string serializedModules = Program.SerializeAllModules(TreeViewer.MainWindow.ModuleTarget.ExcludeFurtherTransformation, addSignature);
sw.WriteLine("\tLength: " + serializedModules.Length + ";");
sw.WriteLine(serializedModules);
sw.WriteLine("End;");
}
}
if (includeAttachments)
{
foreach (KeyValuePair<string, Attachment> kvp in Program.StateData.Attachments)
{
sw.WriteLine();
sw.WriteLine("Begin Attachment;");
sw.WriteLine("\tName: " + kvp.Key + ";");
sw.WriteLine("\tFlags: " + (kvp.Value.StoreInMemory ? "1" : "0") + (kvp.Value.CacheResults ? "1" : "0") + ";");
sw.WriteLine("\tLength: " + kvp.Value.StreamLength + ";");
kvp.Value.WriteBase64Encoded(sw);
sw.WriteLine();
sw.WriteLine("End;");
}
}
}
}
19
Source : Program.cs
with GNU General Public License v3.0
from arklumpus
with GNU General Public License v3.0
from arklumpus
static void Main(string[] args)
{
//Deserialize examples
MarkdownExample[] examples;
using (StreamReader sr = new StreamReader(System.Reflection.replacedembly.GetExecutingreplacedembly().GetManifestResourceStream("MarkdownExamples.spec.json")))
{
examples = JsonSerializer.Deserialize<MarkdownExample[]>(sr.ReadToEnd());
}
//GitHub Markdown css, from https://github.com/sindresorhus/github-markdown-css
string css;
using (StreamReader sr = new StreamReader(System.Reflection.replacedembly.GetExecutingreplacedembly().GetManifestResourceStream("MarkdownExamples.github-markdown.css")))
{
css = sr.ReadToEnd();
}
string exampleHtmlHeader = "<html><head><style>" + css + "</style></head><body clreplaced=\"markdown-body\">";
string exampleHtmlTrailer = "</body></html>";
int exampleFileCount = (int)Math.Ceiling(examples.Length / 20.0);
MarkdownRenderer renderer = new MarkdownRenderer() { Margins = new Margins(10, 10, 10, 10), BaseFontSize = 16 };
for (int i = 0; i < exampleFileCount; i++)
{
using (StreamWriter writer = new StreamWriter("Examples" + (i + 1).ToString() + ".html"))
{
writer.WriteLine("<html>");
writer.WriteLine("\t<head>");
writer.WriteLine("\t\t<replacedle>VectSharp.Markdown rendering examples</replacedle>");
writer.WriteLine("\t\t<style>");
writer.WriteLine("\t\t\tpre {");
writer.WriteLine("\t\t\t\tbackground: #F0F0F0;");
writer.WriteLine("\t\t\t}");
writer.WriteLine("\t\t\ttable {");
writer.WriteLine("\t\t\t\twidth: 100%;");
writer.WriteLine("\t\t\t}");
writer.WriteLine("\t\t\tiframe {");
writer.WriteLine("\t\t\t\twidth: 100%;");
writer.WriteLine("\t\t\t}");
writer.WriteLine("\t\t</style>");
writer.WriteLine("\t</head>");
writer.WriteLine("\t<body>");
writer.WriteLine("\t\t<h1>VectSharp.Markdown rendering examples " + (i * 20 + 1).ToString() + " - " + Math.Min(i * 20 + 20, examples.Length).ToString() + " / " + examples.Length.ToString() + "</h1>");
for (int j = i * 20; j < Math.Min(i * 20 + 20, examples.Length); j++)
{
MarkdownExample example = examples[j];
Page pag = renderer.RenderSinglePage(Markdig.Markdown.Parse(example.markdown), 500, out Dictionary<string, string> linkDestinations);
writer.WriteLine("\t\t<h2>Example #" + example.example.ToString() + "</h2>");
writer.WriteLine("\t\t<h3>" + example.section + ", lines " + example.start_line.ToString() + " - " + example.end_line + "</h3>");
writer.WriteLine("\t\t<table>");
writer.WriteLine("\t\t\t<thead>");
writer.WriteLine("\t\t\t\t<tr>");
writer.WriteLine("\t\t\t\t\t<th scope=\"col\">Markdown source</th>");
writer.WriteLine("\t\t\t\t\t<th scope=\"col\">Reference HTML</th>");
writer.WriteLine("\t\t\t\t\t<th scope=\"col\">VectSharp.Markdown SVG</th>");
writer.WriteLine("\t\t\t\t</tr>");
writer.WriteLine("\t\t\t</thead>");
writer.WriteLine("\t\t\t<tbody>");
writer.WriteLine("\t\t\t\t<tr>");
writer.WriteLine("\t\t\t\t\t<td>");
writer.WriteLine("\t\t\t\t\t\t<pre><code>");
writer.Write(System.Web.HttpUtility.HtmlEncode(example.markdown));
writer.WriteLine("\t\t\t\t\t\t</code></pre>");
writer.WriteLine("\t\t\t\t\t</td>");
writer.WriteLine("\t\t\t\t\t<td>");
writer.Write("\t\t\t\t\t\t<iframe src=\"data:text/html;charset=UTF-8;base64,");
writer.Write(Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(exampleHtmlHeader + example.html + exampleHtmlTrailer)));
writer.WriteLine("\"></iframe>");
writer.WriteLine("\t\t\t\t\t</td>");
writer.WriteLine("\t\t\t\t\t<td>");
string svgSource;
using (MemoryStream ms = new MemoryStream())
{
pag.SavereplacedVG(ms, SVGContextInterpreter.TextOptions.DoNotEmbed, linkDestinations: linkDestinations);
ms.Seek(0, SeekOrigin.Begin);
using (StreamReader sr = new StreamReader(ms))
{
svgSource = sr.ReadToEnd();
}
}
writer.Write("\t\t\t\t\t\t<iframe style=\"height: " + pag.Height.ToString(System.Globalization.CultureInfo.InvariantCulture) + "px\" src=\"data:image/svg+xml;charset=UTF-8;base64,");
writer.Write(Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(svgSource)));
writer.WriteLine("\"></iframe>");
writer.WriteLine("\t\t\t\t\t</td>");
writer.WriteLine("\t\t\t\t</tr>");
writer.WriteLine("\t\t\t</tbody>");
writer.WriteLine("\t\t</table>");
}
writer.WriteLine("\t\t<h2 style=\"text-align: center\">");
if (i > 0)
{
writer.WriteLine("\t\t\t<a href=\"Examples" + (i).ToString() + ".html\">< Prev</a>");
}
if (i < exampleFileCount - 1)
{
writer.WriteLine("\t\t\t<a href=\"Examples" + (i + 2).ToString() + ".html\">Next ></a>");
}
writer.WriteLine("\t\t</h2>");
writer.WriteLine("\t</body>");
writer.WriteLine("</html>");
}
}
}
19
Source : NamedPipes.cs
with GNU Affero General Public License v3.0
from arklumpus
with GNU Affero General Public License v3.0
from arklumpus
public static bool TryStartClient(string[] files, bool startNewProcess)
{
if (files.Length == 1)
{
files = new string[] { files[0], "::OpenWindow" };
}
try
{
using (NamedPipeClientStream client = new NamedPipeClientStream(PipeName))
{
client.Connect(100);
using (StreamWriter writer = new StreamWriter(client))
{
if (!startNewProcess)
{
writer.Write(files.Aggregate((a, b) => a + "\t" + b));
}
else
{
writer.Write("::DoNothing");
}
return true;
}
}
}
catch
{
return false;
}
}
19
Source : C3FileHandler.cs
with GNU General Public License v3.0
from armandoalonso
with GNU General Public License v3.0
from armandoalonso
public Stream GenerateStreamFromString(string s)
{
var stream = new MemoryStream();
var writer = new StreamWriter(stream);
writer.Write(s);
writer.Flush();
stream.Position = 0;
return stream;
}
19
Source : StringExtentions.cs
with GNU General Public License v3.0
from armandoalonso
with GNU General Public License v3.0
from armandoalonso
public static Stream ToStream (this string s)
{
var stream = new MemoryStream();
var writer = new StreamWriter(stream);
writer.Write(s);
writer.Flush();
stream.Position = 0;
return stream;
}
19
Source : Utilities.cs
with MIT License
from arsium
with MIT License
from arsium
public static void ToCSV(ListView listView, string filePath)
{
//make header string
using (StreamWriter sw = new StreamWriter(filePath, false, System.Text.Encoding.Default))
{
//ajout du replacedre des colonnes
foreach (ColumnHeader c in listView.Columns)
sw.Write(string.Format("{0};", c.Text));
sw.WriteLine("");
// ajout des données
foreach (ListViewItem item in listView.Items)
{
foreach (ListViewItem.ListViewSubItem subitem in item.SubItems)
sw.Write(string.Format("{0};", subitem.Text));
sw.WriteLine("");
}
}
}
19
Source : ConfigFileManager.cs
with GNU General Public License v3.0
from arunsatyarth
with GNU General Public License v3.0
from arunsatyarth
public void WriteData()
{
try
{
string filename = GetFileName();
Stream stream = new FileStream(filename, FileMode.Create);
StreamWriter sr = new StreamWriter(stream);
sr.Write(Data);
sr.Close();
}
catch (Exception e)
{
}
}
19
Source : MinerProgramBase.cs
with GNU General Public License v3.0
from arunsatyarth
with GNU General Public License v3.0
from arunsatyarth
public virtual void SaveToBAtFile()
{
try
{
FileStream stream = File.Open(BATFILE, FileMode.Create);
StreamWriter sw = new StreamWriter(stream);
sw.Write(Script);
sw.Flush();
sw.Close();
//generate script and write to folder
}
catch (Exception e)
{
}
}
19
Source : Program.cs
with MIT License
from ashmind
with MIT License
from ashmind
private static void WriteTypeReport(StreamWriter writer, Type type, string typeName, NamespacePolicy namespacePolicy) {
if (!namespacePolicy.Types.TryGetValue(typeName, out TypePolicy? typePolicy))
typePolicy = null;
var effectiveTypeAccess = GetEffectiveTypeAccess(typePolicy?.Access, namespacePolicy.Access);
writer.Write(" ");
writer.Write(typeName);
writer.Write(": ");
writer.WriteLine(effectiveTypeAccess);
if (effectiveTypeAccess == Denied)
return;
foreach (var methodName in type.GetMembers().OfType<MethodBase>().Select(m => m.Name).Distinct().OrderBy(n => n)) {
WriteMethodReport(writer, methodName, typePolicy, effectiveTypeAccess);
}
}
19
Source : Program.cs
with MIT License
from ashmind
with MIT License
from ashmind
private static void WriteMethodReport(StreamWriter writer, string methodName, TypePolicy? typePolicy, ApiAccess effectiveTypeAccess) {
var methodPolicy = (MemberPolicy?)null;
if (typePolicy != null)
typePolicy.Members.TryGetValue(methodName, out methodPolicy);
var effectiveMethodAccess = GetEffectiveMethodAccess(methodPolicy?.Access, typePolicy?.Access, effectiveTypeAccess);
writer.Write(" ");
writer.Write(methodName);
writer.Write(": ");
writer.Write(effectiveMethodAccess);
if (methodPolicy?.HasRewriters ?? false) {
writer.Write(" (");
writer.Write(string.Join(", ", methodPolicy!.Rewriters.Cast<IMemberRewriterInternal>().Select(r => r.GetShortName())));
writer.Write(")");
}
writer.WriteLine();
}
19
Source : Extensions.cs
with GNU General Public License v2.0
from Asixa
with GNU General Public License v2.0
from Asixa
public static Stream ToStream(this string s)
{
var stream = new MemoryStream();
var writer = new StreamWriter(stream);
writer.Write(s);
writer.Flush();
stream.Position = 0;
return stream;
}
19
Source : ChildProcessTest_Redirection.cs
with MIT License
from asmichi
with MIT License
from asmichi
[Fact]
public void ConnectsInputPipe()
{
using var tmp = new TemporaryDirectory();
var outFile = Path.Combine(tmp.Location, "out");
var si = new ChildProcessStartInfo(TestUtil.DotnetCommandName, TestUtil.TestChildPath, "EchoBack")
{
StdInputRedirection = InputRedirection.InputPipe,
StdOutputRedirection = OutputRedirection.File,
StdOutputFile = outFile,
StdErrorRedirection = OutputRedirection.NullDevice,
};
using var sut = ChildProcess.Start(si);
const string Text = "foo";
using (var sw = new StreamWriter(sut.StandardInput))
{
sw.Write(Text);
}
sut.WaitForExit();
replacedert.True(sut.HreplacedtandardInput);
replacedert.False(sut.HreplacedtandardOutput);
replacedert.False(sut.HreplacedtandardError);
replacedert.Equal(Text, File.ReadAllText(outFile));
}
19
Source : BaseView.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
protected void WriteLiteral(string value)
{
Output.Write(value);
}
19
Source : CanonicalRequestPatterns.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
public Task Index(IDictionary<string, object> env)
{
Util.ResponseHeaders(env)["Content-Type"] = new[] { "text/html" };
Stream output = Util.ResponseBody(env);
using (var writer = new StreamWriter(output))
{
writer.Write("<ul>");
foreach (var kv in _paths.Where(item => item.Value.Item2 != null))
{
writer.Write("<li><a href='");
writer.Write(kv.Key);
writer.Write("'>");
writer.Write(kv.Key);
writer.Write("</a> ");
writer.Write(kv.Value.Item2);
writer.Write("</li>");
}
writer.Write("<li><a href='/testpage'>/testpage</a> Test Page</li>");
writer.Write("<li><a href='/Welcome'>/Welcome</a> Welcome Page</li>");
writer.Write("</ul>");
}
return Task.FromResult<object>(null);
}
19
Source : FormsTests.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
[Fact]
public void ReadFromStream()
{
var stream = new MemoryStream();
var writer = new StreamWriter(stream);
writer.Write(OriginalFormsString);
writer.Flush();
stream.Seek(0, SeekOrigin.Begin);
IOwinRequest request = new OwinRequest();
request.Body = stream;
IFormCollection form = request.ReadFormAsync().Result;
replacedert.Equal("v1", form.Get("q1"));
replacedert.Equal("v2,b", form.Get("Q2"));
replacedert.Equal("v3,v4", form.Get("q3"));
replacedert.Null(form.Get("q4"));
replacedert.Equal("v5,v5", form.Get("Q5"));
replacedert.Equal("v 6", form.Get("Q 6"));
}
19
Source : ResponseBodyTests.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
public void CloseResponseBodyAndWriteExtra(IAppBuilder app)
{
// Delayed write
app.Use(async (context, next) =>
{
await next();
var writer = new StreamWriter(context.Response.Body);
writer.Write("AndExtra");
writer.Flush();
writer.Close();
});
app.Run(context =>
{
var writer = new StreamWriter(context.Response.Body);
writer.Write("Response");
writer.Flush();
writer.Close();
return Task.FromResult(0);
});
}
19
Source : FormsTests.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
[Fact]
public void ReadFromStreamTwice()
{
var stream = new MemoryStream();
var writer = new StreamWriter(stream);
writer.Write(OriginalFormsString);
writer.Flush();
stream.Seek(0, SeekOrigin.Begin);
IOwinRequest request = new OwinRequest();
request.Body = stream;
IFormCollection form = request.ReadFormAsync().Result;
replacedert.Equal("v1", form.Get("q1"));
replacedert.Equal("v2,b", form.Get("Q2"));
replacedert.Equal("v3,v4", form.Get("q3"));
replacedert.Null(form.Get("q4"));
replacedert.Equal("v5,v5", form.Get("Q5"));
replacedert.Equal("v 6", form.Get("Q 6"));
form = request.ReadFormAsync().Result;
replacedert.Equal("v1", form.Get("q1"));
replacedert.Equal("v2,b", form.Get("Q2"));
replacedert.Equal("v3,v4", form.Get("q3"));
replacedert.Null(form.Get("q4"));
replacedert.Equal("v5,v5", form.Get("Q5"));
replacedert.Equal("v 6", form.Get("Q 6"));
}
19
Source : TestRazorSourceDocument.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
public static MemoryStream CreateStreamContent(string content = "Hello, World!", Encoding encoding = null, bool normalizeNewLines = false)
{
var stream = new MemoryStream();
encoding = encoding ?? Encoding.UTF8;
using (var writer = new StreamWriter(stream, encoding, bufferSize: 1024, leaveOpen: true))
{
if (normalizeNewLines)
{
content = NormalizeNewLines(content);
}
writer.Write(content);
}
stream.Seek(0L, SeekOrigin.Begin);
return stream;
}
19
Source : ExceptionManager.cs
with GNU General Public License v3.0
from Athlon007
with GNU General Public License v3.0
from Athlon007
public static void GenerateReport()
{
string gameInfo = GetGameInfo();
int reportsInFolder = 0;
while (File.Exists($"{LogFolder}/{DefaultReportLogName}_{reportsInFolder}.txt"))
reportsInFolder++;
string path = $"{LogFolder}/{DefaultReportLogName}_{reportsInFolder}.txt";
using (StreamWriter sw = new StreamWriter(path))
{
sw.Write(gameInfo);
sw.Close();
sw.Dispose();
}
ModConsole.Log("[MOP] Mod report has been successfully generated.");
Process.Start(path);
}
19
Source : JsonWriter.cs
with Apache License 2.0
from atteneder
with Apache License 2.0
from atteneder
public void AddProperty(string name) {
Separate();
m_Stream.Write('"');
m_Stream.Write(name);
m_Stream.Write("\":");
separation = false;
}
19
Source : JsonWriter.cs
with Apache License 2.0
from atteneder
with Apache License 2.0
from atteneder
public void AddArray(string name) {
Separate();
m_Stream.Write('"');
m_Stream.Write(name);
m_Stream.Write("\":[");
separation = false;
}
19
Source : JsonWriter.cs
with Apache License 2.0
from atteneder
with Apache License 2.0
from atteneder
public void AddArrayProperty<T>(string name, IEnumerable<T> values) {
AddArray(name);
foreach (var value in values) {
Separate();
m_Stream.Write(value.ToString());
}
CloseArray();
}
19
Source : JsonWriter.cs
with Apache License 2.0
from atteneder
with Apache License 2.0
from atteneder
public void AddArrayProperty(string name, IEnumerable<float> values) {
AddArray(name);
foreach (var value in values) {
Separate();
m_Stream.Write(value.ToString("R"));
}
CloseArray();
}
19
Source : JsonWriter.cs
with Apache License 2.0
from atteneder
with Apache License 2.0
from atteneder
public void AddArrayProperty(string name, IEnumerable<string> values) {
AddArray(name);
foreach (var value in values) {
Separate();
m_Stream.Write('"');
m_Stream.Write(value);
m_Stream.Write('"');
}
CloseArray();
}
19
Source : JsonWriter.cs
with Apache License 2.0
from atteneder
with Apache License 2.0
from atteneder
public void AddProperty<T>(string name, T value) {
Separate();
m_Stream.Write('"');
m_Stream.Write(name);
m_Stream.Write("\":");
m_Stream.Write(value.ToString());
}
19
Source : JsonWriter.cs
with Apache License 2.0
from atteneder
with Apache License 2.0
from atteneder
public void AddProperty(string name, string value) {
Separate();
m_Stream.Write('"');
m_Stream.Write(name);
m_Stream.Write("\":\"");
m_Stream.Write(value);
m_Stream.Write('"');
}
19
Source : JsonWriter.cs
with Apache License 2.0
from atteneder
with Apache License 2.0
from atteneder
public void AddProperty(string name, bool value) {
Separate();
m_Stream.Write('"');
m_Stream.Write(name);
m_Stream.Write("\":");
m_Stream.Write(value?"true":"false");
}
19
Source : ExtraMetaFiles.cs
with GNU General Public License v3.0
from audiamus
with GNU General Public License v3.0
from audiamus
void writeTextFile (Func<Book, string> nameFunc, string dir) {
if (AaxFileItem is null)
return;
var afi = AaxFileItem;
string filename = $"{nameFunc (Book)}.txt";
string path = Path.Combine (dir, filename);
Log (3, this, () => $"\"{path.SubsreplacedUser ()}\"");
try {
using (var osm = new StreamWriter (path, false)) {
osm.WriteLine ($"{R.HdrAuthor}: {Book.AuthorTag}");
osm.WriteLine ($"{R.Hdrreplacedle}: {Book.replacedleTag}");
osm.WriteLine ($"{R.HdrDuration}: {Duration.ToStringHMS ()}");
osm.WriteLine ($"{R.HdrNarrator}: {afi.Narrator}");
osm.WriteLine ($"{R.HdrGenre}: {Book.CustomNames?.GenreTag ?? TagAndFileNamingHelper.GetGenre (Settings, afi)}");
osm.WriteLine ($"{R.HdrYear}: {Book.CustomNames?.YearTag?.Year ?? afi.PublishingDate?.Year}");
osm.WriteLine ($"{R.HdrPublisher}: {afi.Publisher}");
osm.WriteLine ($"{R.HdrCopyright}: {afi.Copyright}");
osm.WriteLine ($"{R.HdrSampleRate}: {afi.SampleRate} Hz");
osm.WriteLine ($"{R.HdrBitRate}: {afi.AvgBitRate} kb/s");
osm.WriteLine ();
string[] words = afi.Abstract?.Split ();
if (words is null)
return;
int n = 0;
for (int i = 0; i < words.Length; i++) {
string word = words[i];
if (n + 1 + word.Length > 80) {
osm.WriteLine ();
n = 0;
}
if (n > 0) {
osm.Write (' ');
n++;
}
osm.Write (word);
n += word.Length;
}
osm.WriteLine ();
}
} catch (Exception exc) {
Log (1, this, exc.ToShortString ());
}
}
19
Source : Main.cs
with MIT License
from austinvaness
with MIT License
from austinvaness
void Process (Mesh m, float c, bool hollow, bool slopes, bool chunkedProcessing, BackgroundWorker worker, DoWorkEventArgs e)
{
Vector3I size = Vector3.Floor(m.Bounds.size / c) + 1;
BitArray grid = new BitArray(size.x, size.y, size.z);
if (worker.CancellationPending)
{
e.Cancel = true;
return;
}
if (chunkedProcessing)
{
worker.ReportProgress(0, $"Generating MetaGrid... {0}%");
m = new ChunkMesh(((StandardMesh)m), new Vector3I(1, size.y, size.z),
m.Bounds);
}
Vector3 min = m.Bounds.min;
Vector3 max = m.Bounds.max;
Vector3 p = min;
int x = 0;
for (p.x = min.x; p.x < max.x; p.x += c)
{
if (worker.CancellationPending)
{
e.Cancel = true;
return;
}
float percent = Math.Min(x / (float)size.x, 1);
worker.ReportProgress((int)(percent * GlobalConstants.processSplit), $"Building point cloud... {(int)(percent * 100)}% - Points: {grid.Count}");
int y = 0;
for (p.y = min.y; p.y < max.y; p.y += c)
{
if (worker.CancellationPending)
break;
float minZ = m.Bounds.min.z;
Parallel.For(0, size.z, (i) => {
if (m.ContainsPoint(new Vector3(p.x, p.y, minZ + (c * i))))
WriteCube(grid, x, y, i);
});
y++;
}
x++;
}
blockCount.Value = 0;
worker.ReportProgress(GlobalConstants.processSplit, "Processing points... 0% - Blocks: 0");
string name = GetName();
byte [] randId = new byte [8];
rand.NextBytes(randId);
string header = Main.header.Replace("{name}", name).Replace("{id}", BitConverter.ToInt64(randId, 0).ToString());
if (this.cube.Large)
header = header.Replace("{type}", "Large");
else
header = header.Replace("{type}", "Small");
string tempFile = Path.GetTempFileName();
text = File.CreateText(tempFile);
text.Write(header);
Vector3I gridPos = new Vector3I();
for (; gridPos.x < size.x; gridPos.x++)
{
if (worker.CancellationPending)
{
e.Cancel = true;
text.Close();
File.Delete(tempFile);
return;
}
float percent = gridPos.x / (float)size.x;
worker.ReportProgress(GlobalConstants.processSplit + (int)(percent * (100 - GlobalConstants.processSplit)), $"Processing points... {(int)(percent * 100)}% - Blocks: {blockCount.Value}");
for (gridPos.y = 0; gridPos.y < size.y; gridPos.y++)
{
if (worker.CancellationPending)
break;
Parallel.For(0, size.z, (i) => {
Write(grid, gridPos, i, c, hollow, slopes, m);
});
}
}
worker.ReportProgress(100, "Done! - Blocks: " + blockCount.Value);
text.Write(Main.footer.Replace("{name}", name));
text.Close();
string dir = GetDirectory(name);
Directory.CreateDirectory(dir);
File.Delete(dir + "\\bp.sbc");
File.Move(tempFile, dir + "\\bp.sbc");
if (File.Exists(dir + "\\bp.sbcB5"))
File.Delete(dir + "\\bp.sbcB5");
MessageBox.Show("'" + name + "' blueprint complete!");
}
19
Source : Main.cs
with MIT License
from austinvaness
with MIT License
from austinvaness
private void Write (BitArray grid, Vector3I gridPos, int z, float c, bool hollow, bool slopes, Mesh m)
{
gridPos.z = z;
if (CheckSlopes(gridPos, c,hollow, slopes, grid, out ArmorCube cube, m))
{
string s = cube.ToString();
lock (text)
text.Write(s);
lock (blockCount)
blockCount.Value++;
}
}
19
Source : File.cs
with MIT License
from Autodesk
with MIT License
from Autodesk
public void WriteText(string text, bool appendText, Encoding encoding)
{
using (var stream = new StreamWriter(Path, appendText, encoding))
{
stream.Write(text);
}
}
19
Source : FileFactory.cs
with Apache License 2.0
from AutomateThePlanet
with Apache License 2.0
from AutomateThePlanet
public static string CreateTestFile(string destinationFolder, string textToWrite = null, string extension = "")
{
var actualExtension = string.Empty;
if (!string.IsNullOrEmpty(extension))
{
actualExtension = string.Concat(".", extension);
}
var destinationFile = Path.Combine(destinationFolder, string.Concat(Guid.NewGuid().ToString(), actualExtension));
using (var writer = new StreamWriter(destinationFile))
{
if (string.IsNullOrEmpty(textToWrite))
{
textToWrite = Guid.NewGuid().ToString();
}
writer.Write(textToWrite);
}
return destinationFile;
}
19
Source : SchemaMarkdownGenerator.cs
with MIT License
from Avanade
with MIT License
from Avanade
private static void WriteTableItem(StreamWriter sw, string? name, string? replacedle, string? description = null, string? markdown = null, bool isImportant = false, string[]? options = null)
{
if (isImportant)
sw.Write("**");
sw.Write($"`{name}`");
if (isImportant)
sw.Write("**");
sw.Write($" | {replacedle}");
if (options != null)
{
sw.Write(" Valid options are: ");
var isFirst = true;
foreach (var o in options)
{
if (isFirst)
isFirst = false;
else
sw.Write(", ");
sw.Write($"`{o}`");
}
sw.Write(".");
}
if (description != null)
sw.Write($" {description}");
if (markdown != null)
sw.Write($" {markdown}");
sw.WriteLine();
}
19
Source : Utility.cs
with MIT License
from AvapiDotNet
with MIT License
from AvapiDotNet
public static int create()
{
string projectPath = Path.Combine(basePath, "Utility.cs");
using (var fileStream = new FileStream(string.Format(projectPath), FileMode.Create))
using (StreamWriter writer = new StreamWriter(fileStream))
{
writer.Write(str_prefix);
writer.Write(str_content);
writer.Write(str_postfix);
}
return 0;
}
19
Source : AvapiConnection.cs
with MIT License
from AvapiDotNet
with MIT License
from AvapiDotNet
public static int create()
{
string projectPath = Path.Combine(basePath, "AvapiConnection.cs");
using (var fileStream = new FileStream(String.Format(projectPath), FileMode.Create))
using (StreamWriter writer = new StreamWriter(fileStream))
{
writer.Write(str_prefix);
writer.Write(str_content);
writer.Write(str_postfix);
}
return 0;
}
19
Source : Constant.cs
with MIT License
from AvapiDotNet
with MIT License
from AvapiDotNet
private int create()
{
using (var fileStream = new FileStream(String.Format(path), FileMode.Create))
using (StreamWriter writer = new StreamWriter(fileStream))
{
writer.Write(str_prefix);
writer.Write(str_content);
writer.Write(str_postfix);
}
return 0;
}
19
Source : Csproj.cs
with MIT License
from AvapiDotNet
with MIT License
from AvapiDotNet
public static int create()
{
string projectPath = Path.Combine(basePath, "Avapi.csproj");
using (var fileStream = new FileStream(string.Format(projectPath), FileMode.Create))
using (StreamWriter writer = new StreamWriter(fileStream))
{
writer.Write(str_content);
}
return 0;
}
19
Source : Example.cs
with MIT License
from AvapiDotNet
with MIT License
from AvapiDotNet
public static int create()
{
Directory.CreateDirectory(basePath);
string projectPath = Path.Combine(basePath, "Example.cs");
using (var fileStream = new FileStream(string.Format(projectPath), FileMode.Create))
using (StreamWriter writer = new StreamWriter(fileStream))
{
writer.Write(str_using);
writer.Write(str_prefix);
str_content = str_content.Remove(str_content.Length-1);
writer.Write(str_content);
writer.Write(exceptions);
writer.Write(str_postfix);
}
return 0;
}
19
Source : IAvapiConnection.cs
with MIT License
from AvapiDotNet
with MIT License
from AvapiDotNet
public static int create()
{
string projectPath = Path.Combine(basePath, "IAvapiConnection.cs");
using (var fileStream = new FileStream(String.Format(projectPath), FileMode.Create))
using (StreamWriter writer = new StreamWriter(fileStream))
{
writer.Write(str_prefix);
writer.Write(str_content);
writer.Write(str_postfix);
}
return 0;
}
19
Source : FileHelper.cs
with MIT License
from awesomedotnetcore
with MIT License
from awesomedotnetcore
private static void WriteTxt(string content, string path, Encoding encoding, FileMode? fileModel)
{
encoding = encoding ?? Encoding.UTF8;
fileModel = fileModel ?? FileMode.Create;
string dir = Path.GetDirectoryName(path);
if (!Directory.Exists(dir))
Directory.CreateDirectory(dir);
using (FileStream fileStream = new FileStream(path, fileModel.Value))
{
using (StreamWriter streamWriter = new StreamWriter(fileStream, encoding))
{
streamWriter.Write(content);
streamWriter.Flush();
}
}
}
19
Source : WebHelpGenerator.cs
with Apache License 2.0
from aws
with Apache License 2.0
from aws
private void WriteLegacyAliasesPage()
{
var templateFilename = "pstoolsref-legacyaliases.html";
using (var stream = replacedembly.GetExecutingreplacedembly().GetManifestResourceStream("AWSPowerShellGenerator.HelpMaterials.WebHelp.Templates." + templateFilename))
using (var reader = new StreamReader(stream))
{
var finalBody = reader.ReadToEnd();
var aliasTables = new StringBuilder();
if (_legacyAliasesByService.ContainsKey(TOCWriter.CommonTOCName))
{
var aliases = _legacyAliasesByService[TOCWriter.CommonTOCName];
WriteLegacyAliasesForService(aliasTables, TOCWriter.CommonTOCName, aliases);
}
var services = _legacyAliasesByService.Keys.ToList();
services.Sort();
foreach (var service in services)
{
if (service.Equals(TOCWriter.CommonTOCName, StringComparison.Ordinal))
continue;
var aliases = _legacyAliasesByService[service];
WriteLegacyAliasesForService(aliasTables, service, aliases);
}
finalBody = finalBody.Replace("{LEGACY_ALIASES_SNIPPET}", aliasTables.ToString());
var filename = Path.Combine(OutputFolder, "items", templateFilename);
using (var writer = new StreamWriter(filename))
{
writer.Write(finalBody);
}
}
}
19
Source : GenerationSources.cs
with Apache License 2.0
from aws
with Apache License 2.0
from aws
private void WriteCompletionScriptsFile(string completorsScriptModuleFile, string completionScript, string customCompletersFilter = null)
{
string fileHeader;
using (var stream = replacedembly.GetExecutingreplacedembly().GetManifestResourceStream("AWSPowerShellGenerator.CompletersHeader.psm1"))
using (var reader = new StreamReader(stream))
{
fileHeader = reader.ReadToEnd();
}
var customCompletersFolder = Path.Combine(AwsPowerShellModuleFolder, CompletersConfigFoldername);
string[] customCompleterFiles;
if (customCompletersFilter == null)
{
customCompleterFiles = Directory.GetFiles(customCompletersFolder, "*.psm1");
}
else
{
var fileName = Path.Combine(customCompletersFolder, $"{customCompletersFilter}.psm1");
customCompleterFiles = File.Exists(fileName) ? new string[] { fileName } : Array.Empty<string>();
}
using (var writer = File.CreateText(completorsScriptModuleFile))
{
writer.WriteLine(fileHeader);
writer.WriteLine();
writer.WriteLine(completionScript);
foreach(var customCompleterFile in customCompleterFiles)
{
string content = File.ReadAllText(customCompleterFile);
writer.WriteLine();
writer.Write(content);
}
}
}
19
Source : BaseTemplateWriter.cs
with Apache License 2.0
from aws
with Apache License 2.0
from aws
public void Write()
{
var templateName = GetTemplateName();
using (var stream = replacedembly.GetExecutingreplacedembly().GetManifestResourceStream("AWSPowerShellGenerator.HelpMaterials.WebHelp.Templates." + templateName))
using (var reader = new StreamReader(stream))
{
var templateBody = reader.ReadToEnd();
var finalBody = ReplaceTokens(templateBody);
var filename = Path.Combine(OutputFolder, templateName);
using (var writer = new StreamWriter(filename))
{
writer.Write(finalBody);
}
}
}
19
Source : LambdaPackager.cs
with Apache License 2.0
from aws
with Apache License 2.0
from aws
private static void EnsureBootstrapLinuxLineEndings(string rootDirectory, IDictionary<string, string> includedFiles)
{
if (includedFiles.ContainsKey(BootstrapFilename))
{
var bootstrapPath = Path.Combine(rootDirectory, BootstrapFilename);
if (FileIsLinuxShellScript(bootstrapPath))
{
var lines = File.ReadAllLines(bootstrapPath);
using (var sw = File.CreateText(bootstrapPath))
{
foreach (var line in lines)
{
sw.Write(line);
sw.Write(LinuxLineEnding);
}
}
}
}
}
19
Source : BasePageWriter.cs
with Apache License 2.0
from aws
with Apache License 2.0
from aws
public void Write()
{
var filename = Path.Combine(OutputFolder, "items", GenerateFilename());
RelativePathToRoot = ComputeRelativeRootPath(OutputFolder, filename);
var directory = new FileInfo(filename).Directory.FullName;
if (!Directory.Exists(directory))
{
Console.WriteLine("Creating Directory: {0}", directory);
Directory.CreateDirectory(directory);
}
using (var writer = new StringWriter())
{
writer.WriteLine("<html>");
writer.WriteLine("<head>");
writer.WriteLine("<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"/>");
writer.WriteLine("<meta name=\"guide-name\" content=\"Cmdlet Reference\"/>");
writer.WriteLine("<meta name=\"service-name\" content=\"AWS Tools for PowerShell\"/>");
writer.WriteLine("<link rel=\"stylesheet\" type=\"text/css\" href=\"{0}/resources/style.css\"/>", RelativePathToRoot);
writer.WriteLine("<link rel=\"stylesheet\" type=\"text/css\" href=\"{0}/resources/syntaxhighlighter/shCore.css\">", RelativePathToRoot);
writer.WriteLine("<link rel=\"stylesheet\" type=\"text/css\" href=\"{0}/resources/syntaxhighlighter/shThemeDefault.css\">", RelativePathToRoot);
writer.WriteLine("<link rel=\"stylesheet\" type=\"text/css\" href=\"{0}/resources/psstyle.css\"/>", RelativePathToRoot);
// every page needs a replacedle, meta description and canonical url to satisfy indexing
writer.WriteLine("<meta name=\"description\" content=\"{0}\">", GetMetaDescription());
writer.WriteLine("<replacedle>{0} | AWS Tools for PowerShell</replacedle>", Getreplacedle());
writer.WriteLine("<script type=\"text/javascript\" src=\"/replacedets/js/awsdocs-boot.js\"></script>");
writer.WriteLine("<link rel=\"canonical\" href=\"http://docs.aws.amazon.com/powershell/latest/reference/index.html?page={0}&tocid={1}\"/>",
this.GenerateFilename(),
this.GetTOCID());
writer.WriteLine("</head>");
writer.WriteLine("<body>");
// every page needs two hidden divs giving the search indexer the product replacedle and guide name
writer.WriteLine("<div id=\"product_name\">AWS Tools for Windows PowerShell</div>");
writer.WriteLine("<div id=\"guide_name\">Command Reference</div>");
this.WriteRegionDisclaimer(writer);
this.WriteHeader(writer);
this.WriteToolbar(writer);
writer.WriteLine("<div id=\"pageContent\">");
this.WriteContent(writer);
writer.WriteLine("</div>");
this.WriteFooter(writer);
writer.WriteLine("</body>");
writer.WriteLine("</html>");
var content = writer.ToString();
using (var fileWriter = new StreamWriter(filename))
{
fileWriter.Write(content);
}
}
}
See More Examples