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?