This is my sample test,
[Theory]
[BeforeAfterMethod]
[ClassData(typeof(GetTestData))]
public void Test3(int a)
{
ReporterLogs.Pass("value of a: " + a);
//TODO
}
And my GetTestData class is,
public class GetTestData : IEnumerable<object[]>
{
private string _currentTestMethodName;
private List<object[]> _data = new List<object[]>();
public GetTestData()
{
Console.WriteLine(**Print test method name here**);
_data.Add(new object[] { 10 } });
}
public IEnumerator<object[]> GetEnumerator()
{
return _data.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
I want to print the current test(i.e. Test3 in this case) method name inside GetTestData class. How it can be achieved. Thanks in advance.
It can be achieved by using DataAttribute in Xunit as follows,
public class GetTestData : DataAttribute
{
private List<object[]> _data = new List<object[]>();
public override IEnumerable<object[]> GetData(MethodInfo testMethod)
{
if (testMethod == null)
throw new ArgumentNullException(testMethod.Name);
_data.Add(new object[] { 10 });
return _data;
}
}
Related
Take this pseudo example code:
static System.Runtime.InteropServices.ComTypes.IEnumString GetUnmanagedObject() => null;
static IEnumerable<string> ProduceStrings()
{
System.Runtime.InteropServices.ComTypes.IEnumString obj = GetUnmanagedObject();
var result = new string[1];
var pFetched = Marshal.AllocHGlobal(sizeof(int));
while(obj.Next(1, result, pFetched) == 0)
{
yield return result[0];
}
Marshal.ReleaseComObject(obj);
}
static void Consumer()
{
foreach (var item in ProduceStrings())
{
if (item.StartsWith("foo"))
return;
}
}
Question is if i decide to not enumerate all values, how can i inform producer to do cleanup?
Even if you are after a solution using yield return, it might be useful to see how this can be accomplished with an explicit IEnumerator<string> implementation.
IEnumerator<T> derives from IDisposable and the Dispose() method will be called when foreach is left (at least since .NET 1.2, see here)
static IEnumerable<string> ProduceStrings()
{
return new ProduceStringsImpl();
}
This is the class implementing IEnumerable<string>
class ProduceStringsImpl : IEnumerable<string>
{
public IEnumerator<string> GetEnumerator()
{
return new EnumProduceStrings();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
And here we have the core of the solution, the IEnumerator<string> implementation:
class EnumProduceStrings : IEnumerator<string>
{
private System.Runtime.InteropServices.ComTypes.IEnumString _obj;
private string[] _result;
private IntPtr _pFetched;
public EnumProduceStrings()
{
_obj = GetUnmanagedObject();
_result = new string[1];
_pFetched = Marshal.AllocHGlobal(sizeof(int));
}
public bool MoveNext()
{
return _obj.Next(1, _result, _pFetched) == 0;
}
public string Current => _result[0];
void IEnumerator.Reset() => throw new NotImplementedException();
object IEnumerator.Current => Current;
public void Dispose()
{
Marshal.ReleaseComObject(_obj);
Marshal.FreeHGlobal(_pFetched);
}
}
I knew i can! Despite guard, Cancel is called only one time in all circumtances.
You can instead encapsulate logic with a type like IterationResult<T> and provide Cleanup method on it but its essentially same idea.
public class IterationCanceller
{
Action m_OnCancel;
public bool Cancelled { get; private set; }
public IterationCanceller(Action onCancel)
{
m_OnCancel = onCancel;
}
public void Cancel()
{
if (!Cancelled)
{
Cancelled = true;
m_OnCancel();
}
}
}
static IEnumerable<(string Result, IterationCanceller Canceller)> ProduceStrings()
{
var pUnmanaged = Marshal.AllocHGlobal(sizeof(int));
IterationCanceller canceller = new IterationCanceller(() =>
{
Marshal.FreeHGlobal(pUnmanaged);
});
for (int i = 0; i < 2; i++) // also try i < 0, 1
{
yield return (i.ToString(), canceller);
}
canceller.Cancel();
}
static void Consumer()
{
foreach (var (item, canceller) in ProduceStrings())
{
if(item.StartsWith("1")) // also try consuming all values
{
canceller.Cancel();
break;
}
}
}
I'm studying Vladimir Khorikov's Result class and how it can be used to chain Result operations.
Their original article can be found here.
Their original Result class code can be found here.
My edited Result class codes are as follows:
public class Result
{
private bool _isSuccess;
private string _errorMsg = "";
public bool IsSuccess()
{
return _isSuccess;
}
public bool IsFailure()
{
return !_isSuccess;
}
public string ErrorMsg()
{
return _errorMsg;
}
public Result(bool isSuccess, string errorMsg)
{
bool errorMsgIsEmpty = string.IsNullOrEmpty(errorMsg);
if (isSuccess && !errorMsgIsEmpty)
{
throw new Exception("cannot have error message for successful result");
}
else if (!isSuccess && errorMsgIsEmpty)
{
throw new Exception("must have error message for unsuccessful result");
}
_isSuccess = isSuccess;
if (!errorMsgIsEmpty)
{
_errorMsg = errorMsg;
}
}
public static Result Fail(string errorMsg)
{
return new Result(false, errorMsg);
}
public static Result<T> Fail<T>(string errorMsg)
{
return new Result<T>(default(T), false, errorMsg);
}
public static Result OK()
{
return new Result(true, "");
}
public static Result<T> OK<T>(T value)
{
return new Result<T>(value, true, "");
}
public static Result Combine(params Result[] results)
{
foreach (Result result in results)
{
if (result.IsFailure())
{
return result;
}
}
return OK();
}
}
public class Result<T> : Result
{
private T _value;
public T Value()
{
return _value;
}
public Result(T value, bool isSuccess, string errorMsg) : base(isSuccess, errorMsg)
{
_value = value;
}
}
I am working with the following test class:
public class Fruit
{
private string _name = "";
private StringBuilder _attribs;
public bool isBad;
public Fruit(string name)
{
_name = name;
_attribs = new StringBuilder();
}
public string Name()
{
return _name;
}
public string Attribs()
{
string attribs = _attribs.ToString();
if (attribs.Length > 0)
{
return attribs.Remove(attribs.Length - 2);
}
return attribs;
}
public void AddAttrib(string attrib)
{
_attribs.Append(attrib + ", ");
}
}
Below is the class that operates on Fruit:
public class FruitOperator
{
public static Result<Fruit> AddAttribToFruit(Fruit fruit, string attrib, bool fail)
{
if (fail)
{
return Result.Fail<Fruit>("failed");
}
fruit.AddAttrib(attrib);
return Result.OK<Fruit>(fruit);
}
public static void MarkFruitAsBad(Fruit fruit)
{
fruit.isBad = true;
}
}
I have created the following Result extension methods to match the function signatures of AddAttribToFruit and MarkFruitAsBad:
public static class ResultExtensions
{
public static Result<T> OnSuccess<T>(this Result<T> result, Func<T, string, bool, Result<T>> func, T val, string str, bool flag)
{
if (result.IsFailure())
{
return result;
}
return func(val, str, flag);
}
public static Result<T> OnFailure<T>(this Result<T> result, Action<T> action)
{
if (result.IsFailure())
{
action(result.Value());
}
return result;
}
}
My problem is when I try to use the result of OnSuccess in the next operation:
Fruit fruit = new Fruit("apple");
Result<Fruit> fruitResult = FruitOperator.AddAttribToFruit(fruit, "big", false)
.OnSuccess(FruitOperator.AddAttribToFruit, fruit, "red", true)
.OnFailure(lastFruitResult => FruitOperator.MarkFruitAsBad(lastFruitResult.Value()));
Above, lastFruitResult is actually a Fruit instead my expected Result<Fruit>.
Is there something wrong with my extension method signatures, or is there something that I need to change with how I'm using them?
Your signature in OnFailure is slightly wrong. Change it to OnFailure<T>(this Result<T> result, Action<Result<T>> action).
Basically an Action is a delegate that takes a number of parameters. The difference from Func is that Action doesn't return a value.
OnFailure<T>(this Result<T> result, Action<T> action) will let the consumer pass an action with the type T as input. In your case T is Fruit since it is actually defined in AddAttribToFruit because it returns Result<Fruit>.
By changing the signature to:
OnFailure<T>(this Result<T> result, Action<Result<T>> action) it will let the consumer create an action with the type Result<T>, which in your case is Result<Fruit>.
Your OnFailure should probably look something like this:
public static Result<T> OnFailure<T>(this Result<T> result, Action<Result<T>> action)
{
if (result.IsFailure())
{
action(result); // Note that result is Result<T> and action takes Result<T> as parameter
}
return result;
}
lastFruitResult will be the type definied within Action<here>.
I have a custom ConfigurationElementCollection called EnvironmentElementCollection to configure my different environments within a class library I'm writing. I have a static property in a class to get a collection of all the environments that are listed in that section. There is a property of the contained items (EnvironmentElement) that indicates the environment is a "login" environment. My goal is to be able to filter the collection with Linq to get only the "login" environments, but the Linq query always returns null. I implemented IEnumerable using this tutorial, but I can't figure out what I'm doing wrong.
Configuration Classes
public class EnvironmentSection : ConfigurationSection {
private static ConfigurationPropertyCollection properties;
private static ConfigurationProperty propEnvironments;
static EnvironmentSection() {
propEnvironments = new ConfigurationProperty(null, typeof(EnvironmentElementCollection), null, ConfigurationPropertyOptions.IsDefaultCollection);
properties = new ConfigurationPropertyCollection { propEnvironments };
}
protected override ConfigurationPropertyCollection Properties {
get {
return properties;
}
}
public EnvironmentElementCollection Environments {
get {
return this[propEnvironments] as EnvironmentElementCollection;
}
}
}
public class EnvironmentElementCollection : ConfigurationElementCollection, IEnumerable<EnvironmentElement> {
private static ConfigurationPropertyCollection properties;
public EnvironmentElementCollection() {
properties = new ConfigurationPropertyCollection();
}
protected override ConfigurationPropertyCollection Properties {
get {
return properties;
}
}
public override ConfigurationElementCollectionType CollectionType {
get {
return ConfigurationElementCollectionType.BasicMap;
}
}
public EnvironmentElement this[int index] {
get {
return (EnvironmentElement)base.BaseGet(index);
}
}
public EnvironmentElement this[string name] {
get {
return (EnvironmentElement)base.BaseGet(name);
}
}
protected override string ElementName {
get {
return "add";
}
}
protected override ConfigurationElement CreateNewElement() {
return new EnvironmentElement();
}
protected override object GetElementKey(ConfigurationElement element) {
var elm = element as EnvironmentElement;
if (elm == null) throw new ArgumentNullException();
return elm.Name;
}
//for implementing IEnumerable
public new IEnumerator<EnvironmentElement> GetEnumerator() {
int count = base.Count;
for (int i = 0; i < count; i++) {
yield return (EnvironmentElement)base.BaseGet(i);
}
}
}
public class EnvironmentElement : ConfigurationElement {
private static ConfigurationPropertyCollection properties;
private static ConfigurationProperty propLoginEnabled;
public EnvironmentElement() {
propLoginEnabled = new ConfigurationProperty("loginEnabled", typeof(bool), null, ConfigurationPropertyOptions.None);
properties = new ConfigurationPropertyCollection { propLoginEnabled };
}
[ConfigurationProperty("loginEnabled")]
public bool LoginEnabled {
get {
return (bool)base[propLoginEnabled];
}
}
}
And here is my class to get environments:
public class Environment {
//Works fine to get all environments
public static EnvironmentElementCollection All {
get {
EnvironmentSection dls = ConfigurationManager.GetSection("environments") as EnvironmentSection;
return dls.Environments;
}
}
//Returns null
public static EnvironmentElementCollection Login {
get {
EnvironmentSection dls = ConfigurationManager.GetSection("environments") as EnvironmentSection;
EnvironmentElementCollection envs = dls.Environments.Where<EnvironmentElement>(e => e.LoginEnabled == true) as EnvironmentElementCollection;
return envs;
}
}
}
So I can't tell which part is breaking, if my implementation of IEnumerable is bad, or my Linq query, or something else.
I've created a class which derives from IEnumerable<T>. T is a OQTemplate, and this one implements IXmlSerializable correctly. But I don't know how to implement the following class.
public class OQTemplateCollection : IEnumerable<OQTemplate>, IEnumerable
{
private readonly List<OQTemplate> entries;
public OQTemplateCollection()
{
this.entries = new List<OQTemplate>();
}
public OQTemplateCollection(IEnumerable<OQTemplate> source)
{
this.entries = new List<OQTemplate>(source);
}
public void Add(OQTemplate qt)
{
entries.Add(qt);
}
public IEnumerator<OQTemplate> GetEnumerator()
{
return entries.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public OQTemplate this[int index]
{
get { return entries[index]; }
}
}
I'd like just to have a XML like this:
<OQTemplateCollection>
<OQTemplate ... />
<OQTemplate ... />
</OQTemplateCollection>
There is the command hierarchy in my current application.
public interface ICommand
{
void Execute();
}
So, some commands are stateful, some are not.
I need to enumerate IEnumerable in the circular way for some command implementation during command execution.
public class GetNumberCommand : ICommand
{
public GetNumberCommand()
{
List<int> numbers = new List<int>
{
1, 2, 3
};
}
public void Execute()
{
// Circular iteration here.
// 1 => 2 => 3 => 1 => 2 => 3 => ...
}
public void Stop()
{
// Log current value. (2 for example)
}
}
Execute is called from time to time, so it is necessary to store the iteration state.
How to implement that circular enumeration?
I have found two solutions:
Using the IEnumerator<T> interface.
It looks like:
if (!_enumerator.MoveNext())
{
_enumerator.Reset();
_enumerator.MoveNext();
}
Using the circular IEnumerable<T> (yield forever the same sequence): “Implementing A Circular Iterator” - HonestIllusion.Com.
Maybe, there are more ways to achieve it.
What would you recommend to use and why?
Instead of dealing with IEnumerator interface,
foreach (var x in GetSomething())
{
if (someCondition) break;
}
public IEnumerable<int> GetSomething()
{
List<int> list = new List<int>() { 1, 2, 3 };
int index=0;
while (true)
yield return list[index++ % list.Count];
}
Here's one I just implemented as an extension.
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace DroopyExtensions
{
public static class CircularEnumaratorExtensionMethod
{
public static IEnumerator<T> GetCircularEnumerator<T>(this IEnumerable<T> t)
{
return new CircularEnumarator<T>(t.GetEnumerator());
}
private class CircularEnumarator<T> : IEnumerator<T>
{
private readonly IEnumerator _wrapedEnumerator;
public CircularEnumarator(IEnumerator wrapedEnumerator)
{
this._wrapedEnumerator = wrapedEnumerator;
}
public object Current => _wrapedEnumerator.Current;
T IEnumerator<T>.Current => (T)Current;
public void Dispose()
{
}
public bool MoveNext()
{
if (!_wrapedEnumerator.MoveNext())
{
_wrapedEnumerator.Reset();
return _wrapedEnumerator.MoveNext();
}
return true;
}
public void Reset()
{
_wrapedEnumerator.Reset();
}
}
}
}
To use it, all you have to do is
using DroopyExtensions;
class Program
{
static void Main(string[] args)
{
var data = new List<string>() {"One", "Two", "Tree"};
var dataEnumerator = data.GetCircularEnumerator();
while(dataEnumerator.MoveNext())
{
Console.WriteLine(dataEnumerator.Current);
}
}
}
You can use this extension method:
public static IEnumerable<T> Cyclic<T>(this IEnumerable<T> #this)
{
while (true)
foreach (var x in #this)
yield return x;
}
In that way:
public class GetNumberCommand : ICommand
{
private readonly IEnumerator<int> _commandState = new[] { 1, 2, 3 }.Cyclic().GetEnumerator();
public void Execute()
{
_commandState.MoveNext();
var state = _commandState.Current;
//
// Do stuff with state
//
}
public void Stop()
{
var state = _commandState.Current;
// Log state value. (2 for example)
}
}
while (!stop)
{
foreach (var i in numbers)
{
// do something
}
}
I think, the most comfortable way wil be to implement custom collection with custom enumerator and encapsulate circular logic in it.
class Collection<T> : IEnumerable<T>
{
bool circle;
List<T> collection = new List<T>();
public IEnumerable<T> IEnumerable<T>.GetEnumerator()
{
if(circle) return new CustomEnumerator<T>(this);
return circle.GetEnumerator();
}
}
class CustomEnumerator : Enumerator<T> {}
something like this...
You can write a circular enumerable without yield returns.
public class CircularEnumerable<T> : IEnumerable<T>
{
public CircularEnumerable (IEnumerable<T> sequence)
{
InfiniteLoop = sequence.Concat (this);
}
private readonly IEnumerable<T> InfiniteLoop;
public IEnumerator<T> GetEnumerator ()
{
return InfiniteLoop.GetEnumerator ();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator ()
{
return InfiniteLoop.GetEnumerator ();
}
}
public class GetNumberCommand : ICommand
{
public GetNumberCommand()
{
List<int> numbers = new List<int>
{
1, 2, 3
};
infiniteLoopOnNumbers = new CircularEnumerable<int>(numbers).GetEnumerator();
}
IEnumerator<int> infiniteLoopOnNumbers;
public void Execute()
{
infiniteLoopOnNumbers.MoveNext();
}
public void Stop()
{
int value = infiniteLoopOnNumbers.Current;
}
}