UltraGrid as UltraToolBar - c#

What I need is a very custom situation.
I need to add UltraGrid to ultraToolbar as normal tool like buttontool.
Where I need to show customized tabular data.
I have tried to derive a userControl from ToolBase but somehow it didn't work.
I am attaching my code here. It has some errors.
FilterGrid.cs UserControl
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using Infragistics.Win.UltraWinToolbars;
using System.Runtime.Serialization;
using Infragistics.Win.UltraWinGrid;
using System.Security.Permissions;
using Infragistics.Shared.Serialization;
using Infragistics.Win.AppStyling;
namespace WindowsApplication1
{
public partial class FilterGrid : UserControl
{
public FilterGrid()
{
InitializeComponent();
}
[TypeConverter(typeof(FilterGrid.GridInternal))]
[Serializable()]
private class GridInternal : ToolBase
{
internal UltraGrid uGrid = new UltraGrid();
#region Constructors
public GridInternal(String key)
: base(key)
{
this.SharedProps.Width = 200;
this.SharedProps.ToolTipText = "FilterGrid";
this.SharedProps.DisplayStyle = ToolDisplayStyle.DefaultForToolType;
}
/// <summary>
/// Constructor used for de-serialization
/// </summary>
protected GridInternal(SerializationInfo info, StreamingContext context): base(info, context)
{
}
#endregion
#region Constants
internal static readonly string DEFAULTVALUE_CUSTOMPROP = "CustomValue";
#endregion Constants
#region Base Class Overrides
#region GetObjectData
/// <summary>
/// Called from our base class when ISerializable.GetObjectData is called. Serialize all custom property data here.
/// </summary>
/// <param name="info"></param>
/// <param name="context"></param>
[SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)]
protected override void GetObjectData(SerializationInfo info, StreamingContext context)
{
// Call the base implementation
base.GetObjectData(info, context);
// Serialize our CustomProp property if necessary.
//if (this.ShouldSerializeCustomProp())
// Utils.SerializeProperty(info, "CustomProp", this.CustomProp);
}
#endregion GetObjectData
//#region ISerializable Members
//public void GetObjectData(SerializationInfo info, StreamingContext context)
//{
// // Call the base implementation
// base.GetObjectData(info, context);
// // Serialize our CustomProp property if necessary.
// if (this.ShouldSerializeCustomProp())
// Utils.SerializeProperty(info, "CustomProp", this.CustomProp);
//}
//#endregion
#region Initialize
/// <summary>
/// Internal inherited method for initializing the tool when de-serialization completes.
/// Automatically called by toolbars manager.
/// </summary>
protected override void Initialize(ToolsCollectionBase parentCollection)
{
// Let the base do its processing.
base.Initialize(parentCollection);
// Use the temporary member variable to set the actual ExtraSharedProps properties.
// We need to wait until after deserialization is totally complete to ensure that
// our ExtraSharedProps object is properly setup.
//if (this.serializedProps != null)
//{
// this.ExtraSharedProps.customProp = this.serializedProps.customProp;
// this.serializedProps = null;
//}
}
#endregion Initialize
#region Clone
/// <summary>
/// Returns a cloned copy of the tool.
/// </summary>
/// <param name="cloneNewInstance">If true, returns a clone of the tool that can serve as an instance of the tool, sharing the same SharedProps object. If false, returns a tool that can be used as a new tool, with a clone of the original SharedProps object.</param>
/// <returns></returns>
protected override Infragistics.Win.UltraWinToolbars.ToolBase Clone(bool cloneNewInstance)
{
GridInternal tool = new GridInternal(this.Key);
tool.InitializeFrom(this, cloneNewInstance);
return tool;
}
#endregion //Clone
#endregion Base Class Overrides
#region CustomProp
/// <summary>
/// This is a custom property in a custom tool.
/// </summary>
//public string CustomProp
//{
// // Delegate the get/sets for the property to our ExtraSharedProps object
// get { return this.ExtraSharedProps.CustomProp; }
// set { this.ExtraSharedProps.CustomProp = value; }
//}
/// <summary>
/// Returns a Boolean value that determines whether the CustomProp property is set to its default value.
/// Checked during serialization to determine if the property should be serialized.
/// </summary>
internal protected virtual bool ShouldSerializeCustomProp()
{
// We only want to serialize the property if this tool is the Root tool and the
// property is not set to its default value.
return (this.IsRootTool);
}
#endregion CustomProp
protected override Type GetToolbarUIElementType()
{
return typeof(UltraGrid);
}
AccessibleRole rl = AccessibleRole.Pane;
UIRole roleOnMenus ;
UIRole roleOnRibbonGroups ;
UIRole roleOnToolbars;
protected override AccessibleRole DefaultAccessibleRole
{
get { return this.rl; }
}
protected override string DefaultAction
{
get { return "Get"; }
}
public override Infragistics.Win.AppStyling.UIRole UIRoleOnMenus
{
get { return this.roleOnMenus; }
}
public override Infragistics.Win.AppStyling.UIRole UIRoleOnRibbonGroups
{
get { return this.roleOnRibbonGroups; }
}
public override Infragistics.Win.AppStyling.UIRole UIRoleOnToolbars
{
get {return this.roleOnToolbars; }
}
}
private void DrawFilter(UltraToolbarsManager tbm)
{
GridInternal gdInternal = new GridInternal("gridInternal");
DataTable dt = new DataTable();
dt.Columns.Add("Column1");
dt.Rows.Add(new object[] { "MyRow"});
gdInternal.uGrid.DataSource = dt;
gdInternal.SharedProps.Caption = "FilterGrid";
Infragistics.Win.UltraWinToolbars.StateButtonTool stb = new StateButtonTool("isEnabled");
stb.SharedProps.DisplayStyle = ToolDisplayStyle.ImageAndText;
stb.SharedProps.CustomizerCaption = "Enable";
stb.SharedProps.Caption = "Enable";
Infragistics.Win.UltraWinToolbars.LabelTool lb = new LabelTool("FilterStatus");
lb.SharedProps.Caption = "FilterStatus";
Infragistics.Win.UltraWinToolbars.StateButtonTool filterstb = new StateButtonTool("Applied");
filterstb.SharedProps.DisplayStyle = ToolDisplayStyle.ImageOnlyOnToolbars;
filterstb.SharedProps.CustomizerCaption = "Applied";
filterstb.SharedProps.Caption = "Applied";
Infragistics.Win.UltraWinToolbars.LabelTool lb1 = new LabelTool("SetFilterType");
lb1.SharedProps.Caption = "SetFilterType";
Infragistics.Win.UltraWinToolbars.ComboBoxTool cbTool = new ComboBoxTool("FilterList");
cbTool.SharedProps.Caption = "FilterType";
cbTool.DropDownStyle = Infragistics.Win.DropDownStyle.DropDownList;
Infragistics.Win.ValueList vl = new Infragistics.Win.ValueList();
cbTool.ValueList.ValueListItems.Add("Select");
cbTool.ValueList.ValueListItems.Add("List1");
cbTool.ValueList.ValueListItems.Add("List2");
cbTool.ValueList.ValueListItems.Add("List3");
cbTool.ValueList.ValueListItems.Add("List4");
cbTool.SelectedIndex = 0;
Infragistics.Win.UltraWinToolbars.ButtonTool btReset = new ButtonTool("Reset");
btReset.SharedProps.DisplayStyle = ToolDisplayStyle.ImageAndText;
btReset.SharedProps.Caption = "ResetFilters";
tbm.Tools.AddRange(new ToolBase[] { stb, lb, filterstb, lb1, cbTool, btReset, gdInternal });
UltraToolbar tb = new UltraToolbar("Filter");
tbm.Toolbars.AddToolbar("Filter").Tools.AddToolRange(new String[] { "isEnabled", "FilterStatus", "Applied", "SetFilterType", "FilterList", "Reset", "gridInternal" });
// tb.Tools.AddTool("isEnabled");
}
public FilterGrid(UltraToolbarsManager tbm):this()
{
DrawFilter(tbm);
}
}
}
Main.cs main form
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace WindowsApplication1
{
public partial class Main : Form
{
public Main()
{
InitializeComponent();
FilterGrid fg = new FilterGrid(ultraToolbarsManager1);
}
}
}
EDIT
I want to derive a control from Toolbase and show it on UltraToolbar, if it is possible.

Now I got how to do that.
I created an instance of controlContainerTool and assign my ultragrid to it.
controlContainerTool is added to UltraToolbarsManager and toolbar instance too.
Appearance can be set at design time from code.
One most important thing is to handle scrollbar in the grid if gets larger than expected.

Related

Caliburn.Micro GetAllInstances only returns one viewModel(Caliburn.Micro MVVM)

I've been trying to integrate Caliburn.Micro MVVM framework in a C# WPF project I am in the middle off.
I currently only have three view models:
ShellViewModel - (A Window view with a ContentControl)
AboutViewModel - (A usercontrol view)
ChatViewModel - (Another usercontrol view)
Currently I am trying to use a button at the AboutView that is bind to the 'Chat()' method at the AboutViewModel and should take the user to the ChatView, yet I am testing this with the AboutViewModel. (As seen in the handler)
What I need is that all the Screen/ViewModels to be Singleton and only have one instance and when I try to change page, it returns to an already existant page.
The issue here is that I only have one instance registered when I do IoC.GetAllInstances(), the ShellViewModel and even though I've tried multiple configurations at the bootstrapper, I cannot register my other ViewModels in a way to make their instances "reachable"
I thank you for your time, and here is the code I think it's relevant for the issue:
Here is my bootstrapper:
public class AppBootstrapper : BootstrapperBase
{
private SimpleContainer _container = new SimpleContainer();
public AppBootstrapper()
{
Initialize();
var config = new TypeMappingConfiguration
{
DefaultSubNamespaceForViewModels = "ViewModel",
DefaultSubNamespaceForViews = "View"
};
ViewLocator.ConfigureTypeMappings(config);
Caliburn.Micro.ViewModelLocator.ConfigureTypeMappings(config);
}
protected override void Configure()
{
_container.Singleton<ShellViewModel, ShellViewModel>();
_container.Singleton<IWindowManager, WindowManager>();
//tried registering AboutViewModel in multiple ways
_container.Singleton<AboutViewModel, AboutViewModel>();
_container.RegisterSingleton(typeof(AboutViewModel), null,typeof(AboutViewModel));
/
}
protected override void OnStartup(object sender, StartupEventArgs e)
{
DisplayRootViewFor<ShellViewModel>();
}
protected override object GetInstance(Type service, string key)
{
var instance = _container.GetInstance(service, key);
if (instance != null)
return instance;
throw new InvalidOperationException("Could not locate any instances.");
}
protected override IEnumerable<object> GetAllInstances(Type service)
{
return _container.GetAllInstances(service);
}
protected override void BuildUp(object instance)
{
_container.BuildUp(instance);
}
}
ShellViewModel.cs:
public class ShellViewModel : Conductor<object>, IHandle<NavigationMessage>
{
/// <summary>
/// Caliburn.Micro event aggregator. (Publish/Subscribe pattern)
/// </summary>
public IEventAggregator events = new EventAggregator();
public ShellViewModel()
{
//var aaa = IoC.Get<IEventAggregator>();
events.Subscribe(this);
ActivateItem(new AboutViewModel(events));
}
public void Handle(NavigationMessage message)
{
//var instance = IoC.GetInstance(message.ViewModelType,null);
var instances = IoC.GetAllInstances(null);
foreach(var i in instances)
{
MessageBox.Show(i.ToString());
}
ActivateItem(new AboutViewModel(events));
}
}
And the AboutViewModel.cs:
/// <summary>
/// ViewModel belonging to the AboutView.xaml.
/// </summary>
/// <seealso cref="AboutView.xaml"/>
public class AboutViewModel : Screen, IHandle<NavigationMessage>
{
private readonly IEventAggregator _eventAggregator;
/// <summary>
/// Private container for the 'Version' public property.
/// </summary>
/// <see cref="Version"/>
private string _version;
/// <summary>
/// Property containing a string of the application's current version (e.g.: 0.1.3.45)
/// </summary>
/// <see cref="_version"/>
[JsonIgnore]
public string Version
{
get
{
return _version;
}
set
{
_version = value;
NotifyOfPropertyChange(() => Version);
}
}
/// <summary>
/// Base constructor for the AboutViewModel class.
/// </summary>
public AboutViewModel(IEventAggregator eventAggregator)
{
Logging.Info("Initialize AboutViewModel", this.GetType());
Logging.Debug("Subscribing to the eventAggregator", this.GetType());
_eventAggregator = eventAggregator;
_eventAggregator.Subscribe(this);
_version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
Logging.Debug("Version loaded (" + _version + ")", this.GetType());
}
/// <summary>
/// Boolean method connected to the ChatCommand activates or deactivates based on it's return
/// </summary>
/// <param name="obj">Object of type GotoPageMessage received from the messenger</param>
public bool CanChat(object obj)
{
return true;
}
/// <summary>
/// Method connected to the ChatCommand that sends the user to the 'Chat' view
/// </summary>
/// <param name="obj">Object of type GotoPageMessage received from the messenger</param>
public void Chat(object obj)
{
_eventAggregator.PublishOnUIThread(new NavigationMessage(typeof(AboutViewModel)));
}
public void Handle(NavigationMessage message)
{
//This handle is used only to know how many instances I have active
MessageBox.Show("about");
}
}
Edit 1:
P.S.: I used to have my ShellViewModel as Conductor.Collection.OneActive. Still didn't work. Maybe AllActive may work?...
override the SelectAssemblies method for caliburn micro to locate all the views:
protected override IEnumerable<Assembly> SelectAssemblies()
{
return new[]
{
Assembly.GetExecutingAssembly(), typeof(MainViewModel).Assembly
};
}
more on the bootstrapper here.
I actually found a solution right now, without messing with Assemblies.
I noticed that the ShellViewModel's instance was accesible, and by saving the instance into a object and debugging it, I noticed all the viewModel instances I created were there at the 'Items'.
Basically this was what I did, in the handler that is inside the ShellViewModel:
public void Handle(NavigationMessage message)
{
ShellViewModel Shell = (ShellViewModel)IoC.GetInstance(typeof(ShellViewModel), null);
object Instance = null;
foreach (var item in Shell.Items)
{
if (item.ToString().Contains(message.ViewModelType.ToString()))
Instance = item;
}
object AuxObject = new object();
if (Instance == null)
{
try
{
Instance = Activator.CreateInstance(message.ViewModelType, Shell.events);
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}
ActivateItem(Instance);
}

c# winform to inspect an object during runtime

I want to display the public Property/Values of an arbitrary object during runtime in a GUI.
Is there a winform which allows the user to view the content of any object like in debug mode? The object will hold many Dictionaries > and it would be nice to be able to expand and view the contents of those lists during runtime.
If not available, is there someway to achieve something similar?
Thanks
All you need to do is create a form with a PropertyGrid on it. Then set the selected object.
using xxx.CFM.UI.Core;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace xxx.CFM.UI.Forms
{
/// <summary>
/// Form used to inspect objects at runtime
/// </summary>
public partial class frmInspector : BaseForm
{
#region Properties
/// <summary>
/// Gets or Sets the
/// </summary>
public object SelectedObject
{
get { return propertyGrid.SelectedObject; }
set { propertyGrid.SelectedObject = value; }
}
#endregion Properties
#region Constructor
/// <summary>
/// Constructor
/// </summary>
public frmInspector(object objectToInspect)
{
try
{
InitializeComponent();
this.SelectedObject = objectToInspect;
}
catch (Exception ex)
{
UIMessage.DisplayError(ex);
}
}
#endregion Constructor
#region Events
/// <summary>
/// Closes the form
/// </summary>
/// <param name="sender">object</param>
/// <param name="e">args</param>
private void btnClose_Click(object sender, EventArgs e)
{
try
{
this.Close();
}
catch (Exception ex)
{
UIMessage.DisplayError(ex);
}
}
#endregion Events
}
}
I use this on a context menu in a grid for example to expect the data record below it:
/// <summary>
/// Opens the object inspector
/// </summary>
/// <param name="sender">object</param>
/// <param name="e">args</param>
private void inspectorMenuItem_Click(object sender, EventArgs e)
{
try
{
//Get the payload
SectionDataTreeListMenuItemPayload payload = (sender as ToolStripMenuItem).Tag as SectionDataTreeListMenuItemPayload;
if (payload == null || payload.DataRow == null)
return;
using (frmInspector frmInspector = new frmInspector(payload.DataRow))
frmInspector.ShowDialog();
}
catch (Exception ex)
{
UIMessage.DisplayError(ex);
}
}
another little trick you can do is to ensure the form is only available when built in debug mode by using the below code using a 'compiler directive'. (if you want it only used for debugging of course)
#if DEBUG
//Add object inspector menu item if built in debug mode
ToolStripMenuItem inspectorMenuItem = new ToolStripMenuItem();
inspectorMenuItem.Text = "Inspect Object";
inspectorMenuItem.Image = Properties.Resources.Inspect24x24;
inspectorMenuItem.Click += inspectorMenuItem_Click;
inspectorMenuItem.Tag = payload;
contextMenuStrip.Items.Add(inspectorMenuItem);
#endif
There's PropertyGrid:
var form = new Form();
form.Controls.Add
(
new PropertyGrid()
{
SelectedObject = new { A = "Hi", B = new [] { 32, 40 } }
}
);
form.Show();
It's quite far from how the debugger one works, but it can be quite easily modified to handle any special cases you might have.

Coded ui test - Select an item from a combobox without using mouse coordinates

I am trying to pickup an item from a combobox by reverse engineering the code that i got from the coded uitest recorder.
In the code it seems like the value is selected using the mouse coordinate
However i would like to select the value using the combobox controler
here are the two methodes first and the full code is below (many thanks for your help):
public void CodedUITestMethod1()
{
// To generate code for this test, select "Generate Code for Coded UI Test" from the shortcut menu and select one of the menu items.
// For more information on generated code, see http://go.microsoft.com/fwlink/?LinkId=179463
this.UIMap.SelectedComboBoxValue();
this.UIMap.AssertSelectedText();
}
public void SelectedComboBoxValue()
{
#region Variable Declarations
WinClient uITaiwanChinaClient = this.UIAGORAActivitiesPortfWindow.UIActivitiesPortfolioWindow.UICharacteristicsGroup.UITaiwanChinaClient;
WinEdit uIItemEdit = this.UIAGORAActivitiesPortfWindow.UIActivitiesPortfolioWindow.UIItemWindow.UIItemEdit;
#endregion
// Click 'Taiwan, China' client
Mouse.Click(uITaiwanChinaClient, new Point(280, 13));
// Type '{Down}{Enter}' in 'Unknown Name' text box
Keyboard.SendKeys(uIItemEdit, this.SelectedComboBoxValueParams.UIItemEditSendKeys, ModifierKeys.None);
}
public void AssertSelectedText()
{
#region Variable Declarations
WinEdit uIItemEdit = this.UIAGORAActivitiesPortfWindow.UIActivitiesPortfolioWindow.UIItemWindow.UIItemEdit;
#endregion
// Verify that 'Unknown Name' text box's property 'SelectionText' equals 'Tajikistan'
Assert.AreEqual(this.AssertSelectedTextExpectedValues.UIItemEditSelectionText, uIItemEdit.SelectionText);
// Verify that 'Unknown Name' text box's property 'Text' equals 'Tajikistan'
Assert.AreEqual(this.AssertSelectedTextExpectedValues.UIItemEditText, uIItemEdit.Text);
}
-----------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by coded UI test builder.
// Version: 10.0.0.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
// ------------------------------------------------------------------------------
namespace TestProject16
{
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Drawing;
using System.Text.RegularExpressions;
using System.Windows.Input;
using Microsoft.VisualStudio.TestTools.UITest.Extension;
using Microsoft.VisualStudio.TestTools.UITesting;
using Microsoft.VisualStudio.TestTools.UITesting.WinControls;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Keyboard = Microsoft.VisualStudio.TestTools.UITesting.Keyboard;
using Mouse = Microsoft.VisualStudio.TestTools.UITesting.Mouse;
using MouseButtons = System.Windows.Forms.MouseButtons;
[GeneratedCode("Coded UITest Builder", "10.0.30319.1")]
public partial class UIMap
{
/// <summary>
/// SelectedComboBoxValue - Use 'SelectedComboBoxValueParams' to pass parameters into this method.
/// </summary>
public void SelectedComboBoxValue()
{
#region Variable Declarations
WinClient uITaiwanChinaClient = this.UIAGORAActivitiesPortfWindow.UIActivitiesPortfolioWindow.UICharacteristicsGroup.UITaiwanChinaClient;
WinEdit uIItemEdit = this.UIAGORAActivitiesPortfWindow.UIActivitiesPortfolioWindow.UIItemWindow.UIItemEdit;
#endregion
// Click 'Taiwan, China' client
Mouse.Click(uITaiwanChinaClient, new Point(280, 13));
// Type '{Down}{Enter}' in 'Unknown Name' text box
Keyboard.SendKeys(uIItemEdit, this.SelectedComboBoxValueParams.UIItemEditSendKeys, ModifierKeys.None);
}
/// <summary>
/// AssertSelectedText - Use 'AssertSelectedTextExpectedValues' to pass parameters into this method.
/// </summary>
public void AssertSelectedText()
{
#region Variable Declarations
WinEdit uIItemEdit = this.UIAGORAActivitiesPortfWindow.UIActivitiesPortfolioWindow.UIItemWindow.UIItemEdit;
#endregion
// Verify that 'Unknown Name' text box's property 'SelectionText' equals 'Tajikistan'
Assert.AreEqual(this.AssertSelectedTextExpectedValues.UIItemEditSelectionText, uIItemEdit.SelectionText);
// Verify that 'Unknown Name' text box's property 'Text' equals 'Tajikistan'
Assert.AreEqual(this.AssertSelectedTextExpectedValues.UIItemEditText, uIItemEdit.Text);
}
#region Properties
public virtual SelectedComboBoxValueParams SelectedComboBoxValueParams
{
get
{
if ((this.mSelectedComboBoxValueParams == null))
{
this.mSelectedComboBoxValueParams = new SelectedComboBoxValueParams();
}
return this.mSelectedComboBoxValueParams;
}
}
public virtual AssertSelectedTextExpectedValues AssertSelectedTextExpectedValues
{
get
{
if ((this.mAssertSelectedTextExpectedValues == null))
{
this.mAssertSelectedTextExpectedValues = new AssertSelectedTextExpectedValues();
}
return this.mAssertSelectedTextExpectedValues;
}
}
public UIAGORAActivitiesPortfWindow UIAGORAActivitiesPortfWindow
{
get
{
if ((this.mUIAGORAActivitiesPortfWindow == null))
{
this.mUIAGORAActivitiesPortfWindow = new UIAGORAActivitiesPortfWindow();
}
return this.mUIAGORAActivitiesPortfWindow;
}
}
#endregion
#region Fields
private SelectedComboBoxValueParams mSelectedComboBoxValueParams;
private AssertSelectedTextExpectedValues mAssertSelectedTextExpectedValues;
private UIAGORAActivitiesPortfWindow mUIAGORAActivitiesPortfWindow;
#endregion
}
/// <summary>
/// Parameters to be passed into 'SelectedComboBoxValue'
/// </summary>
[GeneratedCode("Coded UITest Builder", "10.0.30319.1")]
public class SelectedComboBoxValueParams
{
#region Fields
/// <summary>
/// Type '{Down}{Enter}' in 'Unknown Name' text box
/// </summary>
public string UIItemEditSendKeys = "{Down}{Enter}";
#endregion
}
/// <summary>
/// Parameters to be passed into 'AssertSelectedText'
/// </summary>
[GeneratedCode("Coded UITest Builder", "10.0.30319.1")]
public class AssertSelectedTextExpectedValues
{
#region Fields
/// <summary>
/// Verify that 'Unknown Name' text box's property 'SelectionText' equals 'Tajikistan'
/// </summary>
public string UIItemEditSelectionText = "Tajikistan";
/// <summary>
/// Verify that 'Unknown Name' text box's property 'Text' equals 'Tajikistan'
/// </summary>
public string UIItemEditText = "Tajikistan";
#endregion
}
[GeneratedCode("Coded UITest Builder", "10.0.30319.1")]
public class UIAGORAActivitiesPortfWindow : WinWindow
{
public UIAGORAActivitiesPortfWindow()
{
#region Search Criteria
this.SearchProperties[WinWindow.PropertyNames.Name] = "AGORA - [Activities Portfolio]";
this.SearchProperties[WinWindow.PropertyNames.ClassName] = "ThunderRT6MDIForm";
this.WindowTitles.Add("AGORA - [Activities Portfolio]");
#endregion
}
#region Properties
public UIActivitiesPortfolioWindow UIActivitiesPortfolioWindow
{
get
{
if ((this.mUIActivitiesPortfolioWindow == null))
{
this.mUIActivitiesPortfolioWindow = new UIActivitiesPortfolioWindow(this);
}
return this.mUIActivitiesPortfolioWindow;
}
}
#endregion
#region Fields
private UIActivitiesPortfolioWindow mUIActivitiesPortfolioWindow;
#endregion
}
[GeneratedCode("Coded UITest Builder", "10.0.30319.1")]
public class UIActivitiesPortfolioWindow : WinWindow
{
public UIActivitiesPortfolioWindow(UITestControl searchLimitContainer) :
base(searchLimitContainer)
{
#region Search Criteria
this.SearchProperties[WinWindow.PropertyNames.ControlId] = "32769";
this.WindowTitles.Add("AGORA - [Activities Portfolio]");
#endregion
}
#region Properties
public UICharacteristicsGroup UICharacteristicsGroup
{
get
{
if ((this.mUICharacteristicsGroup == null))
{
this.mUICharacteristicsGroup = new UICharacteristicsGroup(this);
}
return this.mUICharacteristicsGroup;
}
}
public UIItemWindow UIItemWindow
{
get
{
if ((this.mUIItemWindow == null))
{
this.mUIItemWindow = new UIItemWindow(this);
}
return this.mUIItemWindow;
}
}
#endregion
#region Fields
private UICharacteristicsGroup mUICharacteristicsGroup;
private UIItemWindow mUIItemWindow;
#endregion
}
[GeneratedCode("Coded UITest Builder", "10.0.30319.1")]
public class UICharacteristicsGroup : WinGroup
{
public UICharacteristicsGroup(UITestControl searchLimitContainer) :
base(searchLimitContainer)
{
#region Search Criteria
this.SearchProperties[WinControl.PropertyNames.Name] = "Characteristics";
this.WindowTitles.Add("AGORA - [Activities Portfolio]");
#endregion
}
#region Properties
public WinWindow UITaiwanChinaWindow
{
get
{
if ((this.mUITaiwanChinaWindow == null))
{
this.mUITaiwanChinaWindow = new WinWindow(this);
#region Search Criteria
this.mUITaiwanChinaWindow.SearchProperties[WinWindow.PropertyNames.Name] = "Taiwan, China";
this.mUITaiwanChinaWindow.SearchProperties[WinWindow.PropertyNames.ClassName] = "AfxOleControl42";
this.mUITaiwanChinaWindow.WindowTitles.Add("AGORA - [Activities Portfolio]");
#endregion
}
return this.mUITaiwanChinaWindow;
}
}
public WinClient UITaiwanChinaClient
{
get
{
if ((this.mUITaiwanChinaClient == null))
{
this.mUITaiwanChinaClient = new WinClient(this);
#region Search Criteria
this.mUITaiwanChinaClient.SearchProperties[WinControl.PropertyNames.Name] = "Taiwan, China";
this.mUITaiwanChinaClient.WindowTitles.Add("AGORA - [Activities Portfolio]");
#endregion
}
return this.mUITaiwanChinaClient;
}
}
#endregion
#region Fields
private WinWindow mUITaiwanChinaWindow;
private WinClient mUITaiwanChinaClient;
#endregion
}
[GeneratedCode("Coded UITest Builder", "10.0.30319.1")]
public class UIItemWindow : WinWindow
{
public UIItemWindow(UITestControl searchLimitContainer) :
base(searchLimitContainer)
{
#region Search Criteria
this.SearchProperties[WinWindow.PropertyNames.ControlId] = "110";
this.SearchProperties[WinWindow.PropertyNames.Instance] = "7";
this.WindowTitles.Add("AGORA - [Activities Portfolio]");
#endregion
}
#region Properties
public WinEdit UIItemEdit
{
get
{
if ((this.mUIItemEdit == null))
{
this.mUIItemEdit = new WinEdit(this);
#region Search Criteria
this.mUIItemEdit.WindowTitles.Add("AGORA - [Activities Portfolio]");
#endregion
}
return this.mUIItemEdit;
}
}
#endregion
#region Fields
private WinEdit mUIItemEdit;
#endregion
}
}
// Click 'Taiwan, China' client
Mouse.Click(uITaiwanChinaClient, new Point(280, 13));
can be replaced with
// Click 'Taiwan, China' client
Mouse.Click(uITaiwanChinaClient);
as the Mouse.Click() method has many overloads.
When you record test steps it records the exact spot you click as well as the control you are clicking. During hand coding, just referring to the control can be enough to duplicate the step.
ETA:
uITaiwanChinaClient.SelectedItem= "Value";
or
uITaiwanChinaClient.SelectedIndex= "1"; //usually zero based indexing
Here is a method where you can pass the selected item you need:
public void SelectListItem(string selectedItem, string ListID, UITestControl parent)
{
HtmlList ListControl = new HtmlList(parent);
ListControl.SearchProperties[HtmlList.PropertyNames.Id] = ListID;
ListControl.SelectedItemsAsString = selectedItem;
}
Or you can select by index:
public void SelectListItem(int selectedIndex, string ListID, UITestControl parent)
{
HtmlList ListControl = new HtmlList(parent);
ListControl.SearchProperties[HtmlList.PropertyNames.Id] = ListID;
//Select the item as the specific index.
HtmlListItem listItem = (HtmlListItem) ListControl.GetChildren()[selectedIndex];
listItem.Select();
}
you can also select an index randomly like this:
public void SelectListItemRandom(string ListID,UITestControl parent)
{
HtmlList listDir = new HtmlList(parent);
listDir.SearchProperties[HtmlList.PropertyNames.Id] = ListID;
listDir.SearchConfigurations.Add(SearchConfiguration.AlwaysSearch);
Console.WriteLine("List item Count: " + listDir.ItemCount);
int selectedindex = random.Next(1, listDir.ItemCount);
Console.WriteLine("Selected random index: " + selectedindex);
listDir.SelectedIndices = new int[] { selectedindex };
}

Using a singleton to populate data on a page in wp8 app - Generating error

I am using the RadDataForm which is part of the UI controls from telerik for wp8. The problem I am having I don't think is related to the control but more on something stupid that I have done or not understanding.
I have a class called ProfileFormData and is used to populate DatFields in the DataForm. It obtains its properties from an class called Profile which is in a singleton.
Ok so the code first.
Public class Profile
{
Public sting Name {get;set;}
Public int Gender {get;set;}
}
singleton
public sealed class Globals
{
/// <summary>
/// Current profile
/// </summary>
public Profile profile
private static readonly SingleInstance<Globals> lazy =
new SingleInstance<Globals>(() => new Globals());
public static Globals Instance { get { return lazy.Instance; } }
}
internal sealed class SingleInstance<T> where T : class
{
private readonly Object m_lockObj = new object();
private readonly Func<T> m_delegate;
private Boolean m_isDelegateInvoked;
private T m_value;
/// <summary>
/// Initializes a new instance of the
/// <see cref="SingleInstance<T>"/> class.
/// </summary>
public SingleInstance() : this(() => default(T)) { }
/// <summary>
/// Initializes a new instance of the
/// <see cref="SingleInstance<T>"/> class.
/// </summary>
/// <param name="delegate">The #delegate</param>
public SingleInstance(Func<T> #delegate)
{
m_delegate = #delegate;
}
/// <summary>
/// gets the instance
/// </summary>
/// <value>The instance</value>
public T Instance
{
get
{
if (!m_isDelegateInvoked)
{
T temp = m_delegate();
Interlocked.CompareExchange<T>(ref m_value, temp, null);
Boolean lockTaken = false;
try
{
// WP7 does not support the overload with the
// boolean indicating if the Lock was taken
Monitor.Enter(m_lockObj); lockTaken = true;
m_isDelegateInvoked = true;
}
finally
{
if (lockTaken) { Monitor.Exit(m_lockObj); }
}
}
return m_value;
}
}
}
ProfileFormData
public class ProfileFormData
{
public string Name
{
get { return Globals.Instance.profile.UserName; }
set { Globals.Instance.profile.UserName = value; }
}
[GenericListEditor(typeof(GenderInfoProvider))]
public Gender Gender
{
get { return (Gender)Globals.Instance.profile.Gender; }
set { Globals.Instance.profile.Gender = (int)value; }
}
}
and now the xaml where the error is shown in both blend and vs designer
<Grid Grid.Row="1" Margin="0,6,0,6">
<ScrollViewer>
<telerikInput:RadDataForm Grid.Row="1" Margin="12,0,12,12" x:Name="DataForm">
<telerikInput:RadDataForm.CurrentItem>
<models:ProfileFormData/>
</telerikInput:RadDataForm.CurrentItem>
<Grid>
<telerikInput:DataField Header="Name" TargetProperty="Name"/>
<telerikInput:DataField Header="Gender" TargetProperty="Gender"/>
</Grid>
</telerikInput:RadDataForm>
</ScrollViewer>
</Grid>
all of the xaml above has a red line underneath and I get the error
Object not set to instance of object
Deploying and running the app works fine.
oh and I create the profile like this in the App.xaml.c
/// <summary>
/// Constructor for the Application object.
/// </summary>
public App()
{
// Global handler for uncaught exceptions.
UnhandledException += Application_UnhandledException;
// Standard Silverlight initialization
InitializeComponent();
// Phone-specific initialization
InitializePhoneApplication();
Globals.Instance.profile = new Profile();
}

Adding and updating hashtable(ID and Name) as custom property for each items(Nodes) in c#

I have added hashtable(ID and Name) as custom property for each item (Node).
The user can add and update those properties with respect to each items.
My problem is that while updating the Hash Table value of a particular item, the updated value is assigned to all items (nodes) for example while editing the ID of a node to 2 then each node contains the same id value.
I think the problem is that the Hash Table values are not cloned for that particular item because other properties like int vertexcount are working fine.
How to resolve this problem and how to update the property with respect to that particular item? Thanks in advance..
Here is the code for serialization of properties:
[Serializable]
public class DynamicGroup : Group
{
#region Class members
private int clickCount;
#endregion
#region Class Initialize/Finalize methods
/// <summary>
/// Default constructor.
/// </summary>
public DynamicGroup()
{
}
/// <summary>
/// Initialize a new instance of DynamicGroup.
/// </summary>
/// <param name="nodes">The node collection.</param>
public DynamicGroup(NodeCollection nodes)
: base(nodes)
{ }
/// <summary>
/// Copy constructor.
/// </summary>
/// <param name="src"></param>
public DynamicGroup(DynamicGroup src)
: base(src)
{
this.Properties = src.Properties;
}
/// <summary>
/// Serialization constructor for the MySymbol class.
/// </summary>
/// <param name="info">Serialization state information</param>
/// <param name="context">Streaming context information</param>
protected DynamicGroup(SerializationInfo info, StreamingContext context)
: base(info, context)
{
// The Serialization constructor is invoked during deserialization or during a drag & drop operation.
// If the MySymbol type has serializable members, then initialize them with the serialized data
// obtained from the SerializationInfo param
foreach (SerializationEntry entry in info)
{
switch (entry.Name)
{
case "properties":
properties = (Hashtable)entry.Value;
break;
case "clickCount":
clickCount = (int)entry.Value;
break;
}
}
}
#endregion
#region Class properties
/// <summary>
/// Get or set the dynamic properties collection.
/// </summary>
private Hashtable properties = null;
[Browsable(true), ReadOnly(false)]
public Hashtable Properties
{
get
{
if (properties == null)
{
properties = new Hashtable();
}
return properties;
}
set
{
properties = value;
}
}
[Browsable(true)]
public int ClickCount
{
get
{
return clickCount;
}
set
{
clickCount = value;
}
}
#endregion
[EventHandlerPriority(true)]
protected override void OnMouseClick(EventArgs e)
{
clickCount = clickCount + 1;
}
#region Class overrides
/// <summary>
/// Creates a new object that is a copy of the current instance.
/// </summary>
/// <returns>Copy of the object this method is invoked against</returns>
public override object Clone()
{
return new DynamicGroup(this);
}
/// <summary>
/// Populates a SerializationInfo with the data needed to serialize the target object.
/// </summary>
/// <param name="info">SerializationInfo object to populate.</param>
/// <param name="context">Destination streaming context.</param>
protected override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
//Add the serialization entry for dynamic properties collection
info.AddValue("properties", this.properties);
info.AddValue("clickCount", clickCount);
}
#endregion
}
Editing properties:
grp is a node:
private void button2_Click(object sender, EventArgs e)
{
DynamicGroup grp = diagram1.Controller.SelectionList[0] as DynamicGroup;
listBox1.Items.Add(grp.ClickCount.ToString());
listBox1.Items.Add(grp.Properties["Name"].ToString());
textBox1.Text = grp.Properties["ID"].ToString();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
DynamicGroup grp = diagram1.Controller.SelectionList[0] as DynamicGroup;
grp.Properties["ID"] = textBox1.Text;
}
The issue is raised while duplicating that is copying the already existed node and update the property of duplicated node..
Try changing your Constructor from
public DynamicGroup(DynamicGroup src): base(src)
{
this.Properties = src.Properties;
}
to
public DynamicGroup(DynamicGroup src): base(src)
{
this.Properties = (Hashtable)src.Properties.Clone();
}
Otherwise the safe Hashtable will be referenced by both objects, the original and the "clone".
You pass a reference of a Dictionary here :
public DynamicGroup(DynamicGroup src)
: base(src)
{
this.Properties = src.Properties;
}
I think you can have 2 options:
Do not pass a reference here but have to create a Properties collection inside DynamicMember and if you need apply some changes of parent node to child one, make a function UpdateChildren that iterates over every child of specified Node.
By the way have a member local Properties like in first option, but accept in ctor a Properties and copy values to local var.
I see from code that Keys of your dictionary are basically value types.

Categories

Resources