Here are the examples of the csharp api System.IO.StringWriter.ToString() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
2451 Examples
19
Source : Utils.cs
with GNU General Public License v3.0
from aloopkin
with GNU General Public License v3.0
from aloopkin
public static string GenerateRSAKeyAsPEM(int keySize)
{
try
{
IAsymmetricCipherKeyPairGenerator generator = GeneratorUtilities.GetKeyPairGenerator("RSA");
RsaKeyGenerationParameters generatorParams = new RsaKeyGenerationParameters(
BigInteger.ValueOf(0x10001), new SecureRandom(), keySize, 12);
generator.Init(generatorParams);
AsymmetricCipherKeyPair keyPair = generator.GenerateKeyPair();
using (StringWriter sw = new StringWriter())
{
PemWriter pemWriter = new PemWriter(sw);
pemWriter.WriteObject(keyPair);
return sw.ToString();
}
}
catch (Exception e)
{
logger.Error($"Could not generate new key pair: {e.Message}");
return null;
}
}
19
Source : NabovarselEndToEnd.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn
with BSD 3-Clause "New" or "Revised" License
from Altinn
[Fact]
public async void NaboVarselEndToEndTest()
{
/* SETUP */
string instanceOwnerPartyId = "1337";
Instance instanceTemplate = new Instance()
{
InstanceOwner = new InstanceOwner
{
PartyId = instanceOwnerPartyId,
}
};
SvarPaaNabovarselType svar = new SvarPaaNabovarselType();
svar.ansvarligSoeker = new PartType();
svar.ansvarligSoeker.mobilnummer = "90912345";
svar.eiendomByggested = new EiendomListe();
svar.eiendomByggested.eiendom = new List<EiendomType>();
svar.eiendomByggested.eiendom.Add(new EiendomType() { adresse = new EiendommensAdresseType() { postnr = "8450" }, kommunenavn = "Hadsel" });
string xml = string.Empty;
using (var stringwriter = new System.IO.StringWriter())
{
XmlSerializer serializer = new XmlSerializer(typeof(SvarPaaNabovarselType));
serializer.Serialize(stringwriter, svar);
xml = stringwriter.ToString();
}
#region Org instansiates form with message
string instancereplacedtring = JsonConvert.SerializeObject(instanceTemplate);
string xmlmelding = File.ReadAllText("Data/Files/melding.xml");
string boundary = "abcdefgh";
MultipartFormDataContent formData = new MultipartFormDataContent(boundary)
{
{ new StringContent(instancereplacedtring, Encoding.UTF8, "application/json"), "instance" },
{ new StringContent(xml, Encoding.UTF8, "application/xml"), "skjema" },
{ new StringContent(xmlmelding, Encoding.UTF8, "application/xml"), "melding" }
};
Uri uri = new Uri("/dibk/nabovarsel/instances", UriKind.Relative);
/* TEST */
HttpClient client = SetupUtil.GetTestClient(_factory, "dibk", "nabovarsel");
string token = PrincipalUtil.GetOrgToken("dibk");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
HttpResponseMessage response = await client.PostAsync(uri, formData);
response.EnsureSuccessStatusCode();
replacedert.True(response.StatusCode == HttpStatusCode.Created);
Instance createdInstance = JsonConvert.DeserializeObject<Instance>(await response.Content.ReadreplacedtringAsync());
replacedert.NotNull(createdInstance);
replacedert.Equal(2, createdInstance.Data.Count);
#endregion
#region end user gets instance
// Reset token and client to end user
client = SetupUtil.GetTestClient(_factory, "dibk", "nabovarsel");
token = PrincipalUtil.GetToken(1337);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
string instancePath = "/dibk/nabovarsel/instances/" + createdInstance.Id;
HttpRequestMessage httpRequestMessage =
new HttpRequestMessage(HttpMethod.Get, instancePath);
response = await client.SendAsync(httpRequestMessage);
string responseContent = await response.Content.ReadreplacedtringAsync();
Instance instance = (Instance)JsonConvert.DeserializeObject(responseContent, typeof(Instance));
replacedert.Equal(HttpStatusCode.OK, response.StatusCode);
replacedert.Equal("1337", instance.InstanceOwner.PartyId);
replacedert.Equal("Task_1", instance.Process.CurrentTask.ElementId);
replacedert.Equal(2, instance.Data.Count);
#endregion
#region end user gets application metadata
httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, "/dibk/nabovarsel/api/v1/applicationmetadata");
response = await client.SendAsync(httpRequestMessage);
responseContent = await response.Content.ReadreplacedtringAsync();
Application application = (Application)JsonConvert.DeserializeObject(responseContent, typeof(Application));
replacedert.Equal(HttpStatusCode.OK, response.StatusCode);
#endregion
#region Get Message DataElement
// In this application the message element is connected to Task_1. Find the datatype for this task and retrive this from storage
DataType dataType = application.DataTypes.FirstOrDefault(r => r.TaskId != null && r.TaskId.Equals(instance.Process.CurrentTask.ElementId));
DataElement dataElementMessage = instance.Data.FirstOrDefault(r => r.DataType.Equals(dataType.Id));
httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, instancePath + "/data/" + dataElementMessage.Id);
response = await client.SendAsync(httpRequestMessage);
responseContent = await response.Content.ReadreplacedtringAsync();
Melding melding = (Melding)JsonConvert.DeserializeObject(responseContent, typeof(Melding));
replacedert.Equal(HttpStatusCode.OK, response.StatusCode);
replacedert.Equal("Informasjon om tiltak", melding.Messagereplacedle);
#endregion
#region Get Status
httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, $"{instancePath}/process");
response = await client.SendAsync(httpRequestMessage);
responseContent = await response.Content.ReadreplacedtringAsync();
ProcessState processState = (ProcessState)JsonConvert.DeserializeObject(responseContent, typeof(ProcessState));
replacedert.Equal("Task_1", processState.CurrentTask.ElementId);
#endregion
#region Validate instance (the message element)
httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, $"{instancePath}/validate");
response = await client.SendAsync(httpRequestMessage);
responseContent = await response.Content.ReadreplacedtringAsync();
List<ValidationIssue> messages = (List<ValidationIssue>)JsonConvert.DeserializeObject(responseContent, typeof(List<ValidationIssue>));
replacedert.Empty(messages);
#endregion
// TODO. Add verification of not able to update message and check that statues is updated
#region push to next step
httpRequestMessage = new HttpRequestMessage(HttpMethod.Put, $"{instancePath}/process/next");
response = await client.SendAsync(httpRequestMessage);
responseContent = await response.Content.ReadreplacedtringAsync();
replacedert.Equal(HttpStatusCode.OK, response.StatusCode);
#endregion
#region Get Status after next
httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, $"{instancePath}/process");
response = await client.SendAsync(httpRequestMessage);
responseContent = await response.Content.ReadreplacedtringAsync();
processState = (ProcessState)JsonConvert.DeserializeObject(responseContent, typeof(ProcessState));
replacedert.Equal("Task_2", processState.CurrentTask.ElementId);
#endregion
#region GetUpdated instance to check pdf
httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, instancePath);
response = await client.SendAsync(httpRequestMessage);
responseContent = await response.Content.ReadreplacedtringAsync();
instance = (Instance)JsonConvert.DeserializeObject(responseContent, typeof(Instance));
IEnumerable<DataElement> lockedDataElements = instance.Data.Where(r => r.Locked == true);
replacedert.Single(lockedDataElements);
#endregion
#region Get Form DataElement
dataType = application.DataTypes.FirstOrDefault(r => r.TaskId != null && r.TaskId.Equals(processState.CurrentTask.ElementId));
DataElement dataElementForm = instance.Data.FirstOrDefault(r => r.DataType.Equals(dataType.Id));
httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, instancePath + "/data/" + dataElementForm.Id);
response = await client.SendAsync(httpRequestMessage);
responseContent = await response.Content.ReadreplacedtringAsync();
SvarPaaNabovarselType skjema = (SvarPaaNabovarselType)JsonConvert.DeserializeObject(responseContent, typeof(SvarPaaNabovarselType));
replacedert.Equal(HttpStatusCode.OK, response.StatusCode);
#endregion
#region Update Form DataElement
string requestJson = JsonConvert.SerializeObject(skjema);
StringContent httpContent = new StringContent(requestJson, Encoding.UTF8, "application/json");
httpRequestMessage = new HttpRequestMessage(HttpMethod.Put, instancePath + "/data/" + dataElementForm.Id)
{
Content = httpContent
};
response = await client.SendAsync(httpRequestMessage);
responseContent = await response.Content.ReadreplacedtringAsync();
replacedert.Equal(HttpStatusCode.Created, response.StatusCode);
#endregion
#region push to next step
httpRequestMessage = new HttpRequestMessage(HttpMethod.Put, $"{instancePath}/process/next");
response = await client.SendAsync(httpRequestMessage);
responseContent = await response.Content.ReadreplacedtringAsync();
// Expect conflict since the form contains validation errors that needs to be resolved before moving to next task in process.
replacedert.Equal(HttpStatusCode.Conflict, response.StatusCode);
#endregion
#region Validate data in Task_2 (the form)
httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, $"{instancePath}/validate");
response = await client.SendAsync(httpRequestMessage);
responseContent = await response.Content.ReadreplacedtringAsync();
messages = (List<ValidationIssue>)JsonConvert.DeserializeObject(responseContent, typeof(List<ValidationIssue>));
replacedert.Single(messages);
#endregion
#region Update Form DataElement with missing value
skjema.nabo = new NaboGjenboerType();
skjema.nabo.epost = "[email protected]";
requestJson = JsonConvert.SerializeObject(skjema);
httpContent = new StringContent(requestJson, Encoding.UTF8, "application/json");
httpRequestMessage = new HttpRequestMessage(HttpMethod.Put, instancePath + "/data/" + dataElementForm.Id)
{
Content = httpContent
};
response = await client.SendAsync(httpRequestMessage);
responseContent = await response.Content.ReadreplacedtringAsync();
replacedert.Equal(HttpStatusCode.Created, response.StatusCode);
#endregion
#region push to confirm task
httpRequestMessage = new HttpRequestMessage(HttpMethod.Put, $"{instancePath}/process/next");
response = await client.SendAsync(httpRequestMessage);
responseContent = await response.Content.ReadreplacedtringAsync();
replacedert.Equal(HttpStatusCode.OK, response.StatusCode);
#endregion
#region Get Status after next
httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, $"{instancePath}/process");
response = await client.SendAsync(httpRequestMessage);
responseContent = await response.Content.ReadreplacedtringAsync();
processState = (ProcessState)JsonConvert.DeserializeObject(responseContent, typeof(ProcessState));
replacedert.Equal(HttpStatusCode.OK, response.StatusCode);
replacedert.Equal("Task_3", processState.CurrentTask.ElementId);
#endregion
#region push to end step
httpRequestMessage = new HttpRequestMessage(HttpMethod.Put, $"{instancePath}/process/next");
response = await client.SendAsync(httpRequestMessage);
responseContent = await response.Content.ReadreplacedtringAsync();
replacedert.Equal(HttpStatusCode.OK, response.StatusCode);
#endregion
#region Get Status after next
httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, $"{instancePath}/process");
response = await client.SendAsync(httpRequestMessage);
responseContent = await response.Content.ReadreplacedtringAsync();
processState = (ProcessState)JsonConvert.DeserializeObject(responseContent, typeof(ProcessState));
replacedert.Equal(HttpStatusCode.OK, response.StatusCode);
replacedert.Null(processState.CurrentTask);
replacedert.Equal("EndEvent_1", processState.EndEvent);
#endregion
TestDataUtil.DeleteInstanceAndData("dibk", "nabovarsel", 1337, new Guid(createdInstance.Id.Split('/')[1]));
}
19
Source : NsmKlareringsportalenEndToEndTests.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn
with BSD 3-Clause "New" or "Revised" License
from Altinn
[Fact]
public async void NsmKlareringsportalenEndToEndTest()
{
/* SETUP */
string instanceOwnerPartyId = "1337";
Instance instanceTemplate = new Instance()
{
InstanceOwner = new InstanceOwner
{
PartyId = instanceOwnerPartyId,
}
};
ePOB_M svar = new ePOB_M();
svar.DeusRequest = new Deusrequest();
svar.DeusRequest.clearauthority = "Sivil";
svar.DeusRequest.nationallevel = "1";
string xml = string.Empty;
using (var stringwriter = new System.IO.StringWriter())
{
XmlSerializer serializer = new XmlSerializer(typeof(ePOB_M));
serializer.Serialize(stringwriter, svar);
xml = stringwriter.ToString();
}
#region Org instansiates form with message
string instancereplacedtring = JsonConvert.SerializeObject(instanceTemplate);
string boundary = "abcdefgh";
MultipartFormDataContent formData = new MultipartFormDataContent(boundary)
{
{ new StringContent(instancereplacedtring, Encoding.UTF8, "application/json"), "instance" },
{ new StringContent(xml, Encoding.UTF8, "application/xml"), "epob" },
};
Uri uri = new Uri("/nsm/klareringsportalen/instances", UriKind.Relative);
/* TEST */
HttpClient client = SetupUtil.GetTestClient(_factory, "nsm", "klareringsportalen");
string token = PrincipalUtil.GetOrgToken("nsm");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
HttpResponseMessage response = await client.PostAsync(uri, formData);
string responsestring = await response.Content.ReadreplacedtringAsync();
response.EnsureSuccessStatusCode();
replacedert.True(response.StatusCode == HttpStatusCode.Created);
Instance createdInstance = JsonConvert.DeserializeObject<Instance>(await response.Content.ReadreplacedtringAsync());
replacedert.NotNull(createdInstance);
replacedert.Single(createdInstance.Data);
#endregion
#region end user gets instance
// Reset token and client to end user
client = SetupUtil.GetTestClient(_factory, "nsm", "klareringsportalen");
token = PrincipalUtil.GetToken(1337, 4);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
string instancePath = "/nsm/klareringsportalen/instances/" + createdInstance.Id;
HttpRequestMessage httpRequestMessage =
new HttpRequestMessage(HttpMethod.Get, instancePath);
response = await client.SendAsync(httpRequestMessage);
string responseContent = await response.Content.ReadreplacedtringAsync();
Instance instance = (Instance)JsonConvert.DeserializeObject(responseContent, typeof(Instance));
replacedert.Equal(HttpStatusCode.OK, response.StatusCode);
replacedert.Equal("1337", instance.InstanceOwner.PartyId);
replacedert.Equal("Task_1", instance.Process.CurrentTask.ElementId);
replacedert.Single(instance.Data);
#endregion
TestDataUtil.DeleteInstanceAndData("nsm", "klareringsportalen", 1337, new Guid(createdInstance.Id.Split('/')[1]));
}
19
Source : ModelSerializationDeserializationTests.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn
with BSD 3-Clause "New" or "Revised" License
from Altinn
private static string SerializeToXml(_TestData.Model.CSharp.melding melding)
{
var xmlSerializer = new System.Xml.Serialization.XmlSerializer(typeof(_TestData.Model.CSharp.melding));
var xmlWriter = new Utf8StringWriter();
xmlSerializer.Serialize(xmlWriter, melding);
return xmlWriter.ToString();
}
19
Source : ShaderGenerator.cs
with MIT License
from Aminator
with MIT License
from Aminator
public ShaderGeneratorResult GenerateShader()
{
if (result != null) return result;
CollectStructure(shaderType, shader);
WriteTopLevelStructure();
result = new ShaderGeneratorResult(stringWriter.ToString());
GetEntryPoints(result, shaderType, GetBindingFlagsForType(shaderType));
ShaderAttribute? shaderAttribute = EntryPointAttributes.OfType<ShaderAttribute>().FirstOrDefault();
if (shaderAttribute != null && action != null && !action.Method.IsDefined(typeof(ShaderMemberAttribute)))
{
result.EntryPoints[shaderAttribute.Name] = AnonymousMethodEntryPointName;
}
return result;
}
19
Source : CodeGenerator.cs
with MIT License
from Aminator
with MIT License
from Aminator
private string CodeGenClreplaced(string fileName, out string sourceCodeFileName)
{
var schemaFile = RawClreplaced(fileName, out string clreplacedName);
using CSharpCodeProvider csharpcodeprovider = new CSharpCodeProvider();
sourceCodeFileName = clreplacedName + "." + csharpcodeprovider.FileExtension;
StringWriter stringWriter = new StringWriter();
IndentedTextWriter textWriter = new IndentedTextWriter(stringWriter, " ");
csharpcodeprovider.GenerateCodeFromCompileUnit(schemaFile, textWriter, new CodeGeneratorOptions { BracingStyle = "C", IndentString = " " });
return stringWriter.ToString();
}
19
Source : AnalogySink.cs
with MIT License
from Analogy-LogViewer
with MIT License
from Analogy-LogViewer
public void Emit(LogEvent logEvent)
{
if (logEvent == null)
{
throw new ArgumentNullException(nameof(logEvent));
}
var sr = new StringWriter();
_textFormatter.Format(logEvent, sr);
output = sr.ToString().Trim();
}
19
Source : _term.cs
with MIT License
from ancientproject
with MIT License
from ancientproject
private static void _error<T>(ErrorToken<T> token, string source)
{
var col = token.ErrorResult.Remainder.Column;
var lin = token.ErrorResult.Remainder.Line;
var exp = token.ErrorResult.Expectations.First();
var rem = token.ErrorResult.Remainder.Current;
var nestedLine = source.Split('\n')[lin-1];
var replaced = getFromMiddle(nestedLine, col, nestedLine.Length - col, true);
var startOffset = source.IndexOf(nestedLine, StringComparison.InvariantCultureIgnoreCase);
var nameOffset = (startOffset + col - 1);
var doc2 = new StringDoreplacedent("", source);
var highlightRegion = new SourceRegion(new SourceSpan(doc2, startOffset, nestedLine.Length));
var focusRegion = new SourceRegion(
new SourceSpan(doc2, nameOffset, replaced.Length));
var replacedle = $"{token.ErrorResult.getWarningCode().To<string>().Pastel(Color.Orange)}";
var message = $"character '{exp}' expected".Pastel(Color.Orange);
string Render(MarkupNode node, params NodeRenderer[] extraRenderers)
{
var writer = new StringWriter();
var terminal = new TextWriterTerminal(writer, 160, Encoding.ASCII);
var log = new TerminalLog(terminal).WithRenderers(extraRenderers);
log.Log(node);
return writer.ToString();
}
var result = Render(
new HighlightedSource(highlightRegion, focusRegion),
new HighlightedSourceRenderer(3, Colors.Red));
WriteLine($" :: {replacedle} - {message}");
var ses = result.Split('\n');
var flag1 = false;
foreach (var (value, index) in ses.Select((value, index) => (value, index)))
{
var next = ses.Select((value, index) => new {value, index}).FirstOrDefault(x => x.index == index + 1);
if (next != null && (next.value.Contains('~') && next.value.Contains('^')) && !flag1)
WriteLine(value.Replace(replaced, replaced.Pastel(Color.Red)));
else if (value.Contains('~') && value.Contains('^'))
{
if (flag1)
continue;
WriteLine(value.Pastel(Color.Red));
flag1 = true;
}
else
WriteLine($"{value} ");
}
}
19
Source : JsonSerializer.cs
with Apache License 2.0
from AndcultureCode
with Apache License 2.0
from AndcultureCode
public string Serialize(object obj)
{
using (var stringWriter = new StringWriter())
{
using (var jsonTextWriter = new JsonTextWriter(stringWriter))
{
jsonTextWriter.Formatting = Formatting.Indented;
jsonTextWriter.QuoteChar = '"';
_serializer.Serialize(jsonTextWriter, obj);
var result = stringWriter.ToString();
return result;
}
}
}
19
Source : RoomMeshExporter.cs
with MIT License
from anderm
with MIT License
from anderm
private static string SerializeMeshes(IEnumerable<Mesh> meshes)
{
StringWriter stream = new StringWriter();
int offset = 0;
foreach (var mesh in meshes)
{
SerializeMesh(mesh, stream, ref offset);
}
return stream.ToString();
}
19
Source : RoomMeshExporter.cs
with MIT License
from anderm
with MIT License
from anderm
private static string SerializeMeshFilters(IEnumerable<MeshFilter> meshes)
{
StringWriter stream = new StringWriter();
int offset = 0;
foreach (var mesh in meshes)
{
SerializeMeshFilter(mesh, stream, ref offset);
}
return stream.ToString();
}
19
Source : RazorTemplateCompiler.cs
with MIT License
from andyalm
with MIT License
from andyalm
private replacedembly CompileCompilation(CSharpCompilation compilation)
{
using (var ms = new MemoryStream())
using (var eventContext = new EventContext("ConsulRx", "CompileRazorTemplates"))
{
EmitResult result = compilation.Emit(ms);
if (!result.Success)
{
eventContext.SetLevel(Level.Error);
var failures = result.Diagnostics.Where(diagnostic =>
diagnostic.IsWarningAsError ||
diagnostic.Severity == DiagnosticSeverity.Error).ToArray();
var errorWriter = new StringWriter();
foreach (var diagnostic in failures)
{
errorWriter.WriteLine($"{diagnostic.Id}: {diagnostic.GetMessage()}");
errorWriter.WriteLine(diagnostic.Location.SourceTree);
}
eventContext["Diagnostics"] = errorWriter.ToString();
throw new TemplateCompilationException(failures);
}
else
{
ms.Seek(0, SeekOrigin.Begin);
return replacedemblyLoadContext.Default.LoadFromStream(ms);
}
}
}
19
Source : CsvOutputFormatter.cs
with GNU General Public License v3.0
from andysal
with GNU General Public License v3.0
from andysal
private void writeStream(Type type, object value, Stream stream)
{
Type itemType = type.GetGenericArguments()[0];
StringWriter _stringWriter = new StringWriter();
_stringWriter.WriteLine(
string.Join<string>(
";", itemType.GetProperties().Select(x => x.Name)
)
);
foreach (var obj in (IEnumerable<object>)value)
{
var vals = obj.GetType().GetProperties().Select(
pi => new {
Value = pi.GetValue(obj, null)
}
);
string _valueLine = string.Empty;
foreach (var val in vals)
{
if (val.Value != null)
{
var _val = val.Value.ToString();
//Check if the value contans a comma and place it in quotes if so
if (_val.Contains(","))
_val = string.Concat("\"", _val, "\"");
//Replace any \r or \n special characters from a new line with a space
if (_val.Contains("\r"))
_val = _val.Replace("\r", " ");
if (_val.Contains("\n"))
_val = _val.Replace("\n", " ");
_valueLine = string.Concat(_valueLine, _val, ";");
}
else
{
_valueLine = string.Concat(string.Empty, ";");
}
}
_stringWriter.WriteLine(_valueLine.TrimEnd(';'));
}
var streamWriter = new StreamWriter(stream);
streamWriter.Write(_stringWriter.ToString());
streamWriter.Flush();
}
19
Source : UploadExtensions.cs
with GNU General Public License v3.0
from andysal
with GNU General Public License v3.0
from andysal
private static string GetHtmlFromTagBuilder(TagBuilder tagBuilder)
{
using (var writer = new StringWriter())
{
HtmlEncoder encoder = HtmlEncoder.Default;
tagBuilder.WriteTo(writer, encoder);
var htmlChunk = writer.ToString();
return htmlChunk;
}
}
19
Source : Extensions.cs
with GNU General Public License v3.0
from andysal
with GNU General Public License v3.0
from andysal
public static string ToJsonpString(this JsonSerializer serializer, object data, string callbackName)
{
using(var writer = new StringWriter())
{
serializer.Serialize(writer, data);
var json = writer.ToString();
return $"{callbackName}({json})";
}
}
19
Source : WebRequests.cs
with MIT License
from angelsix
with MIT License
from angelsix
public static async Task<HttpWebResponse> PostAsync(string url, object content = null, KnownContentSerializers sendType = KnownContentSerializers.Json, KnownContentSerializers returnType = KnownContentSerializers.Json, Action<HttpWebRequest> configureRequest = null, string bearerToken = null)
{
#region Setup
// Create the web request
var request = WebRequest.CreateHttp(url);
// Make it a POST request method
request.Method = HttpMethod.Post.ToString();
// Set the appropriate return type
request.Accept = returnType.ToMimeString();
// Set the content type
request.ContentType = sendType.ToMimeString();
// If we have a bearer token...
if (bearerToken != null)
// Add bearer token to header
request.Headers.Add(HttpRequestHeader.Authorization, $"Bearer {bearerToken}");
// Any custom work
configureRequest?.Invoke(request);
#endregion
#region Write Content
// Set the content length
if (content == null)
{
// Set content length to 0
request.ContentLength = 0;
}
// Otherwise...
else
{
// Create content to write
var contentString = string.Empty;
// Serialize to Json?
if (sendType == KnownContentSerializers.Json)
// Serialize content to Json string
contentString = JsonConvert.SerializeObject(content);
// Serialize to Xml?
else if (sendType == KnownContentSerializers.Xml)
{
// Create Xml serializer
var xmlSerializer = new XmlSerializer(content.GetType());
// Create a string writer to receive the serialized string
using (var stringWriter = new StringWriter())
{
// Serialize the object to a string
xmlSerializer.Serialize(stringWriter, content);
// Extract the string from the writer
contentString = stringWriter.ToString();
}
}
// Currently unknown
else
{
// TODO: Throw error once we have Dna Framework exception types
}
//
// NOTE: This GetRequestStreamAsync could throw with a
// SocketException (or an inner exception of SocketException)
//
// However, we cannot return anything useful from this
// so we just let it throw out so the caller can handle
// this (the other PostAsync call for example).
//
// SocketExceptions are a good indication there is no
// Internet, or no connection or firewalls blocking
// communication.
//
// Get body stream...
using (var requestStream = await request.GetRequestStreamAsync())
// Create a stream writer from the body stream...
using (var streamWriter = new StreamWriter(requestStream))
// Write content to HTTP body stream
await streamWriter.WriteAsync(contentString);
}
#endregion
// Wrap call...
try
{
// Return the raw server response
return await request.GetResponseAsync() as HttpWebResponse;
}
// Catch Web Exceptions (which throw for things like 401)
catch (WebException ex)
{
// If we got a response...
if (ex.Response is HttpWebResponse httpResponse)
// Return the response
return httpResponse;
// Otherwise, we don't have any information to be able to return
// So re-throw
throw;
}
}
19
Source : TripleObject.cs
with MIT License
from angshuman
with MIT License
from angshuman
public static string Stringify(JValue jValue)
{
using (var textWriter = new StringWriter()) {
using (var jsonWriter = new JsonTextWriter(textWriter)) {
jValue.WriteTo(jsonWriter);
jsonWriter.Flush();
return textWriter.ToString();
}
}
}
19
Source : NewtonsoftJsonSerializer.cs
with MIT License
from anthturner
with MIT License
from anthturner
public string Serialize(object obj)
{
using (var stringWriter = new StringWriter())
{
using (var jsonTextWriter = new JsonTextWriter(stringWriter))
{
serializer.Serialize(jsonTextWriter, obj);
return stringWriter.ToString();
}
}
}
19
Source : FuzzyLogicInferenceRoles.cs
with MIT License
from antonio-leonardo
with MIT License
from antonio-leonardo
internal static string XmlSerialize<TEnreplacedy>(this TEnreplacedy obj) where TEnreplacedy : clreplaced
{
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
using (StringWriterUtf8 writer = new StringWriterUtf8())
{
XmlSerializer s = new XmlSerializer(typeof(TEnreplacedy));
s.Serialize(writer, obj, ns);
return writer.ToString();
}
}
19
Source : MdDocument.cs
with MIT License
from ap0llo
with MIT License
from ap0llo
public string ToString(MdSerializationOptions? serializationOptions)
{
using (var stringWriter = new StringWriter())
{
Save(stringWriter, serializationOptions);
return stringWriter.ToString();
}
}
19
Source : MdBlock.cs
with MIT License
from ap0llo
with MIT License
from ap0llo
public virtual string ToString(MdSerializationOptions? options)
{
using (var stringWriter = new StringWriter())
{
var doreplacedentSerializer = new DoreplacedentSerializer(stringWriter, options);
Accept(doreplacedentSerializer);
return stringWriter.ToString();
}
}
19
Source : AsciiTreeWriter.cs
with MIT License
from ap0llo
with MIT License
from ap0llo
public override string ToString() => m_Writer.ToString();
19
Source : DocumentSerializerTest.cs
with MIT License
from ap0llo
with MIT License
from ap0llo
private void replacedertToStringEquals(string expected, MdDoreplacedent doreplacedent, MdSerializationOptions? options = null)
{
using (var writer = new StringWriter())
{
var serializer = new DoreplacedentSerializer(writer, options);
serializer.Serialize(doreplacedent);
var actual = writer.ToString();
m_OutputHelper.WriteLine("--------------");
m_OutputHelper.WriteLine("Expected:");
m_OutputHelper.WriteLine("--------------");
m_OutputHelper.WriteLine(expected);
m_OutputHelper.WriteLine("--------------");
m_OutputHelper.WriteLine("Actual:");
m_OutputHelper.WriteLine("--------------");
m_OutputHelper.WriteLine(actual);
m_OutputHelper.WriteLine("--------------");
replacedert.Equal(expected, actual);
}
}
19
Source : MessageBoxAppender.cs
with Apache License 2.0
from apache
with Apache License 2.0
from apache
override protected void Append(LoggingEvent loggingEvent)
{
MessageBoxIcon messageBoxIcon = MessageBoxIcon.Information;
LevelIcon levelIcon = m_levelMapping.Lookup(loggingEvent.Level) as LevelIcon;
if (levelIcon != null)
{
// Prepend the Ansi Color code
messageBoxIcon = levelIcon.Icon;
}
string message = RenderLoggingEvent(loggingEvent);
string replacedle = null;
if (m_replacedleLayout == null)
{
replacedle = "LoggingEvent: "+loggingEvent.Level.Name;
}
else
{
StringWriter replacedleWriter = new StringWriter(System.Globalization.CultureInfo.InvariantCulture);
m_replacedleLayout.Format(replacedleWriter, loggingEvent);
replacedle = replacedleWriter.ToString();
}
MessageBox.Show(message, replacedle, MessageBoxButtons.OK, messageBoxIcon);
}
19
Source : MsmqAppender.cs
with Apache License 2.0
from apache
with Apache License 2.0
from apache
private string RenderLabel(LoggingEvent loggingEvent)
{
if (m_labelLayout == null)
{
return null;
}
System.IO.StringWriter writer = new System.IO.StringWriter();
m_labelLayout.Format(writer, loggingEvent);
return writer.ToString();
}
19
Source : PatternFileAppender.cs
with Apache License 2.0
from apache
with Apache License 2.0
from apache
override protected void Append(LoggingEvent loggingEvent)
{
try
{
// Render the file name
StringWriter stringWriter = new StringWriter();
m_filePattern.Format(stringWriter, loggingEvent);
string fileName = stringWriter.ToString();
fileName = SystemInfo.ConvertToFullPath(fileName);
FileStream fileStream = null;
using(m_securityContext.Impersonate(this))
{
// Ensure that the directory structure exists
string directoryFullName = Path.GetDirectoryName(fileName);
// Only create the directory if it does not exist
// doing this check here resolves some permissions failures
if (!Directory.Exists(directoryFullName))
{
Directory.CreateDirectory(directoryFullName);
}
// Open file stream while impersonating
fileStream = new FileStream(fileName, FileMode.Append, FileAccess.Write, FileShare.Read);
}
if (fileStream != null)
{
using(StreamWriter streamWriter = new StreamWriter(fileStream, m_encoding))
{
RenderLoggingEvent(streamWriter, loggingEvent);
}
fileStream.Close();
}
}
catch(Exception ex)
{
ErrorHandler.Error("Failed to append to file", ex);
}
}
19
Source : SimpleSmtpAppender.cs
with Apache License 2.0
from apache
with Apache License 2.0
from apache
override protected void Append(LoggingEvent loggingEvent)
{
try
{
StringWriter writer = new StringWriter(System.Globalization.CultureInfo.InvariantCulture);
string t = Layout.Header;
if (t != null)
{
writer.Write(t);
}
// Render the event and append the text to the buffer
RenderLoggingEvent(writer, loggingEvent);
t = Layout.Footer;
if (t != null)
{
writer.Write(t);
}
MailMessage mailMessage = new MailMessage();
mailMessage.Body = writer.ToString();
mailMessage.From = m_from;
mailMessage.To = m_to;
if (m_subjectLayout == null)
{
mailMessage.Subject = "Missing Subject Layout";
}
else
{
StringWriter subjectWriter = new StringWriter(System.Globalization.CultureInfo.InvariantCulture);
m_subjectLayout.Format(subjectWriter, loggingEvent);
mailMessage.Subject = subjectWriter.ToString();
}
if (m_smtpHost != null && m_smtpHost.Length > 0)
{
SmtpMail.SmtpServer = m_smtpHost;
}
SmtpMail.Send(mailMessage);
}
catch(Exception e)
{
ErrorHandler.Error("Error occurred while sending e-mail notification.", e);
}
}
19
Source : LineWrappingLayout.cs
with Apache License 2.0
from apache
with Apache License 2.0
from apache
override public void Format(TextWriter writer, LoggingEvent loggingEvent)
{
StringWriter stringWriter = new StringWriter();
base.Format(stringWriter, loggingEvent);
string formattedString = stringWriter.ToString();
WrapText(writer, formattedString);
}
19
Source : RandomStringPatternConverterTest.cs
with Apache License 2.0
from apache
with Apache License 2.0
from apache
[Test]
public void TestConvert()
{
RandomStringPatternConverter converter = new RandomStringPatternConverter();
// Check default string length
StringWriter sw = new StringWriter();
converter.Convert(sw, null);
replacedert.AreEqual(4, sw.ToString().Length, "Default string length should be 4");
// Set string length to 7
converter.Option = "7";
converter.ActivateOptions();
sw = new StringWriter();
converter.Convert(sw, null);
string string1 = sw.ToString();
replacedert.AreEqual(7, string1.Length, "string length should be 7");
// Check for duplicate result
sw = new StringWriter();
converter.Convert(sw, null);
string string2 = sw.ToString();
replacedert.IsTrue(string1 != string2, "strings should be different");
}
19
Source : BulkPayloadTest.cs
with Apache License 2.0
from AppMetrics
with Apache License 2.0
from AppMetrics
[Fact]
public void Can_format_payload_correctly()
{
// Arrange
var textWriter = new StringWriter();
var fields = new Dictionary<string, object> { { "key", "value" } };
var timestamp = new DateTime(2017, 1, 1, 1, 1, 1, DateTimeKind.Utc);
var doreplacedentId = Guid.NewGuid();
var point = new MetricsDoreplacedent
{
MeasurementName = "measurement",
Fields = fields,
WrittenOn = timestamp,
MeasurementType = "counter"
};
// Act
var bulkPayload = new BulkPayload(JsonSerializer.Create(), "index");
bulkPayload.Add(point);
bulkPayload.Write(textWriter, doreplacedentId);
// replacedert
textWriter.ToString().Should().Be("{\"index\":{\"_index\":\"index.counter\",\"_type\":\"counter\",\"_id\":\"" + doreplacedentId.ToString("D") + "\"}}\n{\"name\":\"measurement\",\"fields\":{\"key\":\"value\"},\"tags\":null,\"@timestamp\":\"2017-01-01T01:01:01Z\"}\n");
}
19
Source : BulkPayloadTest.cs
with Apache License 2.0
from AppMetrics
with Apache License 2.0
from AppMetrics
[Fact]
public void Can_format_payload_with_multiple_fields_correctly()
{
// Arrange
var doreplacedentId = Guid.NewGuid();
var textWriter = new StringWriter();
var timestamp = new DateTime(2017, 1, 1, 1, 1, 1, DateTimeKind.Utc);
var fields = new Dictionary<string, object>
{
{ "field1key", "field1value" },
{ "field2key", 2 },
{ "field3key", false }
};
var point = new MetricsDoreplacedent
{
MeasurementName = "measurement",
Fields = fields,
WrittenOn = timestamp,
MeasurementType = "counter"
};
// Act
var bulkPayload = new BulkPayload(JsonSerializer.Create(), "index");
bulkPayload.Add(point);
bulkPayload.Write(textWriter, doreplacedentId);
// replacedert
textWriter.ToString().Should().Be("{\"index\":{\"_index\":\"index.counter\",\"_type\":\"counter\",\"_id\":\"" + doreplacedentId.ToString("D") + "\"}}\n{\"name\":\"measurement\",\"fields\":{\"field1key\":\"field1value\",\"field2key\":2,\"field3key\":false},\"tags\":null,\"@timestamp\":\"2017-01-01T01:01:01Z\"}\n");
}
19
Source : BulkPayloadTest.cs
with Apache License 2.0
from AppMetrics
with Apache License 2.0
from AppMetrics
[Fact]
public void Can_format_payload_with_tags_correctly()
{
// Arrange
var doreplacedentId = Guid.NewGuid();
var textWriter = new StringWriter();
var fields = new Dictionary<string, object> { { "key", "value" } };
var tags = new MetricTags("tagkey", "tagvalue");
var timestamp = new DateTime(2017, 1, 1, 1, 1, 1, DateTimeKind.Utc);
var point = new MetricsDoreplacedent
{
MeasurementName = "measurement",
Fields = fields,
WrittenOn = timestamp,
MeasurementType = "counter",
Tags = tags.ToDictionary()
};
// Act
var bulkPayload = new BulkPayload(JsonSerializer.Create(), "index");
bulkPayload.Add(point);
bulkPayload.Write(textWriter, doreplacedentId);
// replacedert
textWriter.ToString().Should().Be("{\"index\":{\"_index\":\"index.counter\",\"_type\":\"counter\",\"_id\":\"" + doreplacedentId.ToString("D") + "\"}}\n{\"name\":\"measurement\",\"fields\":{\"key\":\"value\"},\"tags\":{\"tagkey\":\"tagvalue\"},\"@timestamp\":\"2017-01-01T01:01:01Z\"}\n");
}
19
Source : HealthStatusTextWriterTests.cs
with Apache License 2.0
from AppMetrics
with Apache License 2.0
from AppMetrics
[Fact]
public async Task Can_apply_ascii_health_formatting()
{
// Arrange
var health = new HealthBuilder()
.OutputHealth.AsPlainText()
.HealthChecks.AddCheck("test", () => new ValueTask<HealthCheckResult>(HealthCheckResult.Healthy()))
.Build();
var serializer = new HealthStatusSerializer();
// Act
var healthStatus = await health.HealthCheckRunner.ReadAsync();
using (var sw = new StringWriter())
{
using (var writer = new HealthStatusTextWriter(sw))
{
serializer.Serialize(writer, healthStatus);
}
// replacedert
sw.ToString().Should().Be(
"# OVERALL STATUS: Healthy\n--------------------------------------------------------------\n# CHECK: test\n\n MESSAGE = OK\n STATUS = Healthy\n--------------------------------------------------------------\n");
}
}
19
Source : MetricSnapshotInfluxDBLineProtocolWriterTests.cs
with Apache License 2.0
from AppMetrics
with Apache License 2.0
from AppMetrics
private void replacedertExpectedLineProtocolString(MetricsDataValueSource dataValueSource, string expected)
{
var settings = new MetricsInfluxDbLineProtocolOptions();
var serializer = new MetricSnapshotSerializer();
var fields = new MetricFields();
using (var sw = new StringWriter())
{
using (var packer = new MetricSnapshotInfluxDbLineProtocolWriter(sw, settings.MetricNameFormatter))
{
serializer.Serialize(packer, dataValueSource, fields);
}
sw.ToString().Should().Be(expected);
}
}
19
Source : LineProtocolPointTests.cs
with Apache License 2.0
from AppMetrics
with Apache License 2.0
from AppMetrics
[Fact]
public void Can_format_payload_correctly()
{
var textWriter = new StringWriter();
var fieldName = "key";
var fieldValue = "value";
var timestamp = new DateTime(2017, 1, 1, 1, 1, 1, DateTimeKind.Utc);
var point = new LineProtocolPointSingleValue("measurement", fieldName, fieldValue, MetricTags.Empty, timestamp);
point.Write(textWriter);
textWriter.ToString().Should().Be("measurement key=\"value\" 1483232461000000000");
}
19
Source : LineProtocolPointTests.cs
with Apache License 2.0
from AppMetrics
with Apache License 2.0
from AppMetrics
[Fact]
public void Can_format_payload_correctly_without_providing_timestamp()
{
var textWriter = new StringWriter();
var fieldName = "key";
var fieldValue = "value";
var point = new LineProtocolPointSingleValue("measurement", fieldName, fieldValue, MetricTags.Empty);
point.Write(textWriter, false);
textWriter.ToString().Should().Be("measurement key=\"value\"");
}
19
Source : LineProtocolPointTests.cs
with Apache License 2.0
from AppMetrics
with Apache License 2.0
from AppMetrics
[Fact]
public void Can_format_payload_with_multiple_fields_correctly()
{
var textWriter = new StringWriter();
var fieldsNames = new[] { "field1key", "field2key", "field3key" };
var fieldsValues = new object[] { "field1value", 2, false };
var timestamp = new DateTime(2017, 1, 1, 1, 1, 1, DateTimeKind.Utc);
var point = new LineProtocolPointMultipleValues("measurement", fieldsNames, fieldsValues, MetricTags.Empty, timestamp);
point.Write(textWriter);
textWriter.ToString().Should().Be("measurement field1key=\"field1value\",field2key=2i,field3key=f 1483232461000000000");
}
19
Source : LineProtocolPointTests.cs
with Apache License 2.0
from AppMetrics
with Apache License 2.0
from AppMetrics
[Fact]
public void Can_format_payload_with_tags_correctly()
{
var textWriter = new StringWriter();
var fieldName = "key";
var fieldValue = "value";
var tags = new MetricTags("tagkey", "tagvalue");
var timestamp = new DateTime(2017, 1, 1, 1, 1, 1, DateTimeKind.Utc);
var point = new LineProtocolPointSingleValue("measurement", fieldName, fieldValue, tags, timestamp);
point.Write(textWriter);
textWriter.ToString().Should().Be("measurement,tagkey=tagvalue key=\"value\" 1483232461000000000");
}
19
Source : TemplateDocument.cs
with MIT License
from aprilyush
with MIT License
from aprilyush
public string GetRenderText()
{
using (StringWriter writer = new StringWriter())
{
this.Render(writer);
return writer.ToString();
}
}
19
Source : Utility.cs
with MIT License
from aprilyush
with MIT License
from aprilyush
public static string XmlEncode(string value)
{
if (!string.IsNullOrEmpty(value))
{
using (StringWriter stringWriter = new StringWriter())
{
using (XmlTextWriter xmlWriter = new XmlTextWriter(stringWriter))
{
xmlWriter.WriteString(value);
xmlWriter.Flush();
value = stringWriter.ToString();
}
}
}
return value;
}
19
Source : Pygmentize.cs
with MIT License
from arbelatech
with MIT License
from arbelatech
public string replacedtring()
{
var tokens = _lexer.GetTokens(_input);
var memoryStream = new StringWriter();
_formatter.Format(tokens, memoryStream);
return memoryStream.ToString();
}
19
Source : JsonBuilder.cs
with MIT License
from armutcom
with MIT License
from armutcom
public static string SerializeObjectToPrettyJson(BaseRequestV2 value)
{
StringBuilder sb = new StringBuilder(256);
StringWriter sw = new StringWriter(sb, CultureInfo.InvariantCulture);
var jsonSerializer = JsonSerializer.CreateDefault();
jsonSerializer.NullValueHandling = NullValueHandling.Ignore;
jsonSerializer.DefaultValueHandling = DefaultValueHandling.Ignore;
jsonSerializer.ContractResolver = new CamelCasePropertyNamesContractResolver();
jsonSerializer.Formatting = Formatting.Indented;
using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)
{
Formatting = Formatting.Indented,
IndentChar = '\t',
Indentation = 1
})
{
jsonSerializer.Serialize(jsonWriter, value, typeof(BaseRequestV2));
}
string json = sw.ToString();
return json.Replace("\r", "");
}
19
Source : Serializer.cs
with GNU General Public License v3.0
from Artentus
with GNU General Public License v3.0
from Artentus
public static string LoadFile(FileInfo file, out AccurateVersion fileVersion, Formatting formatting = Formatting.Indented)
{
using var stream = file.OpenRead();
using var reader = new AccurateBinaryReader(stream);
fileVersion = reader.ReadVersion();
if (!FileVersionSupported(fileVersion)) throw new SerializerException("File version not supported.");
if (fileVersion >= ByteSwitch) reader.ReadByte();
var sb = new StringBuilder();
var sw = new StringWriter(sb);
var writer = new JsonTextWriter(sw) { Formatting = formatting };
try
{
ReadPropertyTree(reader, writer);
return sw.ToString();
}
catch (Exception ex) when (ex is EndOfStreamException || ex is JsonException)
{
throw new SerializerException("Specified file is not a valid settings file.", ex);
}
}
19
Source : ExportableGridView.cs
with MIT License
from aspose-pdf
with MIT License
from aspose-pdf
protected void ExportButton_Click(object sender, EventArgs e)
{
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
if (ExportDataSource != null)
{
this.AllowPaging = false;
this.DataSource = ExportDataSource;
this.DataBind();
}
this.RenderBeginTag(hw);
this.HeaderRow.RenderControl(hw);
foreach (GridViewRow row in this.Rows)
{
row.RenderControl(hw);
}
this.FooterRow.RenderControl(hw);
this.RenderEndTag(hw);
string heading = string.IsNullOrEmpty(ExportFileHeading) ? string.Empty : ExportFileHeading;
string pageSource = "<html><head></head><body>" + heading + sw.ToString() + "</body></html>";
// Check for license and apply if exists
if (File.Exists(LicenseFilePath))
{
License license = new License();
license.SetLicense(LicenseFilePath);
}
string fileName = System.Guid.NewGuid() + ".pdf";
Aspose.Pdf.Doreplacedent pdf;
HtmlLoadOptions htmlLoadOptions = new HtmlLoadOptions();
MemoryStream outputstream = new MemoryStream();
htmlLoadOptions.InputEncoding = "UTF-8";
if (ExportInLandscape)
{
htmlLoadOptions.PageInfo.Width = 800;
htmlLoadOptions.PageInfo.Height = 600;
}
using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(pageSource)))
{
pdf = new Doreplacedent(stream, htmlLoadOptions);
}
if (!string.IsNullOrEmpty(ExportOutputPathOnServer) && Directory.Exists(ExportOutputPathOnServer))
{
try
{
pdf.Save(ExportOutputPathOnServer + "\\" + fileName);
}
catch (Exception) { }
}
pdf.Save(outputstream);
byte[] bytes = outputstream.GetBuffer();
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = "application/pdf";
HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
HttpContext.Current.Response.BinaryWrite(bytes);
HttpContext.Current.Response.End();
}
19
Source : AMLUtils.cs
with MIT License
from AstroTechies
with MIT License
from AstroTechies
public static string SerializeObject<T>(T value)
{
StringBuilder sb = new StringBuilder(256);
StringWriter sw = new StringWriter(sb, CultureInfo.InvariantCulture);
var jsonSerializer = JsonSerializer.CreateDefault();
using (JsonTextWriter jsonWriter = new JsonTextWriter(sw))
{
//jsonWriter.Formatting = Formatting.None;
jsonWriter.Formatting = Formatting.Indented; jsonWriter.IndentChar = ' '; jsonWriter.Indentation = 4;
jsonSerializer.Serialize(jsonWriter, value, typeof(T));
}
return sw.ToString();
}
19
Source : DefaultJsonFormatter.cs
with Apache License 2.0
from asukhodko
with Apache License 2.0
from asukhodko
protected virtual void WriteRenderingsValues(IGrouping<string, PropertyToken>[] tokensWithFormat,
IReadOnlyDictionary<string, LogEventPropertyValue> properties, TextWriter output)
{
var rdelim = "";
foreach (var ptoken in tokensWithFormat)
{
output.Write(rdelim);
rdelim = ",";
output.Write("\"");
output.Write(ptoken.Key);
output.Write("\":[");
var fdelim = "";
foreach (var format in ptoken)
{
output.Write(fdelim);
fdelim = ",";
output.Write("{");
var eldelim = "";
WriteJsonProperty("Format", format.Format, ref eldelim, output);
var sw = new StringWriter();
format.Render(properties, sw);
WriteJsonProperty("Rendering", sw.ToString(), ref eldelim, output);
output.Write("}");
}
output.Write("]");
}
}
19
Source : LogstashHttpSink.cs
with Apache License 2.0
from asukhodko
with Apache License 2.0
from asukhodko
protected override async Task EmitBatchAsync(IEnumerable<LogEvent> events)
{
// ReSharper disable PossibleMultipleEnumeration
if (events == null || !events.Any()) return;
foreach (var e in events)
{
try
{
var sw = new StringWriter();
_state.Formatter.Format(e, sw);
var logData = sw.ToString();
var stringContent = new StringContent(logData);
stringContent.Headers.Remove("Content-Type");
stringContent.Headers.Add("Content-Type", "application/json");
// Using singleton of HttpClient so we need ensure of thread safety. Just use LockAsync.
using (await Mutex.LockAsync().ConfigureAwait(false))
{
await HttpClient.PostAsync(_state.Options.LogstashUri, stringContent).ConfigureAwait(false);
}
}
catch (Exception ex)
{
// Debug me
throw ex;
}
}
}
19
Source : ParameterDirectiveProcessor.cs
with MIT License
from atifaziz
with MIT License
from atifaziz
string StatementsToCode (List<CodeStatement> statements)
{
var options = new CodeGeneratorOptions ();
using (var sw = new StringWriter ()) {
foreach (var statement in statements)
provider.GenerateCodeFromStatement (statement, sw, options);
return sw.ToString ();
}
}
19
Source : GenerateIndentedClassCodeTests.cs
with MIT License
from atifaziz
with MIT License
from atifaziz
static string FixOutput (string output, string newLine = "\n")
{
using (var writer = new StringWriter ()) {
using (var reader = new StringReader (output)) {
string line;
while ((line = reader.ReadLine ()) != null) {
if (!String.IsNullOrWhiteSpace (line)) {
writer.Write (line);
writer.Write (newLine);
}
}
}
return writer.ToString ();
}
}
19
Source : GenerationTests.cs
with MIT License
from atifaziz
with MIT License
from atifaziz
string GenerateCode (ITextTemplatingEngineHost host, string content, string name, string generatorNewline)
{
ParsedTemplate pt = ParsedTemplate.FromText (content, host);
if (pt.Errors.HasErrors) {
host.LogErrors (pt.Errors);
return null;
}
TemplateSettings settings = TemplatingEngine.GetSettings (host, pt);
if (name != null)
settings.Name = name;
if (pt.Errors.HasErrors) {
host.LogErrors (pt.Errors);
return null;
}
var ccu = TemplatingEngine.GenerateCompileUnit (host, content, pt, settings);
if (pt.Errors.HasErrors) {
host.LogErrors (pt.Errors);
return null;
}
var opts = new System.CodeDom.Compiler.CodeGeneratorOptions ();
using (var writer = new System.IO.StringWriter ()) {
writer.NewLine = generatorNewline;
settings.Provider.GenerateCodeFromCompileUnit (ccu, writer, opts);
return writer.ToString ();
}
}
See More Examples