Using UI Automation to read Internet Explorer DOM from a pane(Window) - ui-automation

I am using UISpy.exe (Windows tool) to select UI Elements that also works with IE. However, for some IE Elements, all properties are not loaded in the automation framework or they have weird values with which they can not be uniquely and efficiently identified when looked for(like in the figure below, Name property).
The same properties that are available here are also available using the Windows Automation API Framework. I want to know if there is way, using this or any other library, to access the DOM of a selected window or pane. I know of one other application (UIExplorer from UI Path) that works this way but I can't figure how.
Here is an example of what UIExplorer's selector for the same element looks like. See how they have access to the DOM where as UISpy.exe is only displaying elements.

you can try this:
using System;
using System.Runtime.InteropServices;
using System.Windows.Automation;
using mshtml;
namespace ConsoleApp1
{
class Program
{
#region Native
[DllImport("user32", EntryPoint = "RegisterWindowMessageA", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
private static extern int RegisterWindowMessage(string lpString);
[DllImport("user32", EntryPoint = "SendMessageTimeoutA", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
private static extern int SendMessageTimeout(IntPtr hWnd, int msg, int wParam, int lParam, int fuFlags, int uTimeout, ref int lpdwResult);
[DllImport("oleacc", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
private static extern int ObjectFromLresult(int lResult, ref Guid riid, int wParam, ref IHTMLDocument2 ppvObject);
private const int SMTO_ABORTIFHUNG = 2;
#endregion Native
static void Main(string[] args)
{
var firstIeWindow = GetFirstIeWindow();
var firstIeTab = GetFirstIeTab(firstIeWindow);
var ieDom = GetIeDom(new IntPtr(firstIeTab.Current.NativeWindowHandle));
var firstInput = GetFirstInputElement(ieDom);
Console.WriteLine($"#{firstInput.id}[name={firstInput.name}] = {firstInput.value}");
}
private static AutomationElement GetFirstIeWindow()
{
var firstIeWindow = AutomationElement.RootElement.FindFirst(TreeScope.Children, new AndCondition(
new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Window),
new PropertyCondition(AutomationElement.ClassNameProperty, "IEFrame")))
?? throw new Exception("IEFrame not found");
return firstIeWindow;
}
private static AutomationElement GetFirstIeTab(AutomationElement ieWindow)
{
var frameTab = ieWindow.FindFirst(TreeScope.Children, new AndCondition(
new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Pane),
new PropertyCondition(AutomationElement.ClassNameProperty, "Frame Tab")))
?? throw new Exception("Frame Tab not found");
var tabWindow = frameTab.FindFirst(TreeScope.Children, new AndCondition(
new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Pane),
new PropertyCondition(AutomationElement.ClassNameProperty, "TabWindowClass")))
?? throw new Exception("TabWindowClass not found");
var ieServer = tabWindow.FindFirst(TreeScope.Descendants, new AndCondition(
new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Pane),
new PropertyCondition(AutomationElement.ClassNameProperty, "Internet Explorer_Server")))
?? throw new Exception("Internet Explorer_Server not found");
return ieServer;
}
private static DispHTMLDocument GetIeDom(IntPtr hWnd)
{
var lRes = 0;
var lMsg = RegisterWindowMessage("WM_HTML_GETOBJECT");
SendMessageTimeout(hWnd, lMsg, 0, 0, SMTO_ABORTIFHUNG, 1000, ref lRes);
if (lRes == 0) return null;
IHTMLDocument2 ieDomFromhWnd = null;
var iidIhtmlDocument2 = new Guid("626FC520-A41E-11CF-A731-00A0C9082637");
var hr = ObjectFromLresult(lRes, ref iidIhtmlDocument2, 0, ref ieDomFromhWnd);
if (hr != 0) throw new COMException($"{nameof(ObjectFromLresult)} has thrown an exception", hr);
return ieDomFromhWnd as DispHTMLDocument ?? throw new Exception("IE DOM not found");
}
private static DispHTMLInputElement GetFirstInputElement(DispHTMLDocument ieDom)
{
var firstInput = (ieDom.body as DispHTMLBody)?.getElementsByTagName("input").item(0) as DispHTMLInputElement
?? throw new Exception("Input element not found");
return firstInput;
}
}
}

Related

Open OSM pbf results in Protobuf exception

Using OSMSharp I am having trouble to open a stream for a file (which I can provide on demand)
The error occurs in PBFReader (line 104)
using (var tmp = new LimitedStream(_stream, length))
{
header = _runtimeTypeModel.Deserialize(tmp, null, _blockHeaderType) as BlobHeader;
}
and states: "ProtoBuf.ProtoException: 'Invalid field in source data: 0'" which might mean different things as I have read in this SO question.
The file opens and is visualized with QGis so is not corrupt in my opinion.
Can it be that the contracts do not match? Is OsmSharp/core updated to the latest .proto files for OSM from here (although not sure if this is the real original source for the definition files).
And what might make more sense, can it be that the file I attached is generated for v2 of OSM PBF specification?
In the code at the line of the exception I see the following comment which makes me wonder:
// TODO: remove some of the v1 specific code.
// TODO: this means also to use the built-in capped streams.
// code borrowed from: http://stackoverflow.com/questions/4663298/protobuf-net-deserialize-open-street-maps
// I'm just being lazy and re-using something "close enough" here
// note that v2 has a big-endian option, but Fixed32 assumes little-endian - we
// actually need the other way around (network byte order):
// length = IntLittleEndianToBigEndian((uint)length);
BlobHeader header;
// again, v2 has capped-streams built in, but I'm deliberately
// limiting myself to v1 features
So this makes me wonder if OSM Sharp is (still) up-to-date.
My sandbox code looks like this:
using OsmSharp.Streams;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using OsmSharp.Tags;
namespace OsmSharp
{
class Program
{
private const string Path = #"C:\Users\Bernoulli IT\Documents\Applications\Argaleo\Test\";
private const string FileNameAntarctica = "antarctica-latest.osm";
private const string FileNameOSPbf = "OSPbf";
private const Boolean useRegisterSource = false;
private static KeyValuePair<string, string> KeyValuePair = new KeyValuePair<string, string>("joep", "monita");
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
//string fileName = $#"{Path}\{FileNameAntarctica}.pbf";
string fileName = $#"{Path}\{FileNameOSPbf}.pbf";
string newFileName = $"{fileName.Replace(".pbf", string.Empty)}-{Guid.NewGuid().ToString().Substring(0, 4)}.pbf";
Console.WriteLine("*** Complete");
string fileNameOutput = CompleteFlow(fileName, newFileName);
Console.WriteLine("");
Console.WriteLine("*** Display");
DisplayFlow(fileNameOutput);
Console.ReadLine();
}
private static string CompleteFlow(string fileName, string newFileName)
{
// 1. Open file and convert to bytes
byte[] fileBytes = FileToBytes(fileName);
// 2. Bytes to OSM stream source (pbf)
PBFOsmStreamSource osmStreamSource;
osmStreamSource = BytesToOsmStreamSource(fileBytes);
osmStreamSource.MoveNext();
if (osmStreamSource.Current() == null)
{
osmStreamSource = FileToOsmStreamSource(fileName);
osmStreamSource.MoveNext();
if (osmStreamSource.Current() == null)
{
throw new Exception("No current in stream.");
}
}
// 3. Add custom tag
AddTag(osmStreamSource);
// 4. OSM stream source to bytes
//byte[] osmStreamSourceBytes = OsmStreamSourceToBytes(osmStreamSource);
// 5. Bytes to file
//string fileNameOutput = BytesToFile(osmStreamSourceBytes, newFileName);
OsmStreamSourceToFile(osmStreamSource, newFileName);
Console.WriteLine(newFileName);
return newFileName;
}
private static void DisplayFlow(string fileName)
{
// 1. Open file and convert to bytes
byte[] fileBytes = FileToBytes(fileName);
// 2. Bytes to OSM stream source (pbf)
BytesToOsmStreamSource(fileBytes);
}
private static byte[] FileToBytes(string fileName)
{
Console.WriteLine(fileName);
return File.ReadAllBytes(fileName);
}
private static PBFOsmStreamSource BytesToOsmStreamSource(byte[] bytes)
{
MemoryStream memoryStream = new MemoryStream(bytes);
memoryStream.Position = 0;
PBFOsmStreamSource osmStreamSource = new PBFOsmStreamSource(memoryStream);
foreach (OsmGeo element in osmStreamSource.Where(osmGeo => osmGeo.Tags.Any(tag => tag.Key.StartsWith(KeyValuePair.Key))))
{
foreach (Tag elementTag in element.Tags.Where(tag => tag.Key.StartsWith(KeyValuePair.Key)))
{
Console.WriteLine("!!!!!!!!!!!!!! Tag found while reading !!!!!!!!!!!!!!!!!!".ToUpper());
}
}
return osmStreamSource;
}
private static PBFOsmStreamSource FileToOsmStreamSource(string fileName)
{
using (FileStream fileStream = new FileInfo(fileName).OpenRead())
{
PBFOsmStreamSource osmStreamSource = new PBFOsmStreamSource(fileStream);
return osmStreamSource;
}
}
private static void AddTag(PBFOsmStreamSource osmStreamSource)
{
osmStreamSource.Reset();
OsmGeo osmGeo = null;
while (osmGeo == null)
{
osmStreamSource.MoveNext();
osmGeo = osmStreamSource.Current();
if(osmGeo?.Tags == null)
{
osmGeo = null;
}
}
osmGeo.Tags.Add("joep", "monita");
Console.WriteLine($"{osmGeo.Tags.FirstOrDefault(tag => tag.Key.StartsWith(KeyValuePair.Key)).Key} - {osmGeo.Tags.FirstOrDefault(tag => tag.Key.StartsWith(KeyValuePair.Key)).Value}");
}
private static byte[] OsmStreamSourceToBytes(PBFOsmStreamSource osmStreamSource)
{
MemoryStream memoryStream = new MemoryStream();
PBFOsmStreamTarget target = new PBFOsmStreamTarget(memoryStream, true);
osmStreamSource.Reset();
target.Initialize();
UpdateTarget(osmStreamSource, target);
target.Flush();
target.Close();
return memoryStream.ToArray();
}
private static string BytesToFile(byte[] bytes, string fileName)
{
using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write))
{
fs.Write(bytes, 0, bytes.Length);
}
return fileName;
}
private static void OsmStreamSourceToFile(PBFOsmStreamSource osmStreamSource, string fileName)
{
using (FileStream fileStream = new FileInfo(fileName).OpenWrite())
{
PBFOsmStreamTarget target = new PBFOsmStreamTarget(fileStream, true);
osmStreamSource.Reset();
target.Initialize();
UpdateTarget(osmStreamSource, target);
target.Flush();
target.Close();
}
}
private static void UpdateTarget(OsmStreamSource osmStreamSource, OsmStreamTarget osmStreamTarget)
{
if (useRegisterSource)
{
osmStreamTarget.RegisterSource(osmStreamSource, osmGeo => true);
osmStreamTarget.Pull();
}
else
{
bool isFirst = true;
foreach (OsmGeo osmGeo in osmStreamSource)
{
Tag? tag = osmGeo.Tags?.FirstOrDefault(t => t.Key == KeyValuePair.Key);
switch (osmGeo.Type)
{
case OsmGeoType.Node:
if (isFirst)
{
for (int indexer = 0; indexer < 1; indexer++)
{
(osmGeo as Node).Tags.Add(new Tag(KeyValuePair.Key + Guid.NewGuid(), KeyValuePair.Value));
}
isFirst = false;
}
osmStreamTarget.AddNode(osmGeo as Node);
break;
case OsmGeoType.Way:
osmStreamTarget.AddWay(osmGeo as Way);
break;
case OsmGeoType.Relation:
osmStreamTarget.AddRelation(osmGeo as Relation);
break;
default:
throw new ArgumentOutOfRangeException();
}
}
}
}
}
}
Already I posted this question on the GITHube page of OSMSharp as is linked here. Any help would be very appreciated.

What is the equivalent in swift for a static block in Java

How to put a static block in Swift, like here in Java?
I have tried the static var block = {}
but that doesn't work right. It has to called exclusively.
What I want is like in Java, the entire block within the static braces are executed when the class is initialized. Something like that in Swift. I have searched all over the internet and not one soul has an answer! A similar functionality or workaround would also do.
public class EnumRingLevel
{
public static final EnumRingLevel DEFAULT = new EnumRingLevel(
0, 0, "DEFAULT", 1000, 2000);
public static final EnumRingLevel SILENT = new EnumRingLevel(
10, 1, "SILENT", 1001, 2001);
public static final EnumRingLevel QUIET_BEEP = new EnumRingLevel(
20, 2, "QUIET_BEEP", 1002, 2002);
public static final EnumRingLevel NORMAL_BEEP = new EnumRingLevel(
30, 3, "NORMAL_BEEP",1003, 2003);
private final int gdbval;
private final int gindex;
public final String ginternalname;
private final int gcaptionId;
private final int gdisplaycaptionId;
private static EnumRingLevel[] gRingLevelsSortedOnIndex = null;
private static String[] gCaptionsSortedOnIndex = null;
static
{
gRingLevelsSortedOnIndex = new EnumRingLevel[6];
gRingLevelsSortedOnIndex[0] = DEFAULT;
gRingLevelsSortedOnIndex[1] = SILENT;
gRingLevelsSortedOnIndex[2] = QUIET_BEEP;
gRingLevelsSortedOnIndex[3] = NORMAL_BEEP;
gRingLevelsSortedOnIndex[4] = LOUD_BEEP;
gRingLevelsSortedOnIndex[5] = CUSTOM;
gCaptionsSortedOnIndex = new String[6];
for(int i=0;i<gRingLevelsSortedOnIndex.length;i++)
{
gCaptionsSortedOnIndex[i] = gRingLevelsSortedOnIndex[i].getCaption();
}
}
private EnumRingLevel(
int dbval, int index, String internalname
, int captionResource, int displaycaptionResource)
{
//private constructor
gdbval = dbval;
gindex = index;
ginternalname = internalname;
gcaptionId = captionResource;
gdisplaycaptionId = displaycaptionResource;
}
}
try this,
private static var gRingLevelsSortedOnIndex: [EnumRingLevel] = {
return [DEFAULT, SILENT, QUIET_BEEP, NORMAL_BEEP, LOUD_BEEP, CUSTOM]
}()

EntityFramework 6.0.0-alpha3 - EdmxWriter.WriteEdmx() fails after update to alpha3 from alpha2

The following extension works for EF6 alpha2 but stopped working with alpha3 with null reference exception. The failing statement is the EdmxWriter.WriteEdmx(..)
The views pre-generation is performed on a code-first context.
How to achieve pre-generate views using EF6 alpha3?
public static PreGeneratedViews PreGenerateViews<T>(this T dbContext) where T : DbContext
{
Trace.TraceInformation("PreGenerating views");
//define ef collections
EdmItemCollection edmItemCollection = null;
StoreItemCollection storeItemCollection = null;
StorageMappingItemCollection mappingItemCollection = null;
//get ef collections
GetItemCollections(
GetEdmx(dbContext),
out edmItemCollection,
out storeItemCollection,
out mappingItemCollection);
IList<EdmSchemaError> errors = null;
//get the generated views
Dictionary<string, string> extentViews = GetExtentViews(mappingItemCollection, out errors);
//return the pregenerated views as string (xml document)
return new PreGeneratedViews
{
EdmEntityContainerName = edmItemCollection.GetItems<EntityContainer>().Single().Name,
StoreEntityContainerName = storeItemCollection.GetItems<EntityContainer>().Single().Name,
HashOverMappingClosure =
ReflectionHelper.GetMappingClosureHash(edmItemCollection.EdmVersion,
mappingItemCollection),
HashOverAllExtentViews =
ReflectionHelper.GenerateHashForAllExtentViewsContent(edmItemCollection.EdmVersion,
extentViews),
ViewCount = extentViews.Count,
Views = CreateViews(extentViews),
ViewsEmbeddedResourceName =
string.Format("DbContextViews{0}.xml", Guid.NewGuid().ToString("N")),
};
}
private static XDocument GetEdmx(DbContext dbContext)
{
var ms = new MemoryStream();
using (XmlWriter writer = XmlWriter.Create(ms))
{
EdmxWriter.WriteEdmx(dbContext, writer);
}
ms.Position = 0;
return XDocument.Load(ms);
}
private static void SplitEdmx(XDocument edmx, out XmlReader csdlReader, out XmlReader ssdlReader,
out XmlReader mslReader)
{
// xml namespace agnostic to make it work with any version of Entity Framework
XNamespace edmxNs = edmx.Root.Name.Namespace;
XElement storageModels = edmx.Descendants(edmxNs + "StorageModels").Single();
XElement conceptualModels = edmx.Descendants(edmxNs + "ConceptualModels").Single();
XElement mappings = edmx.Descendants(edmxNs + "Mappings").Single();
ssdlReader = storageModels.Elements().Single(e => e.Name.LocalName == "Schema").CreateReader();
csdlReader = conceptualModels.Elements().Single(e => e.Name.LocalName == "Schema").CreateReader();
mslReader = mappings.Elements().Single(e => e.Name.LocalName == "Mapping").CreateReader();
}
private static void GetItemCollections(XDocument edmx, out EdmItemCollection edmItemCollection,
out StoreItemCollection storeItemCollection,
out StorageMappingItemCollection mappingItemCollection)
{
// extract csdl, ssdl and msl artifacts from the Edmx
XmlReader csdlReader, ssdlReader, mslReader;
SplitEdmx(edmx, out csdlReader, out ssdlReader, out mslReader);
// Initialize item collections
edmItemCollection = new EdmItemCollection(new[] {csdlReader});
storeItemCollection = new StoreItemCollection(new[] {ssdlReader});
mappingItemCollection = new StorageMappingItemCollection(edmItemCollection, storeItemCollection,
new[] {mslReader});
}
private static Dictionary<string, string> GetExtentViews(StorageMappingItemCollection mappingItemCollection,
out IList<EdmSchemaError> errors)
{
Dictionary<EntitySetBase, string> views = ReflectionHelper.GenerateViews(mappingItemCollection, out errors);
if (errors != null && errors.Any())
{
return null;
}
var extentViews = new Dictionary<string, string>(views.Count);
foreach (var kvp in views)
{
extentViews.Add(
GetExtentFullName(kvp.Key),
kvp.Value.Replace("\r\n", "\n")); // replace accounts for Xml new line normalization
}
return extentViews;
}
private static string GetExtentFullName(EntitySetBase entitySet)
{
return string.Format("{0}.{1}", entitySet.EntityContainer.Name, entitySet.Name);
}
private static string CreateViews(Dictionary<string, string> extentViews)
{
var sb = new StringBuilder();
//var embeddedViewsFileName = Path.ChangeExtension(Host.TemplateFile, "xml");
using (XmlWriter writer = XmlWriter.Create(sb, new XmlWriterSettings
{
Indent = true,
Encoding = Encoding.UTF8
}))
{
writer.WriteStartElement("views");
foreach (var kvp in extentViews)
{
writer.WriteStartElement("view");
writer.WriteAttributeString("extent", kvp.Key);
writer.WriteCData(kvp.Value);
writer.WriteEndElement();
}
writer.WriteEndElement();
}
return sb.ToString();
}
#region Nested type: ReflectionHelper
private static class ReflectionHelper
{
private static readonly Assembly efAssembly = typeof (StorageMappingItemCollection).Assembly;
private static readonly MethodInfo generateViewsMethodInfo =
typeof (StorageMappingItemCollection).GetMethod("GenerateEntitySetViews",
BindingFlags.NonPublic | BindingFlags.Instance);
private static readonly MethodInfo getMappingClosureHashMethodInfo =
efAssembly.GetType("System.Data.Entity.Core.Mapping.MetadataMappingHasherVisitor", true)
.GetMethod("GetMappingClosureHash", BindingFlags.Static | BindingFlags.NonPublic);
private static readonly MethodInfo generateHashForAllExtentViewsContentMethodInfo =
efAssembly.GetType("System.Data.Entity.Core.Common.Utils.MetadataHelper", true)
.GetMethod("GenerateHashForAllExtentViewsContent", BindingFlags.Static | BindingFlags.NonPublic);
public static Dictionary<EntitySetBase, string> GenerateViews(
StorageMappingItemCollection mappingItemCollection, out IList<EdmSchemaError> errors)
{
errors = null;
return
(Dictionary<EntitySetBase, string>)
generateViewsMethodInfo.Invoke(mappingItemCollection, new object[] {errors});
}
public static string GetMappingClosureHash(double schemaVersion,
StorageMappingItemCollection mappingItemCollection)
{
return (string) getMappingClosureHashMethodInfo.Invoke(
null,
new object[]
{
schemaVersion,
// CodeFirst currently creates always one entity container
mappingItemCollection.GetItems<GlobalItem>().Single(
i => i.GetType().Name == "StorageEntityContainerMapping")
});
}
public static string GenerateHashForAllExtentViewsContent(double schemaVersion,
Dictionary<string, string> extentViews)
{
return (string) generateHashForAllExtentViewsContentMethodInfo.Invoke(
null,
new object[] {schemaVersion, extentViews});
}
}
The stacktrace is the following:
NullReferenceException
at: System.Data.Entity.Edm.Serialization.EdmSerializationVisitor.VisitEdmAssociationSet(AssociationSet item)
at: System.Data.Entity.Edm.EdmModelVisitor.VisitCollection[T](IEnumerable1 collection, Action1 visitMethod)
at: System.Data.Entity.Edm.EdmModelVisitor.VisitAssociationSets(EntityContainer container, IEnumerable`1 associationSets)
at: System.Data.Entity.Edm.EdmModelVisitor.VisitEdmEntityContainer(EntityContainer item)
at: System.Data.Entity.Edm.Serialization.EdmSerializationVisitor.VisitEdmEntityContainer(EntityContainer item)
at: System.Data.Entity.Edm.EdmModelVisitor.VisitCollection[T](IEnumerable1 collection, Action1 visitMethod)
at: System.Data.Entity.Edm.EdmModelVisitor.VisitEntityContainers(IEnumerable`1 entityContainers)
at: System.Data.Entity.Edm.EdmModelVisitor.VisitEdmModel(EdmModel item)
at: System.Data.Entity.Edm.Serialization.EdmSerializationVisitor.Visit(EdmModel edmModel, String namespaceName, String provider, String providerManifestToken)
at: System.Data.Entity.Edm.Serialization.EdmSerializationVisitor.Visit(EdmModel edmModel, String provider, String providerManifestToken)
at: System.Data.Entity.Edm.Serialization.SsdlSerializer.Serialize(EdmModel dbDatabase, String provider, String providerManifestToken, XmlWriter xmlWriter, Boolean serializeDefaultNullability)
at: System.Data.Entity.ModelConfiguration.Edm.Serialization.EdmxSerializer.WriteEdmxRuntime()
at: System.Data.Entity.ModelConfiguration.Edm.Serialization.EdmxSerializer.Serialize(DbDatabaseMapping databaseMapping, DbProviderInfo providerInfo, XmlWriter xmlWriter)
at: System.Data.Entity.Infrastructure.EdmxWriter.WriteEdmx(DbModel model, XmlWriter writer)
at: System.Data.Entity.Infrastructure.EdmxWriter.WriteEdmx(DbContext context, XmlWriter writer)
at: **.DbContextPreGenerateViewExtension.GetEdmx(DbContext dbContext)
Thanks!
I just submitted a fix for work item 867 (35852e8392ad). It should fix the NRE. The fix should be included in the today's nightly build. Can you give it a try and let me know if this fixed the problem?
This is a known bug in Alpha 3.

clickable Imagemap in Gwt

hii i want clickable image map in gwt project...i have created a simple XY map but now i want clickable imagemap...please help me for that
i just want to create a chart where mouse over effect take place....
here is my code
public class ChartGenerator extends ApplicationFrame{
private List<String> trainTypeArray = new ArrayList<String>();
private String lineType;
private List<Long> startTimeOfTrain = new ArrayList<Long>();
private List<Boolean> labelVisibility = new ArrayList<Boolean>();
private List<Integer> stationDistance= new ArrayList<Integer>();
private List<String> lineColorArray = new ArrayList<String>();
private List<String> lineShadeArray = new ArrayList<String>();
private List<String> stationNames = new ArrayList<String>();
private List<String> trainArray = new ArrayList<String>();
private JFreeChart chart =null;
private int startTimeLong;
private int endTimeLong;
private String timezone;
private boolean prediction;
public ChartGenerator(String title, Date dt, String startTime, String endTime, String serviceDirection, String lineType, int delay, boolean prediction) throws BombardierBaseException, BombardierException {
/*super(title)*/;
String[] startSplit = startTime.split(":");
String[] endTimeSplit = endTime.split(":");
this.timezone = startTime +"-"+endTime;
startTimeLong = Integer.parseInt(startSplit[0])*60*60*1000+Integer.parseInt(startSplit[1])*60*1000;
endTimeLong = Integer.parseInt(endTimeSplit[0])*60*60*1000+Integer.parseInt(endTimeSplit[1])*60*1000;
endTimeLong = endTimeLong+(60*1000);
this.prediction = prediction;
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yy");
String dtOfJourney = "'" +sdf.format(dt)+"'";
this.lineType = lineType;
System.out.println("Create data-set now");
final XYDataset dataset = createDataset(dtOfJourney, startTimeLong,endTimeLong,serviceDirection);
chart= createChart(dataset, dtOfJourney, serviceDirection);
}
public int getStartTimeLong() {
return startTimeLong;
}
public void setStartTimeLong(int startTimeLong) {
this.startTimeLong = startTimeLong;
}
public int getEndTimeLong() {
return endTimeLong;
}
public JFreeChart getChart(){
return chart;
}
public BufferedImage getBufferedImage(int width, int height){
ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
return this.chart.createBufferedImage(width,height, info);
}
private double getStationDistion(String name){
return InitializeProperties.getStationDistance(name);
}
private XYDataset createDataset(String dtOfJourney, long startTime,long endTime,String serviceDirection) throws BombardierBaseException {
ResultSet resultSet =null;
Statement readstatement = null;
Connection con = null;
System.out.println("Entering get Connection now");
System.out.flush();
try{
System.out.println("Getting connection");
System.out.flush();
con = InitializeProperties.getConnection();
System.out.println("Connection initialized");
System.out.flush();
readstatement= con.createStatement();
final XYSeriesCollection dataset1 = new XYSeriesCollection();
String lineTypeFilter = "";
if(!this.lineType.equals("A")){
if(lineType.equals("L")){
lineTypeFilter = "and lt.act_lineType like ' '";
}else{
lineTypeFilter = "and lt.act_lineType like '" + this.lineType + "'";
}
}
int n = 0;
String serviceDirectionClause = "";

Connecting to scroll_event in Vala

I've been struggling to connect to the scroll_event of a TextView widget. I can connect a lambda to it, and then run my method, but I'd like to understand why directly connecting doesn't work. I've been using the code below
using Gtk;
public class TextFileViewer : Gtk.Window {
private TextView text_view;
public TextFileViewer () {
this.title = "Text File Viewer";
this.position = WindowPosition.CENTER;
set_default_size (400, 300);
this.text_view = new TextView ();
this.text_view.editable = true;
this.text_view.cursor_visible = true;
var scroll = new ScrolledWindow (null, null);
scroll.set_policy (PolicyType.AUTOMATIC, PolicyType.AUTOMATIC);
scroll.add (this.text_view);
this.text_view.scroll_event.connect (on_scroll_event);
var vbox = new VBox (true, 0);
vbox.pack_start (this.text_view, true, true, 0);
add (vbox);
}
private void on_scroll_event () {
stderr.printf("We scrollin breds");
}
public static int main (string[] args) {
Gtk.init (ref args);
var window = new TextFileViewer ();
window.destroy.connect (Gtk.main_quit);
window.show_all ();
Gtk.main ();
return 0;
}
}
That code gives me the error:
gtkviewer.vala:20.46-20.60: error: Argument 1: Cannot convert from `TextFileViewer.on_scroll_event' to `Gtk.Widget.scroll_event'
scroll.scroll_event.connect (on_scroll_event);
vala is at version 0.12.0
Check the scroll-event signal arguments:
public virtual signal bool scroll_event (Gdk.EventScroll event);
private bool on_scroll_event (Gdk.EventScroll e) {
stderr.printf("We scrollin breds");
return true;
}