How to send action with AsterNET, C#? - c#

I'm working with AsterNET and C#, I need to get the status of all the extensions, specifically the result of Action: ExtensionStateList but the library doesn't have this action, I'm trying to create it but I can't get it. I hope someone can guide me. Attached is the code.
ResponseEvents re;
try
{
re = manager.SendEventGeneratingAction(new ExtensionStateListAction());
}
catch (EventTimeoutException e)
{
re = e.PartialResult;
}
foreach (ManagerEvent e in re.Events)
{
foreach (KeyValuePair<string, string> d in e.Attributes)
{
Console.WriteLine(e);
}
}
using System;
using AsterNET.Manager.Event;
namespace AsterNET.Manager.Action
{
public class ExtensionStateListAction : ManagerActionEvent
{
public override string Action
{
get { return "ExtensionStateList"; }
}
public override Type ActionCompleteEventClass()
{
return typeof (ExtensionStateListCompleteEvent);
}
}
}
namespace AsterNET.Manager.Event
{
public class ExtensionStateListCompleteEvent : ResponseEvent
{
private int listItems;
public int ListItems
{
get { return this.listItems; }
set { this.listItems = value; }
}
public ExtensionStateListCompleteEvent(ManagerConnection source)
: base(source)
{
}
}
}

Result of this command will come in set of events "ExtensionState" and final "ExtensionStateCompleate"
It will be asyncronous.
You should setup event listener and parse that.

Related

List of objects in C# / Unity and yearly check

I've been working on this app about trees and have found myself stuck. What I have is a Tree class with some attributes to it, like ID, type and others. I need to be able to make a List or some other structure of a user-entered number of trees and have each tree be separately modified (in terms of its attributes). Now a problem I ran into is the fact that I need to have separate attributes for each tree each year (2017, 2018 and so on) since the installation of the app. I seem to not be able to think of a viable solution for this to work. How would I set separate attributes for each year? Hell, how would I even check when a new year is and update the list accordingly? I need the yearly attributes because I need to label a tree that hasn't had problems the past five years as "strong".
Here's the code for my simple Tree class:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Tree : MonoBehaviour {
public string leafType { get { return leafType; } set { } }
public string leafGender { get { return leafGender; } set { } }
public string fruitType { get { return fruitType; } set { } }
public string fruitProblems { get { return fruitProblems; } set { } }
public string bloomingStart { get { return bloomingStart; } set { } }
public string bloomingEnd { get { return bloomingEnd; } set { } }
public string kgHazelnutPerYear { get { return kgHazelnutPerYear; } set { } }
public string problemsInLeaf { get { return problemsInLeaf; } set { } }
public string pests { get { return pests; } set { } }
public string usedPesticides { get { return usedPesticides; } set { } }
public string altitude { get { return altitude; } set { } }
public string region { get { return region; } set { } }
}
Thanks in advance!
you can use Dictionary to manipulate it like bellow
void addYear(string year, Dictionary<string, List<YourTreeClass>> data)
{
if (!data.ContainsKey(year)) data.Add(year, new List<YourTreeClass>());
}
void addTree(string year,YourTreeClass tree, Dictionary<string, List<YourTreeClass>> data)
{
data[year].Add(tree);
}
Dictionary<string, List<YourTreeClass>> data = new Dictionary<string, List<YourTreeClass>>();
addYear("2017", data);
addTree("2017", tree1, data);
addTree("2017", tree2, data);
addYear("2018", data);
addTree("2018", tree3, data);

HttpSessionStateBase losing property values of inherited type

We are using HttpSessionStateBase to store messages in a set up similar to this working example:
public class HttpSessionMessageDisplayFetch : IMessageDisplayFetch
{
protected HttpSessionStateBase _session;
private IList<ICoreMessage> messages
{
get
{
if (_session[EchoCoreConstants.MESSAGE_KEY] == null)
_session[EchoCoreConstants.MESSAGE_KEY] = new List<ICoreMessage>();
return _session[EchoCoreConstants.MESSAGE_KEY] as IList<ICoreMessage>;
}
}
public HttpSessionMessageDisplayFetch()
{
if (HttpContext.Current != null)
_session = new HttpSessionStateWrapper(HttpContext.Current.Session);
}
public void AddMessage(ICoreMessage message)
{
if (message != null)
messages.Add(message);
}
public IEnumerable<IResultPresentation> FlushMessagesAsPresentations(IResultFormatter formatter)
{
var mToReturn = messages.Select(m => m.GetPresentation(formatter)).ToList();
messages.Clear();
return mToReturn;
}
}
When we pass in a QualityExplicitlySetMessage (which inherits from ICoreMessage, see below) it is saved correctly to messages.
This is how the object looks after being inserted into the messages list, at the end of AddMessage(ICoreMessage message) above.
But when we come to access it after changing controllers the inherited member's properties are null, which causes a variety of null reference exceptions.
This is how the object now looks after we call FlushMessagesAsPresentations. I've commented out var mToReturn... as this tries to access one of these null ref properties.
I'd like to ask the following:
Why is the HttpSessionStateBase failing to capture these values taken
by the inherited type?
Is this an issue in saving to the HttpSession or in retrieving?
Is this anything to do with, as I suspect, inheritance?
Or is the fact I'm potentially calling a new controller that dependency injects the HttpSessionMessageDisplayFetch causing an issue?
I'm a first-time poster so please let me know if I'm making any kind of faux pas - Super keen to learn! Any input is very welcome.
Some potentially useful code snippets:
QualityExplicitlySetMessage
public class QualityExplicitlySetMessage : QualityChangeMessage
{
public QualityExplicitlySetMessage(IQPossession before, IQPossession after, IQEffect qEffect)
: base(before, after, qEffect)
{
IsSetToExactly = true;
}
}
QualityChangeMessage - Working example
public abstract class QualityChangeMessage : CoreMessage, IQualityChangeMessage
{
protected PossessionChange Change;
public PossessionChange GetPossessionChange()
{
return Change;
}
protected QualityChangeMessage(IQPossession before, IQPossession after, IQEffect qEffect)
{
Change = new PossessionChange(before, after, qEffect);
StoreQualityInfo(qEffect.AssociatedQuality);
}
public override IResultPresentation GetPresentation(IResultFormatter formatter)
{
return formatter.GetQualityResult(this);
}
#region IQualityChangeMessage implementation
public int LevelBefore
{
get { return Change.Before.Level; }
}
//... And so on with values dependent on the Change property.
}
CoreMessage - Working example
public abstract class CoreMessage : ICoreMessage
{
public string MessageType
{
get { return GetType().ToString(); }
}
public string ImageTooltip
{
get { return _imagetooltip; }
set { _imagetooltip = value; }
}
public string Image
{
get { return _image; }
set { _image = value; }
}
public int? RelevantQualityId { get; set; }
protected void StoreQualityInfo(Quality q)
{
PyramidNumberIncreaseLimit = q.PyramidNumberIncreaseLimit;
RelevantQualityId = q.Id;
RelevantQualityName = q.Name;
ImageTooltip = "<strong>" + q.Name + "</strong><br/>" + q.Description + "<br>" +
q.EnhancementsDescription;
Image = q.Image;
}
public virtual IResultPresentation GetPresentation(IResultFormatter formatter)
{
return formatter.GetResult(this);
}
}
UserController - Working example.
public partial class UserController : Controller
{
private readonly IMessageDisplayFetch _messageDisplayFetch;
public UserController(IMessageDisplayFetch messageDisplayFetch)
{
_messageDisplayFetch = messageDisplayFetch;
}
public virtual ActionResult MessagesForStoryletWindow()
{
var activeChar = _us.CurrentCharacter();
IEnumerable<IResultPresentation> messages;
messages = _messageDisplayFetch.FlushMessagesAsPresentations(_storyFormatter);
var vd = new MessagesViewData(messages)
{
Character = new CharacterViewData(activeChar),
};
return View(Views.Messages, vd);
}
}

After Implementing an UITestPropertyProvider, AccessibleName is still not a valid Searchproperty

I need to implement automatic UI Tests for a Delphi Application with Visual Studio Coded UI Tests. I have already implemented the IAccessible Interface to my Delphi-Contols. It works fine and i get the AccessibleName from the Control.
Then i implemented an extension for visual studio. In this extension i have my own PropertyProvider-, ExtensionPackage- and WinControl-Class.
PropertyProvider:
namespace CUITExtension
{
public class AccessibleNamePropertyProvider : UITestPropertyProvider
{
private static Dictionary<string, UITestPropertyDescriptor> accessibleNamePropertyMap = null;
private static Dictionary<string, UITestPropertyDescriptor> AccessibleNamePropertyMap
{
get
{
if (accessibleNamePropertyMap == null)
{
UITestPropertyAttributes read = UITestPropertyAttributes.Readable
| UITestPropertyAttributes.DoNotGenerateProperties;
accessibleNamePropertyMap = new Dictionary<string, UITestPropertyDescriptor>
(StringComparer.OrdinalIgnoreCase);
accessibleNamePropertyMap.Add("AccessibleName", new UITestPropertyDescriptor(typeof(string), read));
}
return accessibleNamePropertyMap;
}
}
public override UITestPropertyDescriptor GetPropertyDescriptor(UITestControl uiTestControl, string propertyName)
{
return AccessibleNamePropertyMap[propertyName];
}
public override ICollection<string> GetPropertyNames(UITestControl uiTestControl)
{
if (uiTestControl.ControlType.NameEquals("Custom"))
{
// the keys of the property map are the collection of property names
return AccessibleNamePropertyMap.Keys;
}
throw new NotSupportedException();
}
public override object GetPropertyValue(UITestControl uiTestControl, string propertyName)
{
if (String.Equals(propertyName, "AccessibleName", StringComparison.OrdinalIgnoreCase))
{
object[] native = uiTestControl.NativeElement as object[];
IAccessible acc = native[0] as IAccessible;
return acc.accName;
}
throw new NotSupportedException();
}
public override int GetControlSupportLevel(UITestControl uiTestControl)
{
if (string.Equals(uiTestControl.TechnologyName, "MSAA",
StringComparison.OrdinalIgnoreCase) &&
uiTestControl.ControlType.NameEquals("Custom"))
{
return (int)ControlSupport.ControlSpecificSupport;
}
// This is not my control, so return NoSupport
return (int)ControlSupport.NoSupport;
}
public override string[] GetPredefinedSearchProperties(Type specializedClass)
{
return null;
}
public override string GetPropertyForAction(UITestControl uiTestControl, UITestAction action)
{
return null;
}
public override string[] GetPropertyForControlState(UITestControl uiTestControl, ControlStates uiState, out bool[] stateValues)
{
stateValues = null;
return null;
}
public override Type GetPropertyNamesClassType(UITestControl uiTestControl)
{
if (uiTestControl.ControlType.NameEquals("Custom"))
return typeof(AccessibleControl.PropertyNames);
return null;
}
public override Type GetSpecializedClass(UITestControl uiTestControl)
{
if (uiTestControl.ControlType.NameEquals("Custom"))
return typeof(AccessibleControl);
return null;
}
public override void SetPropertyValue(UITestControl uiTestControl, string propertyName, object value)
{
return;
}
}
}
ExtensionPackage:
[assembly: Microsoft.VisualStudio.TestTools.UITest.Extension.UITestExtensionPackage(
"AccessibleNameExtensionPackage",
typeof(CUITExtension.AccessibleNameExtensionPackage))]
namespace CUITExtension
{
class AccessibleNameExtensionPackage : UITestExtensionPackage
{
public override string PackageDescription
{
get { return "Supports coded UI testing by using the AccessibleName"; }
}
public override string PackageName
{
get { return "AccessibleName Extension Package"; }
}
public override string PackageVendor
{
get { return "Microsoft (sample)"; }
}
public override Version PackageVersion
{
get { return new Version(1, 0); }
}
public override Version VSVersion
{
get { return new Version(14, 0); }
}
public override void Dispose() { }
public override object GetService(Type serviceType)
{
if (serviceType == typeof(UITestPropertyProvider))
{
if (propertyProvider == null)
{
propertyProvider = new AccessibleNamePropertyProvider();
}
return propertyProvider;
}
return null;
}
private UITestPropertyProvider propertyProvider = null;
}
}
WinControl:
namespace CUITExtension
{
public class AccessibleControl : WinControl
{
public AccessibleControl(UITestControl c) : base(c)
{
TechnologyName = "MSAA";
SearchProperties.Add(UITestControl.PropertyNames.ControlType, "Custom");
}
public virtual string AccessibleName
{
get
{
return (string)GetProperty("AccessibleName");
}
}
}
}
Now the Coded UI Test Builder is showing the AccessibleName and is also generating AccessibleName as a SearchProperty.
UIMap:
public AccessibleControl UIItemCustom
{
get
{
if ((this.mUIItemCustom == null))
{
this.mUIItemCustom = new AccessibleControl(this);
#region Search Criteria
this.mUIItemCustom.SearchProperties["AccessibleName"] = "UniqueName1";
this.mUIItemCustom.SearchProperties[WinControl.PropertyNames.ClassName] = "TEdit";
this.mUIItemCustom.WindowTitles.Add("Title");
#endregion
}
return this.mUIItemCustom;
}
}
*I have changed the Searchproperties here (only for the post, i didnt changed the generated code)
Now when I start the test, I get an exception that says that AccessibleName is not an valid searchproperty. I got this exception before, when i havent implemented the extension yet. But I thougth by implementing the propertyprovider AccessibleName should be a valid searchproperty now.
I tried to debug it, but it seems like by searching the Control it doesnt use the propertyprovider and i have no idea why?
I hope you can help me and if you need more information just ask.
Paul
I got the problem with the valid searchproperty to work.
I overrode the GetValidSearchProperties method from WinControl.
protected override Dictionary<string, bool> GetValidSearchProperties()
{
Dictionary<string, bool> searchProperties = base.GetValidSearchProperties();
if (!searchProperties.ContainsKey("AccessibleName"))
searchProperties.Add("AccessibleName", true);
return searchProperties;
}

Get Property of generic type object without knowing the generic type

I need to see a property of an object which is of a generic type, without knowing the specific type:
foreach(var n in Nodes)
{
if(n.GetType().GetGenericTypeDefinition() == typeof(VariableNode<>))
{
if((n as VariableNode<>).Variable == myVar) //obviously this does not work
{
toRemove.Add(n);
}
}
}
So, what would be the most elegant way to check the property "Variable" ? (variable is a reference type)
Thanks!
EDIT:
Def of Node:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using KSPComputer.Types;
using KSPComputer.Connectors;
namespace KSPComputer.Nodes
{
[Serializable]
public abstract class Node
{
public SVector2 Position;
public int InputCount
{
get
{
return inputs.Count;
}
}
public int OutputCount
{
get
{
return outputs.Count;
}
}
public FlightProgram Program { get; private set; }
private Dictionary<string, ConnectorIn> inputs;
private Dictionary<string, ConnectorOut> outputs;
public KeyValuePair<string, ConnectorIn>[] Inputs
{
get
{
return inputs.ToArray();
}
}
public KeyValuePair<string, ConnectorOut>[] Outputs
{
get
{
return outputs.ToArray();
}
}
public Node()
{
Position = new SVector2();
inputs = new Dictionary<string, ConnectorIn>();
outputs = new Dictionary<string, ConnectorOut>();
}
internal virtual void Init(FlightProgram program)
{
Program = program;
OnCreate();
}
protected void In<T>(string name, bool allowMultipleConnections = false)
{
var connector = new ConnectorIn(typeof(T), allowMultipleConnections);
connector.Init(this);
inputs.Add(name, connector);
}
protected void Out<T>(string name, bool allowMultipleConnections = true)
{
var connector = new ConnectorOut(typeof(T), allowMultipleConnections);
connector.Init(this);
outputs.Add(name, connector);
}
protected void Out(string name, object value)
{
ConnectorOut o;
if (outputs.TryGetValue(name, out o))
{
if (o.Connected)
{
o.SendData(value);
}
}
}
protected ConnectorOut GetOuput(string name, bool connected = true)
{
ConnectorOut o;
if (outputs.TryGetValue(name, out o))
{
if (o.Connected || !connected)
{
return o;
}
}
return null;
}
protected ConnectorIn In(string name)
{
ConnectorIn o;
if (inputs.TryGetValue(name, out o))
{
return o;
}
return null;
}
public void UpdateOutputData()
{
RequestInputUpdates();
OnUpdateOutputData();
}
protected virtual void OnUpdateOutputData()
{ }
protected virtual void OnCreate()
{ }
protected void RequestInputUpdates()
{
foreach (var i in inputs.Values)
{
i.FreshData = false;
}
foreach (var i in inputs.Values)
{
if (!i.FreshData)
{
i.RequestData();
}
}
}
public IEnumerable<Connector> GetConnectedConnectors()
{
return (from c in inputs.Values where c.Connected select c as Connector).Concat(from c in outputs.Values where c.Connected select c as Connector);
}
public IEnumerable<Connector> GetConnectedConnectorsIn()
{
return (from c in inputs.Values where c.Connected select c as Connector);
}
public IEnumerable<Connector> GetConnectedConnectorsOut()
{
return (from c in outputs.Values where c.Connected select c as Connector);
}
}
}
Definition of VariableNode:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using KSPComputer;
using KSPComputer.Nodes;
using KSPComputer.Connectors;
using KSPComputer.Variables;
namespace KSPComputer.Nodes
{
[Serializable]
public class VariableNode<T> : ExecutableNode
{
internal Variable Variable { get; private set; }
internal void SetVariable(Variable variable)
{
this.Variable = variable;
}
protected override void OnCreate()
{
In<T>("Set");
Out<T>("Get");
}
protected override void OnExecute(ConnectorIn input)
{
Variable.Value = In("Set").Get<T>();
ExecuteNext();
}
protected override void OnUpdateOutputData()
{
Out("Get", Variable.Value);
}
}
}
It looks like you should be able to use reflection:
foreach(var n in Nodes)
{
if(n.GetType().GetGenericTypeDefinition() == typeof(VariableNode<>))
{
if(n.GetType().GetProperty("Variable").GetValue(n, null) == myVar)
{
toRemove.Add(n);
}
}
}
The other solution would be defining a non-generic base class for your VariableNode then you can put your non-generic property there, and finally you can easily cast your node as the base or interface and get the value of your property. Having a non generic base is quite popular practice.

c# class inherits from generics, method return type

I have generic class that should be a tree and I want to inherit the class like this:
public class Tree<T> {
private HashSet<Tree<T>> leaves;
private T data;
public Tree() {
leaves = new HashSet<Tree<T>>();
}
public Tree(T data) : this() {
this.data = data;
}
public T Data {
get {
return this.data;
}
set {
data = value;
}
}
public virtual Tree<T> findInLeaves(T data) {
foreach(Tree<T> leaf in leaves) {
if(leaf.Data.Equals(data)) {
return leaf;
}
}
return null;
}
}
public class ComboTree : Tree<IComboAction> {
private ComboMovement movement;
public ComboTree() : base() {
Movement = null;
}
public ComboTree(IComboAction action) : base(action) {
Movement = null;
}
public ComboMovement Movement {
get {
return this.movement;
}
set {
movement = value;
}
}
}
Putting data works well, but when I try to use method findInLeaves I always get null. I understand there is a problem with type casting, but why if ComboTree inherits Tree?
void readMove(IComboAction action) {
ComboTree leaf = (ComboTree)currentLeaf.findInLeaves(action);
}
Question is why and how to fix it?
Edit: I created console program, run it and it works. So this must be my engine problem!
public ComboTree(IComboAction action)
: base(action)
{
Movement = null; // <---- You are nulling Movement in the second constructor
}

Categories