lundi 16 mars 2020

How to modify TestNG/Allure (@Test(description), @Description, @TmsLink) values based on DataProvider supplied test parameters

Given a TestNG test class with dataProvider and Allure for reporting, it is required to modify Allure's report to have a (@Test(description), @TmsLink, @Description) values depending on DataProvider.

Is there a simple way to do it?

Note: I tried changing test name by using ITest interface, but has no effect on Allure report, I need TestNG test description and Allure @Decription & @TmsLink values modified.





Handle COM events in C# using Reflection

I have a COM object with the main interface and the events interface (from the IDL file):

[
    uuid(<interfaceId>,
    helpstring("AxBitViewerWidget Interface")
]
dispinterface IAxBitViewerWidget
{
    ...
};

[
    uuid(<eventsId>),
    helpstring("AxBitViewerWidget Events Interface")
]
dispinterface IAxBitViewerWidgetEvents
{
    ...
};

[
    aggregatable,
    helpstring("AxBitViewerWidget Class"),
    uuid(<mainClassId>), 
    control
]
coclass AxBitViewerWidget
{
    [default] dispinterface IAxBitViewerWidget;
    [default, source] dispinterface IAxBitViewerWidgetEvents;
};

It was automatically created by Active Qt. Then in C# (in another dll) I want to connect to this COM object and handle its events. The C# class is inherited from AxHost. All COM types are dynamic in my example and used via Reflection. Here is the snippet:

public class BitViewerEx : AxHost
{
    public BitViewerEx()
      : base(<mainClassId>)
    {
    }

    private void Initialize()
    {
        try
        {
            object ocx = GetOcx();
            if (ocx != null)
            {
                Type ocxType = ocx.GetType();
                Guid eventsGuid = new Guid(<eventsId>);
                Type eventsType = Type.GetTypeFromCLSID(eventsGuid);                
                var sinkEventsInterfaceObj = CreateInstanceCore(eventsGuid);

                // runtime error here
                var cookie = new ConnectionPointCookie(ocx, sinkEventsInterfaceObj, eventsType);
            }
        }
        catch (Exception ex)
        {
            System.Diagnostics.Trace.WriteLine(ex.ToString());
        }
    }
}

When calling ConnectionPointCookie from the above - an error occurs (approximately translated from localized message): "Cannot execute Advise() for the event interface '__ComObject'".

Is my code correct? How to correctly connect AxBase to the COM object events? (for dynamic types case, cannot use IAxBitViewerWidgetEvents etc. in C# code)

P.S.: class methods (not events) are called without an issue, like:

ocx.GetType().InvokeMember("initialize", System.Reflection.BindingFlags.InvokeMethod,
                                                null, ocx, new object[] { this.argum1, this.argum2 });

P.S.2: The following code returns an empty array:

System.Reflection.EventInfo[] arr = ocx.GetType().GetEvents();




Using Reflection to find variable names of non instantiated classes

I have been trying to find all the variables of a script through reflection. If a script is attached to the game object or in the scene, then there is no problem getting information about that script, but when I take a script from the project, the below code cannot access any info. It could be something related to Serialization or having to call a constructor at runtime, but I cannot figure out how to do that.

public List<UnityEngine.Object> AllScripts;

[ContextMenu("Test")]

public void Test()

{

var bindingFlags = BindingFlags.Instance |

BindingFlags.NonPublic |

BindingFlags.Public |

BindingFlags.Static ;

foreach (var aObj in AllScripts)

{

Type aType = aObj.GetType();

var aInstance = aType.GetConstructor(Type.EmptyTypes);

var aList = aObj.GetType().GetFields(bindingFlags);

string[] res = Directory.GetFiles(Application.dataPath, aObj.GetType().ToString().Replace("namespace.","") + ".cs", SearchOption.AllDirectories);

Debug.LogError( res[0]+" " + aList.Length + " " + aObj.GetType());

foreach (var aVal in aList)

{

Debug.LogError( aVal.Name+ "" +aVal.IsStatic);

}

}

}




Making a "register method" function [closed]

I am trying to make an Assembly that allows me to do networking for video games, the problem i am facing is having a way to call methods on both sides of the connection so what i thought of doing is to have a List<Action> to store the methods and be able to call them through the network with a index number (for packet weight)

The part that is giving me a bad time is:

How to register those methods in the list so the list is the exact same on every machines

and workflow wise accessing them efficiently (being able to use autocomplete to know what "Command" method is accessible) but i'm facing several problems:

  • The List<Action> has to have a sort of hardcoded order so its the same on every machines so no runtime initialisation

  • Workflow wise it would good be able to get the methods by name in a autocomplete kind of way

  • It has to be loosely coupled in a way that i can compile to a .dll and use it in a other project

For now i tried those things:

  • To register the methods i tried Reflection and Attributes, i tag the methods with an attribute and at runtime i look trought the Assembly for those and add them to the List, i'm hoping the order won't differ from a machine to an other

  • I didn't found a good way to get a method other than iterating through the List by name, i could make a widget that generate some code like an enum but i'd like to avoid code generation as much as possible

  • For the loose coupling the Reflection + Attributes combo could do the trick i'd have to look through the whole solution instead, i still need to find a way to get the methods from the list efficiently

Any bit of wisdom would be appreciated





dimanche 15 mars 2020

Check if a field is true or false with reflections in java

Currently trying to code some menu functionality and wondered if there’s a way to find out if a boolean field is true or false. This is the code I’m currently trying but I get an error

try{

     field = a.getClass().getField(b); 

     if(toggle==1&&field){
     }else if(toggle==1&&!field){
       field.set(a, true);
     }else if(toggle==0&&!field){
     }else if(toggle==0&&field){
       field.set(a, false);
     }
}catch (NullPointerException e) {
}catch (NoSuchFieldException e) {
}catch (IllegalAccessException e) {
}

The error is

The operator && is undefined for the argument type(s) boolean, Field




C# Networking - How to register methods reliably

Ok this might be a tought one,

I am making my multiplayer transport layer for my game and i am getting at the RPC part, so what i need is to have methods that i can call over the network, immidiatly i thought of a List at least for the simple commands that return void, so now i can call the methods with an index number over the network but before i got to the part of actually making reliable/callbacks/threadsafe parts i am having a workflow problem...

How can i register those methods in a way so it is as easy as writing a method anywhere and initiating the network calling by a simple action like just calling the method, the goal is to avoid large code and make sure the methods are linked the same way for all players (ex: KickAllPlayers() should be at the same index on all machines)

To register the methods i thought of Reflection and Attributes, i just put attributes on my methods and at the instantiation of the Server class i get all the methods in the assembly that have the attribute and add them to the list

        [Rpc]
        public void KickAllPlayers()
        {
            throw new NotImplementedException();
        }
        public Server()
        {
            var taggedMethods = from t in Assembly.GetExecutingAssembly().GetTypes()
                                from m in t.GetMethods()
                                where m.GetCustomAttributes<RpcAttribute>().Any()
                                select m;

            foreach (var method in taggedMethods)
            {
                Rpc.Commands.Add((Action)Delegate.CreateDelegate(typeof(Action), null, method));
            }
        }

This is all well and good but now i need to be able to call those methods, i would have loved to be able to just call the methods like any other method KickAllPlayers(); but of course it requires that the method gets changed in some way so when KickAllPlayers(); gets called, under the hood the networking part works out the response from the Server and plays the method as a Callback answere. I have looked all day only to find that the AOP pattern might maybe do it...

So while still keeping the previous code i thought of making a static method responsible for doing the network part, something like

        Server.Call(<Action or Index>); // Send command request to server and return callback method

But now the stupid thing is that i can't rely on autocompletion to pass the right method to call since methods will be registered at runtime, i can probably generate yet an other list for method index but it this is horrible coding design and i'd like to avoid code generation.

Of course i could just write the methods in a ServerCommands class and we could problably call it a day but i had in mind to make this assembly loosely coupled so i could export it to a .dll and use it everywhere...

Is there a way to do this ?

Am i mad ?





automatically detect settings changes using reflection

Hello there stack overflow community, am new and English is not my native language so please be patient with me.

the problem:

i started developing a wpf application using mvvm pattern and faced a problem with having many settings (30+ setting rows some are user defined types that include lists) and needed to implement a way to detect settings changes, so using the "Settings.Default.ProperyChanged" event wasn't enough i needed to detect every value change in all objects that has a ProperyChanged/CollectionChanged event.

my solution:

a helper class that uses reflection to map all settings properties and hook every ProperyChanged/CollectionChanged event to 2 event handlers.

code below is only part of the class code (all explained in comments),please keep in mind that am still learning c# so it might be messy and buggy:

              struct ObservableCollectionInfo
             {
              public object obj { get; set; }
              public PropertyInfo PropertyInfo { get; set; }
              public EventInfo EventInfo { get; set; }
             }

      //mapped lists info 
      private Dictionary<string, ObservableCollectionInfo> ObservableCollectionList;
      //determines if Settings are Changed
      public bool SettingsChanged { get; set; }
      //global count var used in methods below
      int count = 0;

      //Starts mapping settings properties, its called in App class (OnLoadCompleted override)
      public void MappSettingsObjects()
      {
        HookObjectEvents(Settings.Default);
      }

      //object mapping method
      private void HookObjectEvents(object obj)
      {
       count = 0;
       //get object  Properties
       var Properties = obj.GetType().GetProperties();
       //get object  Events
       var Events = obj.GetType().GetEvents();
       //Hook object  Events
       HookEvents(Events, obj);
       foreach (var Property in Properties)
       {
        count++;
        try
        {
         //get Property  Events
         Events = Property.PropertyType.GetEvents();
         //add non observable lists (No NotifyCollectionChanged Event) to Dictionary
         if (Property.GetValue(obj) is IList && Events.Count() == 0)
         {
          var observableCollectionInfo = new ObservableCollectionInfo() { EventInfo = null, obj = obj, PropertyInfo = Property };
          //remove old value if exist
          if (ObservableCollectionList.ContainsKey(Property.Name))
          {
           ObservableCollectionList.Remove(Property.Name);
          }
          //add the new value
          ObservableCollectionList.Add(Property.Name, observableCollectionInfo);
          //maping list items too 
          HookAllListItems(observableCollectionInfo);
         }
         //add Event Handlers
         HookEvents(Events, obj, Property);
        }
        catch (Exception) { }
       }
      }

      private void HookAllListItems(ObservableCollectionInfo info)
      {
       try
       {
        if (info.obj != null)
        {
         var collectionList = info.PropertyInfo.GetValue(info.obj);
         if (collectionList is IList)
         {
          foreach (var item in (collectionList as IList))
          {
           HookObjectEvents(item);
          }
         }
        }
       }
       catch (Exception) { }
      }


      private void HookEvents(EventInfo[] Events, object obj, PropertyInfo Property = null)
      {
       foreach (var Event in Events)
       {
        try
        {
         //comparing events names
         if (Event.EventHandlerType.Name.Equals(nameof(PropertyChangedEventHandler)))
         {
          //add handler
          Event.AddEventHandler(Property == null ? obj : Property.GetValue(obj), new PropertyChangedEventHandler(Default_PropertyChanged));
         }
         else if (Event.EventHandlerType.Name.Equals(nameof(NotifyCollectionChangedEventHandler)))
         {
          var observableCollectionInfo = new ObservableCollectionInfo() { EventInfo = Event, obj = obj, PropertyInfo = Property };
          //add observable list to Dictionary  
          if (ObservableCollectionList.ContainsKey(Property.Name))
          {
           ObservableCollectionList.Remove(Property.Name);
          }
          ObservableCollectionList.Add(Property.Name, observableCollectionInfo);
          HookAllListItems(observableCollectionInfo);
          Event.AddEventHandler(Property == null ? obj : Property.GetValue(obj), new NotifyCollectionChangedEventHandler(Default_CollectionChanged));
         }
         //this condition is to avoid stackoverflow exception (the first Property is the object itself witch causes infinity loop, i dont know why yet)
         if (count > 1)
          //mapping the Property itself
          HookObjectEvents(Property == null ? obj : Property.GetValue(obj));
        }
        catch (TargetParameterCountException)
        {
         //i don't know what causes this exception yet 
        } 
       }
      }

      //Collection Change event handler
      private void Default_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
      {
       //hook new items
       if ((e.Action == NotifyCollectionChangedAction.Add || e.Action == NotifyCollectionChangedAction.Replace) && e.NewItems != null)
        foreach (var item in e.NewItems)
        {
         HookObjectEvents(item);
        }
       //settings changed
       SettingsChanged = true;
      }

      //Property Change event handler
      private void Default_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
      {
       //rehook new lists and its items/events
       if (ObservableCollectionList.ContainsKey(e.PropertyName))
       {
        try
        {
         var info = ObservableCollectionList.FirstOrDefault(li => li.Key == e.PropertyName);
         if (info.Key != null)
         {
          //check if its an observable list or not
          if (info.Value.EventInfo != null)
           //add handler to list changes
           info.Value.EventInfo.AddEventHandler(info.Value.PropertyInfo.GetValue(info.Value.obj), new NotifyCollectionChangedEventHandler(Default_CollectionChanged));
          //hook list items
          HookAllListItems(info.Value);
         }
        }
        catch (Exception) { }
       }
       //settings changed
       SettingsChanged = true;
      }

The code above works fine, all changes are detected even within list items,new items here are some screenshots.

Default Settings:

[https://i.stack.imgur.com/eQPbb.png]

on property changes:

[https://i.stack.imgur.com/u2oK3.png]

on Collection Changes:

[https://i.stack.imgur.com/1Rln3.png]

problems :

  • when using the application for long time while continuously changing the settings makes some changes undetected with no exceptions or warnings what causes this bug ?.

  • with 100+ settings attributes, it starts to slow startup time up to 2-5 seconds, how to improve the code ?.

  • my tutor told me that using reflection is a bad design, so am asking for other mvvm friendly ways if possible (no click/check event handlers in code behind) to detect settings changes i found nothing online.

thanks to anyone that help.