I'm very new to C#
I'm trying to create code that takes input from a user and saves it in an array in the SignUp() method and then if I call the Profile() method it displays the personal information
The error that occurs is when I try and call the Profile() method in the main line it says "There is no argument given that corresponds to the required formal parameter 'privinfo' of Profile(string[])' "
using System;
namespace SDD_Assessment_2
{
class Program
{
static void Main(string[] args)
{
//SignUp();
var privInfo = SignUp();
Profile(privInfo);
}
static string[] SignUp()
{
string[] privinfo = new string[4];
Console.Write("First Name: ");
privinfo[0] = Console.ReadLine();
Console.Write("Last Name: ");
privinfo[1] = Console.ReadLine();
Console.Write("Email: ");
privinfo[2] = Console.ReadLine();
Console.Write("Password: ");
privinfo[3] = Console.ReadLine();
return privinfo;
}
static void Profile(string[] privinfo)
{
Console.WriteLine("Name: " + privinfo[0] + " " + privinfo[1]);
Console.WriteLine("Email: " + privinfo[2]);
Console.WriteLine("Password: " + privinfo[3]);
}
}
}
You're not saving the value returned from SignUp(), so when the method ends, the local data is deleted. You need to catch the value, and pass it to Profile method, which expects an array of strings as an input.
static void Main(string[] args)
{
var privInfo = SignUp();
Profile(privInfo);
...
}
Related
I have an existing .txt file that I would like to use to store my data, but when using this code I get an error at line 39 at switch case 1.
using System;
using System.Collections.Generic;
using System.IO;
class Program
{
public static List<Pw> Site = new List<Pw>();
static void Main(string[] args)
{
string file = #"C: \Users\james\Documents\DataFolder\Vault.txt";
string command = "";
while (command != "exit")
{
Console.Clear();
Console.WriteLine("Please enter a command: ");
command = Console.ReadLine().ToLower();
switch (command)
{
case "1":
AddPw();
File.AppendAllLines(file, Pw.Site);
break;
case "2":
if (File.Exists(file))
{
// Read all the content in one string
// and display the string
string str = File.ReadAllText(file);
Console.WriteLine(str);
}
break;
}
}
}
private static void AddPw()
{
Pw pw = new Pw();
Console.Write("Enter the Username/Email: ");
pw.Username = Console.ReadLine();
Console.Write("Enter Full Name: ");
pw.FullName = Console.ReadLine();
Console.Write("Enter Phone Number: ");
pw.PhoneNumber = Console.ReadLine();
Console.Write("Enter Your Password: ");
string password = Console.ReadLine();
pw.Password = password;
Site.Add(pw);
}
private static void PrintPw(Pw pw)
{
Console.WriteLine("Username/Email: " + pw.Username);
Console.WriteLine("Full Name: " + pw.FullName);
Console.WriteLine("Phone Number: " + pw.PhoneNumber);
Console.WriteLine("Password: " + pw.Password[0]);
Console.WriteLine("-------------------------------------------");
}
private static void ListPw()
{
if (Site.Count == 0)
{
Console.WriteLine("Your address book is empty. Press any key to continue.");
Console.ReadKey();
return;
}
Console.WriteLine("Here are the current people in your address book:\n");
foreach (var pw in Site)
{
PrintPw(pw);
}
Console.WriteLine("\nPress any key to continue.");
Console.ReadKey();
}
}
public class Pw
{
public string Username { get; set; }
public string FullName { get; set; }
public string PhoneNumber { get; set; }
public string Password { get; set; }
}
I have updated your existing function.
using this function you can add and append data in existing file.
private static void AddPw(string filePath)
{
try
{
Pw pw = new Pw();
if (!File.Exists(filePath))
{
using (System.IO.StreamWriter sw = new System.IO.StreamWriter(filePath))
{
Console.Write("Enter the Username/Email: ");
pw.Username = Console.ReadLine();
sw.WriteLine(pw.Username);
Console.Write("Enter Full Name: ");
pw.FullName = Console.ReadLine();
sw.WriteLine(pw.FullName);
Console.Write("Enter Phone Number: ");
pw.PhoneNumber = Console.ReadLine();
sw.WriteLine(pw.PhoneNumber);
Console.Write("Enter Your Password: ");
pw.Password = Console.ReadLine();
sw.WriteLine(pw.Password);
}
}
else
{
using (StreamWriter sw = File.AppendText(filePath))
{
Console.Write("Enter the Username/Email: ");
pw.Username = Console.ReadLine();
sw.WriteLine(pw.Username);
Console.Write("Enter Full Name: ");
pw.FullName = Console.ReadLine();
sw.WriteLine(pw.FullName);
Console.Write("Enter Phone Number: ");
pw.PhoneNumber = Console.ReadLine();
sw.WriteLine(pw.PhoneNumber);
Console.Write("Enter Your Password: ");
pw.Password = Console.ReadLine();
sw.WriteLine(pw.Password);
}
}
}
catch (Exception ex)
{
}
}
File.AppendAllLines(file, Pw.Site);
In this line, you need to pass an IEnumerable for AppendAllLines to work. You can easily convert Site (which is List<Pw>) to an IEnumerable<string> using the ConvertAll method. Here's one way of achieving this:
Replace that line with this:
File.AppendAllLines(file, Site.ConvertAll<string>(
(p) => string.Format("{0} | {1} | {2} | {3}\n",
p.Username,
p.FullName,
p.PhoneNumber,
p.Password
))
);
This "lambda" basically takes your Pw object and converts it into a string inline.
I need to create an EXE file with my application, I can pass strings with manipulating the string format but I cannot pass the other variables that I need to ex:byte array, here is my code if this helps:
using Microsoft.CSharp;
using System;
using System.CodeDom.Compiler;
using System.Windows;
namespace ACompiler.CompWorker
{
class CompilerWorker
{
public static byte[] testarray = SomeClass.SomeArray;
public static string Key = "Testkey12";
public static void Compile()
{
CSharpCodeProvider CompileProvider = new CSharpCodeProvider();
CompilerParameters CompileProviderParameters = new CompilerParameters(new[] { "mscorlib.dll", "System.Core.dll" }, AppDomain.CurrentDomain.BaseDirectory + "Compiled.exe", true);
CompileProviderParameters.GenerateExecutable = true;
string test= #"using System;
namespace Tests
{
class Program
{
static void Main(string[] args)
{
byte[] Content = " + testarray + #";
string Key = """ + Key + #""";
Console.WriteLine(""Key: "" + EKey);
Console.WriteLine(Content);
Console.ReadLine();
}
}
}
";
var Result = CompileProvider.CompileAssemblyFromSource(CompileProviderParameters, test);
}
}
}
Basically I want to move the "testarray" into the compiled app, I hope someone can point me to the right direction!
The trick is to "serialize" the data back in to code the compiler can compile. Try this:
var arrayCode = "new byte[] { " + string.Join(", ", testarray) + " }";
string test = #"using System;
namespace Tests
{
class Program
{
static void Main(string[] args)
{
byte[] Content = " + arrayCode + #";
string Key = """ + Key + #""";
Console.WriteLine(""Key: "" + EKey);
foreach(byte b in Content)
{
Console.WriteLine(b.ToString());
}
Console.ReadLine();
}
}
}
";
Keep in mind, you can't do Console.WriteLine on a byte array object and have it spit out each item. You will have to iterate over the items to print them out. I updated your code to do it the proper way.
I tried to get the filename and sourceline number when an exception is thrown.
But I got nothing.
class Program
{
static void Main(string[] args)
{
try
{
throw new InvalidOperationException();
}
catch (InvalidOperationException exception)
{
var stackTrace = new StackTrace(exception);
var currentFrame = stackTrace.GetFrame(0);
var fileName = currentFrame.GetFileName();
var sourceLineNumber = currentFrame.GetFileLineNumber();
Console.WriteLine("File Name: " + fileName);
Console.WriteLine("Source line number: " + sourceLineNumber);
Console.ReadKey();
}
}
}
There is only one frame is available. So I use the index 0 in GetFrame(index).
I would write a method and use CallerFilePath, CallerLineNumber and CallerMemberName attributes
public void Log([CallerFilePath]string path="",[CallerLineNumber]int lineNumber=0,[CallerMemberName] string memberName="")
{
Console.WriteLine(path + " " + lineNumber + " " + memberName);
}
Usage: Log()
For more Info: https://msdn.microsoft.com/en-us/library/hh534540.aspx
I have two classes "allmethods.cs" and "caller.cs"
I have two methods in the "allmethods.cs" class which are "WritingMethod" and "ReadingMethod"
The program should write and read from a text file. It writes smoothly when I call the "WritingMethod" but When I call the "ReadingMethod" it shows null as if there is no data in the text file.
I can't identify the problem in my code, I'd be glad if anyone help me identify the problem.
Here is my code:
public class allmethods
{
private static string Name;
private static int ID;
private static int Age;
private static string Email;
private static string output;
public static void WritingMethod()
{
int count = 0;
while (count < 2)
{
Console.Write(" Enter your Name: ");
Name = Console.ReadLine();
Console.Write(" Enter your ID: ");
ID = int.Parse(Console.ReadLine());
Console.Write(" Enter your Age: ");
Age = int.Parse(Console.ReadLine());
Console.Write(" Enter your E-mail: ");
Email = Console.ReadLine();
StreamWriter Sw = new StreamWriter("fileone.txt", true);
string output = string.Format("Thank you for registration! Your Submitted information are:" + Environment.NewLine + "Name: {0}"
+ Environment.NewLine + "ID: {1}" + Environment.NewLine + "Age: {2}" + Environment.NewLine + "E-mail: {3}", Name, ID, Age, Email);
Console.WriteLine(output);
Sw.WriteLine(output + Environment.NewLine);
Console.ReadLine();
Sw.Close();
count++;
}
}
public static void ReadingMethod()
{
FileStream fsr = new FileStream("fileone.txt", FileMode.Open, FileAccess.Read);
StreamReader Sr = new StreamReader(fsr);
string line = Sr.ReadLine();
Console.WriteLine("--Reading The File--" + Environment.NewLine + output + Environment.NewLine);
Console.ReadLine();
Sr.Close();
fsr.Close();
}
}
Thank you very much. Waiting for your answers.
It seems that you have not set the variable output. You have set line variable.
public static void ReadingMethod()
{
FileStream fsr = new FileStream("fileone.txt", FileMode.Open, FileAccess.Read);
StreamReader Sr = new StreamReader(fsr);
string line = Sr.ReadToEnd();
Console.WriteLine("--Reading The File--" + Environment.NewLine + line + Environment.NewLine);
Console.ReadLine();
Sr.Close();
fsr.Close();
}
What I have modified is changed from output to line.
Hope it helps.
This is the total solution for the series of your questions:
public partial class AllMethods {
static T ReadData<T>(String prompt, T value) {
Console.Write(prompt);
return (T)Convert.ChangeType(Console.ReadLine(), typeof(T));
}
public static void WritingMethod(int timesToInput) {
using(var sw=new StreamWriter(path, true))
for(var list=items.ToArray(); timesToInput-->0; ) {
var inputs=new Dictionary<String, object>();
for(var i=0; i<list.Length; ++i) {
var item=list[i];
var prompt=String.Format(" Enter your {0}: ", item.Key);
inputs.Add(
item.Key, AllMethods.ReadData(prompt, item.Value));
}
var output=String.Format(format, inputs.Values.ToArray());
sw.WriteLine(output+Environment.NewLine);
Console.WriteLine(output);
Console.ReadLine();
}
}
public static void ReadingMethod() {
var textFromFile=
String.Join(Environment.NewLine, File.ReadAllLines(path));
Console.WriteLine(
"--Reading The File--"+Environment.NewLine+textFromFile);
Console.ReadLine();
}
static AllMethods() {
items=new Dictionary<String, object>();
// add any item with name and type default value
items.Add("Name", default(String));
items.Add("ID", default(int));
items.Add("Age", default(int));
items.Add("Email", default(String));
var prompts=items.Select(
(item, index) => String.Format("{0}: {{{1}}}", item.Key, index));
format=
"Thank you for registration! Your Submitted information are: "
+Environment.NewLine
+String.Join(Environment.NewLine, prompts.ToArray());
path="fileone.txt";
}
static Dictionary<String, object> items;
static String format, path;
}
I'd suggest that to prepare for complete code, and don't ask duplicate questions.
I have the following two methods:
class Debug
{
static bool OutputToConsole = true;
public static void Log(string Type, string URL, StringBuilder Parameters)
{
string Output = Type + ":" + new string(' ', 9 - Type.Length) + URL + " { " + Parameters.ToString() + " }";
Trace.WriteLine(Output);
if(OutputToConsole) Console.WriteLine(Output);
}
public static void Log(string Data)
{
string Output = "Response: " + Data;
Trace.WriteLine(Output);
if(OutputToConsole) Console.WriteLine(Output);
}
}
If you'll notice, it's only the string Output that changes.
The 2 lines after it are the same in both methods.
I was just wondering if there is there a way to keep to the DRY principle and combine these 2 methods?
Refactor the common code to a private helper function: (Visual studio will do all of this for you by highlighting the relevant section of code, right clicking, and choosing Refactor -> extract method...)
private static void LogHelper(string text)
{
Trace.WriteLine(text);
if(OutputToConsole) Console.WriteLine(text);
}
(Note the name change to ensure it has a different signature from Log(string Data).)
Then just call that function from both of the others.
Not sure how much of an improvement this is...
class Debug
{
static bool OutputToConsole = true;
public static void LogRequest(string type, string url, StringBuilder params)
{
log(type + ":" + new string(' ', 9 - type.Length) + url + " { " + params.ToString() + " }");
}
public static void LogResponse(string data)
{
log("Response: " + data);
}
private static void log(string msg)
{
Trace.WriteLine(msg);
if(OutputToConsole) Console.WriteLine(msg);
}
}
There is likely no way to combine the two methods and get any real value out of it because the Output generated is different, but you could create a method that does the actual trace:
public static void Trace(string Output)
{
Trace.WriteLine(Output);
if(OutputToConsole) Console.WriteLine(Output);
}
and then call that from those methods.
You could use optional parameters if you wanted, it's a bit unusual, but interesting:
public static void Log(string Data = null, string Type = null, string URL = null, StringBuilder Parameters = null)
{
string Output = "";
if (Data != null)
{
Output = "Response: " + Data;
}
else if (Type != null && URL != null && Parameters != null)
{
Output = Type + ":" + new string(' ', 9 - Type.Length) + URL + " { " + Parameters.ToString() + " }";
}
else
{
throw new ArgumentException("Provide yada yada arguments lala");
}
Trace.WriteLine(Output);
if (OutputToConsole) Console.WriteLine(Output);
}
Use it like this:
Log(Data: "Test");
StringBuilder sb = new StringBuilder();
Log(Type: "myType", URL: "www.bla", Parameters: sb);