C# console reference use on windows form application project - c#

I am Learning C#, but when i was trying to do a reference on a windows form application using a console code, the error The type or namespace name 'TidPunkt' could not be found (are you missing a using directive or an assembly reference?)
Posting reference code below, then the Desinger.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class TidPunkt
{
int tim, min, sek;
bool VisaSek = true;
public void Sätt(int t, int m, int s)
{
if (t >= 0 && t < 24 && m >= 0 && m < 60 && s >= 0 && s < 60)
{
tim = t; min = m; sek = s;
}
else
Console.WriteLine("Felaktig tidpunkt");
}
}
public void SättVisaSek(bool visa)
{
VisaSek = visa;
}
public int AvLäsTim()
{
return tim;
}
public int AvläsMin()
{
return min;
}
public int AvläsSek()
{
return sek;
}
public void Ticka()
{
if (++sek == 60)
{
sek = 0; ++min;
}
if (min == 60)
{
min = 0; ++tim;
}
if (tim == 24)
{
tim = 0;
}
}
public override string ToString()
{
string tid = tim + ":" + min;
if (VisaSek)
tid = tid + ":" + sek;
return tid;
}
}
}
Thats the reference code. posting the "Klockvisare.cs" code.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Klockvisare : Form
{
TidPunkt tp = new TidPunkt();
public Klockvisare()
{
InitializeComponent();
DateTime dt = DateTime.Now;
tp.Sätt(dt.Hour, dt.Minute, dt.Second);
a.Text = tp.ToString();
}
private void timer1_Tick(object sender, EventArgs e)
{
tp.Ticka();
a.Text = tp.ToString();
}
}
}

Change class TidPunkt to public class TidPunkt.

Be sure your assembly is referenced in the second project.
Add public before class TidPunkt
Add this to your second file
using ConsoleApplication1;
Anyway, you should create a Class Library project and put there your first file logic (without the Console.WriteLine). Then you create another project, let's say a WinForm like you did, and you add the previous assembly as reference. After you import the appropriate namespaces you can use the types of the class library.

You have to add your ConsoleApplication1 reference to your winforms application. If it's in another solution, then you have to add the ConsoleApplication1 dll to the references (right click on the references, then browse the dll). If it's in the same solution, then you have to right click on the references again, choose Solution option, then choose the ConsoleApplication1. After these, you can just use the "CTRL" + "." combination on the TidPunkt class and Visual Studio will find the correct namespace for you.

Related

How to declare an instance of another class?

I have following question, right now like 2 minutes ago a guy posted his code.
He couldn't use his instance obj , and I don't know why he deleted his question.
He had also some usings, I think he had using static N.Form1
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
int Y(int a)
{
a = 10;
Console.WriteLine(a);
return a;
}
}
}
}
namespace WindowsFormsApp1
{
class Class1
{
N.Form1 obj = new N.Form1();
public void X(int a)
{
var v = obj.Y(a);
Console.WriteLine(v);
}
}
}
So first I've seperate the method, and made it public so I can create instance and use it in another class.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public int Y(int a)
{
a = 10;
Console.WriteLine(a);
return a;
}
}
And then instead of using N.From1, I used the namespace for declaring instance WindowsFormsApp1.Form1 obj = new WindowsFormsApp1.Form1();
My Class1 looks like this now:
class Class1
{
WindowsFormsApp1.Form1 obj = new WindowsFormsApp1.Form1();
public void X(int a)
{
var v = obj.Y(a);
Console.WriteLine(v);
}
}
So there isn't any error, and my question is, is this the right way to declare and instance and use it later? Also are you allowed to use the namespace ?
Thanks,

Getting Invalid Token error when trying to access variables in a class that will be used multiple times by Windows Forms in C#

I am a C# beginner, and have been working through some code where I can type in the day of the week for a given month and then the dates (3/29/2019) that match the day (For example, Friday) are printed out. I have successfully got this working using a console app.
I'd like to now have the same functionality while using Forms. I've watched multiple videos and done research on implementing Forms and while it seems rather simple, I'd like to have most of the code running outside of the buttons in its own class so that I don't have to enter the same code each and every time for each button (Example shown below).
Here is my code in Forms:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace DesktopApp5
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public class A
{
public static void Main()
{
DateTime timenow = DateTime.Now;
//Creates 2 strings with year and month
string currentyearstr = DateTime.Now.Year.ToString();
string currentmonthstr = DateTime.Now.Month.ToString();
//Turns two strings into integers for further use
int currentyear = int.Parse(currentyearstr);
int selectmonth = int.Parse(currentmonthstr);
//Outputs total days for the current month, Number of times to loop command
var totaldaysinmonth = DateTime.DaysInMonth(currentyear, selectmonth);
List<string> meetingdates = new List<string>();
for (int i = 0; i < totaldaysinmonth; i++)
{
DateTime dateofmonth = new DateTime(timenow.Year, timenow.Month, 1 + i);
Calendar mycal = CultureInfo.InvariantCulture.Calendar;
string dayofweek = mycal.GetDayOfWeek(dateofmonth).ToString();
if (dayofweek == "Friday")
{
meetingdates.Add(dateofmonth.Date.ToString("MM/dd"));
}
}
}
}
public void Form1_Load(object sender, EventArgs e)
{
}
public void textBox1_TextChanged(object sender, EventArgs e)
{
textBox1.Text = A.currentyearstr;
}
}
}
Expected Result: I created the A class to keep variables that I would be using for throughout different places, such as textboxes in the same place. I am expecting to be able to locate the currentyearstr variable for example.
I understand that if I only create the class and do not have the code inside of Main() that it is then accessible after declaring string, int, and others static. The problem I have with this is that then if and for do not function if they are not inside the Main(). Atleast that's what I think anyways. What I just described, can be seen here:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace DesktopApp7
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public static class A
{
static DateTime timenow = DateTime.Now;
//Creates 2 strings with year and month
public static string currentyearstr = DateTime.Now.Year.ToString();
static string currentmonthstr = DateTime.Now.Month.ToString();
//Turns two strings into integers for further use
static int currentyear = int.Parse(currentyearstr);
static int selectmonth = int.Parse(currentmonthstr);
//Outputs total days for the current month, Number of times to loop command
static var totaldaysinmonth = DateTime.DaysInMonth(currentyear, selectmonth);
//Gives all dates in the month
static List<string> meetingdates = new List<string>();
static for (int i = 0; i<totaldaysinmonth; i++)
{
static DateTime dateofmonth = new DateTime(timenow.Year, timenow.Month, 1 + i);
Calendar mycal = CultureInfo.InvariantCulture.Calendar;
static string dayofweek = mycal.GetDayOfWeek(dateofmonth).ToString();
static if (dayofweek == "Friday")
{
meetingdates.Add(dateofmonth.Date.ToString("MM/dd"));
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
textBox1.Text = A.currentyearstr;
}
}
}
One doubt I have is why do I have to specify in this case that everything is static? when in the first example, when most of the code is in Main, I only needed to do this once. I understand that public is what allows me use the variable outside of the class.
The errors that appear are this:
Invalid token 'for' in class, struct, or interface member
Invalid token 'if' in class, struct, or interface member
What is the cause of these errors? As a higher level question, how should I organize code that will be repeatedly used, so that it is accessible to all other classes? In my project for example, I need to call on those strings different integers, strings, and datetime, when using different windows forms.
Thanks ahead of time for any help. It is much appreciated. :)
Edit:
Per comment below here is my new code now that I have employed a method DatesCalculated
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace DesktopApp7
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public class A
{
public void DatesCalculated(string[] args)
{
DateTime timenow = DateTime.Now;
//Creates 2 strings with year and month
string currentyearstr = DateTime.Now.Year.ToString();
string currentmonthstr = DateTime.Now.Month.ToString();
//Turns two strings into integers for further use
int currentyear = int.Parse(currentyearstr);
int selectmonth = int.Parse(currentmonthstr);
//Outputs total days for the current month, Number of times to loop command
var totaldaysinmonth = DateTime.DaysInMonth(currentyear, selectmonth);
//Gives all dates in the month
List<string> meetingdates = new List<string>();
for (int i = 0; i < totaldaysinmonth; i++)
{
DateTime dateofmonth = new DateTime(timenow.Year, timenow.Month, 1 + i);
Calendar mycal = CultureInfo.InvariantCulture.Calendar;
string dayofweek = mycal.GetDayOfWeek(dateofmonth).ToString();
if (dayofweek == "Friday")
{
meetingdates.Add(dateofmonth.Date.ToString("MM/dd"));
}
}
return;
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
}
}
When you define a class, its members can be fields, properties, and methods.
public static class MyClass
{
static string _thisIsAField = "hello!";
static string ThisIsAProperty {get; set;}
static int ThisIsAMethod(int value1, int value2)
{
return value1 + value2;
}
}
A for loop isn't any one of those things, so you can't do this:
static for (int i = 0; i<totaldaysinmonth; i++)
A for loop can only exist within a method. "Invalid token" means that the compiler doesn't understand what it means in the place where you're putting it. Depending on what you're trying to accomplish, you would have to create a method that does something, like (this is a really lame example)
static List<int> GetRangeOfNumbers(int start, int end)
{
var list = new List<int>();
for(var x = start; x <= end; x++)
{
list.Add(x);
}
return list;
}

How do I get a string from a TextBox in VS and then compare it to an integer using an if statement?

Alright, I'm pretty new to C# and I'm trying to figure out how I could grab a string or a number from my TextBox in Visual Studio(Windows Form Application) and then figure out if that string is 0.
I've tried doing
if(Calculations.Text == 0)
{
Calculations.Text = 1
}
but to my avail it did not work.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Calculatrice : Form
{
public Calculatrice()
{
InitializeComponent();
}
private void One_Click(object sender, EventArgs e)
{
if(Calculations.Text)
{
}
}
private void Calculatrice_Load(object sender, EventArgs e)
{
}
}
}
This is all I have right now I'm pretty stuck.
I want to be able to use the if statement to make comparisons with int values.
You should enclose your string in quotes before using them
if(Calculations.Text.Trim () == "0")
{
Calculations.Text = "1";
}
//Example:if Calculations is your textbox id,then
string input = calculations.text.tostring();
//then compare zero with " "
if(input == "0")
{
calculations.text= 1;
}
A user can put anything in a TextBox. Use TryParse which will provide a zero even if it fails (returns false)
private void OPCode()
{
int.TryParse(Calculations.Text, out int i);
if (i == 0)
{
Calculations.Text = 1.ToString();
}
}

Linux Mono + Postsharp + Log4Net = No automated Exception catching

We are developing a C# project with Monodevelop under Linux.
We have added Log4Net(1.2.11.0), Postsharp (4.1.24.0) and also Postsharp for Log4Net to our project via NuGet.
The following code throws an IndexOutOfRangeException:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using PostSharp;
using PostSharp.Aspects;
[System.Diagnostics.DebuggerStepThrough]
[Loggable]
class Program
{
static void Main (string[] args)
{
String[] myArray= new String[] { "X" };
for (int i = 0; i <= 100; i++) {
Console.WriteLine (myArray[i]);
}
}
}
Unfortunately, Postsharp doesn't even catch the exception.
We even tried to replace "[Loggable]" with "[LoggableAttribute]", since the Class' name is like that.
Here it is:
using System;
using System.Collections.Generic;
using System.Linq;
using PostSharp;
using PostSharp.Aspects;
using System.Collections;
[Serializable]
public class LoggableAttribute : OnExceptionAspect
{
public override void OnException(MethodExecutionArgs event_args)
{
Logging.SetExecutionTime(DateTime.Now);
Logging.SetParameter("parameters", ParametersToString(event_args));
Logging.SetParameter("method_name", event_args.Method.Name);
Logging.SetParameter("class_name", event_args.Instance.GetType().ToString());
Logging.Error("Error Encountered in " + event_args.Method, event_args.Exception);
}
private static String ParametersToString(MethodExecutionArgs event_args)
{
String output = "";
if (event_args.Method.GetParameters() != null)
{
for (int i = 0; i < event_args.Method.GetParameters().Length; i++)
{
output += String.Format("[{0} = {1}]", event_args.Method.GetParameters()[i].Name, event_args.Method.GetParameters()[i]);
}
}
return output;
}
}
Even a break point within OnException doesn't help. It doesn't get in there.
PostSharp works fine with mono, I actually use it there for quite some time already. I cannot now test on your mono version (3.2.8 is quite old already), but on 4.0.4 this code runs without problem:
[Loggable]
internal class Program {
private static void Main(string[] args) {
String[] myArray = new String[] {"X"};
for (int i = 0; i <= 100; i++) {
Console.WriteLine(myArray[i]);
}
}
}
[Serializable]
public class LoggableAttribute : OnExceptionAspect {
public override void OnException(MethodExecutionArgs args) {
Console.WriteLine("Caught by postsharp: " + args.Exception);
args.FlowBehavior = FlowBehavior.Continue;
}
}
Outputs "Caught by postsharp: ..." and no exception is thrown. As for log4net, you say yourself that it's not related to your question in any way - your code does not enter block where log4net is used.
So, just update to modern mono version and you'll be fine.

Bankteller console application

I'm making a simple application to simulate the bankteller problem.
What I'm trying to simulate is:
You have 4 counters in a store. 1 counter is open. Customers start coming in and enter the line for the first counter.
When the fourth customer enters the line for the first counter, another counter should open. The line should be equally divided between the 2 counters.When the customer at the second counter is helped and no new customers enter the line, the counter should close. Basically 4 is too many.
I can't seem to figure it out. I know I need to use a queue. But how? Could someone give me an example in console application? Preferable C#.
Thanks in advance.
Here is what I tried so far,
register class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RegisterCounter
{
class Register
{
private int customerCount;
public Queue<Customer> Line = new Queue<Customer>();
public Register()
{
customerCount = 2;
}
public Register(int customerCount)
{
this.customerCount = customerCount;
}
public int getCustomers()
{
return customerCount;
}
}
}
Customer class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RegisterCounter
{
class Customer
{
private int checkoutTime;
public Customer()
{
checkoutTime = 3;
}
public Customer(int checkoutTime)
{
this.checkoutTime = checkoutTime;
}
public int GetCheckoutTime()
{
return checkoutTime;
}
}
}
Register manager:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RegisterCounter
{
class RegisterManager
{
public List<Register> registers = new List<Register>();
Register r1 = new Register();
Customer c1 = new Customer();
public RegisterManager()
{
registers.Add(r1);
}
public void ManageCustomers()
{
for (int i = 0; i < registers.Count; i++)
{
registers.Insert(i, new Register());
if (i / 4 <= registers..Line.Count)
{
}
}
}
}
}

Categories