Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have an application that writes all sorts of status update and times to the console. I also have an email function that emails to clients. I would like at the end of the application send an email with all lines from the console (same application).
There does not seem to be a function Console.ReadAllLines.
I saw some ideas with GetStdHandle but could get it to work.
Any ideas how I could do this in c# pls?
You can do this by implementing your own TextWriter and Console.SetOut
public class MyWriter : TextWriter
{
private List<string> lines = new List<string>();
private TextWriter original;
public MyWriter(TextWriter original)
{
this.original = original;
}
public override Encoding Encoding
{
get { return Encoding.Default; }
}
public override void WriteLine(string value)
{
lines.Add(value);
original.WriteLine(value);
}
//You need to override other methods also
public string[] GetLines()
{
return lines.ToArray();
}
}
And use it like this
var writer = new MyWriter(Console.Out);
Console.SetOut(writer);
Console.WriteLine("Hello world");
Console.WriteLine("Bye!");
var lines = writer.GetLines();
Reading information back that's already been output to the console is a backwards design. Instead, store the information away in a DB/File/Memory so it can be re-used. continue to display the output as you do. However, when you need to send an email dig the info out of the DB/File/Memory.
It could be done like:
List<string> outputList = new List<string>();
string output = GetOutput();//Run continuously...perhaps in a loop or event trigger..whatever applies
outputList.Add(output);
Console.Writeline(output);
//when ready
SendEmail(outputList);
You could write a wrapper class to take care of it easily.
public class ConsoleWriter()
{
public static List<string> AllLines = new List<string>();
public static WriteConsole(string text)
{
AllLines.Add(text);
Console.Write(text);
}
}
Then read AllLines when you want to send the mail.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 hours ago.
Improve this question
Enter a string of characters S. Indicates whether the string S is cyclic or not.
For example S='abcdabcdabcdabcd' is cyclic.
My teacher want me to do this but i think it's too hard. I'm thinking using SplitString but it's just an idea and i dont know how to do. I'm very thankful if someone gives me help
using System;
using System.Collections;
public class MYCLASSNAME {
public static void Main(string[] args){
var str = "abcdabcdabcdabcd";
Console.Write(checkCyclicString(str));
}
static bool checkCyclicString (string str){
var checkString ="";
for(var i=0;i<str.Length-1;i++){
checkString= checkString+ str[i];
var countOfCycles =0;
var haveCycles = false;
for(var j=i+1;j<str.Length-checkString.Length+1;j= j+checkString.Length){
if(checkString==str.Substring(j,checkString.Length)){
haveCycles = true;
countOfCycles++;
}else{
haveCycles =false;
}
}
if(haveCycles && countOfCycles == Math.Ceiling((double)(str.Length/checkString.Length))-1){
return true;
}
}
return false;
}
}
check the cyclic behavior by creating substrigs and comparing them with all the parts of the given string
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I am able to convert my nested dictionary to json but in attempting to use Json.Net.JsonNet.Deserialize<SortedDictionary<string, dynamic>>(js) it causes a null reference exception where js is loaded from a file containing: "{"Table":{"RowEntries":{}}}". Not sure what to do from here.
here is code to those it may concern:
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
if (openFileDialog1.FileName != "" && openFileDialog1.FileName.EndsWith(".fdb"))
{
defaultPath = openFileDialog1.FileName;
js = #File.ReadAllText(openFileDialog1.FileName);
Console.WriteLine(js);
SortedDictionary<string, dynamic> cd;
try
{
cd = Json.Net.JsonNet.Deserialize<SortedDictionary<string, dynamic>>(js);
DatabaseFunct.currentData.Concat(cd);
//load tables
string[] mainTableKeys = DatabaseFunct.GetMainTableKeys();
foreach (string mainTableKey in mainTableKeys)
{
Program.mainForm.tabControl1.TabPages.Add(mainTableKey, mainTableKey);
}
//fileName = openFileDialog1.FileName.Remove(openFileDialog1.FileName.Length-4, openFileDialog1.FileName.Length);
Program.mainForm.label1.Visible = false;
//triggers event
Program.mainForm.tabControl1.SelectedIndex = 0;
}
catch(Exception e)
{
System.Windows.Forms.MessageBox.Show(e.Message);
}
}
else
{
System.Windows.Forms.MessageBox.Show("no valid file selected!");
}
}
Edit:
Was using the wrong Json.net package instead of the newtonsoft one.
Not sure what you are trying to achieve exactly, but based on provided json this should work:
class MyClass
{
public dynamic RowEntries { get; set; }
}
JsonNet.Deserialize<Dictionary<string, MyClass>>("{\"Table\":{\"RowEntries\":{}}}")
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I want to create a new database using c#. I just want to pass database name from user interface and for that database name i want to run a sql script of database for creating the same schema of that script for new database.
I do not have exactly whay you intend to do, but I have done some functionality to seed some default data to the master tables.
//sql file location
private static readonly string IndexScriptSeedMasterDataLocation = "SqlSeedMasterData.sql";
In the function I have :
private static void SeedMasterData ( IpDataContext context, string databaseName)
{
context.Database.CreateIfNotExists();
var sqlContent = Content(IndexScriptSeedMasterDataLocation);
var modifiedSqlScript = sqlContent.Replace("#DatabaseName", databaseName);
context.Database.ExecuteSqlCommand(modifiedSqlScript);
}
// Content function :
private static string Content(string fileLocation)
{
using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(fileLocation))
{
if (stream == null)
{
return string.Empty;
}
var streamReader = new StreamReader(stream);
return streamReader.ReadToEnd();
}
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have implemented a method that requires 2 parameters (arguments) : the first one is the source of the xml file ( type string) and the second one is the destination path of the generated pdf file (type string)
This application will be used by another application that will assign automatically the 2 parameters.
My question is how should I declare the 2 arguments until I can assign external parameters?
in other meaning : I implemented a console appication . When calling it from cmd , it looks like that : C:> name_of_apllication "path1" "path2". How should I implement the parameters if the called method until they will replaced by "path1" and "path2"?
this is the code of the main class : the method that will be used is : GeneratePDF_CTAF
static void Main(string[] args)
{
string input = "";
string output = "";
GeneratePDF.GeneratePDF_Ctaf( ref input, ref output );
}
this is the error screen , it is in french and that means can not find file
The command line arguments are passed to the Main method as an array of strings. This is the args parameter in your code, so you can simply extract the parameters you need from there:
static int Main(string[] args)
{
if (args.Length != 2)
{
Console.Error.WriteLine("This program requires exactly 2 parameters");
return 1; // error code
}
string input = args[0];
string output = args[1];
GeneratePDF.GeneratePDF_Ctaf(input, output);
return 0; // no error
}
Note here, I've modified Main to return an int. A non-zero return value is often used in console applications to provide error information to the calling program. I've also removed the ref keyword from your parameters because it's almost never necessary to use ref parameters in .NET.
I think there is something fundamental about using a function that you are not understanding so I will give a short example -- if it does not solve your problem please explain why not:
void Main(string[] args)
{
aFunction(args[1], args[2]);
}
void aFunction(string arg1, string arg2)
{
Console.WriteLine(arg1);
Console.WriteLine(arg2);
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
I am using ASP.Net web api for my service, that is called from a third party application. When I test it in chrome postman it works fine in localhost and deployed server, but I have tried it in fiddler, hurl it and the string val is always null, should I be adding something else? I cant understand why it works fine in postman! Going kinda crazy with this one !
Thanks in advance
public bool PostProperty([FromBody] string val)
{
try
{
var reader = new StringReader(val);
var serializer = new XmlSerializer(typeof(property));
var instance = (property)serializer.Deserialize(reader);
}
}
Change your signature to be
public async Task<bool> PostProperty()
{
try
{
var reader = new StringReader(await Request.Content.ReadAsStringAsync());
var serializer = new XmlSerializer(typeof(property));
var instance = (property)serializer.Deserialize(reader);
}
}
or
public bool PostProperty([FromBody] property val)
{
}
If you do the second option, you might have to add the following line to your setup,
config.Formatters.XmlFormatter.UseXmlSerializer = true;