How to Drag and Drop an element using Proractor.net c# UI Automation - protractor-net

What will be the possible reason for the Drag And Drop functionality stopped working for me with Protractor.net c#?
Used http://marceljuenemann.github.io/angular-drag-and-drop-lists/demo/#/advanced to test this feature. But didn't worked for me.
Here is the sample code i tried:
Wait.Until(ExpectedConditions.ElementIsVisible(By.XPath("//h3[.='Container (effects allowed: all)']")));
var elem = NgDriver.FindElement(By.XPath("//h3[.='Container (effects allowed: all)']"));
IWebElement parentElement = elem.FindElement(By.XPath(".."));
IWebElement mov = parentElement.FindElement(NgBy.Repeater("item in container.items"));
Wait.Until(ExpectedConditions.ElementIsVisible(By.XPath("//h3[.='Container (effects allowed: move)']")));
var drropElem = NgDriver.FindElement(By.XPath("//h3[.='Container (effects allowed: move)']"));
IWebElement parentElement2 = drropElem.FindElement(By.XPath(".."));
IWebElement mov2 = parentElement2.FindElement(NgBy.Repeater("item in container.items"));
Actions builder = new Actions(Driver);
Actions action = builder.ClickAndHold(mov);
builder.Build();
action.Perform();
builder = new Actions(Driver);
action = builder.MoveToElement(mov2);
builder.Release(mov2);
builder.Build();
action.Perform();
Also Tried with DragAndDrop() function in thee Action .
Any help will be appreciated.

Create a Javscript file named "drop.js" and set the following content.
function e(e,t,n,i){var r=a.createEvent("DragEvent");r.initMouseEvent(t,!0,!0,o,0,0,0,c,g,!1,!1,!1,!1,0,null),Object.defineProperty(r,"dataTransfer",{get:function(){return d}}),e.dispatchEvent(r),o.setTimeout(i,n)}var t=arguments[0],n=arguments[1],i=arguments[2]||0,r=arguments[3]||0;if(!t.draggable)throw new Error("Source element is not draggable.");var a=t.ownerDocument,o=a.defaultView,l=t.getBoundingClientRect(),u=n?n.getBoundingClientRect():l,c=l.left+(l.width>>1),g=l.top+(l.height>>1),s=u.left+(u.width>>1)+i,f=u.top+(u.height>>1)+r,d=Object.create(Object.prototype,{_items:{value:{}},effectAllowed:{value:"all",writable:!0},dropEffect:{value:"move",writable:!0},files:{get:function(){return this._items.Files}},types:{get:function(){return Object.keys(this._items)}},setData:{value:function(e,t){this._items[e]=t}},getData:{value:function(e){return this._items[e]}},clearData:{value:function(e){delete this._items[e]}},setDragImage:{value:function(e){}}});if(n=a.elementFromPoint(s,f),!n)throw new Error("The target element is not interactable and need to be scrolled into the view.");u=n.getBoundingClientRect(),e(t,"dragstart",101,function(){var i=n.getBoundingClientRect();c=i.left+s-u.left,g=i.top+f-u.top,e(n,"dragenter",1,function(){e(n,"dragover",101,function(){n=a.elementFromPoint(c,g),e(n,"drop",1,function(){e(t,"dragend",1,callback)})})})})
And in your code
string jsScript = Path.Combine(currentDirectory, "JavaScript", "drop.js");
if (File.Exists(jsScript))
{
string dragAndDropScript = File.ReadAllText(jsScript);
IJavaScriptExecutor jse = (IJavaScriptExecutor)NgDriver;
jse.ExecuteScript(dragAndDropScript, dragFrom, dragTo);
}
drafFrom and dragTo are the controls used for dragging and dripping. These control should contain attributes like "draggable" or "dropable" in their HTML tag.

Related

Update autoComplete JavaFx?

I'm currently working on a JavaFX project.I'm using Autcomplete TextField of ControlFx .Each time i add new rows in database table, it should to update Autocomplete ,i did this but my problem is showing double Context-Menu ,we can say double autocompletes because i call method that create autocomplete each adding of new elements in table.
When i click a tab editBill i call this method :
public void showEditBill() {
if (!BillPane.getTabs().contains(EditBillTab)) {
BillPane.getTabs().add(EditBillTab);
}
SingleSelectionModel<Tab> selectionModel = BillPane.getSelectionModel();
selectionModel.select(EditBillTab);
/*it should remove the old autocomplete from textfield*/
pushBills(); //Call for cheking new items
}
pushBills method () :
public void pushBills() {
ArrayList list = new ArrayList<>();
bills = new BillHeaderDao().FindAll();
for (int i = 0; i < bills.size(); i++) {
list.add(bills.get(i).getIdClient());
}
//How can i remove the old bind before bind again
autoCompletionBinding = TextFields.bindAutoCompletion(SearchBill, SuggestionProvider.create(list));
}
How i can remove the old autocomplete and bind new automplete?
Just in any case if you need to keep instance of AutoCompletionTextFieldBinding object, thus avoiding use of:
autoCompleteBinding = TextFields.bindingAutoCompletion(TextField,List);
, which will change the instance, we could go a little bit deeper and use this:
// let's suppose initially we have this possible values:
Set<String> autoCompletions = new HashSet<>(Arrays.asList("A", "B", "C"));
SuggestionProvider<String> provider = SuggestionProvider.create(autoCompletions);
new AutoCompletionTextFieldBinding<>(textField, provider);
// and after some times, possible autoCompletions values has changed and now we have:
Set<String> filteredAutoCompletions = new HashSet<>(Arrays.asList("A", "B"));
provider.clearSuggestions();
provider.addPossibleSuggestions(filteredAutoCompletions);
So, through SuggestionProvider, we have "updated" auto completion values.
To avoid doubling of suggestions menu, don't use again (for the 2nd time):
TextFields.bindAutoCompletion(..)
In order to provide updates to the auto-complete suggestion list, retain a reference to the SuggestionProvider and update the suggestion provider instead:
TextField textField = new TextField();
SuggestionProvider suggestionProvider = SuggestionProvider.create(new ArrayList());
new AutoCompletionTextFieldBinding<>(textField, suggestionProvider);
When you want to update the suggestion list:
List<String> newSuggestions = new ArrayList();
//(add entries to list)
suggestionProvider.clearSuggestions();
suggestionProvider.addPossibleSuggestions(newSuggestions);
This will do the trick:
Instead of: TextFields.bindAutoCompletion(textField, list);
, try this:
List<String> strings = new ArrayList<>();
Then create binding between your textField with the list through:
new AutoCompletionTextFieldBinding<>(textField, SuggestionProvider.create(strings));
So any changes, including removing, from the list, will be reflected in the autoCompletion of the textField;
And you will have dynamic filtering of suggestions, showed in pop-up, when user enter some text in textField;
I had the same problem some time ago I try to do as #MaxKing mentions, but it didnt work. I managed to give it a soluciĆ³n even though I don't think it's the right way.
// Dispose the old binding and recreate a new binding
autoCompleteBinding.dispose();
autoCompleteBinding = TextFields.bindingAutoCompletion(TextField,List);
try this:
public void pushBills() {
ArrayList list = new ArrayList<>();
bills = new BillHeaderDao().FindAll();
for (int i = 0; i < bills.size(); i++) {
list.add(bills.get(i).getIdClient());
}
autoCompletionBinding.dispose();
autoCompletionBinding = TextFields.bindAutoCompletion(SearchBill, SuggestionProvider.create(list));
}

Listing WorkItem State Reasons programmatically

We have a customised TFS workflow, I want to be able to access the Reasons I can close a Bug (change the state from Active to Closed) from TFS so that we don't have to update our code every time we want to tweak our process.
This is what I have so far:
WorkItemType wiType = this.GetWorkItemStore().Projects[this.ProjectName].WorkItemTypes["Bug"];
var reason = wiType.FieldDefinitions["Reason"];
var state = wiType.FieldDefinitions["State"];
var filterList = new FieldFilterList();
FieldFilter filter = new FieldFilter(wiType.FieldDefinitions[CoreField.State], "Active");
filterList.Add(filter);
var allowedReasons = reason.FilteredAllowedValues(filterList);
However I'm not getting any results. I'd like to get a list of all the reasons why I can close a bug (Not Reproduceable, Fixed etc)
There isn't any easy way to get the transition via API directly as I know since the API read the allowed values from database directly.
The alternative way would be export the workitemtype definition via WorkItemType.Export() method and then get the information from it. Vaccano's answer in this question provided the entire code sample you can use.
Edited to give an example of how I solved this using the above recommendation:
public static List<Transition> GetTransistions(this WorkItemType workItemType)
{
List<Transition> currentTransistions;
// See if this WorkItemType has already had it's transistions figured out.
_allTransistions.TryGetValue(workItemType, out currentTransistions);
if (currentTransistions != null)
return currentTransistions;
// Get this worktype type as xml
XmlDocument workItemTypeXml = workItemType.Export(false);
// Create a dictionary to allow us to look up the "to" state using a "from" state.
var newTransistions = new List<Transition>();
// get the transistions node.
XmlNodeList transitionsList = workItemTypeXml.GetElementsByTagName("TRANSITIONS");
// As there is only one transistions item we can just get the first
XmlNode transitions = transitionsList[0];
// Iterate all the transitions
foreach (XmlNode transition in transitions)
{
XmlElement defaultReasonNode = transition["REASONS"]["DEFAULTREASON"];
var defaultReason = defaultReasonNode.Attributes["value"].Value;
var otherReasons = new List<string>();
XmlNodeList otherReasonsNodes = transition["REASONS"].SelectNodes("REASON");
foreach (XmlNode reasonNode in otherReasonsNodes)
{
var reason = reasonNode.Attributes["value"].Value;
otherReasons.Add(reason);
}
// save off the transistion
newTransistions.Add(new Transition
{
From = transition.Attributes["from"].Value,
To = transition.Attributes["to"].Value,
DefaultReason = defaultReason,
OtherReasons = otherReasons
});
}
// Save off this transition so we don't do it again if it is needed.
_allTransistions.Add(workItemType, newTransistions);
return newTransistions;
}

Google Script Get UI textbox value

I have created a simple GUI with 2 textboxes and 1 button. The button handler goes as below
function handleButton1(e)
{
var app = UiApp.getActiveApplication();
var v1 = e.parameter.TextBox1;
var v2 = e.parameter.TextBox2;
Logger.log(v1);
app.getElementById("TextBox1").setText(v2);
app.getElementById("TextBox2").setText(v1);
return app;
}
When I run the app the textbox values are TextBox1 and TextBox2.
When press button then both the textbox value displayed is undefined.
Where am I going wrong.
With a server-side click handler, you need to explicitly include values in the handler event by using .addCallbackElement(). If you do so, the current value of the named elements you add will be included in the event delivered to your handler.
Since you are seeing undefined, it's likely that you didn't add the callbacks. You should have something like this in your UI definition:
var handler = app.createServerHandler('handleButton1')
.addCallbackElement(textBox1)
.addCallbackElement(textBox2);
button.addClickHandler(handler);
The name of the element will be used to label the callback value (.setName()), while the id will be used to access the element in your handler (.setId()).
Here's a working version of your script:
function doGet() {
var app = UiApp.createApplication();
var textBox1 = app.createTextBox().setName("TextBox1").setId("TextBox1");
var textBox2 = app.createTextBox().setName("TextBox2").setId("TextBox2");
var button = app.createButton('Swap Contents');
app.add(textBox1).add(textBox2).add(button);
var handler = app.createServerHandler('handleButton1')
.addCallbackElement(textBox1)
.addCallbackElement(textBox2);
button.addClickHandler(handler);
return app;
}
function handleButton1(e)
{
//Logger.log(JSON.stringify(e));
var app = UiApp.getActiveApplication();
var v1 = e.parameter.TextBox1;
var v2 = e.parameter.TextBox2;
app.getElementById("TextBox1").setText(v2);
app.getElementById("TextBox2").setText(v1);
return app;
}

Reading remote text file with AIR, spaces and links

I have a text file(txt) in my web server. I will read the file contents and show it to user. The problem is that it does not show line separations and spaces the right way. Also i will need to activate possible links. For example if there is http://www.google.com then user can just click on the link and default browser opens it.
So far i have this:
var fileContents:String;
try{
var myLoader:URLLoader = new URLLoader();
myLoader.addEventListener(Event.COMPLETE, onFileLoaded);
myLoader.load(new URLRequest("http://my.website.com/test.txt"));
function onFileLoaded(e:Event):void
{
fileContents = String(e.currentTarget.data);
var alertMessage = fileContents;
I have done this same thing in java, but I am not so familiar with ActionScript.
Java code:
URL url = new URL(getString(R.string.url));
BufferedReader r = new BufferedReader(new InputStreamReader(
url.openStream(), "UTF-8"));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line);
total.append(System.getProperty("line.separator"));
}
str = total.toString();
r.close();
return str;
Links in java:
final SpannableString s = new SpannableString(sUrl);
Linkify.addLinks(s, Linkify.WEB_URLS);
You might consider using the Text Layout Framework (TLF) from Adobe. You can import the text as HTML and it will create clickable links for any URL's found in the text. TLF is a bit unwieldy, but very powerful.
private var myTextFlow:TextFlow = TextConverter.importToFlow(sourceText, TextConverter.TEXT_FIELD_HTML_FORMAT);
If you are using Flex 4, can assign the resulting TextFlow object to one of the text components:
<s:RichText textFlow="{myTextFlow}" />
In an Actionscript project, you have to do a little more work to use the TextFlow. TLF uses an MVC approach. The TextFlow serves as the model, you can use a Sprite for the view, and a ContainerController as the controller:
private var container:Sprite = new Sprite();
addChild(container);
private var controller:ContainerController = new ContainerController(container, 800,600);
myTextFlow.flowComposer.addController(controller);
myTextFlow.flowComposer.updateAllControllers();

Autofac with Open Generics and Type Specified at Runtime

The documentation states that Autofac supports open generics and I am able to register and resolve in a basic case like so:
Registration:
builder.RegisterGeneric(typeof(PassThroughFlattener<>))
.As(typeof(IFlattener<>))
.ContainerScoped();
Resolve:
var flattener = _container.Resolve<IFlattener<Address>>();
The above code works just fine. However, assuming that I will not know the type provided to IFlattener until runtime, I want to do something like this:
object input = new Address();
var flattener = (IFlattener)_container.Resolve(typeof(IFlattener<>), new TypedParameter(typeof(IFlattener<>), input.GetType()));
Is this possible with AutoFac? I got the idea from the following using StructureMap:
http://structuremap.sourceforge.net/Generics.htm
I'm trying to achieve the same goal outlined in this article.
This is certainly possible with Autofac. At "register time", this is what you basically do:
Register the open generic type (PassThroughFlattener<>)
Register any specific types (AddressFlattener)
Register a method that can be used to resolve an IFlattener based on a input object
At "resolve time", you will do:
Resolve the method
Call the method with input parameter(s) to resolve the IFlattener implementation
Here's a (hopefully) working sample:
var openType = typeof(IFlattener<>);
var builder = new ContainerBuilder();
builder.RegisterGeneric(typeof(PassThroughFlattener<>)).As(openType);
builder.Register<AddressFlattener>().As<IFlattener<Address>>();
builder.Register<Func<object, IFlattener>>(context => theObject =>
{
var closedType =
openType.MakeGenericType(theObject.GetType());
return (IFlattener) context.Resolve(closedType,
new PositionalParameter(0, theObject));
});
var c = builder.Build();
var factory = c.Resolve<Func<object, IFlattener>>();
var address = new Address();
var addressService = factory(address);
Assert.That(addressService, Is.InstanceOfType(typeof(AddressFlattener)));
var anything = "any other data";
var anyService = factory(anything);
Assert.That(anyService, Is.InstanceOfType(typeof(PassThroughFlattener<string>)));
If you don't know type until runtime you can build it using MakeGenericType:
var addressFlattener = _container.Resolve(typeof(IFlattener<>).MakeGenericType(typeof(Address)));

Resources