vendredi 31 décembre 2021

Get Items of ListView from Designer class within WinForms using Reflection in C#

I am not sure if I am on right way to prove this concept. Here is the situation, I am trying to solve.

I have one WinForms project (VB.Net) and there is on form called frmMain.vb. It has designer class called frmMain.Designer.vb. I placed one ListView control on that form and set some static item collection to its Items property.

I am calling this WinForm assembly into one C# console application using Reflection. I wan to get list of items of that particulat ListView.

 Assembly AssemblyObject = Assembly.LoadFrom(AppDomain.CurrentDomain.BaseDirectory + "/WinForms.exe");
            if (AssemblyObject != null)
            {
                Type ExceptedType = AssemblyObject.GetTypes().ToList().Where(a => a.Name == "frmMain").FirstOrDefault();

                if (ExceptedType != null)
                {

                    MemberInfo members = ((TypeInfo)ExceptedType).DeclaredMembers.Where(x => x.Name == "ListView").FirstOrDefault();
                }
            }




jeudi 30 décembre 2021

Usage of Activator.CreateInstance()

What is actually the difference between the below two code snippets?

Object o = Activator.CreateInstance(typeof(StringBuilder));

StringBuilder sb = (StringBuilder) o;

and

StringBuilder sb = new StringBuilder();




lundi 27 décembre 2021

How to get method arguments using reflection

This method is first checked by beanDefintirions for the original Beans (Configureablelistablebeanfactory beanFactory is used; ).

ConfigurableListableBeanFactory beanFactory; injected.

Then all the methods of the original bean, which was obtained from the BeanFactory, are iterated over. After searching over the methods of a certain annotation, we get the Bean from the Applicationcontext.

This Bean is a proxy wrapper over the original Bean, which was formed at the - > postProcessBeforeInitialization() stage. Now through this bean, I call a method that has been marked with the annotation I need, but it requires another argument Obj ..args.

How do I get the missing argument ?

Использую Srping 5.x, java 11

private void runMethodWithPostProxyThirdPhaseAnnotation(String beanName, ApplicationContext applicationContext) {

      BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName);


      try {
          String originalBeanClassName = beanDefinition.getBeanClassName();

          if (originalBeanClassName != null) {
              Class<?> originalClass = Class.forName(originalBeanClassName);
              Method[] methods = originalClass.getMethods();

              for (Method method : methods) {
                  if (method.isAnnotationPresent(PostProxyThirdPhase.class)) {
                      

                      String originalMethodName = method.getName();
                      Class<?>[] parameterTypesFromOriginalMethod = method.getParameterTypes();

                      Object beanAfterProxy = applicationContext.getBean(beanName);

                      Method methodFromProxyBean = beanAfterProxy
                              .getClass()
                              .getMethod(originalMethodName, parameterTypesFromOriginalMethod);

                      methodFromProxyBean.invoke(beanAfterProxy, ?);
                  }
              }
          }

      } catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
          e.printStackTrace();
      }

}




Closure obtained from reflection cannot properly address input parameters

A hardcore Swift question I guess. Given this trivial code:

struct Container {
    let closure: (Int) -> Void
}

let container = Container { param in
    print("\(param)")
}

One can assume calling container.closure(42) will print out 42, which is true.

However, if this same closure is retrieved from the container's Mirror:

let mirror = Mirror(reflecting: container)
let closure = mirror.children
    .first(where: { $0.label == "closure" })!
    .value as! ((Int) -> Void)

... then calling closure(42) distorts the parameter's value, and it prints out 6166589480.

The same thing happens if you use String instead of Int, and I assume with other types too. If I pass a reference to an object, expectedly that reference get messed up too and I get EXC_BAD_ACCESS when trying to access the object.

Is this a bug in Swift / Xcode 13.2 or am I missing something?





How to use methods from another class, called by the client

I am making a program that lets the user call a class, like it takes a string input, then calls the run() method of that class, is there any way to do that? I was hoping something like:

String inp=new Scanner(System.in).nextLine();
Class cl=new Class(inp);
cl.run();

I know that the code isn't correct, but that is my main idea





Invoke a Method of Child form opened with Using Statement

I am trying to figure out how to invoke a method of a child form which is opened in a using block.

In my code, I have a MainForm which is a MDI parent. MDI parent holds a reference of parent form . A parent form where the below method is declared.

  1. The ParentForm Instance is available in MDIParent form as shown in the following code.

    MainForm.cs

     private void OpenParentForm()
     {
         try
         {
    
             FormParent frmParent = null;
             frmParent = Application.OpenForms["frmParent"] as FormParent;
    
             if (frmParent != null)
             {
                 frmParent.Focus();
             }
             else
             {
                 frmParent = new FormParent();
                 frmParent.Name = "frmParent";
                 frmParent.MdiParent = this;
                 frmParent.Show();
             }
    
         }
         catch { }
     }
    
  2. The Child form is opened in

    frmParent.cs

     private void ShowChildForm()
     {
         try
         {
             using (ChildForm frmChild = new ChildForm())
             {
    
                 if (frmChild.ShowDialog() == DialogResult.OK)
                     this.RefreshData();
    
                 frmChild.Dispose();
             }
         }
         catch { }
     }
    

The ChildForm having following method.

ChildForm.cs

private void ChildMethod()
{
    //........
    //........
    //........
}

Following is my InvokeMethod

ReflectionHelper.cs

public static async Task<bool> InvokeMethod(Form Window, string methodName, object param)
{
    try
    {
        Form mainWindow = Window;
        var MainWindowtype = mainWindow.GetType();
        MethodInfo MethodtoInvoke = MainWindowtype.GetMethod(methodName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
        if (MethodtoInvoke != null)
        {
            ParameterInfo[] pars = MethodtoInvoke.GetParameters();
            object[] Parameter = null;

            try
            {
                object returnValue = null;
                if (pars != null && pars.Length > 0)
                {
                    Parameter = new object[pars.Length];
                    foreach (var item in pars)
                    {
                        int index = item.Position;
                        if (param != null)
                        {
                            if (param.GetType() == item.ParameterType || item.ParameterType == typeof(object))
                            {
                                Parameter[index] = param;
                            }
                        }
                    }
                    returnValue = MethodtoInvoke.Invoke(mainWindow, Parameter);
                  
                }
                else
                    returnValue = MethodtoInvoke.Invoke(mainWindow, null);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Exception InvokeMethod  \n" + ex.Message);
            }
        }
    }
    catch (Exception ex)
    {
        return false;
    }
    return true;
}

Currently, I am able to invoke Parentform instance methods which are available in MainForm.

Helper.cs

public class Helper
{
    private async void OpenParentForm()
    {
        ReflectionHelper.InvokeMethod(static Instance of MainForm, MethodName, null);
    }
}

I want to invoke MainForm>>frmParent>>[Instance of ChildForm in using block of frmParent.cs].ChildMethod()





vendredi 24 décembre 2021

Reflection considers properties to have different values despite them appearing equal

I have 2 types:

public class TypeA
{
    public int SomeProperty { get; set; }
}
public class TypeB
{
    public int SomeProperty { get; set; }
}

If I create an instance of both types, and in both cases give 'SomePropety' a value of 3, I can retrieve the values of these properties with reflection:

var aProperty = a.GetType().GetProperties().Single(p => p.Name == "SomeProperty");
var bProperty = b.GetType().GetProperties().Single(p => p.Name == "SomeProperty");

var aValue = aProperty.GetValue(a);
var bValue = bProperty.GetValue(b);

Here aValue and bValue now have the value of 3.

But I'm finding that when I compare these raw values, C# does not consider them equal:

if (aValue != bValue)
{
    //this code is hit
}

I look in the debugger and both are clearly '3'. I've never actually encountered this before, have I walked into some scenario where C# considers them unequal because they came from different properties even though they're a raw data type?





Common Language Runtime detected an invalid program in DateTime getter

I'm making a class for generating wrappers in runtime, that get a class like this:

class Test
{
    public int A { get; set; }

    public int B { get; set; }

    public string C { get; set; }

    public DateTimeOffset D { get; set; }
    
    public bool E { get; set; }
}

and creates a wrapper type like

class newTest
{
    private Test _inner;

    public newTest(Test inner)
    {
        _inner = inner;
    }
    
    public int A { get => _inner.A; }

    public int B { get => _inner.B; }

    public string C
    {
        get => _inner.C;
    }

    public DateTime D
    {
        get => _inner.D.UtcDateTime;
    }
    
    public short E
    {
        get => (short)(_inner.E ? 1 : 0);
    }
}

and all works fine, except getter for property D (only the DateTime part in utc timezone is needed). Code for adding property for DateTimeOffset is

        private static void AddDateTimeOffsetProperty(TypeBuilder typeBuilder, FieldInfo fieldBuilder,
        PropertyInfo field)
    {
        var propBuilder = typeBuilder.DefineProperty(field.Name
            , PropertyAttributes.HasDefault
            , typeof(DateTime)
            , null);

        var getBuilder = typeBuilder.DefineMethod($"get_{field.Name}",
            _getAttr,
            typeof(DateTime),
            Type.EmptyTypes);

        ILGenerator ilGen = getBuilder.GetILGenerator();
        // load args to memory
        ilGen.Emit(OpCodes.Ldarg_0);
        // load required field from "_inner" obj
        ilGen.Emit(OpCodes.Ldfld, fieldBuilder);
        // call _inner getter
        ilGen.EmitCall(OpCodes.Callvirt, field.GetMethod!, Array.Empty<Type>());

        // alloc local variable
        ilGen.Emit(OpCodes.Stloc_0);
        ilGen.Emit(OpCodes.Ldloca_S);

        MethodInfo utcDateTimeMethod = typeof(DateTimeOffset).GetProperty("UtcDateTime").GetMethod;
        // get UtcDateTime
        ilGen.EmitCall(OpCodes.Call, utcDateTimeMethod!, Array.Empty<Type>());
        // return
        ilGen.Emit(OpCodes.Ret);

        propBuilder.SetGetMethod(getBuilder);
    }

Here "field" is the property of inner class. After class was generated, create instance of Test class and wrap it

                var testObj = new Test
        {
            A = 7,
            B = 6,
            C = "World",
            E = false,
            D = DateTimeOffset.UtcNow.ToOffset(TimeSpan.FromHours(7)),
            F = 14
        };

        var wrapper = Activator.CreateInstance(wrapperTypeForTest, testObj);

after that wrapper.D will return "Common Language Runtime detected an invalid program.", other properties work.





How to get the method GetCustomAttribute from MemberInfo?

I try to do some reflection on some types.

So I have this

 public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }

        public string FirstName { get; set; }

        public string LastName { get; set; }

        [MethodForRun(RunCount = 3)]
        public void Print()
        {
            Console.WriteLine($"{FirstName} {LastName}");
        }


        [MethodForRun(RunCount =2)]
        public void SayHello()
        {
            Console.WriteLine($"Hello THere {FirstName}");
        }

        static void AttributeTest(Type type)
        {
            var allMethods = type.GetMethods();
            var methodWithAttributes = allMethods.Where(x => x.GetCustomAttribute(typeof(MethodForRunAttribute)) != null);
        }
    }

    public class MethodForRunAttribute:Attribute
    {
        public int RunCount { get; set; }
    }

And it is about the method AttributeTest.

I just can't do

x.GetCustomAttribute

I only can do GetCustomAttributes - so plural. But not just GetCustomAttribute.

What I have to change?

Thank you

And the Library





mardi 21 décembre 2021

Java Modules: access to public member failed

I am trying to get 2 Java 9+ modules to play nice with each other while using reflection, and while only using the module-path, but for the life of me can't get it to work. (Putting them on the classpath poses of course no problem.)

  1. One module contains a BeanReader class that uses reflection to collect a JavaBean's properties and then MethodHandles to read them
  2. The other module contains a simple JavaBean (Person) and a Main class. The Main class instantiates a Person and passes it to the BeanReader. The BeanReader reads one of its properties. In module-info.java I've defined it as an open module.

The command line invocation of the main class looks like this:

java --module-path naturalis-common.jar:test.jar -m test/Main

Yet I keep getting an IllegalAccessException. What am I missing? It all seems pretty bare-bones vanilla.

This is the 2nd module's module-info.java:

open module test {
  requires nl.naturalis.common;
  exports test;
}

And this is the 2nd module's Main class:

package test;
import nl.naturalis.common.invoke.BeanReader;

public class Main {
  public static void main(String[] args) {
    Person p = new Person(2, "Jan");
    BeanReader<Person> br = new BeanReader<>(Person.class);
    br.read(p, "id");
  }
}




mercredi 15 décembre 2021

How to create child class with parant reference with java reflection and without switch

I have a class A which is parant of classes AB, AC, AD. Also class A have enum field "type" which can be "A" \ "AB" \ "AC" \ "AD". So, how can i replace this switch with java reflections?

       public A f(A aa){
           A a;
           switch (aa.type){
                    case A:
                        a = new A();
                        break;
                    case AB:
                        a = new AB();
                        break;
                    case AC:
                        a = new AC();
                        break;
                    case AD:
                        a = new AD();
                        break;
            }
        }
    ```




How to get a hash of a Java class' structure?

Imagine I have the following two classes:

public class A {
    private String field1;
    private B field2;
}

public class B {
    private String field3;
}

What I want to do is use Java Reflection to get all the fields and all the subfields from class A and create a hash out of it. In this example, I would get, say, a list of Strings saying ["field1", "field2", "field3"], and I would hash the entire list.

In case it helps, the reason I am doing this is because I have a MongoDB collection for A. However, every once in a while, I add new fields to A or B, and I need to refresh the entire collection with the new fields when that happens. For this, I need to keep track, in a separate collection, of whether I have already refreshed A's collection yet or not for its current structure. The easiest way would be to just hash its fields and subfields names.





Undeclared identifie trying to make a reflection token

I'm gettin "undeclared identifier" in this line:

// set the rest of the contract variables
    wannaSwapRouterV2 = _wannaSwapRouterV2;

Not sure exactly what I need to change. Full code:

contract TOKEN is Context, IERC20, Ownable {
using SafeMath for uint256;
using Address for address;

mapping (address => uint256) private _rOwned;
mapping (address => uint256) private _tOwned;
mapping (address => mapping (address => uint256)) private _allowances;

mapping (address => bool) private _isExcludedFromFee;

mapping (address => bool) private _isExcluded;
address[] private _excluded;

uint256 private constant MAX = ~uint256(0);
uint256 private _tTotal = 1000000000 * 10**6 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;

string private _name = "TOKEN";
string private _symbol = "TOKEN";
uint8 private _decimals = 9;

uint256 public _taxFee = 5;
uint256 private _previousTaxFee = _taxFee;

uint256 public _liquidityFee = 5;
uint256 private _previousLiquidityFee = _liquidityFee;

IWannaSwapRouterV2 public immutable wannaswapV2Router;
address public immutable uniswapV2Pair;

bool inSwapAndLiquify;
bool public swapAndLiquifyEnabled = true;

uint256 public _maxTxAmount = 5000000 * 10**6 * 10**9;
uint256 private numTokensSellToAddToLiquidity = 500000 * 10**6 * 10**9;

event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap);
event SwapAndLiquifyEnabledUpdated(bool enabled);
event SwapAndLiquify(
    uint256 tokensSwapped,
    uint256 ethReceived,
    uint256 tokensIntoLiqudity
);

modifier lockTheSwap {
    inSwapAndLiquify = true;
    _;
    inSwapAndLiquify = false;
}

constructor () public {
    _rOwned[_msgSender()] = _rTotal;
    
    IWannaSwapRouterV2 _wannaSwapRouterV2 = IWannaSwapRouterV2(0xa3a1eF5Ae6561572023363862e238aFA84C72ef5);
     // Create a uniswap pair for this new token
    IWannaSwapPair = IWannaSwapFactory(_wannaSwapRouterV2.factory())
        .createPair(address(this), _wannaSwapRouterV2.WETH());

    // set the rest of the contract variables
    wannaSwapRouterV2 = _wannaSwapRouterV2;
    
    //exclude owner and this contract from fee
    _isExcludedFromFee[owner()] = true;
    _isExcludedFromFee[address(this)] = true;
    
    emit Transfer(address(0), _msgSender(), _tTotal);
}

function name() public view returns (string memory) {
    return _name;
}

function symbol() public view returns (string memory) {
    return _symbol;
}

function decimals() public view returns (uint8) {
    return _decimals;
}

function totalSupply() public view override returns (uint256) {
    return _tTotal;
}

function balanceOf(address account) public view override returns (uint256) {
    if (_isExcluded[account]) return _tOwned[account];
    return tokenFromReflection(_rOwned[account]);
}

function transfer(address recipient, uint256 amount) public override returns (bool) {
    _transfer(_msgSender(), recipient, amount);
    return true;
}

function allowance(address owner, address spender) public view override returns (uint256) {
    return _allowances[owner][spender];
}

function approve(address spender, uint256 amount) public override returns (bool) {
    _approve(_msgSender(), spender, amount);
    return true;
}

function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
    _transfer(sender, recipient, amount);
    _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
    return true;
}

function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
    _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
    return true;
}

function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
    _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
    return true;
}

function isExcludedFromReward(address account) public view returns (bool) {
    return _isExcluded[account];
}

function totalFees() public view returns (uint256) {
    return _tFeeTotal;
}

function deliver(uint256 tAmount) public {
    address sender = _msgSender();
    require(!_isExcluded[sender], "Excluded addresses cannot call this function");
    (uint256 rAmount,,,,,) = _getValues(tAmount);
    _rOwned[sender] = _rOwned[sender].sub(rAmount);
    _rTotal = _rTotal.sub(rAmount);
    _tFeeTotal = _tFeeTotal.add(tAmount);
}

function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) {
    require(tAmount <= _tTotal, "Amount must be less than supply");
    if (!deductTransferFee) {
        (uint256 rAmount,,,,,) = _getValues(tAmount);
        return rAmount;
    } else {
        (,uint256 rTransferAmount,,,,) = _getValues(tAmount);
        return rTransferAmount;
    }
}

function tokenFromReflection(uint256 rAmount) public view returns(uint256) {
    require(rAmount <= _rTotal, "Amount must be less than total reflections");
    uint256 currentRate =  _getRate();
    return rAmount.div(currentRate);
}

function excludeFromReward(address account) public onlyOwner() {
    // require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.');
    require(!_isExcluded[account], "Account is already excluded");
    if(_rOwned[account] > 0) {
        _tOwned[account] = tokenFromReflection(_rOwned[account]);
    }
    _isExcluded[account] = true;
    _excluded.push(account);
}

function includeInReward(address account) external onlyOwner() {
    require(_isExcluded[account], "Account is already excluded");
    for (uint256 i = 0; i < _excluded.length; i++) {
        if (_excluded[i] == account) {
            _excluded[i] = _excluded[_excluded.length - 1];
            _tOwned[account] = 0;
            _isExcluded[account] = false;
            _excluded.pop();
            break;
        }
    }
}
    function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private {
    (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount);
    _tOwned[sender] = _tOwned[sender].sub(tAmount);
    _rOwned[sender] = _rOwned[sender].sub(rAmount);
    _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
    _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);        
    _takeLiquidity(tLiquidity);
    _reflectFee(rFee, tFee);
    emit Transfer(sender, recipient, tTransferAmount);
}

    function excludeFromFee(address account) public onlyOwner {
    _isExcludedFromFee[account] = true;
}

function includeInFee(address account) public onlyOwner {
    _isExcludedFromFee[account] = false;
}

function setTaxFeePercent(uint256 taxFee) external onlyOwner() {
    _taxFee = taxFee;
}

function setLiquidityFeePercent(uint256 liquidityFee) external onlyOwner() {
    _liquidityFee = liquidityFee;
}

function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner() {
    _maxTxAmount = _tTotal.mul(maxTxPercent).div(
        10**2
    );
}

function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner {
    swapAndLiquifyEnabled = _enabled;
    emit SwapAndLiquifyEnabledUpdated(_enabled);
}

 //to recieve ETH from uniswapV2Router when swaping
receive() external payable {}

function _reflectFee(uint256 rFee, uint256 tFee) private {
    _rTotal = _rTotal.sub(rFee);
    _tFeeTotal = _tFeeTotal.add(tFee);
}

function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
    (uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues(tAmount);
    (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidity, _getRate());
    return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity);
}

function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) {
    uint256 tFee = calculateTaxFee(tAmount);
    uint256 tLiquidity = calculateLiquidityFee(tAmount);
    uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity);
    return (tTransferAmount, tFee, tLiquidity);
}

function _getRValues(uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
    uint256 rAmount = tAmount.mul(currentRate);
    uint256 rFee = tFee.mul(currentRate);
    uint256 rLiquidity = tLiquidity.mul(currentRate);
    uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity);
    return (rAmount, rTransferAmount, rFee);
}

function _getRate() private view returns(uint256) {
    (uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
    return rSupply.div(tSupply);
}

function _getCurrentSupply() private view returns(uint256, uint256) {
    uint256 rSupply = _rTotal;
    uint256 tSupply = _tTotal;      
    for (uint256 i = 0; i < _excluded.length; i++) {
        if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal);
        rSupply = rSupply.sub(_rOwned[_excluded[i]]);
        tSupply = tSupply.sub(_tOwned[_excluded[i]]);
    }
    if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
    return (rSupply, tSupply);
}

function _takeLiquidity(uint256 tLiquidity) private {
    uint256 currentRate =  _getRate();
    uint256 rLiquidity = tLiquidity.mul(currentRate);
    _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity);
    if(_isExcluded[address(this)])
        _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity);
}

function calculateTaxFee(uint256 _amount) private view returns (uint256) {
    return _amount.mul(_taxFee).div(
        10**2
    );
}

function calculateLiquidityFee(uint256 _amount) private view returns (uint256) {
    return _amount.mul(_liquidityFee).div(
        10**2
    );
}

function removeAllFee() private {
    if(_taxFee == 0 && _liquidityFee == 0) return;
    
    _previousTaxFee = _taxFee;
    _previousLiquidityFee = _liquidityFee;
    
    _taxFee = 0;
    _liquidityFee = 0;
}

function restoreAllFee() private {
    _taxFee = _previousTaxFee;
    _liquidityFee = _previousLiquidityFee;
}

function isExcludedFromFee(address account) public view returns(bool) {
    return _isExcludedFromFee[account];
}

function _approve(address owner, address spender, uint256 amount) private {
    require(owner != address(0), "ERC20: approve from the zero address");
    require(spender != address(0), "ERC20: approve to the zero address");

    _allowances[owner][spender] = amount;
    emit Approval(owner, spender, amount);
}

function _transfer(
    address from,
    address to,
    uint256 amount
) private {
    require(from != address(0), "ERC20: transfer from the zero address");
    require(to != address(0), "ERC20: transfer to the zero address");
    require(amount > 0, "Transfer amount must be greater than zero");
    if(from != owner() && to != owner())
        require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");

    // is the token balance of this contract address over the min number of
    // tokens that we need to initiate a swap + liquidity lock?
    // also, don't get caught in a circular liquidity event.
    // also, don't swap & liquify if sender is uniswap pair.
    uint256 contractTokenBalance = balanceOf(address(this));
    
    if(contractTokenBalance >= _maxTxAmount)
    {
        contractTokenBalance = _maxTxAmount;
    }
    
    bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity;
    if (
        overMinTokenBalance &&
        !inSwapAndLiquify &&
        from != uniswapV2Pair &&
        swapAndLiquifyEnabled
    ) {
        contractTokenBalance = numTokensSellToAddToLiquidity;
        //add liquidity
        swapAndLiquify(contractTokenBalance);
    }
    
    //indicates if fee should be deducted from transfer
    bool takeFee = true;
    
    //if any account belongs to _isExcludedFromFee account then remove the fee
    if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){
        takeFee = false;
    }
    
    //transfer amount, it will take tax, burn, liquidity fee
    _tokenTransfer(from,to,amount,takeFee);
}

function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap {
    // split the contract balance into halves
    uint256 half = contractTokenBalance.div(2);
    uint256 otherHalf = contractTokenBalance.sub(half);

    // capture the contract's current ETH balance.
    // this is so that we can capture exactly the amount of ETH that the
    // swap creates, and not make the liquidity event include any ETH that
    // has been manually sent to the contract
    uint256 initialBalance = address(this).balance;

    // swap tokens for ETH
    swapTokensForEth(half); // <- this breaks the ETH -> HATE swap when swap+liquify is triggered

    // how much ETH did we just swap into?
    uint256 newBalance = address(this).balance.sub(initialBalance);

    // add liquidity to uniswap
    addLiquidity(otherHalf, newBalance);
    
    emit SwapAndLiquify(half, newBalance, otherHalf);
}

function swapTokensForEth(uint256 tokenAmount) private {
    // generate the uniswap pair path of token -> weth
    address[] memory path = new address[](2);
    path[0] = address(this);
    path[1] = wannaswapV2Router.WETH();

    _approve(address(this), address(wannaswapV2Router), tokenAmount);

    // make the swap
    wannaswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
        tokenAmount,
        0, // accept any amount of ETH
        path,
        address(this),
        block.timestamp
    );
}

function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
    // approve token transfer to cover all possible scenarios
    _approve(address(this), address(wannaswapV2Router), tokenAmount);

    // add the liquidity
    wannaswapV2Router.addLiquidityETH{value: ethAmount}(
        address(this),
        tokenAmount,
        0, // slippage is unavoidable
        0, // slippage is unavoidable
        owner(),
        block.timestamp
    );
}

//this method is responsible for taking all fee, if takeFee is true
function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private {
    if(!takeFee)
        removeAllFee();
    
    if (_isExcluded[sender] && !_isExcluded[recipient]) {
        _transferFromExcluded(sender, recipient, amount);
    } else if (!_isExcluded[sender] && _isExcluded[recipient]) {
        _transferToExcluded(sender, recipient, amount);
    } else if (!_isExcluded[sender] && !_isExcluded[recipient]) {
        _transferStandard(sender, recipient, amount);
    } else if (_isExcluded[sender] && _isExcluded[recipient]) {
        _transferBothExcluded(sender, recipient, amount);
    } else {
        _transferStandard(sender, recipient, amount);
    }
    
    if(!takeFee)
        restoreAllFee();
}

function _transferStandard(address sender, address recipient, uint256 tAmount) private {
    (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount);
    _rOwned[sender] = _rOwned[sender].sub(rAmount);
    _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
    _takeLiquidity(tLiquidity);
    _reflectFee(rFee, tFee);
    emit Transfer(sender, recipient, tTransferAmount);
}

function _transferToExcluded(address sender, address recipient, uint256 tAmount) private {
    (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount);
    _rOwned[sender] = _rOwned[sender].sub(rAmount);
    _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
    _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);           
    _takeLiquidity(tLiquidity);
    _reflectFee(rFee, tFee);
    emit Transfer(sender, recipient, tTransferAmount);
}

function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private {
    (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount);
    _tOwned[sender] = _tOwned[sender].sub(tAmount);
    _rOwned[sender] = _rOwned[sender].sub(rAmount);
    _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);   
    _takeLiquidity(tLiquidity);
    _reflectFee(rFee, tFee);
    emit Transfer(sender, recipient, tTransferAmount);
}

}





Assign class fields with reflection BEFORE construction of the instance

I want to either guarantee that fields used in the constructor are populated before construction, or somehow throw an exception if one of these fields is used in the constructor.

I am writing an injection framework for Unity3D. I have a use-case like this that emerged:

public class TestInjectable : IInjectable
{
     [Inject] TestDependency testDependency;

     int testValue;          

     public TestInjectable()
     {
          testValue = testDependency.value;
          //testValue is NULL here, because testDependency is injected AFTER construction
     }
}

public class TestDependency : IInjectable
{
     public int value = 5;
}

If I go like this, it works jus fine:

public class TestInjectable : IInjectable
{
     TestDependency testDependency;

     int testValue;          

     public TestInjectable(TestDependency testDependency)
     {
          testValue = testDependency.value;
          //testValue is 5 here, because testDependency is injected as a constructor parameter
     }
}

public class TestDependency : IInjectable
{
     public int value = 5;
}

I can use construction-parameter injection to make this work. However, after adding the [Inject] attribute for class fields, the idea of using those fields at construction, without constructor parameters, has entered the mix.

First: It would be nice to make the above work somehow... The created instance is required to set its field values, meaning construction must occur first regardless. I am not sure how to get around needing the constructor to run before injecting the fields.

Second: I would also be fine just throwing an exception for now, alerting the user that using an [Inject] field inside the constructor cannot occur... I was not able to find a solution for detecting if a field is used inside a constructor.

Third: If neither of these can be accomplished, I will have to rely on users reading the documentation, where I can explain this issue. Or, I will have to consider removing the [Inject] feature, which besides for this pit-fall, can be very useful for defining injection.... I would hate to take it out.





lundi 13 décembre 2021

Listing object properties using reflection, including nested lists and user defined property types

I am currently trying to create a custom UI component that simply displays all the properties of custom type object, including properties that are nested lists or other custom types. I am not sure if I have the best approach though. What I am doing now is, using reflection, I am going through the property types and display key-value pairs. If the property I am currently processing is a custom type, I iterate through its properties again and display those as well, same for lists (iterate through list, then for each object iterate through its properties and display them). Is there a better way to do this using reflection?





dimanche 12 décembre 2021

Why well-know symbols are in Symbol and not in Reflect API

I don't understand one thing about well-known symbols in Javascript. What is the reason of putting those well-known symbols into Symbol instead of Reflect API? For me seems that the right place for them is the Reflect API as the Reflect API is made for metaprogramming, particularly for reflection and particularly for introspection and self-modification? Does anyone knows the reason of doing so?





vendredi 10 décembre 2021

Access class fields by field name of custom object [duplicate]

I've named textboxes in my UI the same as the field-names in the 'Stuff' class below, I'm iterating over the controls and trying to populate them programmatically with the respective fields from Stuff-

I did search, extensively. But the line below (gettype.getproperty.getvalue[stuff,null]) has never returned a value, at all. It just keeps crashing out as null- I found this line here on Stack

foreach (Control c in gbInfo.Controls) {
    if (c.Name.StartsWith("tb")) {

        string fieldIWantToAccess = c.Name.Substring(2); //removes the tb from tbWeAllAre

        // it's this line below that's giving me issues- I'm just looking for a simple
        // way to accomplish this. Back in the perl days it was just:
        // $name = "IsNerd"; c.Text = $$name;
        c.Text = stuffObj.GetType().GetProperty(fieldIWantToAccess).GetValue(Stuff, null);

        }
    }

public class Stuff {
    public string Name;
    public string Age;
    public string IsNerd;
    public string WeAllAre;
    }

In my actual code, 'Stuff' has about 2 dozen public strings, and there's a large array of TextBox controls on the UI that I'd like to populate this way.. Rather than doing them all individually.





How to reflect Dart library name?

Is there a way to reflect specific library properties (like the library name) in Dart? How do you get the library object reference?





jeudi 9 décembre 2021

Add and remove async event handlers using reflection in c#

I have the following code sample that actually works:

namespace DeviceLib
{
    public interface IInstrument
    {
        event Action<InstrumentConnectionStatus> OnConnectionChanged;
        event Action OnRemoteMeasureRequested;
    }

public class InstrumentInstance
{
    public delegate Task EventCompletedHandler(object sender, dynamic eventArgs);
    public event EventCompletedHandler StatusChanged = async delegate { };
    public event EventCompletedHandler RemoteMeasureRequested = async delegate { };
    IInstrument Instrument;

    public InstrumentInstance(string DriverName)
    {
        Instrument = DriverName switch
        {
            Instrument1.DRIVER => new Instrument1Driver(),
            instrument2.DRIVER => new Instrument2Driver(),
            _ => throw new NotSupportedException($"Driver {DriverName} not supported"),
        };
    }

    public async Task<object> OnStatusChanged()
    {
        Instrument.OnConnectionChanged += async (InstrumentConnectionStatus status) =>
        {
            await StatusChanged(nameof(OnStatusChanged), status.ToString());
        };

        return null;
    }

    public async Task<object> OnRemoteMeasureRequested()
    {
        Instrument.OnRemoteMeasureRequested += async () =>
        {
            await RemoteMeasureRequested(nameof(OnRemoteMeasureRequested), null);
        };

        return null;
    }
}

}

namespace DeviceConsumer 
{
    public class InstrumentService
    {
        static Type Type = typeof(DeviceLib.InstrumentInstance);
        DeviceLib.InstrumentInstance InstrumentInstance;
        static List<MethodInfo> AvailableEventHandlers =  Type.GetMethods().Where(x => x.DeclaringType == Type && !x.IsSpecialName && x.Name.StartsWith("On")).ToList();
        static List<EventInfo> AvailableEvents=Type.GetEvents().ToList();
    

        public InstrumentService()
        {

        }

        public async Task CreateInstrumentInstance(string driverName)
        {
            this.InstrumentInstance = new DeviceLib.InstrumentInstance(driverName);
        
        
            // Invoking the methods that wrap the event handlers with reflection
            foreach (MethodInfo eventHandler in AvailableEventHandlers)
                await (Task<object>)eventHandler.Invoke(InstrumentInstance, new object[] { });


            InstrumentInstance.StatusChanged +=  async(s,e) => await ProcessInstrumentEvent(s,e);
            InstrumentInstance.RemoteMeasureRequested += async (s, e) => await ProcessInstrumentEvent(s, e);
        }

        private async Task ProcessInstrumentEvent(object sender, dynamic eventArgs)
        {
            await Task.Run(() =>
            {
                Console.Write($"Event {sender} Fired!");
            });
        }

}

 

Now I want to substitute the static part that associates the events to the ProcessInstrumentEvent method:

InstrumentInstance.StatusChanged +=  async(s,e) => await ProcessInstrumentEvent(s,e);
InstrumentInstance.RemoteMeasureRequested += async (s, e) => await ProcessInstrumentEvent(s, e);

With something like:

        foreach (EventInfo ev in AvailableEvents)
        {
           // EventHandler handler = async delegate (object s, dynamic e) { await ProcessInstrumentEvent(s, e); };
          
           //  EventHandler handler = new EventHandler(async (s, e) => await ProcessInstrumentEvent(s,e));


             ev.AddEventHandler(InstrumentInstance, handler);

        }

None of the 2 approaches to define "handler" worked, where I'm failing here? I think I'm very close, the goal of this implementation is to dynamically add (and later remove) the handlers that target the method "ProcessInstrumentEvent" in class "InstrumentService" so without using += and -= operators, so I thought that I could achieve that using the reflection methods "AddEventHandler" and "RemoveEventHandler"





mercredi 8 décembre 2021

Permanently change the java class private field default value

I have a following use case: assume that we have a class

public class MyClass {
   
   private boolean isEmpty = true; 

}

As you can see here, isEmpty get initialized as true by default for any new instance of MyClass. I do not have access to this class source code - this class is included into transitive dependency jar. I need to change the default value of isEmpty to false for every new object. Also note, that field has no public setters and other possible methods in order for me to set it even per object basis. Even worse, that default reflection approach:

MyClass.class.getDeclaredField("isEmpty")

and then change the value for each object is not an option in my use case, becuase not all of the creations of this object appeared in my source code, but also there are creations of MyClass instances in already compiled code of the included JAR. So, is it, from any stretch of the imagination, possible to change the default value of isEmpty value?

I am running out of ideasm really, any help will be appreciated





lundi 6 décembre 2021

Reflection model does not work correctly in OpenGl using glColor3f

I have a depth map as 2D double array 480x640. I visualize it using openGL using glBegin(GL_TRIANGLES). This is my code, it works correctly:

int main(int argc, char** argv){


ifstream ifs("D:\\DepthMaps1-20\\DepthMap_1.dat", std::ios::binary);
if (ifs) {
    double dheight, dwidth;

    
    ifs.read(reinterpret_cast<char*>(&dheight), sizeof dheight);
    ifs.read(reinterpret_cast<char*>(&dwidth), sizeof dwidth);

    
    height = static_cast<size_t>(dheight);
    width = static_cast<size_t>(dwidth);

    
    vector<vector<double>> dmap(height, vector<double>(width));

    
    for (auto& row : dmap) {
        for (double& col : row)
            ifs.read(reinterpret_cast<char*>(&col), sizeof col);
    }

    double fx = 525.0;
    double fy = 525.0; // default focal length
    double cx = 319.5;
    double cy = 239.5; // default optical center

    vector<vector<double>> x(height, vector<double>(width));
    vector<vector<double>> y(height, vector<double>(width));
    vector<vector<double>> z(height, vector<double>(width));

    
    for (unsigned i = 0; i < dmap.size(); i++)
    {
        for (unsigned j = 0; j < dmap[i].size(); j++)
        {
            z[i][j] = dmap[i][j] / 500.0;
            x[i][j] = (j - cx) * z[i][j] / fx;
            y[i][j] = (i - cy) * z[i][j] / fy;
        }

    }
    
    
    GLFWwindow * window;

    
    if (!glfwInit())
        return -1;

    
    window = glfwCreateWindow(640, 640, "Hello World", NULL, NULL);
    if (!window)
    {
        glfwTerminate();
        return -1;
    }

    
    glfwMakeContextCurrent(window);

    
    glfwSetKeyCallback(window, keyCallback);
    
    while (!glfwWindowShouldClose(window))
    {

        glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        glLoadIdentity();

        glBegin(GL_TRIANGLES);

        glColor3f(189.0/255.0, 140.0 / 255.0, 194.0 / 255.0);
        for (unsigned i = 0; i < dmap.size(); i++)
        {
            for (unsigned j = 0; j < dmap[i].size(); j++)
            {
                if (j < dmap[i].size() - 2 && i < dmap.size() - 2)
                {
                    if (z[i][j] != 0 && z[i][j + 1] != 0 && z[i + 1][j] != 0 && z[i + 1][j+1] != 0)
                    {
                        glVertex3d(x[i][j], y[i][j], z[i][j]);
                        glVertex3d(x[i][j + 1], y[i][j + 1], z[i][j + 1]);
                        glVertex3d(x[i + 1][j], y[i + 1][j], z[i + 1][j]);

                        glVertex3d(x[i][j+1], y[i][j+1], z[i][j+1]);
                        glVertex3d(x[i + 1][j + 1], y[i + 1][j + 1], z[i + 1][j + 1]);
                        glVertex3d(x[i + 1][j], y[i + 1][j], z[i + 1][j]);

                    }
                }
            }
        }
        glEnd();

        glFlush();

        glfwSwapBuffers(window);
        glfwPollEvents();

    }
    ifs.close();

}

return 0;}

So now I need to add lighting using mathematical formulas for reflection model. Idea is - lighting is taken as parallel (unidirectional) beams of the same intensity, the size of the light source is not limited. Illumination is set by the direction L [Lx Ly Lz]. This is my code for Lambert reflection model and it works, but I want better result.

float coord = -1.0f;
float coord1 = -1.0f;
float coord2 = -0.0f;
float coord4 = -1.0f;
float coord5 = -2.0f;
float coord6 = -1.0f;


int main(int argc, char** argv)
{
    
    ifstream ifs("D:\\DepthMaps1-20\\DepthMap_1.dat", std::ios::binary);
    if (ifs) {
        double dheight, dwidth;

        ifs.read(reinterpret_cast<char*>(&dheight), sizeof dheight);
        ifs.read(reinterpret_cast<char*>(&dwidth), sizeof dwidth);

        height = static_cast<size_t>(dheight);
        width = static_cast<size_t>(dwidth);

        
        vector<vector<double>> dmap(height, vector<double>(width));

        
        for (auto& row : dmap) {
            for (double& col : row)
                ifs.read(reinterpret_cast<char*>(&col), sizeof col);
        }

        double fx = 525.0;
        double fy = 525.0; // default focal length
        double cx = 319.5;
        double cy = 239.5; // default optical center

        vector<vector<double>> x(height, vector<double>(width));
        vector<vector<double>> y(height, vector<double>(width));
        vector<vector<double>> z(height, vector<double>(width));

        vector<vector<int>> brightness(height, vector<int>(width));

        
        for (unsigned i = 0; i < dmap.size(); i++)
        {
            for (unsigned j = 0; j < dmap[i].size(); j++)
            {
                z[i][j] = dmap[i][j] / 500.0;
                x[i][j] = (j - cx) * z[i][j] / fx;
                y[i][j] = (i - cy) * z[i][j] / fy;
    
            }

        }
        
        
        GLFWwindow * window;

        
        if (!glfwInit())
            return -1;

        
        window = glfwCreateWindow(640, 640, "Hello World", NULL, NULL);
        if (!window)
        {
            glfwTerminate();
            return -1;
        }

        
        glfwMakeContextCurrent(window);

    
        glfwSetKeyCallback(window, keyCallback);
        
        while (!glfwWindowShouldClose(window))
        {

            glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
            glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

            glLoadIdentity();


            glRotatef(tippangle, 1, 0, 0);  
            glRotatef(viewangle, 0, 1, 0);  

            glScalef(scaleF, scaleF, scaleF);
            

            //x
            glRasterPos3f(1.1, 0.0, 0.0);
            //y
            glRasterPos3f(0.0, 1.1, 0.0);

            //z
            glRasterPos3f(0.0, 0.0, 1.1);

            glTranslatef(d[0], d[1], d[2]);   

            glBegin(GL_TRIANGLES);

            
            for (unsigned i = 0; i < dmap.size(); i++)
            {
                for (unsigned j = 0; j < dmap[i].size(); j++)
                {
                    if (j < dmap[i].size() - 2 && i < dmap.size() - 2)
                    {
                        if (z[i][j] != 0 && z[i][j + 1] != 0 && z[i + 1][j] != 0 && z[i + 1][j + 1] != 0)
                        {
                            


                            //Determination of the normal
                            glm::vec3 left = glm::vec3(0, 1, (z[i][j + 1] - z[i][j+1]));
                            glm::vec3 right = glm::vec3(1, 0, (z[i + 1][j] - z[i + 1][j]));
                            
                            glm::vec3 normal = glm::normalize(glm::cross(left, right));


                        
                            glm::vec3 Position_Light = glm::vec3(coord + 0, coord1+ 0, coord2 + 0); //Light source
                            glm::vec3 Position_View = glm::vec3(coord4, coord5, coord6); //observer
                            glm::vec3 Position_Point = glm::vec3(x[i][j], y[i][j], z[i][j]);


                    

                            //Directions
                            glm::vec3 Light_Direction = glm::normalize(Position_Light - Position_Point); //To source 
                            glm::vec3 View_Direction = glm::normalize(Position_View - Position_Point); // To the observer
                            glm::vec3 HalfWay_Direction = glm::normalize(Light_Direction + View_Direction); //Median vector (halfway)

                            double kd = 1;//diffuse reflectance for the Lambert model 
                            double I = 0; //variable brightness

                            
                            I = kd * glm::dot(Light_Direction, normal);

                            glColor3f(I, I, I);
                            glVertex3d(x[i][j], y[i][j], z[i][j]);
                            glVertex3d(x[i][j + 1], y[i][j + 1], z[i][j + 1]);
                            glVertex3d(x[i + 1][j], y[i + 1][j], z[i + 1][j]);

                            glVertex3d(x[i][j+1], y[i][j+1], z[i][j+1]);
                            glVertex3d(x[i + 1][j + 1], y[i + 1][j + 1], z[i + 1][j + 1]);
                            glVertex3d(x[i + 1][j], y[i + 1][j], z[i + 1][j]);
                            
                        }
                    }
                }
            }
            glEnd();

            glFlush();

            glfwSwapBuffers(window);
            glfwPollEvents();

        }
        ifs.close();
    }

    return 0;
}

This is my result.

enter image description here

And I want this result.

enter image description here

Second result is an example for this work, but using c#. Sourse code here:

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {

        double[,] depth;
        int[,] brightness;
        bool glConrerolIsLoaded; 
        
        float coord = 501.5f;
        float coord1 = -17.5f;
        float coord2 = -2979.5f;
        float coord4 = -73.0f;
        float coord5 = 1269.0f;
        float coord6 = 413.5f; 

        int resNum = 0; 

        private void glControl1_Load(object sender, EventArgs e)
        {
            glConrerolIsLoaded = true;
            GL.ClearColor(Color.Black);        
        }

        private void numericUpDown1_ValueChanged(object sender, EventArgs e)
        {            
            glControl1.Invalidate();
            panel1.Invalidate();
        }

        private void numericUpDown2_ValueChanged(object sender, EventArgs e)
        {           
            glControl1.Invalidate();
            panel1.Invalidate();
        }

        private void numericUpDown3_ValueChanged(object sender, EventArgs e)
        {
            glControl1.Invalidate();
            panel1.Invalidate();
        }


        

private void glControl1_Paint(object sender, PaintEventArgs e)
        {      

            GL.LoadIdentity();
            GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
            GL.Viewport(0, 0, glControl1.Width, glControl1.Height);
            GL.MatrixMode(MatrixMode.Projection);
            GL.LoadIdentity();
            Matrix4 perspectiveMatrix = Matrix4.CreatePerspectiveFieldOfView(MathHelper.DegreesToRadians(45), glControl1.Width / glControl1.Height, 1.0f, 100.0f);
            GL.LoadMatrix(ref perspectiveMatrix);
            GL.MatrixMode(MatrixMode.Modelview);

            GL.Translate(-25.0, -9.0, -45.0);
            GL.Scale(0.04, 0.04, 0.04); 

            GL.Begin(BeginMode.Points);

            for (int i = 0; i < depth.GetLength(0) - 1 ; i++)
            {
                for (int j = 0; j < depth.GetLength(1) - 1 ; j++)
                {
                    if (depth[i, j] != 0 && depth[i + 1, j] != 0 && /*depth[i + 1, j + 1] != 0 &&*/ depth[i, j + 1] != 0)
                    {   
                        
                        Vector3 left = new Vector3(0, 1, Convert.ToSingle(depth[i, j + 1]) - Convert.ToSingle(depth[i, j]));
                        Vector3 right = new Vector3(1, 0, Convert.ToSingle(depth[i + 1, j]) - Convert.ToSingle(depth[i, j]));
                        Vector3 Normal = Vector3.Normalize(Vector3.Cross(left, right));

                        
                        Vector3 Position_Light = new Vector3(coord + Convert.ToSingle(numericUpDown1.Value), coord1 
                            + Convert.ToSingle(numericUpDown2.Value), coord2 + Convert.ToSingle(numericUpDown3.Value));
                        Vector3 Position_View = new Vector3(coord4, coord5, coord6);
                        Vector3 Position_Point = new Vector3(i, j, Convert.ToSingle(depth[i, j]));

                        
                        Vector3 Light_Direction = Vector3.Normalize(Position_Light - Position_Point);                  
                        Vector3 View_Direction = Vector3.Normalize(Position_View - Position_Point);
                        Vector3 HalfWay_Direction = Vector3.Normalize(Light_Direction + View_Direction); 

                        double kd = 1;
                       
                        double I = 0; 


                      
                            I = kd * Vector3.Dot(Light_Direction, Normal);
    
                        GL.Color3(I, I, I);
                        GL.Vertex3(i, j, depth[i, j]);

                        
                }                
            }            

            GL.End();

            glControl1.SwapBuffers();
        }
       
        private void Form1_Load(object sender, EventArgs e)//Считывание карты глубины
        {            
            string path = @"DepthMap_1.dat";
            BinaryReader reader = new BinaryReader(File.Open(path, FileMode.Open));            
            double Height1 = reader.ReadDouble();
            double Width1 = reader.ReadDouble();
            depth = new double[Convert.ToInt16(Height1), Convert.ToInt16(Width1)];
            brightness = new int[Convert.ToInt16(Height1), Convert.ToInt16(Width1)];
            for (int i = 0; i < depth.GetLength(0); i++)
            {
                for (int j = 0; j < depth.GetLength(1); j++)
                {
                    depth[i, j] = reader.ReadDouble();
                }
            }
            reader.BaseStream.Close();
        }

        private void panel1_Paint(object sender, PaintEventArgs e)
        { 
        }
    }
}

So my question is what is incorrect in my code? If it light position could you please help me to fix it.





Access Themes/Generic.xaml via reflection

Is there any way to access the Themes/Generic ResourceDictionary using reflection?

I tried digging through Application.Resources but this appears to be the wrong place. Then I tried analysing the Assembly's ResourceStream but that wasn't succesful either.

So does anyone know how I can get the instance of the mentioned ResourceDictionary from an assembly?

Before someone asks "Why" => because i want to mess with it.

This is the closest i got, but it throws errors that some parts of it cannot be loaded, so I assume its a "copy" and not the one used?

        System.Uri resourceLocater = new System.Uri("/ASMNAME;component/themes/generic.xaml", System.UriKind.Relative);

        ResourceDictionary dictionary =(ResourceDictionary) Application.LoadComponent(resourceLocater);




dimanche 5 décembre 2021

sqlalchemy reflection on bigquery database gives me empty model [duplicate]

I have couple of tables in my bigquery dataset. I would like to not write by hand model definitions, but to use reflection as described on page: https://docs.sqlalchemy.org/en/14/orm/extensions/automap.html . I have prepared some example:

from sqlalchemy import create_engine, Table, MetaData, Column, Integer, String
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session

engine = create_engine('bigquery://<my-gcloud-project-id>')
metadata = MetaData()
metadata.reflect(engine, only=['websites.<my-table-to-reflect>',])
Base = automap_base(metadata=metadata)
Base.prepare()
print(Base.classes.items())
print(list(Base.classes))

But I'm getting empty list. Am I doing something wrong, or automap is not supported with bigquery? My deps: sqlalchemy-bigquery==1.2.2; SQLAlchemy==1.4.27; google-cloud-bigquery==2.27.0;





Why does mocha chai should not prove identity for `return this`, if I use Proxy:get in the constructor?

I want to write a class, that deals with undefined properties. I also want to return this to be able to chain methods to create a domain specific language (DSL).

I return a Proxy from the constructor, to handle undefined properties. Now when testing the instance, it does happen, that return this does not prove to be identical with the instance. I fear bugs resulting from this, although I can chain the methods as intended.

This is a mocha chai test to show the behaviour. Replace o.that().should.not.equal(o); with o.that().should.equal(o); in the last instruction to see how it fails.

require('chai').should();

describe('chai testing classes using Proxy', () => {
    it('asserts object identity, if an instance method returns this', () => {
        const o = new class NormalClass{ }
        o.that = function() { return this; }
        o.that().should.equal(o);
    });
    it('observes the same behaviour for constructors returning a dummy Proxy', () => {
        const o = new class ProxyClass{
            constructor() { return new Proxy(this, {}); }
        }
        o.that = function() { return this; }
        o.that().should.equal(o);
    });
    it('requires deep.equal on the other hand, if the Proxy handles get', () => {
        const o = new class ProxyClassPlusGet{
            constructor() {
                return new Proxy(this, {
                    get: function(target, prop) { return target[prop]; },
                });
            }
        }
        o.that = function() { return this; }
        o.that().should.deep.equal(o);
        o.that().should.not.equal(o);
    });
});




samedi 4 décembre 2021

How To Use Static Reflection To Get The Name Of A Resx Resource Class Property?

I have numerous resx files in my project for localization for various languages.

I need to use static reflection to be able to get the property name of the resx class when using dot notation. For example:

MyStrings.This_is_a_test_string

I read several posts on static reflection and found the GetProperty method example which I converted from C# to VB using an online converter.

I attempted to use the following code:

Dim strPropertyName As PropertyInfo = GetProperty(DevStrings.This_is_a_test_string)

Public Function GetProperty(Of TEntity)(ByVal expression As Expression(Of Func(Of TEntity, Object))) As PropertyInfo

Dim memberExpression As MemberExpression = TryCast(expression.Body, MemberExpression)

If memberExpression Is Nothing Then Throw New InvalidOperationException("Not a member access.")

Return TryCast(memberExpression.Member, PropertyInfo)

End Function

However, it results in this error:

BC36645: Data type(s) of the type parameter(s) in method 'Public Function GetProperty(Of TEntity)(ByVal expression As Expression(Of Func(Of TEntity, Object))) As PropertyInfo' cannot be inferred from these arguments. Specifying the data type(s) explicitly might correct this error.

I don't know anything about the reflection classes so I need very specific, step-by-step help.

Can anyone provide me with a working example in VB where I can get the name of the property reflected back to me a string?

In other words when I pass the parameter MyStrings.This_is_a_test to the reflection function I get back the string "This is a test"?

Thanks for the help!





c# reflection read from json and fieldinfo.setvalue error

i got a question here,hope warmheat developer help.

this is the problem i meet:

i want to save a class instance's fields due to reflection,the code below:

private void SaveFields()
{
    fieldItemList.Clear();
    FieldInfo[] fields = GetType().GetFields(BindingFlags.Public | BindingFlags.Instance);
    for (int i = 0; i < fields.Length; i++)
    {
        FieldInfo finfo = fields[i];
        FieldItem item = new FieldItem()
        {
            ValName = finfo.Name,
            ValType = finfo.FieldType,
            ValValue = finfo.GetValue(this),
        };
        fieldItemList.Add(item);
    }
    string json = JsonModule.GetInstance().Serialize(fieldItemList);
    json = JsonModule.GetInstance().FormatJsonString(json);
    Debug.LogFormat("json = {0}", json);
    File.WriteAllText(@"E:\GithubRepo\ShaderSamples\ShaderSamples\fields.json", json);
}

it works,and the saved json like this:

[
{
    "ValName": "fVar",
    "ValType": "System.Single, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089",
    "ValValue": 2.0
},
{
    "ValName": "iVar",
    "ValType": "System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089",
    "ValValue": 1
},
{
    "ValName": "Gears",
    "ValType": "GearParam[], Assembly-CSharp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null",
    "ValValue": [
        {
            "Vec3": {
                "x": 1.0,
                "y": 2.0,
                "z": 3.0
            },
            "Vec2": {
                "x": 1.0,
                "y": 2.0
            },
            "FVar": 1.0,
            "IVar": 2
        }
    ]
}

]

then when i use it for fill in new class instance's fields,code like this:

private void ApplyFields()
{
    string json = File.ReadAllText(@"E:\GithubRepo\ShaderSamples\ShaderSamples\fields.json");
    fieldItemList = JsonModule.GetInstance().Deserialize<List<FieldItem>>(json);
    Debug.LogFormat("fieldItemList = {0}", fieldItemList.Count);
    FieldInfo[] fields = GetType().GetFields(BindingFlags.Public | BindingFlags.Instance);
    for (int i = 0; i < fields.Length; i++)
    {
        FieldInfo finfo = fields[i];
        for (int k = 0; k < fieldItemList.Count; k++)
        {
            FieldItem item = fieldItemList[k];
            if (finfo.Name == item.ValName)
            {
                finfo.SetValue(this, item.ValValue);
            }
        }
    }
}

it cause error:

ArgumentException: Object of type 'System.Double' cannot be converted to type 'System.Single'. System.RuntimeType.CheckValue (System.Object value, System.Reflection.Binder binder, System.Globalization.CultureInfo culture, System.Reflection.BindingFlags invokeAttr) (at :0) System.Reflection.MonoField.SetValue (System.Object obj, System.Object val, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, System.Globalization.CultureInfo culture) (at :0) System.Reflection.FieldInfo.SetValue (System.Object obj, System.Object value) (at :0) TestReflectEnum.ApplyFields () (at Assets/Scripts/TestReflectEnum.cs:82)

i think reflect fieldinfo.setvalue need the exactly object type to fill in,so i change code like this:

object obj = Convert.ChangeType(item.ValValue, item.ValType);
finfo.SetValue(this, obj);

but still cause error:

InvalidCastException: Object must implement IConvertible. System.Convert.ChangeType (System.Object value, System.Type conversionType, System.IFormatProvider provider) (at :0) System.Convert.ChangeType (System.Object value, System.Type conversionType) (at :0) TestReflectEnum.ApplyFields () (at Assets/Scripts/TestReflectEnum.cs:82)

now the only way for me is write out all kind of object type condition,and change type object one by one,it's so troublesome way,i hope there is a common function for read object from txt/json,and could setvalue right - -





vendredi 3 décembre 2021

How do I determine the type of a Python type annotation at runtime?

I want to inspect the type annotation of a class variable, and if it is a typing.Literal, extract the literal value and do something with it. But:

from typing import Literal
class Foo:
    bar: Literal['baz']

l = Foo.__annotations__['bar']
isinstance(l, Literal)

yields:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/tbabb/.pyenv/versions/3.8.5/lib/python3.8/typing.py", line 342, in __instancecheck__
    raise TypeError(f"{self} cannot be used with isinstance()")
TypeError: typing.Literal cannot be used with isinstance()

Also, l.__class__ == Literal is False, so that doesn't work either.

Why doesn't the isinstance() check succeed? How do I check the type of annotation that's being used?





Access Class at runtime with reflections from JAR file

I'm working on a correcting system for assignments for students. Let me try to break my problem down into a simple example.

The projects I want to check look like this:

  • project-name
    • src

      • Task1

        • Solution1.java
        • Solution2.java

Now I want to check if the project has a correct implementation, but I can not assure, that Solution1.java exists, so I'm using reflection to access the classes.

I'm copying a package into the src folder, so the new project looks like this.

  • project-name
    • src

      • Task1

        • Solution1.java
        • Solution2.java
        • Correction
          • Correction.java

I don't know, if the Solution.java actually exists, so I'm using reflections.

Class.forName("Task1.Solution1");

Now I'm compiling everything inside the project and run the Correction.java - file in Linux.

This works fine so far.

In order to speed up the process, I tried to create a Solution.jar file, so I don't have to compile the file for every project. When I run the jar-file I'm getting a ClassNotFound exception, when I try to access Solution1. The jar file lies within the Correction-package.

I'm starting inside the src folder, and I run:

java -jar ./Correction/Correction.jar

Does anyone know, why this might be happening?





How to get value of KProperty1

I have an object

I try to get access to field "english"

val englishSentence = dbField::class.declaredMemberProperties.filter { it.name == "english" }[0]

But when I

model.addAttribute("sentence", englishSentence)

I get val com.cyrillihotin.grammartrainer.entity.Sentence.english: kotlin.String

while I expect bla





How to cast object to interface with generic type [duplicate]

I want to cast an object instantiated from the Activator to a interface with a generic type.

public interface IFoo { }

public interface IBar<T> where T : IFoo {
   void Bal(T item);
}

public abstract class Bar<T> : IBar<T>
  where T : IFoo
{ 
  public abstract void Bal(T item);
}

public class Foo : IFoo
{ }

Now I have a lot of classes like Baz:

public class Baz : Bar<Foo>
{
  public override void Bal(Foo item);
}

I instantiale Baz with the activator.

var instanceOfBaz = Activator.CreateInstance(typeof(Baz));

Now I want to cast Baz back to the base implementation so I can call method Bal from the caller.

public IBar<IFoo> CreateInstanceOfBaz()
{
  var instanceOfBaz = Activator.CreateInstance(typeof(Baz));

  var castedBaz = (IBar<IFoo>) instanceOfBaz;
  var alsoCastedBaz = instanceOfBaz as IBar<IFoo>;

  return castedBaz;
}

But castedBaz will throw a InvalidCastException and alsoCastedBaz is null. So now I can't call the Bal method, nor get the object as IBar<IFoo>. I need this because I have a List of the IBar<IFoo> which I need in another place.

Above code will compile because the relations are valid, but runtime it will fail.

The project is running .NET Framework 4.7.2 and C# 7.

How do I solve my project so I can get the instantiated object as IBar<IFoo>? It is not an option to use reflection to call the Bal method, because I will still need the object in my list.





jeudi 2 décembre 2021

JSon deserialization of runtime types

I'm working on a small (.Net 5 wpf) app, which loads and saves its state from/into json files (using Newtonsoft library). I save it with $type and $id fields.

Now I have added a plugin system, where I load assemblies from a folder and create objects from them into my app state (say, my model/viewmodel). When I'm saving my model, everything runs fine. I checked the $type, and it's the real name.

My issue is: how to load it back (without writing custom parsing code) ? My plugin types are stored in a List in my plugin service, and newtonsoft has no knowledge of them. So, I have 2 questions:

  • how do I tell newtonsoft lib to take my types into account ?
  • and/or how do I tell the environment running my app (framework ? app domain ?) to meet my types, and consider them as known for the rest of the time my app is launched ?

I have no useful code to show cause everything happens in a DeserializeObject() method. Thank you for any help.





Set a property given a lambda expression for that property

I'm looking to create a slick helper function that compares two values, returns true if they are different, and also updates the first value to equal the second value. This is what I came up with:

bool UpdateHelper<T>(ref T originalProperty, T newProperty) =>
    !Equals(originalProperty, newProperty) && (originalProperty = newProperty) is T _;

bool changes = false;
changes |= UpdateHelper(ref name, frmName.Text);
changes |= UpdateHelper(ref description, frmDescription.Text);
...

The goal is that when doing this for dozens of properties, to avoid copy-pasting the same 5 lines of code for each property:

if (myModel.SomeProperty != someUserInput.Text)
{
   myModel.SomeProperty = someUserInput.Text
   changes = true
}

(Especially after having seen someone copy paste and update the if statement portion but forgetting to update the assignment!)

My above helper works for for the most part, but unfortunately this falls apart when I try to use it on properties:

changes |= UpdateHelper(ref myModel.Name, frmName.Text);
changes |= UpdateHelper(ref myModel.Description, frmDescription.Text);

Property access returns temporary value. 'ref' argument must be an assignable variable, field or an array element

Can anyone think of a solution that would work for both?


I tried playing around with expressions, e.g.:

bool UpdateHelper<T>(Expression<Func<T>> originalProperty, T newProperty) =>
    !Equals(originalProperty.Compile().Invoke(), newProperty) && (originalProperty.Body.??? = newProperty) is T _;

changes |= UpdateHelper(() => myModel.Name, frmName.Text);
changes |= UpdateHelper(() => myModel.Description, frmDescription.Text);
changes |= UpdateHelper(() => myModel.ChildObject.Name, frmChildName.Text);

but I feel like it's going to turn into a nightmare of parsing expression trees, especially if it needs to handle a special case of accessing properties nested a few layers down (like the last example above).

Anyone ideas for how to do this elegantly?





How to get list of method names present in a .cs class file using C# .NET [closed]

Consider that, I have a .cs file present at a physical location which has the following information

using System;

namespace GetMethodNamesFromCsFile
{
    class Program
    {
        void Main(string[] args)
        {
            GetName();
            GetAddress();
            GetPhoneNumber();
            Console.WriteLine("Hello World!");
        }
        //Private Mehtods
        private void GetName()
        {
            Console.WriteLine("Test Name");
        }
        public void GetAddress()
        {
            Console.WriteLine("Test Address");
        }
        protected void GetPhoneNumber()
        {
            Console.WriteLine("Test Phone");
        }
    }
}

So, I wanted to write a separate console program which will return me the list of methods present in the .cs file.





How to know if Invoke was called in C#

I have an event Action Event in my code.

where I put many events there like this:

  public class TheClass 
  {
        public static Action Event;
    
        public TheClass() {
            // dummy example but many others methods could be registerd here 
            //even outside this class because it is static
            TheClass.Event += myMethod;
        }
    
        public void myMethod() {
            // dummy example
        }

        public void DoInvokeTest() {
            Event.Invoke(); // here I'd like to know if my method was invoked and by who
        }
}

How to know if myMethod was called and by who on Even.Invoke()





Create instance of struct via reflection and set values

what I try to do

I try to pass an instance of a struct - including json tags to a func, create a new instance, and set value on field
after this i try to serialize (JSON), but the values are empty

NOTICE: i looked up loads of articles on SO about setting values via reflection, but it seems i missed a little detail

struct definition

this part defines the struct with json and xml tags

type Person struct {
    Name string `json:"Name" xml:"Person>FullName"`
    Age  int    `json:"Age" xml:"Person>Age"`
}

create instance (+wrapping into empty interface)

afterwards I create an instance and store it in an interface{} - why? because in my production code this stuff will be done in a func which accepts a interface{}

var iFace interface{} = Person{
        Name: "Test",
        Age:  666,
    }

creating a new instance of the struct and setting values via reflection

iFaceType := reflect.TypeOf(iFace)
    item := reflect.New(iFaceType)
    s := item.Elem()
    if s.Kind() == reflect.Struct {
        fName := s.FieldByName("Name")
        if fName.IsValid() {
            // A Value can be changed only if it is
            // addressable and was not obtained by
            // the use of unexported struct fields.
            if fName.CanSet() {
                // change value of N
                switch fName.Kind() {
                case reflect.String:
                    fName.SetString("reflectedNameValue")
                    fmt.Println("Name was set to reflectedNameValue")
                }
            }
        }
        fAge := s.FieldByName("Age")
        if fAge.IsValid() {
            // A Value can be changed only if it is
            // addressable and was not obtained by
            // the use of unexported struct fields.
            if fAge.CanSet() {
                // change value of N
                switch fAge.Kind() {
                case reflect.Int:
                    x := int64(42)
                    if !fAge.OverflowInt(x) {
                        fAge.SetInt(x)
                        fmt.Println("Age was set to", x)
                    }
                }
            }
        }
    }

Question

what am I doing wrong?
in production code I fill multiple copies with data and add it to a slice...
but this only makes sense if the json tags are kept in place and the stuff serializes just the same way.

code sample for play

package main

import (
    "encoding/json"
    "fmt"
    "reflect"
)

func main() {
    type Person struct {
        Name string `json:"Name" xml:"Person>FullName"`
        Age  int    `json:"Age" xml:"Person>Age"`
    }

    var iFace interface{} = Person{
        Name: "Test",
        Age:  666,
    }
    fmt.Println("normal: \n" + JSONify(iFace))
    iFaceType := reflect.TypeOf(iFace)
    item := reflect.New(iFaceType)
    s := item.Elem()
    if s.Kind() == reflect.Struct {
        fName := s.FieldByName("Name")
        if fName.IsValid() {
            // A Value can be changed only if it is
            // addressable and was not obtained by
            // the use of unexported struct fields.
            if fName.CanSet() {
                // change value of N
                switch fName.Kind() {
                case reflect.String:
                    fName.SetString("reflectedNameValue")
                    fmt.Println("Name was set to reflectedNameValue")
                }
            }
        }
        fAge := s.FieldByName("Age")
        if fAge.IsValid() {
            // A Value can be changed only if it is
            // addressable and was not obtained by
            // the use of unexported struct fields.
            if fAge.CanSet() {
                // change value of N
                switch fAge.Kind() {
                case reflect.Int:
                    x := int64(42)
                    if !fAge.OverflowInt(x) {
                        fAge.SetInt(x)
                        fmt.Println("Age was set to", x)
                    }
                }
            }
        }
    }
    fmt.Println("reflected: \n" + JSONify(item))
}

func JSONify(v interface{}) string {
    var bytes []byte
    bytes, _ = json.MarshalIndent(v, "", "\t")
    return string(bytes)
}





mercredi 1 décembre 2021

Java using a '<' symbol to read file contents from command line [closed]

I am trying to solve the josephus problem, but with a bit of a twist when it comes to syntax. The user needs to be able to enter data in the following format:

java Josephus 3 java.util.ArrayList < test.txt

the 3 is used as the number of people skipped in the problem itself, but the rest is where it becomes complicated, the user is to enter the name of a class that extends a list, as well as use the '<' symbol to enter the file to be used, only problem is I have no earthly idea how to access the contents of this file and reflect the classname to create an object

edit: for clarification, the test.txt file contains names, and will be taken into the list as strings.

I am currently using the following line for reflection:

List list = (List) Class.forName(args[1]).getDeclaredConstructor().newInstance();

and the following lines for reading from the file:

      Scanner scan =  new Scanner(System.in);

      while (scan.hasNext()) {
         list.add(scan.next());
      }




Is it possible to determine lvalue at compile / run time?

Out of curiosity: is it possible to determine lvalue at compile / run time?

Example:

int x1 = 1;
#define x2 2

bool b1 = IS_LVALUE(x1)?   // true
bool b2 = IS_LVALUE(x2)?   // false

Something like this, but for C.





How to get all types into a reference interop assembly

I have a couple interop assemblies which i need to get all types in them. I have seen this question and it does not work and doesn't apply to my case. All these referenced assembly are used in my application directly but are not showing anywhere.

What i have tried and with the results i get is the following. Note that i simply tried with a single random class i have laying around and it does do same for all the other interop library i have in the project.

// Doesn't contain the assembly SldWorks.
var allAssemblies = AppDomain.CurrentDomain.GetAssemblies().ToList();

// {MyApp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null}
// this is wrong
var assemblyOfClassInDLL = System.Reflection.Assembly.GetAssembly(typeof(Component2));

// {MyApp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null}
// this is wrong
var assemblyOfClassInDLL2 = typeof(Component2).Assembly;

// SldWorks.Component2, MyApp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// this is very wrong
var assemblyNameOfClassInDLL = typeof(Component2).AssemblyQualifiedName;

// Doesn't contain the assembly SldWorks.
var referencedAssemblies = System.Reflection.Assembly.GetExecutingAssembly().GetReferencedAssemblies();

try
{
    var testLoad = System.Reflection.Assembly.Load(assemblyNameOfClassInDLL);
}
catch (Exception ex)
{
    // Could not load file or assembly 'SldWorks.Component2\, MyApp\, Version\=0.0.0.0\,
    // Culture\=neutral\, PublicKeyToken\=null' or one of its dependencies. The given assembly name or codebase
    // was invalid. (Exception from HRESULT: 0x80131047)
}

Note above that Component2 is a class within the assembly SldWorks which is an interop dll. Although the only line that seems to find it is typeof(Component2).AssemblyQualifiedName which return it wrong as it thinks it's in MyApp. Then you see in the Try...Catch that i am tryin to load that same assembly i just receive from the code and it crashes. Why C# return an assembly name that definitively do not exist ?

It msut be possible as i can in visual studio browse everything within the Object Browser window. So if the solution is to use the same code the Object Browser window does it's not an issue and performance either. This code save literally about 2 or 3 days work every time it's used instead of writing manually every class in a DLL in the code and update every time the companies release automatic updates.

I only have 2 requirements :

1 - I ONLY get to receive an object that i need to find it's type and assembly it come from and return all the types in the same assembly

2 - My app is a dynamically loaded addin so it is NOT an executable





mardi 30 novembre 2021

What is the best way of getting default value from Type

I have Type and I want to get the default value. For example, if Type is class or nullable I should get null. But if it is integer, DateTime. decimal, ... I should get 0. What is the best way of doing this?





lundi 29 novembre 2021

Java Reflect newInstance() causing a ConcurrentModificationException (CME) resulting in a crash

To sum up my project I'm trying to make an event processor that runs methods from a given list of methods. In order to invoke these methods I need to pass in the newInstance of the method. The method is correctly run, however, right after the whole program crashes with a "ConcurrentModificationException".

@EventHandler
private Listener<EventKeyInput> eventKeyInput = new Listener<>(event ->
{
    for(Method m : event.getMethods())
    {
        try {
            m.invoke(m.getDeclaringClass().newInstance(), event);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

});

One of the methods I wish to call

@EventAnnotation()
public void eventKeyInputeTest(EventKeyInput event)
{
    System.out.println("EventKeyInput test!");
}

Please let me know if I need to provide anymore code. Thank you for any help!





Dynamic execution of methods and registration of event handlers with reflection in c#

I have a series of instruments with different implementations that share the same IInstrument interface, the instantation was made in this way:

public async Task<object> CreateInstrumentDriver(dynamic input)
    {
        IInstrument instrument = ((string)input.Name) switch
        {
            InstrumentA.DRIVER => new InstrumentADriver(),
            InstrumentB.DRIVER => new InstrumentBDriver(),
            InstrumentC.DRIVER => new InstrumentCDriver(),
            _ => throw new NotSupportedException($"{input.driverName} is not supported"),
        };

        return new
        {
            connect = (Func<object, Task<object>>)(
                async (dynamic arg) =>
                {
                    var info = new InstrumentConnectionInfo
                    {
                        Id = (string)arg.id,
                        Name = (string)arg.name
                    };

                    InstrumentDescriptor descriptor = await instrument.Connect(info);

                    return descriptor.CovertToJSONObject();
                }
            ),
            disconnect = (Func<object, Task<object>>)(
                async (dynamic arg) =>
                {
                    await instrument.Disconnect();
                    return null;
                }
            ),
            calibrate = (Func<object, Task<object>>)(
                async (dynamic arg) =>
                {
                    return await instrument.Calibrate();
                }
            ),
            measure = (Func<object, Task<object>>)(
                async (dynamic arg) =>
                {
                    Measurement measurement = await instrument.Measure();
                    return measurement.CovertToJSONObject();
                }
            ),
            status = (Func<object, Task<object>>)(
                async (dynamic arg) =>
                {
                    return instrument.ConnectionStatus;
                }
            ),
            descriptor = (Func<object, Task<object>>)(
                async (dynamic arg) =>
                {
                    return instrument.Descriptor;
                }
            ),
            onStatusChanged = (Func<object, Task<object>>)(
                async (dynamic arg) =>
                {
                    instrument.OnConnectionChanged += (InstrumentConnectionStatus status) =>
                    {
                        ((Func<object, Task<object>>)arg.handler)(status);
                    };

                    return null;
                }
            ),
            onRemoteMeasureRequested = (Func<object, Task<object>>)(
                async (dynamic arg) =>
                {
                    instrument.OnRemoteMeasureRequested += () =>
                    {
                        ((Func<object, Task<object>>)arg.handler)(null);
                    };

                    return null;
                }
             ),
            onRemoteMeasurementResult = (Func<object, Task<object>>)(
                async (dynamic arg) =>
                {
                    instrument.OnRemoteMeasurementResult += (Measurement measurement, InstrumentRemoteMeasurementStatus status, string message) =>
                    {
                        ((Func<object, Task<object>>)arg.handler)(new { measurement, status, message }.CovertToJSONObject());
                    };

                    return null;
                }
             )
        };
    }

Now I'm calling the instrument instance with this code and it's OK, the object MyInstance is populated correctly with all methods and events of DeviceA and I can persist it somewhere for future use:

var instrumentInstance = new DeviceLib.Startup();
object MyInstance = await instrumentInstance.CreateInstrumentDriver(new InstrumentConnectionInfo { Name = "DeviceA" });

Now the dumb question, since I've not written the CreateInstrumentDriver method (which I admit I din't fully understood the syntax) but in some way I have to call it from another project (where the dll that contains the methos is linked of course) how I can, (I imagine using Reflection) invoke the various functions (connect, calibrate, measure...) and register the event handlers (onStatusChanged, onRemoteMeasureRequested... ) possibly in a dynamic way so, for example if I have in input a string variable with the value "connect" I can invoke the method "connect" (with its parameters), in brief I need a sort of a dynamic Execute(string command, dynamic params) method and a way for dynamically handling the events generated by the instrument so I can execute some code when they have been triggered





dimanche 28 novembre 2021

Create instance of implementation of generic class based on type of Class

I have the following class layout:

abstract class GenericClass<TArgs> where TArgs : ArgsBaseClass { }
abstract class ArgsBaseClass { }

class RandomArgs : ArgsBaseClass { }
class RandomClass : GenericClass<RandomArgs> { }

Now I want to be able to create an instance of RandomClass from an instance of RandomArgs, without knowing that it should be RandomClass. I.e. somehow I need to derive the fact that RandomClass implements GenericClass<RandomArgs>.

I'm able to create an instance of GenericClass<RandomArgs> using:

void CreateSpecificInstance(ArgsBaseClass args)
{
    Type genericType = typeof(GenericClass<>).MakeGenericType(typeof(args));
    var genericInstance = Activator.CreateInstance(genericType, typeof(args));
    // But then I need help for the following step:
    Type specificType = ...  // in this case RandomClass, but should be derived from 'args'.
    var specificInstance = (specificType)genericInstance;
}

Any help is appreciated.





Getting access to class methods after creating an object using reflection

I get different class names (String) from external source e.g: reflection.Test1, reflection.Test2, reflection.OtherTest etc.

I need change these classes to new Objects so that I can use all the methods of a given object I am trying to create a dedicated method:

public static <T extends Base> T createObject(String nameOfClass) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        Class<T> clazz = (Class<T>) Class.forName(nameOfClass);
        return clazz.getDeclaredConstructor().newInstance();
    }

But when I try to use it:

createObject("reflection.Test1").fillTest1();  //I want to use method fillTest1 from Test1.class
or:
createObject("reflection.Test2").fillTest2(); // //I want to use method fillTest1 from Test1.class

i get error in IntelliJ:

Cannot resolve method 'fillTest1' in 'Object'

How to make these methods visible? IntelliJ gives me access only to methods in Base.class: I can't see method in my Test1.class and Test2.class

Main.class:

public class Main {
    public static <T extends Base> T createObject(String nameOfClass) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        Class<T> clazz = (Class<T>) Class.forName(nameOfClass);
        return clazz.getDeclaredConstructor().newInstance();
    }

    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        // ... I get different class names from external source e.g: reflection.Test1, reflection.Test2, reflection.OtherTest etc.
        createObject("reflection.Test2").fillTest1(); //error :(
    }
}

Test1.class:

package reflection;

public class Test1 extends Base{
    private String name;

    public void fillTest1(String name){
        this.name = name;
    }

}

Test2.class:

package reflection;

public class Test2 extends Base{
    private String test2;

    public void fillTest2(String test2){
        this.test2 = test2;
    } }

Base Class:

package reflection;

public class Base {
    public void setBase(){
        System.out.println("Base method");
    }
}




samedi 27 novembre 2021

Extension method for string variable to read attribute

I have a class with string constants:

public static class Days 
{
    [Description("Wow!")]
    public const string Mon = "Hi!";
}

I've found that it is possible for enum to have an extension method to read Description attribute:

using System.ComponentModel;
public enum Days 
{    
    [Description("Wow!")]
    Mon
}

An extension method for enum:

public static string ToName(this Enum value) 
{
    var attribute = value.GetAttribute<DescriptionAttribute>();
    return attribute == null ? value.ToString() : attribute.Description;
}

And call it like that:

Days.Mon.ToName()

Is it possible to write an extension method for string to get Wow! from Description attribute of Mon string variable and call extension method for string like that?

string description = Days.Mon.ToName(); // Output: "Wow!"




Kotlin Android reflection get class in runtime

I have a response from the server that returns me different objects and each object has a type. How I can match class in runtime with the type I get from the response? This code for example works but I am trying to get rid of the when statement and make it more dynamic.

   JsonParser.parseString(jsonArrayString).asJsonArray
            .map { tileJsonObject ->
                tileJsonObject as JsonObject
                val tile = when (tileJsonObject.get("type").asString) {
                    Red.TYPE -> Red::class.java
                    Blue.TYPE -> Blue::class.java
                    else -> Red::class.java
                }
                Gson().fromJson(tileJsonObject, tile)
            }
    }




vendredi 26 novembre 2021

Dynamically casting objects from FieldInfo.GetValue in c#

I'm trying to iterate through all the fields in an instance of a class and extract their name / data. The fields themselves are instances of custom classes for storing data with some specific features I needed. The following works:

        foreach (var v in typeof(CentralParams).GetFields())
        {

            if(v.GetValue(_centralParams).GetType() == typeof(BoolEventProperty))
            {
                BoolEventProperty prop = (BoolEventProperty) v.GetValue(_centralParams);
                print(v.Name + "   " + prop.Value);
            }
            
            if(v.GetValue(_centralParams).GetType() == typeof(FloatEventProperty))
            {
                FloatEventProperty prop = (FloatEventProperty) v.GetValue(_centralParams);
                print(v.Name + "   " + prop.Value);
            }
            
            if(v.GetValue(_centralParams).GetType() == typeof(IntEventProperty))
            {
               IntEventProperty prop = (IntEventProperty) v.GetValue(_centralParams);
               print(v.Name + "   " + prop.Value);
            }

        }

However I have to manually check for the type of the object in the field, then cast it to a new instance of that type in order to access the Value member. This is annoying as every time I add a new data type to the CentralParams class I will have to handle it explicitly here.

Is there a way I can dynamically cast it to an empty variable of the correct type?

v.GetValue(_centralParams).GetType() returns the type I need so seems like it should be possible.

Something along the lines of

            var type = v.GetValue(_centralParams).GetType();

            var prop = (type)v.GetValue(_centralParams);

Thanks





jeudi 25 novembre 2021

Sneaky Inject variable in class constructor

I'm using typescript for test automation and I have a tons of classes like this:

class Something {
//properties
constructor(page:Page){}
//methods
}
class Account {
//properties
constructor(page:Page, accountNumber: string){}
//methods
}
class Navigation {
//properties
constructor(page:Page, navigation: NavigationStrategy){}
//methods
}

same page:Page object I should pass to all my constructors e.g

it("some test" async => {
const page = await browser.newPage();
const searchPage = new SearchPage(page);
const account = new Account(page, "2135");
const navigation = new Navigation(page, new LHSNavigation(page));
})

How can I automaticaly inject this page object to all constructors? For examaple I want to get next result

it("some test" async => {
const page = await browser.newPage();
const pageProvider = new PageProvider(page)
const searchPage = pageProvider.create(SearchPage);
// OR
const account = pageProvider.create(Account)("2135");

// OR maybe
const navigation = pageProvider.create(Navigation, LHSNavigation);
})
//Or maybe without page provider
const navigation = Navigation(LHSNavigation);

And all types should be resolved in compile time