I use Selenium2 WebDriver with C#
Actions.Build - returns a composite IAction which can be used to perform the actions. (IActions has a Perform method to execute the actions)
Actions.Perform - Performs the currently built action.
In most of the examles use Actions like this:
new Actions(IWebDriverObj).actions...Build().Perform()
but this works as well
new Actions(IWebDriverObj).actions...Perform() //no Build before Perform
Is it necessary to use the Build() before the Perform() or Build() is for some compatibility purpose only?
Thanks in advance for the answers
Always keep in mind that Selenium is open source.
The source of WebDriver/Interactions/Actions.cs is here, clearly you can see Perform() includes Build(), so the answer is no, you don't need to build before perform, unless you want to pass the built IAction around without performing.
/// <summary>
/// Builds the sequence of actions.
/// </summary>
/// <returns>A composite <see cref="IAction"/> which can be used to perform the actions.</returns>
public IAction Build()
{
CompositeAction toReturn = this.action;
this.action = new CompositeAction();
return toReturn;
}
/// <summary>
/// Performs the currently built action.
/// </summary>
public void Perform()
{
this.Build().Perform();
}
Also, for anyone else reading this post:
Java binding: build() is included in perform(). Source: interactions/Actions.java
Ruby/Python: only have perform, no such thing called build. Source: action_chains.py, action_builder.rb
Actually, the .perform() includes a .build().
So you can only write : new Actions(IWebDriverObj).actions....perform()
Related
I was trying to add a Permission based Attribute to be used by an existing Windows application built with WPF that I should work on.
the idea was to intercept the calls to the Canexecute methods of certain commands and return false -which would disable the buttons-
so I made a simple example on a solution where I have added the Nuget Package of Postsharp and override the OnInvoke Method as follows:
[Serializable]
public class PermissionBasedAttribute : MethodInterceptionAspect
{
public string PermissionName { get; private set; }
public PermissionBasedAttribute (string permissionName)
{
PermissionName = permissionName;
}
/// <summary>
/// Upon invocation of the calling method, the PermissionName is checked.
/// If no exception is thrown, the calling method proceeds as normal.
/// If an exception is thrown, the virtual method MethodOnException is called.
/// </summary>
/// <seealso cref="MethodOnException(SecurityPermissionException)"/>
public override void OnInvoke(MethodInterceptionArgs args)
{
try
{
/*
* some logic to check the eligibility of the user, in case of
not authorised an exception should be thrown.
*/
args.Proceed();
}
catch (SecurityPermissionException ex)
{
args.ReturnValue = false;
// MethodOnException(ex);
}
}
/// <summary>
/// Method can be overridden in a derived attribute class.
/// Allows the user to handle the exception in whichever way they see fit.
/// </summary>
/// <param name="ex">The exception of type SecurityPermissionException</param>
public virtual void MethodOnException(SecurityPermissionException ex)
{
throw ex;
}
}
anyway , every thing works fine within the small example with different approaches in the simple example like using devexpress or not.
but when added to the existing application it does not work at all, to be more precise: the OnInvoke method is never hit, while the Constructor of the Attribute is already being called.
I am not sure what is wrong, but an additional information is that I found out that the existing solution was utilizing Postsharp already for logging aspects.
so I have used the exact same version as the one used by the Project which is 4.2.26 by choosing this version from the Nuget Package Manager.
Another thing I have tried is that i have implemented the CompileTimeValidate method and purposefully added a code that should raise an exception upon build.
in the Small -Working- example it has raised an exception upon build.
while in the Existing application where it has not worked yet. upon build it does not raise any exception !!!.
Update:
I am Using at as follow:
[PermissionBasedAttribute("Permission1") ]
public bool CanShowView()
{
return true;
}
It turns out that Post Sharp was disabled in this project !!! I Installed the Post sharp Extension, then went to Post Sharp Section i found that it was disabled, once enabled it worked out fine
I updated Mvvm Light to version 5 and noticed that RelayCommand stopped working.
The problem seems to be that the CanExecute() is not being called to validate. It only validates one time, like when the window is loaded.
Could this be a bug from the recent update or is there something I need to change in the XAML?
Everything was working correctly before the update. I'm working with WPF.
See this MVVM Light 5 issue:
WPF is the only XAML framework that uses the CommandManager to
automagically raise the CanExecuteChanged event on ICommands. I never
liked that approach, because of the "magic" part, but this is a
"feature" of WPF and of course I have to support it. No question here.
In V5, I moved to portable class library for all the newest versions
of the XAML frameworks, including WPF4.5. Unfortunately, there is no
CommandManager in PCL, and I have to admit that I didn't realize that
at first sight. So of course now the automagical part doesn't work
anymore. Again, so sorry about that.
I am not expecting you to raise CanExecuteChanged everywhere now, not
after using the CommandManager in your application, which is what the
WPF team intended. So I will try to find a way to restore the
CommandManager usage in the WPF4.5 version of the toolkit.
Definitely not looking for excuses ;) but hope that explaining why the
issue arose helps to make sense of this. It's going to be my priority
No. 1 until I find a way to solve this in the PCL version. In the meantime, like I mentioned before, I think that going back to
V4.4.32.7 should fix that. Please let me know if it does not.
So the temporary recommended solution is to revert back to the previous version. I did it and it worked.
I agree that the CommandManager is doing "magic". Once I had null reference exception within the CanExecute condition and as a result I have obtained neverending cycle of error messages like cards in Windows Solitaire. If I started a new project I would prefer not to use this "magic" but to change an existing and already deployed project would be quite painful.
Looks like you have to call RaiseCanExecuteChanged on the command whenever a relevant property is changed. I think this was previously done by the wpf command manager, but the recent PCL changes probably made that unsupportable.
I use MvvmCross which requires a similar method to be called, so in my base view model I have a method allowing me to register a command so that whenever a property changed occurs I can loop all registered commands and force canexecute to be called again. To make things easier you could do it that way.
Check out this sample
As this seems to be doubted, here is some code I have tested
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using System;
namespace TestingApp.ViewModel
{
/// <summary>
/// This class contains properties that the main View can data bind to.
/// <para>
/// Use the <strong>mvvminpc</strong> snippet to add bindable properties to this ViewModel.
/// </para>
/// <para>
/// You can also use Blend to data bind with the tool's support.
/// </para>
/// <para>
/// See http://www.galasoft.ch/mvvm
/// </para>
/// </summary>
public class MainViewModel : ViewModelBase
{
private Int32 _increment = 0;
public Int32 Increment
{
get { return _increment; }
set
{
_increment = value;
RaisePropertyChanged("Increment");
GoCommand.RaiseCanExecuteChanged();
}
}
/// <summary>
/// Initializes a new instance of the MainViewModel class.
/// </summary>
public MainViewModel()
{
////if (IsInDesignMode)
////{
//// // Code runs in Blend --> create design time data.
////}
////else
////{
//// // Code runs "for real"
////}
}
private RelayCommand _incrementCommand;
public RelayCommand IncrementCommand
{
get
{
if (_incrementCommand == null)
{
_incrementCommand = new RelayCommand(IncrementCommand_Execute);
}
return _incrementCommand;
}
}
private void IncrementCommand_Execute()
{
Increment++;
}
private RelayCommand _goCommand;
public RelayCommand GoCommand
{
get
{
if (_goCommand == null)
{
_goCommand = new RelayCommand(GoCommand_Execute, GoCommand_CanExecute);
}
return _goCommand;
}
}
private bool GoCommand_CanExecute()
{
return Increment > 5;
}
private void GoCommand_Execute()
{
//
}
}
}
Without the line
GoCommand.RaiseCanExecuteChanged();
the canexecute method is never called after the initial call, but with the line it is called everytime the Increment property changes
Setup
I want to pass an instance of a cache as a dependency to one or more types. When a concrete instance of the cache is instantiated, it must be provided information about the type that will use it.
I realize that this a common task and that injecting cache dependencies appears in various questions/answers; I'm setting up a specific problem I'm having with Ninject.
interface IMethodCache { }
public class MethodCache : IMethodCache
{
public MethodCache( Type type )
{
// type information is used to build unique cache keys
}
}
public class CacheConsumer
{
public CacheConsumer( IMethodCache cache ) { }
}
Documentation
The Ninject documentation shows how to do just that (using logging as an example):
class ClassThatLogs {
readonly ILog _log;
public ClassThatLogs(ILog log){
_log = log;
}
}
Bind<ILog>().ToMethod( context => LogFactory.CreateLog( context.Request.Target.Type ) );
The previous example shows that context.Request.Target.Type will contain the type information for the type into which injection occurs.
Furthermore, the comments on context.Request.Target state:
Gets the target that will receive the injection, if any.
Results
Based on this, I expect to see information about the instance receiving the injection. I setup my binding as follows:
kernel.Bind<IMethodCache>().ToMethod(
ctx =>
{
return new MethodCache( ctx.Request.Target.Type );
} );
But the result is unexpected.
The Type property of Target is set to the type being bound (IMethodCache), not the "target that will receive injection" (CacheConsumer).
To state it another way: when the dependency is created, I need to pass the injectable's type to it.
I can obtain the desired information by using context.Request.Target.Member.DeclaringType. However, I'm concerned because I don't know the ramifications of relying on the declaring type and—more importantly—because this seems contrary to the documentation.
Questions
Am I understanding the documentation correctly?
If so, what am I doing wrong?
If not, how can I accomplish the goal of passing type information to the constructor of my dependency (the cache)?
Other Details
Ninject 3.0.1.10
Composition root is the start event of a Windows service
I'm using the StandardKernel
Yes, it seems that the documentation is incomplete/incorrect in this case.
you can get the "target" type information starting from ctx.Request.Target property but but you need to go "one step further" with using the Member and the ctx.Request.Target.Member.DeclaringType as you've already noticed.
So it is completely fine to use the context.Request.Target.Member.DeclaringType in fact if you check the mentioned Ninject.Extensions.Loggin you will see the following in the
source code:
/// <summary>
/// Gets the logger for the specified activation context, creating it if necessary.
/// </summary>
/// <param name="context">The ninject creation context.</param>
/// <returns>The newly-created logger.</returns>
public ILogger GetLogger(IContext context)
{
return this.GetLogger(context.Request.Target.Member.DeclaringType);
}
I have made my first attempt at using dependency injection to loosely couple a new application. My problem is how to pass status information back to the user. In the old days with all the code crammed into the GUI it was pretty easy if very messy and unmaintainable. The arrangement of classes is something like this (please do not check my UML skills - they are non existent):
If we take the right hand side. The AirportsInformationRepository just stores data and makes it available to the Controller when asked. At the start it gets the information using the Persist class to get files matching a given filter from the users hard drive. It uses the decompiler to extract information from a file. All this works fine and the information itself gets to the GUI as it should.
My problem is, in parallel, how to tell the user what is happening. This can occur in the decompiler, for example, if the file it gets cannot be decompiled or perhaps contains no data. It can occur in the Persist class if the config file is telling lies and some folder does not exist. Such issues should not stop the process unless there is a fatal error.
If there is a fatal error then it needs to get back to the user at once and the overall process should stop. Otherwise warnings can be collected through the process somehow and then displayed when the scan is completed.
I am familiar with logging and the application does have a logger that is monitoring the application for unhandled exceptions and other failures. This writes to disk and I use this like most would to deal with bugs. I don't want to use this for status reporting to the user since to be honest nothing is wrong with the app if a file is not found or the user entered an invalid path to the config file.
I have considered:
accumulating a log in each class and passing it back to the consumer when the process completes (or fails). I am finding that really messy
using events but if the consumer is subscribing and the events are passing up the chain in the same way as the log then I don't see that is much better. I guess an alternative is to have the GUI subscribe directly but it should not know anything about the decompiler....
A home rolled logger that is either a static class or is instantiated in program.cs
Some sort of messaging framework - which I admit I am not clear about but I think is rather similar to a central event handler whereby the GUI could subscribe to it without having to know anything about the other classes.
So to summarise. What is the best way to accumulate 'business as usual' status information and give it to the GUI at the end of a scan, at the same time being able to stop on a fatal issue.
Thanks in advance for reading this. Apologies for the length of the post.
EDIT
I should have said that the app is using NET 3.5. I would change this to get an elegant solution but....
When you deal with a typical "flow" of processing, possibly even multithreaded/concurrent processing flow the best approach to take is "mailslots"/message pumps. By exchaging messages you can easily coordinate multiple layers of your application and that includes reporting errors, notifying the next chain of command etc.. I do not mean Windows messages, I mean something like:
public abstract class Message
{
public abstract void Process();
}
Then:
public class MessageQueue
{
private Queue m_Queue;
public void Post(Message msg) {....}
public void Process() {.....}
}
Then you allocate a MessageQueue on every thread/processing tier of your app and pass messages like so:
GUIMessageQueue.Post(
new ErrorMessage("Internal async file reader ran out of buffer"));
On GUI thread put a timer that read GUI queue and calls it's Process().
Now you can create many Message-derived work items to execute various tasks that very easily orchestrate between threads/logical tiers. Also, messages may contain references for datapieces that they relate to:
public AirplaneLandedMessage: Message
{
public Airplane Plane ......
}
Here is some real code that I use in massively parallel chain-processing system:
/// <summary>
/// Defines a base for items executable by WorkQueue
/// </summary>
public interface IWorkItem<TContext> where TContext : class
{
/// <summary>
/// Invoked on an item to perform actual work.
/// For example: repaint grid from changed data source, refresh file, send email etc...
/// </summary>
void PerformWork(TContext context);
/// <summary>
/// Invoked after successfull work execution - when no exception happened
/// </summary>
void WorkSucceeded();
/// <summary>
/// Invoked when either work execution or work success method threw an exception and did not succeed
/// </summary>
/// <param name="workPerformed">When true indicates that PerformWork() worked without exception but exception happened later</param>
void WorkFailed(bool workPerformed, Exception error);
}
/// <summary>
/// Defines contract for work queue that work items can be posted to
/// </summary>
public interface IWorkQueue<TContext> where TContext : class
{
/// <summary>
/// Posts work item into the queue in natural queue order (at the end of the queue)
/// </summary>
void PostItem(IWorkItem<TContext> work);
long ProcessedSuccessCount{get;}
long ProcessedFailureCount{get;}
TContext Context { get; }
}
Well, the fatal errors are the easy part, they're simply handled via exceptions. The worker threads can just throw an exception when they run into a problem that prevent continuing on with work, and then at some point when it bubbles up to the UI layer you can catch the exception and display an appropriate error message to the user without actually crashing the application. You can use different types of exceptions and exception message to allow different problems to result in different UI responses.
As for indicating non-fatal statuses, you can use the IProgress interface for that. In your UI layer you can create a Progress instance that, when called, updates...whatever with the new status. You can then pass the IProgress instance down through the worker classes and fire it when you have information to provide.
Since you're pre 4.5 it's easy enough to rewrite this class.
public interface IProgress<T>
{
public void Report(T parameter);
}
public class Progress<T>:IProgress<T>
{
public event Action<T> ProgressChanged;
public Progress() { }
public Progress(Action<T> action)
{
ProgressChanged += action;
}
void IProgress<T>.Report(T parameter)
{
ProgressChanged(parameter);
}
}
Note: the real Progress class marshals the event into the UI thread, I didn't add that part, so either add that in or do it in the event handler(s).
My question is very similar to these two:
C# component events?
C# - writing a COM server - events not firing on client
However, what worked for them is not working for me. The type library file, does not have any hints of events definitions, so Delphi doesn't see it. The class works fine for other C# applications, as you would expect.
COM Server tools:
Visual Studio 2010
.NET 4.0
Delphi applications:
Delphi 2010
Delphi 7
Here's a simplified version of the code:
/// <summary>
/// Call has arrived delegate.
/// </summary>
[ComVisible(false)]
public delegate void CallArrived(object sender, string callData);
/// <summary>
/// Interface to expose SimpleAgent events to COM
/// </summary>
[ComVisible(true)]
[GuidAttribute("1FFBFF09-3AF0-4F06-998D-7F4B6CB978DD")]
[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface IAgentEvents
{
///<summary>
/// Handles incoming calls from the predictive manager.
///</summary>
///<param name="sender">The class that initiated this event</param>
///<param name="callData">The data associated with the incoming call.</param>
[DispId(1)]
void OnCallArrived(object sender, string callData);
}
/// <summary>
/// Represents the agent side of the system. This is usually related to UI interactions.
/// </summary>
[ComVisible(true)]
[GuidAttribute("EF00685F-1C14-4D05-9EFA-538B3137D86C")]
[ClassInterface(ClassInterfaceType.None)]
[ComSourceInterfaces(typeof(IAgentEvents))]
public class SimpleAgent
{
/// <summary>
/// Occurs when a call arrives.
/// </summary>
public event CallArrived OnCallArrived;
public SimpleAgent() {}
public string AgentName { get; set; }
public string CurrentPhoneNumber { get; set; }
public void FireOffCall()
{
if (OnCallArrived != null)
{
OnCallArrived(this, "555-123-4567");
}
}
}
The type library file has the definitions for the properties and methods, but no events are visible. I even opened the type library in Delphi's viewer to make sure. The Delphi app can see and use any property, methods, and functions just fine. It just doesn't see the events.
I would appreciate any pointers or articles to read.
Thanks!
I finally got this resolved after much trial and error. There were 2 things that I needed to change on the C# code.
1) [ClassInterface(ClassInterfaceType.None)] needed to be changed to [ClassInterface(ClassInterfaceType.AutoDual)]
2) The class that is the source of the events needs to inherit from MarshalByRefObject. This helps if there is any threading done in the source class.
I only needed one thing on the Delphi side. I needed to make sure to have the "Generate Component Wrapper" checkbox checked. This is what will actually build the event scaffolding on Delphi's side.
This is how you do it in Delphi 7:
Select from the menu Project -> Import Type Library
Make sure that "Generate Component Wrapper" is checked
Select the COM class from the list
Click on the "Add Unit" button
The new unit will have the definitions of your COM events.
Step-By-Step blog post on how to do this