Apologies if this sounds complex my vocab isn't fully with me today.
I have an method where I want to use .click
Example
middle.click();
But I also have another
end.click();
What if I want to pass either "middle" or "end" as a parameter, is it possible to do so
MethodGo(string usedforSomethingElse, Func<string> thisMethod)
{
thisMethod.click();
}
It would have to look more like this:
MethodGo(string usedforSomethingElse, ISomeObjectWithClickMethod thisObject)
{
thisObject.click();
}
Or, you could do this:
MethodGo(string usedforSomethingElse, Func<string> thisMethod)
{
thisMethod();
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Student
{
public interface IMyClick
{
string click();
}
}
--------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Student
{
public class Middle : IMyClick
{
public string click()
{
return "Middle Click";
}
}
}
---------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Student
{
public class End :IMyClick
{
public string click()
{
return "End Click";
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Student;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
IMyClick m1 = new Middle();
IMyClick e1 = new End();
string result = MethodtoGo(m1);
Console.WriteLine(result);
Console.Read();
}
static string MethodtoGo(IMyClick cc)
{
return cc.click();
}
}
}
in the above code now you can pass the Middle or End class instance as both are implementing the same interface.
string result = MethodtoGo(m1);
The MethodToGo has one parameter of type interface, that mean any class that is implementing the interface can be pass as input to the method.
hope this helps.
Related
So I have the following ViewModel:
using Prism.Commands;
using Prism.Events;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using TrackIt.Model;
using TrackIt.UI.Event;
namespace TrackIt.UI.ViewModel
{
public class NavigationItemViewModel : ViewModelBase
{
private string _displayMember;
private IEventAggregator _eventAggregator;
private string _detailViewModelName;
public NavigationItemViewModel(int id,
IEventAggregator eventAggregator,
string detailViewModelName)
{
Id = id;
_detailViewModelName = detailViewModelName;
OpenDetailViewCommand = new DelegateCommand(OnOpenDetailViewExecute);
_eventAggregator = eventAggregator;
}
public int Id { get; }
public ICommand OpenDetailViewCommand { get; set; }
private void OnOpenDetailViewExecute()
{
_eventAggregator.GetEvent<TestEvent>()
.Publish(Id);
_eventAggregator.GetEvent<OpenDetailViewEvent>()
.Publish(
new OpenDetailViewEventArgs
{
Id = Id,
ViewModelName = _detailViewModelName
}
);
}
}
}
Thus I have an ICommand above, that upon executing, will trigger the TestEvent and OpenDetailViewEvent events, with the TestEvent having an integer argument, and the OpenDetailViewEvent having a custom class argument OpenDetailViewEventArgs class.
I'm testing that upon executing the command, the Publish method of each event is called. I use Moq to mock the GetEvent calls. This is my code:
using Moq;
using Prism.Events;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TrackIt.UI.Event;
using TrackIt.UI.ViewModel;
using Xunit;
namespace TrackIt.UITests.ViewModel
{
public class NavigationItemViewModelTests
{
[Fact]
public void ShouldPublishOpenFriendDetailViewEvent()
{
const string displayMember = "test string";
const int id = 4;
const string detailViewMemberName = nameof(FriendDetailViewModel); // Just take a random detail view
var _mockedOpenDetailViewEvent = new Mock<OpenDetailViewEvent>();
var _mockedTestEvent = new Mock<TestEvent>();
var eventAggregatorMock = new Mock<IEventAggregator>();
eventAggregatorMock
.Setup(dp => dp.GetEvent<OpenDetailViewEvent>())
.Returns(_mockedOpenDetailViewEvent.Object);
eventAggregatorMock
.Setup(dp => dp.GetEvent<TestEvent>())
.Returns(_mockedTestEvent.Object);
var _itemViewModel = new NavigationItemViewModel(id,
displayMember, eventAggregatorMock.Object, detailViewMemberName);
_itemViewModel.OpenDetailViewCommand.Execute(null);
_mockedTestEvent.Verify(e => e.Publish(id),
Times.Once);
_mockedOpenDetailViewEvent.Verify(e => e.Publish(new OpenDetailViewEventArgs { Id = id, ViewModelName = detailViewMemberName }),
Times.Once);
}
}
}
The thing is, the test passes the Verify for TestEvent event, but it fails for OpenDetailViewEvent with error Expected invocation on the mock once, but was 0 times, even though I debugged and saw the event actually published. Maybe it's because I'm supplying a custom class as its argument, while TestEvent uses a native C# class (i.e. int)? How to fix this?
Use an argument matcher instead since the instances can't be the same object reference in this scenario.
// ....
_mockedOpenDetailViewEvent
.Verify(
_ => _.Publish(It.Is<OpenDetailViewEventArgs>(arg => arg.Id == id && arg.ViewModelName == detailViewMemberName)),
Times.Once
);
It.Is above is used to create a predicate to match the argument that was used to invoke the member.
Hi Everyone sorry i have a question, i have a simple code to get cheaper books from a list, i use one class book with properties, one class to set the books to the list and one main program. here is the book class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AdvanceCSHarpLambda
{
public class Book
{
public string Title { get; set; }
public int Price { get; set; }
}
}
and here the BookRepository class (List)
using System;
using System.Collections.Generic;
namespace AdvanceCSHarpLambda
{
public class BookRepository
{
public List<Book> GetBooks()
{
return new List<Book>
{
new Book() {Title="T1", Price=1 },
new Book() {Title="T2", Price=2 },
new Book() {Title="T3", Price=3 }
};
}
}
}
and here the main program
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AdvanceCSHarpLambda
{
class Program
{
static void Main(string[] args)
{
var books = new BookRepository();
var cheapBooks = books.FindAll(bookCheaper);
foreach (var book in cheapBooks)
{
Console.WriteLine(book.Title);
}
}
static bool bookCheaper(Book book)
{
return book.Price < 10;
}
}
}
the problem is i got red line in books.FindAll(bookCheaper), any one can help me whats going on in this redline? thx before
You need to call GetBooks
books.GetBooks().FindAll(bookCheaper)
Your books should be a List, not BookRepository.
You need a Predicate for the FindAll function.
books.FindAll(x=>x.Price < 3)
Something like this.
The error I got :
"object" doesn't contain a definition for "test"
I also tried game.test() but I keep getting this error
This solution is divided in two distinct projects :
The first one is a .dll
The second one is a console
the goal is to call the get method from the 'iw4mp' class dynamicaly. So I would be able to call any from the class while it will be loaded.
the COD class should look useless but in the futur it will look if the process is running on the computer but for my test I use a string (but it actually work same way as if it was looking for a process).
Code from the DLL
COD
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CODOffsets.Interface;
using CODOffsets.Offsets;
namespace CODOffsets
{
public class COD
{
static string[] games = { "iw4mp", "iw5mp", "bo1" };
static Type CallofDuty;
public static bool checkGame()
{
foreach (string game in games)
{
if (ProcessHandle(game))
{
CallofDuty = Type.GetType("CODOffsets.Offsets" + "." + game);
return true;
}
}
return false;
}
public static object Game()
{
return Activator.CreateInstance(CallofDuty) as ICODClass;
}
public static bool ProcessHandle(string game)
{
if (game == "iw4mp")
return true;
else
return false;
}
}
}
Interface
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CODOffsets.Interface
{
interface ICODClass
{
string test { get; }
}
}
Offset
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CODOffsets.Interface;
namespace CODOffsets.Offsets
{
class iw4mp : ICODClass
{
public string test { get { return "this is mw2"; } }
}
}
Code from the Console project
Main
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CODOffsets;
namespace TestGenericClass
{
class Program
{
static void Main(string[] args)
{
if (COD.checkGame())
{
dynamic game = COD.Game();
Console.WriteLine(game.test);
Console.ReadKey();
}
}
}
}
It should basically work as the way you did. But, if not so, here are some alternatives.
you can use reflections in c# to get all the properties of the dynamic object.
var nameOfProperty = "test";
var propertyInfo = game.GetType().GetProperty(nameOfProperty);
var value = propertyInfo.GetValue(game, null);
Moreover, you can simply use this way to get the value if you know the property name
string value = game["test"];
There have two dll's namely
a) lib1
b) lib2
These two library are loaded using reflection( as against to adding a direct reference in visual studio). I'm creating an object of a class , then want to type cast that object to the type of the interface (interface being in the dll loaded in the main program). I get an error saying type mismatch. Any possible solution to this problem.
Here is my code block:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
namespace Interfaceconversion
{
class Program
{
public static object classobj;
public static object interfaceobj;
static void Main(string[] args)
{
// Loading assembley 1
Assembly assembly1 = Assembly.LoadFrom(#"D:\WCFService\Aug9\Interfaceconversion\Lib1\bin\Debug\Lib1.dll");
Type[] type1 = assembly1.GetTypes();
foreach (Type item in type1)
{
if (item.FullName.ToString() == "Lib1.Class1")
{
classobj = Activator.CreateInstance(item);
}
}
// Loading assembly 2
Assembly assembly2 = Assembly.LoadFrom(#"D:\WCFService\Aug9\Interfaceconversion\Lib2\bin\Debug\Lib2.dll");
Type[] type2 = assembly2.GetTypes();
Type libtype = type2[1];
foreach (Type item in type2)
{
if (item.FullName.ToString() == "Lib2.Ilib2Interface1")
{
TODO: cast the object "classobj " to type Lib2.Ilib2Interface1
interfaceobj = classobj as item ;
}
}
#region old code
}
}
Lib2 dll's code is :
lib2
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Lib2
{
interface Ilib2Interface1
{
void lib2disp1();
}
}
Lib1 code is :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Lib1
{
interface ISttutil
{
void displayutil1();
void displayutil2();
}
interface Isttinterface
{
void displayinterface1();
void displayinterface2();
}
}
We don't see lib1.Class1 in the example given, but provided it derives from the interface you want to cast it to, something like this should work:
lib1:
using lib2;
using System;
namespace lib1
{
public class Class1 : IInterface1
{
public void MethodOne ( )
{
Console.WriteLine ( "MethodOne called!" );
}
}
}
lib2:
namespace lib2
{
public interface IInterface1
{
void MethodOne ( );
}
}
Main:
using lib2;
using System;
using System.IO;
using System.Reflection;
namespace ConsoleApplication1
{
class Program
{
static void Main ( string [ ] args )
{
var fileInfo = new FileInfo ( #".\lib1.dll" );
var assembly = Assembly.LoadFile ( fileInfo.FullName );
var obj = assembly.CreateInstance ( "lib1.Class1" ) as IInterface1;
if ( obj != null ) obj.MethodOne ( );
Console.ReadLine ( );
}
}
}
I'm trying to create a simple index, which includes two fields from my document: TraceRowID, LoadDate.
So I've created the following class:
using Model;
using Raven.Abstractions.Indexing;
using Raven.Client.Indexes;
using Raven.Client.Linq;
using Raven.Client.Document;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Indexes
{
public class IDLoadDateIndex : AbstractIndexCreationTask<ServiceTrace>
{
public IDLoadDateIndex()
{
Map = serviceTrace => from st in serviceTrace
select new { ID = st.TraceRowID, LoadDate = st.LoadDate };
}
}
}
My model is "ServiceTrace":
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Model
{
public class ServiceTrace
{
public int TraceRowID { get; set; }
public string StatusDescription { get; set; }
public string FullExceptionText { get; set; }
public string LoadDate { get; set; }
}
}
And there goes my DAL:
using Indexes;
using Raven.Client.Indexes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DAL
{
public class DbConnection
{
private readonly static DbConnection instance = new DbConnection();
private Raven.Client.Document.DocumentStore documentStore;
static DbConnection()
{
}
private DbConnection()
{
this.documentStore = new Raven.Client.Document.DocumentStore { Url = "http://btadmins:8080/" };
this.documentStore.Initialize();
IndexCreation.CreateIndexes(typeof(IDLoadDateIndex).Assembly, this.documentStore);
}
public static DbConnection Instance
{
get
{
return instance;
}
}
public Raven.Client.Document.DocumentStore DocumentStore
{
get
{
return documentStore;
}
}
}
}
For some reason, when stepping over on debug mode on the "CreateIndexes" line, it is done succesfully. BUT I can't see any indexes added on the RavenDB management studio silverlight app.
What can be the problem ?
Perhaps you are looking in a named database in the studio? By not naming a specific database here, you are creating the index in Raven's system database.