How to reuse method by passing different class object to the same method? - c#-4.0

How to reuse method by passing different class object? I have 2 different classes, ClassOne and ClassTwo, in the method ProcessMessage I want to pass the Class also, but how?
Like this in someway //ProcessMessage(classText, objectTwo);
class ClassOne
{
public string MethodOne()
{
return ("ClassOne");
}
}
class ClassTwo
{
public string MethodOne()
{
return ("ClassTwo");
}
}
class Program
{
static void Main()
{
var objectOne = new ClassOne();
var classText = objectOne.MethodOne();
ProcessMessage(classText, objectOne);
var objectTwo = new ClassTwo();
classText = objectTwo.MethodOne();
//ProcessMessage(classText, objectTwo);
Console.ReadKey();
}
public static void ProcessMessage(string classText, ClassOne testClass)
{
Console.WriteLine("ClassText:{0}", classText);
}
}
If I use this(after getting help from you guys), I recognise know, how can I use testClass?
Like: var text= testClass.MethodOne(); or something
public static void ProcessMessage(string classText, ClassOne testClass)
{
Console.WriteLine("ClassText:{0}", classText);
}

I'm not sure why you want this since you are not using the testClass parameter in ProcessMessage anywhere.But you can use a generic method to pass any type of class to your method:
public static void ProcessMessage<T>(string classText, T testClass)
where T : class
{
Console.WriteLine("ClassText:{0}", classText);
}
Another alternative is creating a common interface or a base class for ClassOne and ClassTwo.And change the method:
public static void ProcessMessage(string classText, CommonInterface testClass)
{
Console.WriteLine("ClassText:{0}", classText);
}

It is possible to use Generics, but Like Prerak K said, why?
class ClassOne
{
public string MethodOne()
{
return ("ClassOne");
}
}
class ClassTwo
{
public string MethodOne()
{
return ("ClassTwo");
}
}
class Program
{
static void Main()
{
var objectOne = new ClassOne();
var classText = objectOne.MethodOne();
ProcessMessage(classText, objectOne);
var objectTwo = new ClassTwo();
classText = objectTwo.MethodOne();
ProcessMessage(classText, objectTwo);
Console.ReadKey();
}
public static void ProcessMessage<T>(string classText, T testClass)
{
Console.WriteLine("ClassText:{0}", classText);
}
}

Or you can create an interface like this:
interface IProcessable {
string MethodOne();
}
class ClassOne : IProcessable
{
public string MethodOne()
{
return ("ClassOne");
}
}
class ClassTwo : IProcessable
{
public string MethodOne()
{
return ("ClassTwo");
}
}
class Program
{
static void Main()
{
IProcessable objectOne = new ClassOne();
var classText = objectOne.MethodOne();
ProcessMessage(classText, objectOne);
IProcessable objectTwo = new ClassTwo();
classText = objectTwo.MethodOne();
ProcessMessage(classText, objectTwo);
Console.ReadKey();
}
public static void ProcessMessage(string classText, IProcessable testClass)
{
Console.WriteLine("ClassText:{0}", classText);
}
}

Related

Groovy Inner Classes wont work with Apache Wicket

Im trying to write simple things with Apache Wicket (6.15.0) and Groovy (2.2.2 or 2.3.1). And Im having trouble with inner classes.
class CreatePaymentPanel extends Panel {
public CreatePaymentPanel(String id) {
super(id)
add(new PaymentSelectFragment('currentPanel').setOutputMarkupId(true))
}
public class PaymentSelectFragment extends Fragment {
public PaymentSelectFragment(String id) {
super(id, 'selectFragment', CreatePaymentPanel.this) // problem here
add(new AjaxLink('cardButton') {
#Override
void onClick(AjaxRequestTarget target) {
... CreatePaymentPanel.this // not accessible here
}
})
add(new AjaxLink('terminalButton') {
#Override
void onClick(AjaxRequestTarget target) {
... CreatePaymentPanel.this // not accessible here
}
});
}
} // end of PaymentSelectFragment class
} // end of CreatePaymentPanel class
Groovy tries to find a property "this" in CreatePaymentPanel class.. How to workaround this? It is a valid java code, but not groovy.
However,
Test.groovy:
class Test {
static void main(String[] args) {
def a = new A()
}
static class A {
A() {
def c = new C()
}
public void sayA() { println 'saying A' }
class B {
public B(A instance) {
A.this.sayA()
instance.sayA()
}
}
/**
* The problem occurs here
*/
class C extends B {
public C() {
super(A.this) // groovy tries to find property "this" in A class
sayA()
}
}
}
}
Above code wont work, the same error occurs, like in Wicket's case.
And TestJava.java, the same and working:
public class TestJava {
public static void main(String[] args) {
A a = new A();
}
static class A {
A() {
C c = new C();
}
public void sayA() {
System.out.println("saying A");
}
class B {
public B(A instance) {
instance.sayA();
}
}
/**
* This works fine
*/
class C extends B {
public C() {
super(A.this);
sayA();
}
}
}
}
What I am missing?
You can't refer to a CreatePaymentPanel.this inside of PaymentSelectFragment because there is no instance of CreatePamentPanel that would be accessible there. What would you expect that to evaluate to if it were allowed?

Map Expression Language(EL) Reference object has not been found

I have following case:
Flex class
public class Flex {
private String key;
private String val;
public Flex () {
}
public void setKey(String key) {
this.key = key;
}
public String getKey() {
return key;
}
public void setVal(String val) {
this.val = val;
}
public String getVal() {
return val;
}
FlexManager class
public class FlexManager {
private Map<String, Flex> keyValue = new HashMap<String, Flex>();
public FlexManager () {
populateFlexFieldMap();
}
private void populateFlexFieldMap() {
if (keyValue.isEmpty()) {
List<Flex> fieldds = loadKVFromFile();
for (Flexfield : fieldds) {
keyValue.put(field.getKey(), field);
}
}
}
public void setKeyValue(Map<String, FlexField> keyValue) {
this.keyValue = keyValue;
}
public Map<String, Flex> getKeyValue() {
return keyValue;
}
}
The input with managedBean is ready.
How can I get the val value in Flex class through getKeyValue() method with EL?
My approach is this: ${managedBeanName.keyValue['key'].val}
but I get this warning in my IDE
Reference ${managedBeanName.keyValue['key'].val} not found
You don't need to type get in order to invoke a getter.
${managedBeanName.keyValue['key'].val}

proxy pattern no suitable methods found to override? Help i'm not sure what just went wrong

This is all in the form...
namespace Proxy_Pattern
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
double bankAmount = 1000.00;
private void btnCheck_Click(object sender, EventArgs e)
{
double amount;
amount = double.Parse(txtAmount.Text);
CheckProxy cp =new CheckProxy();
cp.CheckTransactionRequest(amount);
lbltotal.Text = bankAmount.ToString();
}
private void btnCreditCard_Click(object sender, EventArgs e)
{
}
}
abstract class BankSubject
{
public abstract void CreditTransactionRequest(double amount);
public abstract void CheckTransactionRequest(double amount);
}
class RealBankSubject : BankSubject
{
double bank;
public RealBankSubject(double m_bacc)
{
bank = m_bacc;
}
public override void CreditTransactionRequest(double num)
{
bank -= num;
}
public override void CheckTransactionRequest(double num)
{
bank += num;
}
}
Does not implement inherited abstract members.... but why?
class CreditCardProxy : BankSubject
{
RealBankSubject realSubject;
double amount;
public CreditCardProxy (double m_bacc)
{
amount = m_bacc ;
}
no suitable method to override?... how is this an error? I have a method right here?
public override void CreditTransactionRequest()
{
if (realSubject == null)
{
realSubject = new RealBankSubject(amount);
}
realSubject.CreditTransactionRequest(amount);
}
public override void CheckTransactionRequest()
{
}
}
class CheckProxy : BankSubject
{
RealBankSubject realSubject;
double amount;
public override void CreditTransactionRequest()
{
}
public override void CheckTransactionRequest()
{
if (realSubject == null)
{
realSubject = new RealBankSubject(amount);
}
realSubject.CheckTransactionRequest(amount);
}
}
}
In your proxy, you are not specifying the amount as a parameter to the method:
public override void CreditTransactionRequest();
So it cannot override
public abstract void CreditTransactionRequest(double amount);
as the method signature doesn't not match
CreditTransactionRequest in CreditCardProxy does not take any arguments but CreditTransactionRequest in BankSubject does. This is why you can not override the method the signatures do not match.

generic delete does not work?

I have this abstract repository class with a Delete method:
public abstract class MyRepository<C, T> :
IMyRepository<T>
where T : class
where C : ObjectContext, new()
{
private C _entities = new C();
public C Context
{
get { return _entities; }
set { _entities = value; }
}
public virtual void Delete(T entity)
{
_entities.Attach(entity);
_entities.DeleteObject(entity);
_entities.SaveChanges();
}
}
however this does not compile? how can I Create a generic delete method here?
Instead of this
private C _entities = new C();
Use Activator.CreateInstance:
private C _entities = Activator.CreateInstance<T>();
Modify your Delete method as follows
public virtual void Delete(T entity)
{
_entities.CreateObjectSet<T>().Attach(entity);
_entities.DeleteObject(entity);
_entities.SaveChanges();
}
public virtual void Update(T entity)
{
_entities.CreateObjectSet<T>().Attach(entity);
_entities.ObjectStateManager
.ChangeObjectState(entity, System.Data.EntityState.Modified);
_entities.SaveChanges();
}

Ninject summon graphs with argument

Here is my problem. I have a presenter class, lets call it 'Presenter' that takes an IDataSource as a constructor argument. There are different implementations of the IDataSource interface. I would like to be able to pass some argument to Ninject and based on that argument one of several IDataSource implementations should by used. I've provided some sample code below. I think that my solution is really ugly and that there must be a smarter, cleaner way to do this. How are you guys solving this type of problem?
Here is my sample code
public class Presenter
{
public Presenter(IDataSource dataSource)
{
DataSource = dataSource;
}
private IDataSource DataSource { get; set; }
public List<string> GetData()
{
return DataSource.GetAll();
}
}
public class InMemoryDataSource : IDataSource
{
public List<string> GetAll()
{
return new List<string> {"a", "b"};
}
}
public class DbDataSource : IDataSource
{
public List<string> GetAll()
{
return new List<string> { "1", "2" };
}
}
public interface IDataSource
{
List<string> GetAll();
}
public class Module : NinjectModule
{
public override void Load()
{
Bind<Presenter>().To<Presenter>().Named("Db");
Bind<Presenter>().To<Presenter>().Named("InMemory");
Bind<IDataSource>().To<InMemoryDataSource> ().WhenParentNamed("InMemory");
Bind<IDataSource>().To<DbDataSource>().WhenParentNamed("Db");
}
}
[Test]
public void Run()
{
using (var kernel = new StandardKernel(new Module()))
{
var p = kernel.Get<Presenter>(x => x.Name == "InMemory");
foreach(var s in p.GetData())
{
Console.Out.WriteLine(s);
}
}
}
This depends on what you want to do. I assume that you want to use a different db for testing than for production. In this case would create the module with the production configuration in mind and simply Rebind everything for testing:
public class Presenter
{
public Presenter(IDataSource dataSource)
{
DataSource = dataSource;
}
private IDataSource DataSource { get; set; }
public List<string> GetData()
{
return DataSource.GetAll();
}
}
public class InMemoryDataSource : IDataSource
{
public List<string> GetAll()
{
return new List<string> {"a", "b"};
}
}
public class DbDataSource : IDataSource
{
public List<string> GetAll()
{
return new List<string> { "1", "2" };
}
}
public interface IDataSource
{
List<string> GetAll();
}
public class Module : NinjectModule
{
public override void Load()
{
Bind<Presenter>().To<Presenter>();
Bind<IDataSource>().To<DbDataSource>();
}
}
[Test]
public void Run()
{
using (var kernel = new StandardKernel(new Module()))
{
kernel.Rebind<IDataSource>().To<InMemoryDataSource>();
var p = kernel.Get<Presenter>();
foreach(var s in p.GetData())
{
Console.Out.WriteLine(s);
}
}
}

Resources