Git Product home page Git Product logo

ionad's Introduction

Ionad.Fody

Chat on Gitter NuGet Status

Ionad replaces static types with your own.

See Milestones for release notes.

This is an add-in for Fody

It is expected that all developers using Fody become a Patron on OpenCollective. See Licensing/Patron FAQ for more information.

Usage

See also Fody usage.

NuGet installation

Install the Ionad.Fody NuGet package and update the Fody NuGet package:

PM> Install-Package Fody
PM> Install-Package Ionad.Fody

The Install-Package Fody is required since NuGet always defaults to the oldest, and most buggy, version of any dependency.

Your Code

[StaticReplacement(typeof(DateTime))]
public static class DateTimeSubstitute
{
    public static IDateTime Current { get; set; }

    public static DateTime Now { get { return Current.Now; } }
}

public void SomeMethod()
{
    var time = DateTime.Now;
    // ...
}

What gets compiled

public void SomeMethod()
{
    var time = DateTimeSubstitute.Now;
    // ...
}

You can also reference methods within the original static class to add defaults to optional parameters. For example:

[StaticReplacement(typeof(System.Reactive.Linq.Observable))]
public static class QueryableSubstitute
{
    public static IObservable<IList<TSource>> Delay<TSource>(this IObservable<TSource> source, TimeSpan timeSpan)
    {
        return Linq.Delay<TSource>(source, timeSpan, RxApp.TaskpoolScheduler);
    }
}

public async Task<int> SomeMethod()
{
    return await Observable.Return(1).Delay(TimeSpan.FromSeconds(1)).ToTask();
}

What gets compiled

public async Task<int> SomeMethod()
{
    return await Observable.Return(1).Delay(TimeSpan.FromSeconds(1), RxApp.TaskpoolScheduler).ToTask();
}

Icon

Interchange designed by Laurent Patain from The Noun Project.

ionad's People

Contributors

arontsang avatar dependabot-preview[bot] avatar dependabot-support avatar dependabot[bot] avatar distantcam avatar geertvanhorrik avatar simoncropp avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ionad's Issues

Ionad does not support method overloading

Ionad always picks up the FIRST method overload with the correct name, and does not implement overloading resolution correctly.

In the below example we get an InvalidProgramException. But if you swap the order of declaration of the two overloads of TaskRx.Delay, the program runs.

    class Program
    {
        static async Task<int> Main(string[] args)
        {
            await Task.Delay(100000);
            return 0;
        }

    }

    [StaticReplacement(typeof(Task))]
    public static class TaskRx
    {

        public static Task Delay(int delay, CancellationToken cancellationToken)
        {
            return Observable.Timer(TimeSpan.FromMilliseconds(delay)).ToTask(cancellationToken);
        }

        public static Task Delay(int delay)
        {
            return Observable.Timer(TimeSpan.FromMilliseconds(delay)).ToTask();
        }
    }

Weave to-be-test dll in unit test project

My project is using some static class's static method and should not be weaved in production environment. However when I unit test this project, I need to replace the static class's static method to mock it's behavior, How can I achieve this?
The current situation is, when I add the nuget package to my Unit Test project, the to-be-test dll won't be weaved; if I add the nuget package to my to-be-test project, the weaved dll can not be used in production.
What I expect is, when build my unit test project, the to-be-test dll will be copied to my unit test project's output directory and that dll will be weaved.
Any idea?

Is it possible to run Ionad on-demand?

I'm evaluating if Fody + Ionad is an option for a project I'm building, and that would require me to write a small console app that I can pass some assembly file paths and then run Fody + Ionad to perform some replacements of static function calls on these assemblies.

Is this a supported scenario for Fody & Ionad? Any pointers on how to go about it?

Clarify how to specify scope of replacement class.

From ReadMe is not clear, how to specify the scope of replacement. E.g. When calling from test code I want to use DateTimeSubstitute, but when calling from production code I want to use DateTime. Please clarify in documentation.
Btw, why Ionad?

Doe this work for Static Method

Does Ionad work on static methods. My substitute isn't being called when running my spec.

Substitute

    [StaticReplacement(typeof(AppUtils))]
    public static class AppUtilsSubsitute
    {
        public static void LogException(string func, Exception ex) => Write("Exception", ex.ToJson());

        public static void LogError(string err) => Write("Error", err);

        public static void LogInfo(string info) => Write("Info", info);

        public static void LogWarning(string info) => Write("Warning", info);

        public static void LogCypherQuery(string func, ICypherFluentQuery query) => Write(func, query.ToJson());

        static void Write(string logType, string message)
        {
            var dictionary = new Dictionary<string, string> { { logType, message } };
            var assembly = Assembly.GetExecutingAssembly();
            using (var writer = new StreamWriter(assembly.Location + "Machine.Specifications.log"))
            {
                writer.Write(dictionary.ToJson());
            }
        }

        public static Dictionary<string, string> Log()
        {
            var assembly = Assembly.GetExecutingAssembly();
            Dictionary<string, string> content;
            using (var reader = new StreamReader(assembly.GetManifestResourceStream("Machine.Specifications.log")))
            {
                content = JsonConvert.DeserializeObject<Dictionary<string, string>>(reader.ReadToEnd());
            }
            return content;
        }
    }

Dependent Method

[AttributeUsage(AttributeTargets.Method)]
    public class EnsurePresencesOfAttribute : ActionFilterAttribute
    {
        internal virtual string Required { get; }
        internal virtual string Param { get; }
        public EnsurePresencesOfAttribute(string required = "", string param="request")
        {
            Required = required;
            Param = param;
        }

        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            Dictionary<string, object> model = actionContext.ActionArguments;
            if (model == null || model.Count == 0 || !model.ContainsKey(Param))
            {
                ValueError(actionContext, $"{Param} parameter");
                return;
            }
            foreach (var requirement in Required.Split(',').Select(e => e.Trim()))
            {
                if (model[requirement] == null)
                {
                    ValueError(actionContext, requirement);
                    return;
                }
            }
            base.OnActionExecuting(actionContext);
        }

        public override Task OnActionExecutingAsync(HttpActionContext context, CancellationToken token)
        {
            Dictionary<string, object> model = context.ActionArguments;
            if(model == null || model.Count == 0 || !model.ContainsKey(Param))
            {
                ValueError(context, $"{Param} parameter");
                return Task.FromResult(0);
            }
            foreach (var requirement in Required.Split(',').Select(e => e.Trim()))
            {
                if (model[requirement] == null)
                {
                    ValueError(context, requirement);
                    Task.FromResult(0);
                }
            }
            return base.OnActionExecutingAsync(context, token);
        }

        private static void ValueError(HttpActionContext context, string requirement)
        {
            var action = context.ActionDescriptor.ActionName;
            AppUtils.LogError($"{action} Failed : Missing Required Attribute {requirement}. ");
            using (var controller = new BaseApiController { Request = new HttpRequestMessage() })
            {
                controller.Request.Properties.Add(HttpPropertyKeys.HttpConfigurationKey, new HttpConfiguration());
                context.Response = controller.InvalidInputResponse();
            }
        }
    }

Update to Fody Version 2

Fody Version 2 is out and you will need to do an update for your addin to be usable with it

Specifically:

  • Update to the newest Fody.Cecil nuget
  • Change the min dependency range for Fody to be at least 2.0

Please ping me if u need help

Unable to weave async/await

Fody 4.2.1
Ionad.Fody 1.0.2
MsBuild 15
VS2017

Trying to weave

public static TaskRx
{
public Task Delay(int delay)
{
return Observerable.Timer(delay, RxApp.BackgroundThreadScheduler).ToTask();
}
}

Possibly because I was trying to weave this inside a lambda, will try to create a SSCCE tomorrow at work.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.