vendredi 5 mars 2021

Why can't I catch this exception from a constructor?

In this test code, why does the test fail with an ArgumentNullException, despite that it is handled?

        [Test]
        public void ExceptionBehaviorTest()
        {
            // This works. An instance is returned
            var testInstance = (TestClass)Activator.CreateInstance(typeof(TestClass), "Hello World");
            Assert.NotNull(testInstance);

            // This passes. Exception is generated and caught
            Assert.Throws<ArgumentNullException>(() => new TestClass(null));

            try
            {
                // This throws ArgumentNullException but the catch handler is not invoked. This fails the test
                testInstance = (TestClass)Activator.CreateInstance(typeof(TestClass), (string)null);
                Assert.Fail("Should not get here");
            }
            catch (ArgumentNullException)
            {
            }
        }

        private sealed class TestClass
        {
            public TestClass(string arg)
            {
                Argument = arg ?? throw new ArgumentNullException(nameof(arg));
            }

            public string Argument
            {
                get;
            }
        }

If I run the code in the debugger, it stops in the TestClass ctor, saying that the exception is not handled. But the calling function is visible in the stack, so the problem is not related to some part being executed on a different thread.

[Background: In my real-world code, I'm iterating over a bunch of classes and testing whether they have a ctor with a specific argument. This is to prevent runtime errors later, as the classes are constructed using dependency injection.]





jeudi 4 mars 2021

Alternative to BeanUtils Java (error SonarQube)

I'm currently looking for a way to set dynamically a property into a Object, I have this:

public static void assign(Object instance, String attribute, Object value) {
    try {
        if (value != null) {
            BeanUtils.setProperty(instance, attribute, value);
        }
    } catch (IllegalAccessException | InvocationTargetException ex) {
        throw new TechnicalException(ex.getMessage(), ex);
    }
}

But Sonarqube throw me an error:

"Make sure that setting JavaBean properties is safe here."

So I need an alternative to fill my object dynamically or a way to avoid the exception in "BeanUtils.setProperty" (Avoid the exception because due to the nature of the project there are no risks of vulnerabilities).

Or some way to receive an object, and assign a field with a specific value by converting the data type of the value dynamically.

Any idea?

Beforehand thank you very much.





Why is AssemblyQualifiedName of anonymous type not always the same?

I was trying to find an anonymous type from a collection of assemblies by AssemblyQualifiedName, but though the anonymous type is present in the scanned assembly it's not found. GetTypes() seems to return types with other AssemblyQualifiedNames.

Why is that, and what can I do to find the type in the given assemblies?

    [Fact]
    public void AnonTypes()
    {
        var entity = new { SomeString = "Asger" };
        var type = entity.GetType();
        var assemblyQualifiedName = type.AssemblyQualifiedName;

        var types = type.Assembly.GetTypes()
            .Where(x => x.AssemblyQualifiedName == assemblyQualifiedName)
            .ToList();

        types.Count.ShouldBe(1);
    }

Please note that Type.GetType(assemblyQualifiedName) finds the type, but I can not use this method as I not always have the AssemblyQualifiedName, but some other qualifier to search for.

Also note that same thing happens if entity is a ValueTuple.





How to target scripts and its operations from multiple versions of a assembly which is compiling the script internally From a different application

Preqrequisite

  1. There are n versions of Web Application A.
  2. Creating Objects in A from UI creates its own database.
  3. When Application A is opened the URL which represents the path of version takes care of respective version when clicking on objects created in step 2
  4. Now to avoid making changes to code everytime based on clients request, A C# script addition facility is already provided in system. Which is being compiled during runtime and executed if already added in system. E.g. at the end of update from UI send a file to a location. This script has same namespace as our Application A and uses its property and methods
  5. System uses reflection to compile script and create instance of it and invoke its method based on its type e.g. the type of that is some Interface

Requirement I have an application B which updates to DB but now also has to perform same operation as mentioned in 4,5 for application A(this can be of any version, version found at runtime and assemblies are stored separately and can be derived using Assembly.Load).

SO I used reflection and somehow reached to the point where i can successfully compile the script but unable to proceed further from that.

1st problem :- The compiled script requires the the application A assembly for execution as namespace is same for both and script internally uses A's methods and properties. But this assembly must be present at dynamic location i.e. of Appdomain.current.dynamicdirectory, whose path cant be defined beforehand. This can be solved only if Application A's assembly is being referenced in source project of B, but then again question is if I am dealing with multiple versions how to add them all in source project

Questions

  1. Tried using Appdomain to set new appdomain but could not use it since I cannot modify Application A to have its proxyObject or to make its serializable since code is freezed.

  2. Thought of building a seperate web application but question is again how to make script inside Assembly A to invoke its content. so that process can be performed





Executing method by yaml

My yaml file is

myYaml.yaml
myVal1:  "println(\"Hello Yaml\")"
myVal: "if (1 == 1) println(\"First statement!\") else println(\"Second statement\")"

both executing successfully by my code in scala

So far I have a executed condition in yaml that runs successfully This variable 'myval' is in yaml file.

'''myVal: "if (1 == 1) println(\"First statement!\") else println(\"Second statement\")"'''

and This variable 'myval1' is in yaml file too.

'''myVal1: "println(\"Hello Yaml\")"'''
using
'''

import scala.reflect.runtime.universe
import scala.tools.reflect.ToolBox
'''

and in class i have

'''val myStringExecTest: ToolBox[universe.type] = universe.runtimeMirror(getClass.getClassLoader).mkToolBox()
   myStringExecTest.eval(myStringExecTest.parse(confVar2.getString("myVal1")))
'''

Now, I want to execute my function from yaml as

if abc//some variable from my class where yaml will be called
= true
do this
else if
xyz //some variable from my class where yaml will be called
do that
else 
this

I am unable to get values based on some variables from the class. How can I achieve this?





Reflection To check if field exist in containing class [duplicate]

class A{
   String name;
   B b;
}

class B{
   String text;
}

Now if I do A.class.getField("text"); This will give exception. How can I use reflection to see if field exist in Containing class B

If its a direct field in Class A reflection works. But if the field is within another containing Class Object(In this case class B) it wont retrieve the field





mercredi 3 mars 2021

How to I output the name of an input?

For example, if I have char character = a, how would I be able to print out it's name, which is "character", along with it's output within a single printf? I know I can do printf("character = %c", character);, but how can I still print out the input's name if I enter char something = b and make it print out "something = b" instead of "character = b"?