I am using a library which measure metrics for running code.
The usage of the library is something like this.
_Library.Wrap("AnyStringForMetrics", Func<T>);
So whatever I pass into the Func as a lambda will be measured and result of it will be returned.
At the moment, I have method where I want to measure this line where it tries to create or get a user with that id. (newlyCreated will be true if the user was created)
public User GetOrCreate(long id, out bool newlyCreated) {
// some random checks
return UserDatabase.GetOrCreate(id, out newlyCreated);
}
But now, if I try to wrap my code around
public User GetOrCreate(long id, out bool newlyCreated) {
// some random checks
return _Library.Wrap(
"UserGetOrCreate", () => UserDatabase.GetOrCreate(id, out newlyCreated));
}
I will get an exception for using "out" inside lambda expression. How should I resolve this?
If possible please write out a concrete code example... Thanks.
Use a ValueTuple as return type instead and thus avoid using an out parameter.
public (User user, bool newlyCreated) GetOrCreate(long id) {
var user = ....;
bool created = ....;
return (user, created);
}
and map it to Func<(User, bool)>.
Related
What i got
So basically I am all over the a generic solution for a dll wrapper function to achieve logging/errorhandling easily. All my dll functions return a bool. dll is in c++
after looking at this and that that to name just a few i got to the point, that i basically do not care for the passed parameters of my dll function and all calls basically work like this:
ExecuteCommand(() => DllInterface.DllFunction([someParams]));
with
private static void ExecuteCommand(Func<bool> aCommand, string logmessage = null, bool DoThrow = true)
{
if (!aCommand())
{
if (DoThrow)
{
throw new Exception(DllInterface.LastError());
}
else
{
Log.Error(aCommand.Method.Name);
}
}
else
{
Log.Information(aCommand.Method.Name);
}
}
with that i should be able to call any function regardless of its signature.
problem is, I sometimes want to receive informations from the dll as well and therefore use ref or out.
since Func<bool> doesnt like ref i tried to do something like this:
public delegate V RefFunc<in T, U , out V>(T input, out U refType);
according to link one. this works fine as long T and V are nice types, but i couldn't found a solution, to write a lambda if Tis a Func<bool>. Test usage was implented in this way;
RefFunc<double, int, bool> refFunc = (double adouble, out int testint) =>
{
testint = (int)Math.Truncate(adouble);
return true;
};
Reffunc(adouble, out int aInt);
what i wanted (and already got)
is basically a overload of Execute command which accepts
ExecuteCommand(() = > DllInterface.DllFunctions(ref int rval));
and actually executes
...if(!acCommand(ref rval) ...
is this possible?
Answer
The Answer was already there, as it turns out I can pass any functions to the current ExecuteCommand(), since the signature passed as a command is defined by the Lambda, not the function the Lambda is calling.
Hey i was wondering if i can convert an Expression to an Action.
I need to use the Expression to get the details of the lambda expression and at the same time i need to execute it using a different method. I need to get the Expression and the actual action with just using a single parameter (either Action or Expression):
BTW i need this for Getting details on what kind of assert i did. ex(Assert.true, Assert.False)
public void otherMethod()
{
SomeMethod(() => Assert.Equals("Dog","Cat"));
}
public void SomeMethod(Expression<Action> neededAction) //or public void SomeMethod(Action neededAction)
{
//i need to run the neededAction and get the details whether what assert i did and the inputs i used for the assertion
}
So basically i need to run the Action and i need to get its method infos.
Thanks~
You need to call Compile() on the expression.
// Compile it.
var actualNeededAction = neededAction.Compile();
// Execute it.
actualNeededAction();
I'm trying to create some unit tests for an application I've recently inherited. Currently using NSubstitute because that's what the previous programmer used, but I'm not attached to it.
The method I'm testing calls the DataService class' Create method.
Calling Create Method
var contactProductLink = this.dsService.Create<ContactProductLink>(x =>
{
x.ContactRoleId = prod.RoleId;
x.ContactId = contactViewModel.ContactId;
x.ProductId = prod.ProductId;
x.Active = true;
x.InsertDate = DateTime.Now;
x.InsertUserId = user.employeeId;
x.UpdateDate = DateTime.Now;
x.UpdateUserId = user.employeeId;
});
DataService Create Method:
public TEntity Create<TEntity>(Action<TEntity> propertySetter = null) where TEntity : class
{
var tEntity = this.Context.Create<TEntity>();
if (propertySetter != null)
{
propertySetter(tEntity);
}
return tEntity;
}
The approach I've taken (and maybe there's a better way) is to use NSubstitute to mock the DataService. When I'm doing my assertions at the end, I'm checking to make sure that the Create method was called:
mockDataSupplierService.Received().Create<ContactProductLink>(Arg.Any<Action<ContactProductLink>>());
However, I'd like to also verify the input that was sent to the method is correct, and here's where I'm running into trouble. I can get the System.Action object that was passed to the Create method, but I can't figure out how to pull out the parameters (such as ContactRoleId, ContactId, etc. as posted in the calling create method code snippet).
So after all of that what I'm asking is:
How can I access those input parameters so I can verify the correct arguments are being passed to the data service? Is it even possible?
Is there a better way to do this than what I'm currently trying to do?
Solution
//Arrange
mockDataSupplierService.Create<ContactProductLink>(Arg.Do<Action<ContactProductLink>>(x=> actionToPopulateEntity = x));
//Assert
mockDataSupplierService.Received().Create<ContactProductLink>(Arg.Any<Action<ContactProductLink>>());
var entity = new ContactProductLink();
actionToPopulateEntity.Invoke(entity);
Assert.AreEqual(ExpectedContactId, entity.ContactId);
How can I access those input parameters so I can verify the correct arguments are being passed to the data service? Is it even possible?
Essentially you can't, as it is not possible to extract "code" details from action (consider what happens when you pass an action that doesn't set any properties - this is totally legal, but would break hypothetical mechanism).
However, you can try this instead:
Create entity with initial values
Use Arg.Invoke argument, telling NSubstitute to use chosen object as action parameter
Verify that entity properties values changed
For example:
// Arrange
var entity = new ContactProductLink
{
ContactRoleId = // ...
// ...
};
mockDataSupplierService
.Create<ContactProductLink>(Arg<ContactProductLink>.Invoke(entity));
// Act
// ...
Assert.That(entity.ContactRoleId, Is.EqualTo(2));
// ...
Actually I need to know how this line is getting executed.
Example:
Browser("InternetExplorer").Page("Stackoverflow").WebElement("textbox").set "user"
The above lines executes like setting browser to Internet Explorer and finding page "stackoverflow" in it and then finding webelement "textbox" in it and then sets it values to "user". in this way the operation is done.
I want to know how this sequence call are be done. I don't want how browser is set to Internet Explorer and so on.
I need to execute a simple statement like
Fun("add").values("2,3").compute
I need the above line to execute by calling "add" function then values "2,3" are passed as parameter then "compute" add it and the final result should "5" be return.
How to do this? Whether we have to use different class for "Fun" and "values" or we need to implement them as "functions" of same class.
How to process sequence call ?
It is enough to return a reference to an existing object to achieve this effect:
class Operator
{
public:
Operator(const string& opAsStr)
{
...
}
Operator& Values(const string& operands)
{
....
return *this;
}
int Compute() // Compute must be a function, no properties in C++
{
...
}
};
// Usable like this
Operator("Add").Values("2,3").Compute()
By defining more function returning *this you can chain many calls. Note that you could return a value (i.e. Operator instead of a reference, or a const reference depending on your use cases).
You can also return a reference (or value) to an object of another class:
class A
{
public:
void DoSomething()
{
....
}
};
class B
{
public:
A MakeA()
{
return A();
}
};
B().MakeA().DoSomething();
I have the following code which I am are currently using .... Basically, this method assigns the correct boolean flag (TRUE/FALSE) for each Task. As more and more tasks need to be added .. I can see that the switch statement will have to grow to cater for every task.
There has to be an easier way ... to keep the method small.
Code: (forget naming convention, it has been changed for posting)
public ClassStructure.User AssignTaskStatusToUser(ClassStructure.User,
List<ClassStructure.Tasks> TaskStatus)
{
foreach (ClassStructure.Tasks data in TaskStatus)
{
string Task_CallID = data.Task_Call_ID;
switch (Task_CallID)
{
case ClassStructure.Tasks_CallIDs_Strings.TASK1:
User.TASK1 = data.Task_Flag;
break;
case ClassStructure.Tasks_CallIDs_Strings.TASK2:
User.TASK2 = data.Task_Flag;
break;
case ClassStructure.Tasks_CallIDs_Strings.TASK3:
User.TASK3 = data.Task_Flag;
break;
}
}
return User;
}
ClassStructure.Tasks_CallIDs_Strings = String Representation of the Tasks
data.Task_Flag = boolean
User.TASKX = boolean
Any feedback is welcome. I am sure there is an easy solution.
For a lot of values like these, I would use a map something like this:
Dictionary<ClassStructure.Tasks_CallIDs_Strings, Task_Flag>
and retrieve values by mapping the CallIDs strings.
Edit:
As everyone can now see, the real problem of refactoring this example lies in refactoring User.TASKX. Making it a list should suffice - as it could then be indexed by the same string ClassStructure.Tasks_CallIDs_Strings
Oh... Reconsider your naming scheme.
public delegate void TaskAssigner(User user, bool taskFlag)
IDictionary<string, TaskAssigner> taskAssigners = new Dictionary<string, TaskAssigner>();
...
taskAssigners.Add(ClassStructure.Tasks_CallIDs_Strings.TASK1, (u, t) => u.TASK1 = t;);
taskAssigners.Add(ClassStructure.Tasks_CallIDs_Strings.TASK2, (u, t) => u.TASK2 = t;);
...
foreach(ClassStructure.Tasks data in TaskStatus)
taskAssigners[data.Task_Call_ID](user, data.Task_Flag);
I was thinking something like this - but maybe I missed the point of what it is all for?
public class User
{
private Dictionary<string,Task> tasks;
internal Dictionary<string,Task> Tasks
{
get { return tasks; }
set { tasks = value; }
}
internal void AddTask(Task task)
{
tasks.Add(task.Task_Call_ID,task);
}
internal void AddTasks(List<Task> task)
{
foreach(Task task in Tasks)
{
tasks.Add(task.Task_Call_ID,task);
}
}
}
The Task class could have properties that allowed you to pass a function pointer (to the function that actually executes a task) if you needed that kind of flexibility - and you could add other methods like ExecuteTasks to User as well...
Could you have an array/list of tasks instead and use Task_CallID as an index into that?
e.g.
User.Tasks[Task_CallID] = data.Task_Flag;
If you must have them all as members there are other options:
Maintain a mapping from Task_Call_ID to PropertyInfo reference and use that to set the correct property
Use reflection to find the property based on the number bit (X) and set that property
Both of these are reflection based and a bit nasty.
Why not make a Users Tasks structured as a list:
User Class
public List<ClassStructure.Tasks> Tasks {
get; set;
}
Your Method becomes:
public void AssignTasks(User user, List<ClassStructure.Tasks> TaskStatus)
{
user.Tasks.AddRange(TaskStatus)
}
Which is to say that you don't need the method at all.
Your accessor then becomes running Find on a user's Tasks and checking the Tasks flag.
Dictionary is a great alternative for this. However, when a switch/case gets very complex look at using the strategy pattern (not for your scenario though).