vendredi 3 avril 2020

How to make an objects implements Serializable through Reflection dynamically?

I have to add implements Serializable dynamically in an object(different classes as Object) to as Spring requires some functionality. I found workarounds but it does not fit because the adapter pattern is not compatible with with "dynamically" term. I found Proxy.newProxyInstance() but it creates only a new instance of interface or class and doesn't make a class implement an interface. And I didn't find any methods that I might use in getClass()

Do you know how to do this?





How to get class which invokes static method?

This is my code:

class A {

    public static void doIt() {
        //Class currentClass = new Object() { }.getClass().getEnclosingClass();
        //Class currentClass = MethodHandles.lookup().lookupClass();
        String currentClass = Thread.currentThread().getStackTrace()[1].getClassName();
        System.out.println("CALLING CLASS:" + currentClass);
    }
}

class B extends A { }

public class NewMain {

    public static void main(String[] args) {
        A.doIt();
        B.doIt();
    }
}

As you see doIt method can be called by A and B classes. In doIt I want to know what class was used to call method (A or B). Is it possible? Three solutions I tried didn't work - it always says A class.





How to pass data from View to Controller, when View was genereted by reflection object?

Environment:

ASP.NET Core MVC 3.1 and Library .NET Standard

Goals:

  1. Create object from DLL (dll can be changed at any moment) with no constant structure, ex. class Obj{ int, string, string}, but another dll will has class Obj {int, int, int}.

  2. Pass this object to view.

  3. Generate single "form box" without knowing what properties have object. ex. string => textbox, bool => checkbox etc.

  4. Pass this data to method/controller/api.

My problem:

On that moment I can first three points, but I can't pass data to the Controller. I tried debug it, but method Index(int x, int y) always is call with params x = 0, y = 0.

Code:

HomeController.cs

    [HttpGet]
    public IActionResult Index()
    {
        Assembly dllAssembly = Assembly.LoadFile(Environment.CurrentDirectory + 
                                                 "\\TestLib.dll");
        Type dllType = dllAssembly.GetType("TestLib.TestModel");
        tempObj = Activator.CreateInstance(dllType);

        ViewBag.Message = tempObj;
        return View();
    }
    [HttpPost]
    public IActionResult Index(int x, int y)
    {
        Assembly dllAssembly = Assembly.LoadFile(Environment.CurrentDirectory + 
                                                 "\\TestLib.dll");
        Type dllType = dllAssembly.GetType("TestLib.TestModel");
        tempObj = Activator.CreateInstance(dllType);

        dllType.GetProperty("X").SetValue(tempObj, x);
        dllType.GetProperty("Y").SetValue(tempObj, y);

        ViewBag.Message = tempObj;
        return View();
    }

TestModel.cs

public class TestModel
{
    [Range(0, 10)]
    public int X { get; set; }
    [Range(0, 10)]
    public int Y { get; set; }
}

Index.cshtml

@{
    ViewData["Title"] = "Home Page";
    var data = ViewBag.Message;
}

@using (@Html.BeginForm())
{
    @Html.EditorFor(model => data)
    <input type="submit" />
}

Generated html

<form action="/" method="post">
<div class="editor-label">
<label for="data_X">X</label>
</div>
<div class="editor-field">
<input class="text-box single-line" data-val="true" data-val-range="The field X must be between 0 and 10." data-val-range-max="10" data-val-range-min="0" data-val-required="The X field is required." id="data_X" name="data.X" type="number" value="0"> 
<span class="field-validation-valid" data-valmsg-for="data.X" data-valmsg-replace="true"></span>
</div>
<div class="editor-label">
<label for="data_Y">Y</label>
</div>
<div class="editor-field"><input class="text-box single-line" data-val="true" data-val-range="The field Y must be between 0 and 10." data-val-range-max="10" data-val-range-min="0" data-val-required="The Y field is required." id="data_Y" name="data.Y" type="number" value="0"> 
<span class="field-validation-valid" data-valmsg-for="data.Y" data-valmsg-replace="true"></span>
</div>
<input type="submit">
<input name="__RequestVerificationToken" type="hidden" value="CfDJ8Aif0fO55UxKoguBNLmuYLdNU-SzXiXyGEcaohb3AphnylgsdCg_Dq-J4el3v_tf5lWzTHB6aF-ifu7rVNpXroUk6TrBVj1hn9T4cSgwankNmSXjyWiIoE-UHDwl_LVBL4SL6vmdJLnPDOAFOv2cip4">
</form>




jeudi 2 avril 2020

ReflectionException - Class ... does not exist

My project (laravel app) was working fine until I Installed the latest version of xampp (php 7.4) then when I login to my app , I get this error

ReflectionException
Class App\Repositories\StatsRepository does not exist

StatsRepository (dependency injection) is injected in my StatsController

class StatsController extends Controller
{
    private $statsRepository;

    public function __construct(StatsRepository $statsRepository)
    {
        $this->statsRepository = $statsRepository;

I changed NOTHING in my code I already tested with :

  1. composer dump-autoload
  2. php artisan cache:clear
  3. php artisan optimize ... etc




Get the original class if casted to its implemented interface

Assume a class as follows

interface Dummy{
}

class Funny implements Dummy {
}

Now I want to find a way to retrieve Class of a Funny object even if it is cast to Dummy





C# Reflection performance comparison when invoking class with parameter

I have heard a lot about Linq Expression performance. But wasn't able to check it myself. Please take a look on the next .NET Core app example:

 class Program
    {
        static void Main(string[] args)
        {
            var classType = Type.GetType("ConsoleApp1.TestClass");
            var classConstructor = classType.GetConstructor(new[] { typeof(string) });

            //var param = Expression.Parameter(typeof(string));
            //var newExpression = Expression.New(classConstructor, param);
            //LambdaExpression lambda = Expression.Lambda(newExpression, param);
            //var compiled = lambda.Compile();
            //var instance = compiled.DynamicInvoke("test");

            //var instance = Activator.CreateInstance(classType, "test");

            //var instance = classConstructor.Invoke(new object[] { "test" });

            Console.ReadLine();
        }
    }

    class TestClass
    {
        public TestClass(string param)
        {

        }
    }

When I am running this code with Expression version uncommented then code works 10 times slower. Please advice what could be wrong or it is as expected.





Jenkins throw java.lang.NoSuchFieldException: theCaseInsensitiveEnvironment

I am trying to set environment variable through unit test, when I am running my code on local machine it is working fine.

But when I deploying it on jenkins pipeline it start throwing an exception

Exception :-

java.lang.NoSuchFieldException: theCaseInsensitiveEnvironment

Code snippet :-

Class<?> processEnvironmentClass = Class.forName("java.lang.ProcessEnvironment");
            Field theEnvironmentField = processEnvironmentClass.getDeclaredField("theEnvironment");
            theEnvironmentField.setAccessible(true);
            Map<String, String> env = (Map<String, String>) theEnvironmentField.get(null);
            env.clear();
            env.putAll(newenv);
            Field theCaseInsensitiveEnvironmentField = processEnvironmentClass.getDeclaredField("theCaseInsensitiveEnvironment");
            theCaseInsensitiveEnvironmentField.setAccessible(true);
            Map<String, String> cienv = (Map<String, String>) theCaseInsensitiveEnvironmentField.get(null);
            cienv.clear();
            cienv.putAll(newenv);