mardi 5 octobre 2021

C# Reflection: How to search assembly and get generic types [duplicate]

I have different audittrail factories for different events:

DomainEventA: DomainEvent
DomainEventB: DomainEvent

...

How can I iterate over each event deriving from DomainEvent and check if I have a AuditTrailFactory of T?

 foreach (var type in typeof(DomainEvent).Assembly.GetTypes().Where(x => !x.IsAbstract && x.IsSubclassOf(typeof(DomainEvent))))
            {
                Assert.NotNull(AuditTrailFactoryProvider.GetAuditTrailFactory<T>());
            }




lundi 4 octobre 2021

Is there a programmatic way to check whether specific CSS rules are valid or respected by the browser, or it is discarded / less specific?

In other words, I am looking for a way in JS to inspect or check current state of CSS rules dynamically at runtime (using browser's reflection feature, possibly) instead of only relying for browser developer's tool to see which rules are "overriden" or filtered. To think an analogy in procedural languages, there's normally a way to check the status or result of a statement or instruction (e.g true/false).

.mybutton#submit {
  color: red;
}
.mybutton {
  color: blue;
}
var sheet = document.styleSheets[0];
var rules = sheet.cssRules || sheet.rules;
is_valid(rules[0]); //True
is_valid(rules[1]); //False




Is there a fast way to uniquely identify a function caller in Go?

As a background, I have a logging facility that wants to output filename and line number, as well as manage some other unique-per-caller information. In c++ this is relatively straightforward using static variables, but I'm having trouble coming up with an equivalent in Go.

I've come across runtime.Caller(), which will get me the PC of the caller (and thus uniquely identify it), but clocking in at ~500ns it's not a cost I want to pay on every invocation of every log statement!

As a really basic example of the behaviour I have

package main

import (
        "fmt"
        "runtime"
)

type Info struct {
        file string
        line int
        // otherData
}

var infoMap = map[uintptr]Info{}

func Log(str string, args ...interface{}) {
        pc, file, line, _ := runtime.Caller(1)
        info, found := infoMap[pc]
        if !found {
                info = Info{file, line}
                infoMap[pc] = info
                // otherData would get generated here too
        }
        fmt.Println(info.file, info.line)
}

// client code
func foo() {
        // do some work
        Log("Here's a message with <> some <> args", "foo", "bar")
        // do more work
        Log("The cow jumped over the moon")
}

func main() {
        foo()
        foo()
}

This outputs

/tmp/foo/main.go 33
/tmp/foo/main.go 35
/tmp/foo/main.go 33
/tmp/foo/main.go 35

Now, runtime.Caller(1) is being evaluated on every call here. Ideally, it is evaluated once per statement.

Something like

func Log(str string, args ...interface{}) {
        uniqueId = doSomethingFasterThanCaller()
        info, found := infoMap[uniqueId]
        if !found {
                _, file, line, _ := runtime.Caller(1)
                info = Info{file, line}
                infoMap[pc] = info
                // otherData would get generated here too
        }
        fmt.Println(info.file, info.line)
}

Or even something done from the caller that allows it to be uniquely identified without hardcoding ids.

func Log(uniqueId int, str string, args ...interface{}) {
        info, found := infoMap[uniqueId]
        if !found {
                _, file, line, _ := runtime.Caller(1)
                info = Info{file, line}
                infoMap[uniqueId] = info
                // otherData would get generated here too
        }
        fmt.Println(info.file, info.line)
}

func Foo() {
   Log( uniqueIdGetter(), "message" )
   Log( uniqueIdGetter(), "another message" )

   // If I could get the offset from the beginning of the function
   // to this line, something like this could work.
   //
   //Log((int)(reflect.ValueOf(Foo).Pointer()) + CODE_OFFSET, "message")
}

Is this something that can be done natively, or am I stuck with the cost of runtime.Caller (which does a bunch of extra work above-and-beyond just getting the pc, which is really all I need)?





List of all possible values of a function

I have multiple objects each associated with a String. Is there some pattern that allows a type safe way to get the list of all Strings?

data MyObject = Foo | Bar 

getObjectString :: MyObject -> String
getObjectString Foo = "Foo"
getObjectString Bar = "Bar"

-- Bad because not type safe and String duplication
listOfAllObjectStrings :: [String]
listOfAllObjectStrings = ["Foo", "Bar"] 

Different solution that is still not type safe but reduces String duplication.

data MyObject = Foo | Bar 

getObjectString :: MyObject -> String
getObjectString Foo = listOfAllObjectString !! 0
getObjectString Bar = listOfAllObjectString !! 1

listOfAllObjectStrings :: [String]
listOfAllObjectStrings = ["Foo", "Bar"]




dimanche 3 octobre 2021

How to get values from derived classes by reflection in C# dynamically?

I have this code with one base class and two derived classes :

public abstract class BaseClass
    {
        public BaseClass(string message)
        {
            //TODO
        }
        public abstract int ErrorCode { get;  }
        public abstract string ErrorName { get; }
    }

    public class Concrete1 : BaseClass
    {
        public Concrete1(int p1, string message) : base(message)
        {
            //TODO
        }

        public override int ErrorCode { get; } = 1022;
        public override string ErrorName { get; } = "NotFound";
    }
    public class Concrete2 : BaseClass
    {
        public Concrete2(int p1, int p2, string message) : base(message)
        {
            //TODO
        }

        public override int ErrorCode { get; } = 1023;
        public override string ErrorName { get; } = "NotSettle";
    }

Now I want to get all derived classes by using reflection and getting their parameter values including ErrorCode and ErroName. this is my code for getting all derived classes that is working:

 public static List<Type> GetAllDerivedTypes(Type type)
    {
        var assemblies = AppDomain.CurrentDomain.GetAssemblies();
        _listTypes = new List<Type>();
        foreach (var item in assemblies)
        {
            _listTypes.AddRange(item
                .GetTypes()
                .Where(t => t != type && type.IsAssignableFrom(t))
                .ToList());
        }

        return _listTypes;
    }

but for getting values my code doesn't work:

   var listOfDerived = GetAllDerivedTypes(typeof(ExceptionBase));
        var src = listOfDerived.First();//for instance

        Type[] emptyArgumentTypes = Type.EmptyTypes;
        var p = ((ObjectType)Activator.CreateInstance(src, true)).GetType().GetConstructor(emptyArgumentTypes);

How can I solve this problem?





Best way to check if a field has a particular custom attribute

What is the best way to check if a field has a particular custom attribute?

My current approach is like so, but it seems a little redundant:

foreach (FieldInfo fi in typeof(ClassName).GetFields(BindingFlags.Instance | BindingFlags.NonPublic))
{
    if (fi.GetCustomAttribute<AttributeName>() is AttributeName)
    {
        Debug.Log($"my GetCustomAttribute check was true for {fi.Name}.");
    }
}




samedi 2 octobre 2021

How to detect null default value for non-typed class property via reflection in PHP?

When using reflection (ReflectionClass), is it possible to detect, whether a non-typed class property has a null default value specified, or has no default value at all?

class A {
    public $foo;
    public $bar = null;
}

Here, for both foo and bar, the ReflectionProperty::getDefaultValue() returns null and ReflectionProperty::hasDefaultValue() returns true.

$rc = new ReflectionClass(A::class);
var_dump($rc->getProperty("foo")->hasDefaultValue()); // true
var_dump($rc->getProperty("foo")->getDefaultValue()); // null
var_dump($rc->getProperty("bar")->hasDefaultValue()); // true
var_dump($rc->getProperty("bar")->getDefaultValue()); // null

How can I differentiate between the two properties?