is it right way to use interface? - c#-3.0

how interface knows which class method to call?
it is the correct code? or not
namespace IntExample
{
interface Iinterface
{
void add();
void sub();
}
public partial class Form1 : Form,Iinterface
{
public Form1()
{
InitializeComponent();
}
public void add()
{
int a, b, c;
a = Convert.ToInt32(txtnum1.Text);
b = Convert.ToInt32(txtnum2.Text);
c = a + b;
txtresult.Text = c.ToString();
}
public void sub()
{
int a, b, c;
a = Convert.ToInt32(txtnum1.Text);
b = Convert.ToInt32(txtnum2.Text);
c = a - b;
txtresult.Text = c.ToString();
}
private void btnadd_Click(object sender, EventArgs e)
{
add();
}
private void button2_Click(object sender, EventArgs e)
{
sub();
}
class cl2 : Form1,Iinterface
{
public void add()
{
int a, b, c;
a = Convert.ToInt32(txtnum1.Text);
b = Convert.ToInt32(txtnum2.Text);
c = a + b;
txtresult.Text = c.ToString();
}
}
private void Form1_Load(object sender, EventArgs e)
{
}

Interface does not "know" which class method to call. It just defines what methods are available.
The code you posted would not compile since cl2 does not implement sub method but it's pretty much meaningless anyway.
I have no idea what you are trying to do so I will give example for valid usage of the interface.
You can have several forms implementing that interface, then in your main form you can choose which of those forms to show according to index or name.
So, to store all the forms you can use generic list:
List<Iinterface> forms = new List<Iinterface>();
Adding to the list all the forms implementing the interface:
forms.Add(new Form1());
forms.Add(new Form2());
forms.Add(new Form3());
//...
Then you can show specific form and call a method from the interface:
//find by index:
forms[index].Show();
forms[index].add();
//find by name:
string name="form 2";
Iinterface form = forms.Find(f => f.Name == name);
if (form != null)
{
form.Show();
form.add();
}

Related

Why does my ArrayList of objects print out one variable stored inside the object, but not the other

HandDrawn class extends the super-class Car, as you can see. The problem is it doesn't print out the the String name when i try to print the ArrayList that stores the objects. Btw, the ArrayList stores objects of the class Car.
Calm down, if i did something that offends your little feelings with this question, dont down vote... tell me what's up so i know in the future.
public class HandDrawn extends Card {
private boolean niceDrawing;
public HandDrawn(String name, boolean niceDrawing) {
super(name);
this.niceDrawing = niceDrawing;
}
#Override
public String toString() {
return "HandDrawn{" +
"niceDrawing=" + niceDrawing +
'}';
}
public void setNiceDrawing() {
this.niceDrawing = niceDrawing;
}
public boolean getNiceDrawing(boolean niceDrawing) {
return this.niceDrawing;
}
}
public class Main {
static ArrayList<Card> cards = new ArrayList<>();
public static void main(String[] args) {
cards.add(new HandDrawn("Anna", true));
cards.add(new HandDrawn("Kalle", false));
Main myApp = new Main();
myApp.cardList(cards);
}
public void cardList(ArrayList<Card> e) {
for (int i = 0; i <e.size(); i++) {
System.out.println(e.get(i));
}
}
}
This is the Main class and the HandDrawn class
Again, I don't know what is in your super class "Card" but maybe this will help:
In your HandDrawn.java file:
public class HandDrawn extends Card {
private boolean niceDrawing;
public HandDrawn(String name, boolean niceDrawing) {
super(name);
this.niceDrawing = niceDrawing;
}
#Override
public String toString() {
return "HandDrawn{" + "niceDrawing=" + this.niceDrawing + "}";
}
// Notice I have modified the parameters of your getters
// and setters because it looked as if you had swapped them:
public void setNiceDrawing(boolean niceDrawing) {
this.niceDrawing = niceDrawing;
}
public boolean getNiceDrawing() {
return this.niceDrawing;
}
}
In your Main.java file:
public class Main {
static ArrayList<Card> cards = new ArrayList();
public static void main(String[] args) {
// This is the entry point of your program... execution begins here.
cards.add(new HandDrawn("Anna", true));
cards.add(new HandDrawn("Kalle", false));
cardList(cards);
}
// The following two lines are out of place and should not be in class definition:
// Main myApp = new Main();
// myApp.cardList(cards);
// I added static keyword so that it could be used in call above
public static void cardList(ArrayList<Card> e) {
for (int i = 0; i < e.size(); i++) {
System.out.println(e.get(i));
}
}
If you are wanting to use the "Main" class as a piece in another part of your code then probably that means that execution starts somewhere else and never hits the "main" method. If that is the case you will need to call it explicitly (example: Main.main(null);) or reorganize your code to do it in a constructor for the "Main" class. Then your Main myApp = new Main(); and myApp.cardList(cards); lines would make sense in that context and the cardList method would need to be a non-static member method as you had originally written.
EDIT:
I think I misunderstood your formatting... Your code should work as follows:
In your Main.java file:
public class Main {
static ArrayList<Card> cards = new ArrayList();
public static void main(String[] args) {
// This is the entry point of your program... execution begins here.
cards.add(new HandDrawn("Anna", true));
cards.add(new HandDrawn("Kalle", false));
Main myApp = new Main();
myApp.cardList(cards);
}
public void cardList(ArrayList<Card> e) {
for (int i = 0; i < e.size(); i++) {
System.out.println(e.get(i));
}
}
What were you expecting to see? Again I cannot test your code because I don't have "Card" class but when I use the "HandDrawn" class in place of "Card" (without extending "Card") it works as I would expect and prints:
HandDrawn{niceDrawing=true}
HandDrawn{niceDrawing=false}

how to pass class to another form?

im trying to passing a class which preserves the values in it across all forms. but i have no idea how to do it.
my default class:
namespace bankaccount
{
class Account
{
private string _name, _accountNo, _accountType;
private double _balance = 0;
public string Name
{
get{ return _name;}
set{ _name = value;}
}
public string AccountNo
{
get { return _accountNo; }
set { _accountNo = value; }
}
public string AccountType
{
get { return _accountType; }
set { _accountType = value; }
}
public double Balance
{
get { return _balance; }
set { _balance = value; }
}
public Account()
{
}
public Account(string name, string accountNo, string accountType, double balance)
{
_name = name;
_accountNo = accountNo;
_accountType = accountType;
_balance = balance;
}
public double withdraw(double withdraw)
{
return _balance = _balance - withdraw;
}
public double deposit(double deposit)
{
return _balance = _balance + deposit;
}
}
}
main menu form:
public partial class frmMainMenu : Form
{
public frmMainMenu()
{
InitializeComponent();
}
public void btnNewAccount_Click(object sender, EventArgs e)
{
this.Hide();
frmNewAccount NewAccount = new frmNewAccount();
NewAccount.Show();
}
public void btnDeposit_Click(object sender, EventArgs e)
{
this.Hide();
frmDeposit Deposit = new frmDeposit();
Deposit.Show();
}
public void btnWithdraw_Click(object sender, EventArgs e)
{
this.Hide();
frmWithdraw Withdraw = new frmWithdraw();
Withdraw.Show();
}
public void btnBalance_Click(object sender, EventArgs e)
{
this.Hide();
frmBalance Balance = new frmBalance();
Balance.Show();
}
}
New Account form (form to create object from the class)
public partial class frmNewAccount : Form
{
public frmNewAccount()
{
InitializeComponent();
}
private void btnRegister_Click(object sender, EventArgs e)
{
//Account newAccount = new Account();
string name = string.Copy(txtName.Text);
string accountNo = string.Copy(txtAccountNo.Text);
string accountType = string.Copy(txtAccountType.Text);
double amount = double.Parse(txtAmount.Text);
Account newAccount = new Account(name, accountNo, accountType, amount);
}
private Account btnMainMenu_Click(object sender, EventArgs e)
{
this.Hide();
frmMainMenu MainMenu = new frmMainMenu();
MainMenu.Show();
}
}
Deposit form
public partial class frmDeposit : Form
{
public frmDeposit()
{
InitializeComponent();
}
private void btnDeposit_Click(object sender, EventArgs e)
{
}
private void btnMainMenu_Click(object sender, EventArgs e)
{
this.Hide();
frmMainMenu MainMenu = new frmMainMenu();
MainMenu.Show();
}
}
what im trying to do here is create Account newAccount on New Account Form, using the data its created to be accessible in another form...
Your code has to be changed minimally to give this reference of an account to a child form. I would do it explicitly in constructor.
public partial class frmDeposit : Form
{
Account _account;
public frmDeposit(Account account)
{
_account = account;
InitializeComponent();
}
(...)
After this you can use inside the frmDeposit class the _account field.
This approach is typically better than using a property as you enforce the form to be initialized with an account.
And when you create your dialog to set deposit information, you will have to write instead of:
var depositForm = new frmDeposit(); //here you will get compilation error
depositForm.ShowDialog()
You will have to write:
var depositForm = new frmDeposit(account); //compilation error is fixed
depositForm.ShowDialog()
You usually don't pass classes, but instances (i.e. objects). Create an instance of the class in the form that starts your workflow. In every child form that's called, add a property
public BankAccount Account { get; set; }
and set the value of that property before showing the child form.
using (FrmChildForm frm = new FrmChildForm())
{
frm.Account = myBankAccount;
...
}
Another solution would be to create an instance variable in every child form as well and pass the account in the constructor:
using (FrmChildForm frm = new FrmChildForm(myBankAccount))
...
public class FrmChildForm : Form
{
private BankAccount _account;
public FrmChildForm(BankAccount theAccount)
{
_account = theAccount;
}
}
About your navigation
You're doing it wrong! You're filling up memory for nothing, creating instances over and over the place. Why?
Well, your main menu creates a child form, then hides itself. Your child form then generates a new main menu instead of just closing itself and showing the existing main form again! That's highly inefficient and prevents you from keeping the account instance I talked about above.
What you should do is this:
public void btnNewAccount_Click(object sender, EventArgs e)
{
frmNewAccount NewAccount = new frmNewAccount();
NewAccount.Account = myAccount;
NewAccount.FormClosing += SubFormClosing;
NewAccount.Show();
this.Hide();
}
Then, have a method SubFormClosing:
private void SubFormClosing(object sender, FormClosingEventArgs e)
{
this.Show();
}
Then, the code to return to the main form comes down to:
private void btnMainMenu_Click(object sender, EventArgs e)
{
this.Close();
}
This creates one main menu. Upon selecting an module, the module window is opened, the main menu is hidden. Instead of creating a new main menu when closing the module window, the old main menu is restored when the module window is closed.
The trick here is to attach an event handler to the closing event of the module form so the hidden menu form gets notified that it should show itself again.
And you should learn about modal dialogs. The "window" where a new account is created should actually be a modal dialog that collects the information. Then, the main menun sets its myAccount member variable based on the new account information. There's no need to pass the account to the "New Account" mask, as it creates a new account.

How to write test case for the given code using powermockito

I just want to know if i have a code like -
public class A {
static String b = "hello";
public static String a() {
String b = b();
String d = d(b);
String e = e(d, b);
return e;
}
public static String b() {
return b;
}
public static void c(String c) {
b = c;
}
public static String d(String d) {
return d;
}
public static String e(String e1, String e2) {
return e1 + e2;
}
}
than how will i write the test cases for this using power mockito since all the methods are static and a method is even void too.
The first thing i got is that i only need to write the test case for method a since it is using all the other methods so all others will also get cover in it.
Can anybody help me and tell me how i can test this .

How can I make ITD available in the code of the aspect subject?

I am not sure if my terminology is right, but here is what I want. I have an aspect that injects a Log field into certain types, here is the aspect code:
public aspect LoggingAspect {
private interface HttpHandlerType {}
declare parents: (#Path *) implements HttpHandlerType;
private Logger HttpHandlerType.Log = Logger.getLogger(getClass());
pointcut httpHandlerMethods(HttpHandlerType o) : within(HttpHandlerType+) &&
execution(#(GET || PUT || POST || DELETE) public * *.*(..)) && this(o);
before(HttpHandlerType o): httpHandlerMethods(o) {
if (o.Log.isInfoEnabled()) {
o.Log.info(logMethod(thisJoinPoint));
}
}
after(HttpHandlerType o) returning (Object result): httpHandlerMethods(o) {
if (o.Log.isDebugEnabled()) {
o.Log.debug(logMethod(thisJoinPoint, result));
}
}
after(HttpHandlerType o) throwing (Exception e): httpHandlerMethods(o) {
if (o.Log.isEnabledFor(Level.ERROR)) {
o.Log.error(logMethod(thisJoinPoint), e);
}
}
private static String logMethod(JoinPoint jp) {
...
}
private static String logMethod(JoinPoint jp, Object result) {
...
}
}
The question is how the aspect subjects can make use of this field. For instance, here is a sample class affected by this aspect:
#Path("user")
public class UserHandler {
#GET
#Path("{id}")
public User getUser(#PathParam("id") int id) {
...
}
}
The question is how the code of getUser can utilize the Log field injected by the aspect?
Thanks.
Simply change the visibility of the log field from private to public and this should work.

Form Method on another thread not invoking the events

I am trying to achieve an update form.
I use a library to open a form when there is an updated file and download using edtFTPNet
In the form I pass the FTP object and start download, in FormLoad i handle two events and i use Thread to StartDownload(). My two events never invoking, i use them to set a progress bar.
public partial class UpdateProgressForm : XtraForm
{
public FTPConnection FtpConn { get; set; }
public string UpdateFileName { get; set; }
public UpdateProgressForm()
{
InitializeComponent();
}
private void OnLoad(object sender, EventArgs e)
{
FtpConn.Downloading += FileDownLoading;
FtpConn.BytesTransferred += FileBytesTransfered;
}
private void FileDownLoading(object sender, FTPFileTransferEventArgs e)
{
progressBar.Properties.Maximum = (int) e.FileSize;
}
private void FileBytesTransfered(object sender, BytesTransferredEventArgs e)
{
progressBar.Position = (int) e.ByteCount;
}
public void StartDownload()
{
FtpConn.DownloadFile(#".\" + UpdateFileName, UpdateFileName);
}
private void OnShown(object sender, EventArgs e)
{
Thread tt = new Thread(StartDownload) {IsBackground = true};
tt.Start();
}
}
Library method calling the Form:
private void DownloadUpdateFile(string updateFileName)
{
using (ProgressForm = new UpdateProgressForm { FtpConn = FtpConn, UpdateFileName = updateFileName })
{
ProgressForm.ShowDialog();
}
}
Any help? Thank you.
Take a look in the designer and make sure you subscribe to those events
Make sure you Instanciate and Show the from from the Main Thread.
Are you sure that the event handlers are not invoked? I think your problem rather is that you try to update the progress bar on the worker thread on which the event handlers are invoke (which is not the thread on which the GUI was created). You should make sure that the GUI updates are performed on the correct thread:
private void FileDownLoading(object sender, FTPFileTransferEventArgs e)
{
progressBar.Invoke((MethodInvoker) delegate
{
progressBar.Properties.Maximum = (int) e.FileSize;
});
}