LoadException with FXML created with Scene Builder 2.0 - javafx-8

I got a problem that i absolutly cant solve on my own because i have just started using JAVA FX. I get a nasty javafx.fxml.LoadException: , but i have done exactly like a guide (http://docs.oracle.com/javafx/scenebuilder/1/get_started/jsbpub-get_started.htm), but i cant get my Main to run. This is the console:
ant -f P:\\FXML\\IssueTrackingLite jfxsa-run
init:
deps-jar:
Created dir: P:\FXML\IssueTrackingLite\build
Updating property file: P:\FXML\IssueTrackingLite\build\built-jar.properties
Created dir: P:\FXML\IssueTrackingLite\build\classes
Created dir: P:\FXML\IssueTrackingLite\build\empty
Created dir: P:\FXML\IssueTrackingLite\build\generated-sources\ap-source-output
Compiling 6 source files to P:\FXML\IssueTrackingLite\build\classes
warning: [options] bootstrap class path not set in conjunction with -source 1.6
1 warning
Copying 4 files to P:\FXML\IssueTrackingLite\build\classes
compile:
Detected JavaFX Ant API version 1.3
Launching <fx:jar> task from C:\Program Files\Java\jdk1.8.0\jre\..\lib\ant-javafx.jar
Warning: From JDK7u25 the Codebase manifest attribute should be used to restrict JAR repurposing.
Please set manifest.custom.codebase property to override the current default non-secure value '*'.
Launching <fx:deploy> task from C:\Program Files\Java\jdk1.8.0\jre\..\lib\ant-javafx.jar
jfx-deployment-script:
jfx-deployment:
jar:
Copying 12 files to P:\FXML\IssueTrackingLite\dist\run910302418
jfx-project-run:
Executing P:\FXML\IssueTrackingLite\dist\run910302418\IssueTrackingLite.jar using platform C:\Program Files\Java\jdk1.8.0\jre/bin/java
before ........!
IssueTrackingLiteController.initialize
août 11, 2014 12:24:01 PM issuetrackinglite.Main start
GRAVE: null
javafx.fxml.LoadException:
file:/P:/FXML/IssueTrackingLite/dist/run910302418/IssueTrackingLite.jar!/issuetrackinglite/IssueTrackingLite.fxml
at javafx.fxml.FXMLLoader.constructLoadException(FXMLLoader.java:2617)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2595)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2441)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3230)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3191)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3164)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3140)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3120)
at javafx.fxml.FXMLLoader.load(FXMLLoader.java:3113)
at issuetrackinglite.Main.start(Main.java:55)
at com.sun.javafx.application.LauncherImpl$8.run(LauncherImpl.java:837)
at com.sun.javafx.application.PlatformImpl$7.run(PlatformImpl.java:335)
at com.sun.javafx.application.PlatformImpl$6$1.run(PlatformImpl.java:301)
at com.sun.javafx.application.PlatformImpl$6$1.run(PlatformImpl.java:298)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl$6.run(PlatformImpl.java:298)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.access$300(WinApplication.java:39)
at com.sun.glass.ui.win.WinApplication$4$1.run(WinApplication.java:112)
at java.lang.Thread.run(Thread.java:744)
Caused by: java.lang.NullPointerException
at issuetrackinglite.IssueTrackingLiteController.configureTable(IssueTrackingLiteController.java:481)
at issuetrackinglite.IssueTrackingLiteController.initialize(IssueTrackingLiteController.java:119)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2548)
... 19 more
BUILD STOPPED (total time: 50 minutes 46 seconds)
What does it mean and how can I fix it?
the main class:
package issuetrackinglite;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
public class Main extends Application {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Application.launch(Main.class, (java.lang.String[])null);
}
#Override
public void start(Stage primaryStage) {
try {
System.out.println(" before ........!");
AnchorPane page = (AnchorPane) FXMLLoader.load(Main.class.getResource("/issuetrackinglite/IssueTrackingLite.fxml"));
System.out.println(" after .............!");
Scene scene = new Scene(page);
primaryStage.setScene(scene);
primaryStage.setTitle("Issue Tracking Lite Sample");
primaryStage.show();
} catch (Exception ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
}

my FXML file is in the same path as Main class.
the class Controller:
package issuetrackinglite;
public class IssueTrackingLiteController implements Initializable {
#FXML
Button newIssue;
#FXML
Button deleteIssue;
#FXML
Button saveIssue;
TableView<ObservableIssue> table;
#FXML
TableColumn<ObservableIssue, String> colName;
#FXML
TableColumn<ObservableIssue, IssueStatus> colStatus;
#FXML
TableColumn<ObservableIssue, String> colSynopsis;
#FXML
ListView<String> list;
#FXML
TextField synopsis;
private String displayedBugId; // the id of the bug displayed in the details section.
private String displayedBugProject; // the name of the project of the bug displayed in the detailed section.
#FXML
Label displayedIssueLabel; // the displayedIssueLabel will contain a concatenation of the
// the project name and the bug id.
#FXML
AnchorPane details;
#FXML
TextArea descriptionValue;
ObservableList<String> projectsView = FXCollections.observableArrayList();
TrackingService model = null;
private TextField statusValue = new TextField();
final ObservableList<ObservableIssue> tableContent = FXCollections.observableArrayList();
/**
* Initializes the controller class.
*/
#Override
public void initialize(URL url, ResourceBundle rsrcs) {
assert colName != null : "fx:id=\"colName\" was not injected: check your FXML file 'IssueTrackingLite.fxml'.";
assert colStatus != null : "fx:id=\"colStatus\" was not injected: check your FXML file 'IssueTrackingLite.fxml'.";
assert colSynopsis != null : "fx:id=\"colSynopsis\" was not injected: check your FXML file 'IssueTrackingLite.fxml'.";
assert deleteIssue != null : "fx:id=\"deleteIssue\" was not injected: check your FXML file 'IssueTrackingLite.fxml'.";
assert descriptionValue != null : "fx:id=\"descriptionValue\" was not injected: check your FXML file 'IssueTrackingLite.fxml'.";
assert details != null : "fx:id=\"details\" was not injected: check your FXML file 'IssueTrackingLite.fxml'.";
assert displayedIssueLabel != null : "fx:id=\"displayedIssueLabel\" was not injected: check your FXML file 'IssueTrackingLite.fxml'.";
assert newIssue != null : "fx:id=\"newIssue\" was not injected: check your FXML file 'IssueTrackingLite.fxml'.";
assert saveIssue != null : "fx:id=\"saveIssue\" was not injected: check your FXML file 'IssueTrackingLite.fxml'.";
assert synopsis != null : "fx:id=\"synopsis\" was not injected: check your FXML file 'IssueTrackingLite.fxml'.";
assert table != null : "fx:id=\"table\" was not injected: check your FXML file 'IssueTrackingLite.fxml'.";
assert list != null : "fx:id=\"list\" was not injected: check your FXML file 'IssueTrackingLite.fxml'.";
System.out.println(this.getClass().getSimpleName() + ".initialize");
configureButtons();
configureDetails();
configureTable();
connectToService();
if (list != null) {
list.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);
list.getSelectionModel().selectedItemProperty().addListener(projectItemSelected);
displayedProjectNames.addListener(projectNamesListener);
}
}
/**
* Called when the NewIssue button is fired.
*
* #param event the action event.
*/
#FXML
public void newIssueFired(ActionEvent event) {
final String selectedProject = getSelectedProject();
if (model != null && selectedProject != null) {
ObservableIssue issue = model.createIssueFor(selectedProject);
if (table != null) {
// Select the newly created issue.
table.getSelectionModel().clearSelection();
table.getSelectionModel().select(issue);
}
}
}
/**
* Called when the DeleteIssue button is fired.
*
* #param event the action event.
*/
#FXML
public void deleteIssueFired(ActionEvent event) {
final String selectedProject = getSelectedProject();
if (model != null && selectedProject != null && table != null) {
// We create a copy of the current selection: we can't delete
// issue while looping over the live selection, since
// deleting selected issues will modify the selection.
final List<?> selectedIssue = new ArrayList<Object>(table.getSelectionModel().getSelectedItems());
for (Object o : selectedIssue) {
if (o instanceof ObservableIssue) {
model.deleteIssue(((ObservableIssue) o).getId());
}
}
table.getSelectionModel().clearSelection();
}
}
/**
* Called when the SaveIssue button is fired.
*
* #param event the action event.
*/
#FXML
public void saveIssueFired(ActionEvent event) {
final ObservableIssue ref = getSelectedIssue();
final Issue edited = new DetailsData();
SaveState saveState = computeSaveState(edited, ref);
if (saveState == SaveState.UNSAVED) {
model.saveIssue(ref.getId(), edited.getStatus(),
edited.getSynopsis(), edited.getDescription());
}
// We refresh the content of the table because synopsis and/or description
// are likely to have been modified by the user.
int selectedRowIndex = table.getSelectionModel().getSelectedIndex();
table.getItems().clear();
displayedIssues = model.getIssueIds(getSelectedProject());
for (String id : displayedIssues) {
final ObservableIssue issue = model.getIssue(id);
table.getItems().add(issue);
}
table.getSelectionModel().select(selectedRowIndex);
updateSaveIssueButtonState();
}
private void configureButtons() {
if (newIssue != null) {
newIssue.setDisable(true);
}
if (saveIssue != null) {
saveIssue.setDisable(true);
}
if (deleteIssue != null) {
deleteIssue.setDisable(true);
}
}
// An observable list of project names obtained from the model.
// This is a live list, and we will react to its changes by removing
// and adding project names to/from our list widget.
private ObservableList<String> displayedProjectNames;
// The list of Issue IDs relevant to the selected project. Can be null
// if no project is selected. This list is obtained from the model.
// This is a live list, and we will react to its changes by removing
// and adding Issue objects to/from our table widget.
private ObservableList<String> displayedIssues;
// This listener will listen to changes in the displayedProjectNames list,
// and update our list widget in consequence.
private final ListChangeListener<String> projectNamesListener = new ListChangeListener<String>() {
#Override
public void onChanged(Change<? extends String> c) {
if (projectsView == null) {
return;
}
while (c.next()) {
if (c.wasAdded() || c.wasReplaced()) {
for (String p : c.getAddedSubList()) {
projectsView.add(p);
}
}
if (c.wasRemoved() || c.wasReplaced()) {
for (String p : c.getRemoved()) {
projectsView.remove(p);
}
}
}
FXCollections.sort(projectsView);
}
};
// This listener will listen to changes in the displayedIssues list,
// and update our table widget in consequence.
private final ListChangeListener<String> projectIssuesListener = new ListChangeListener<String>() {
#Override
public void onChanged(Change<? extends String> c) {
if (table == null) {
return;
}
while (c.next()) {
if (c.wasAdded() || c.wasReplaced()) {
for (String p : c.getAddedSubList()) {
table.getItems().add(model.getIssue(p));
}
}
if (c.wasRemoved() || c.wasReplaced()) {
for (String p : c.getRemoved()) {
ObservableIssue removed = null;
// Issue already removed:
// we can't use model.getIssue(issueId) to get it.
// we need to loop over the table content instead.
// Then we need to remove it - but outside of the for loop
// to avoid ConcurrentModificationExceptions.
for (ObservableIssue t : table.getItems()) {
if (t.getId().equals(p)) {
removed = t;
break;
}
}
if (removed != null) {
table.getItems().remove(removed);
}
}
}
}
}
};
// Connect to the model, get the project's names list, and listen to
// its changes. Initializes the list widget with retrieved project names.
private void connectToService() {
if (model == null) {
model = new TrackingServiceStub();
displayedProjectNames = model.getProjectNames();
}
projectsView.clear();
List<String> sortedProjects = new ArrayList<String>(displayedProjectNames);
Collections.sort(sortedProjects);
projectsView.addAll(sortedProjects);
list.setItems(projectsView);
}
// This listener listen to changes in the table widget selection and
// update the DeleteIssue button state accordingly.
private final ListChangeListener<ObservableIssue> tableSelectionChanged =
new ListChangeListener<ObservableIssue>() {
#Override
public void onChanged(Change<? extends ObservableIssue> c) {
updateDeleteIssueButtonState();
updateBugDetails();
updateSaveIssueButtonState();
}
};
private static String nonNull(String s) {
return s == null ? "" : s;
}
private void updateBugDetails() {
final ObservableIssue selectedIssue = getSelectedIssue();
if (details != null && selectedIssue != null) {
if (displayedIssueLabel != null) {
displayedBugId = selectedIssue.getId();
displayedBugProject = selectedIssue.getProjectName();
displayedIssueLabel.setText( displayedBugId + " / " + displayedBugProject );
}
if (synopsis != null) {
synopsis.setText(nonNull(selectedIssue.getSynopsis()));
}
if (statusValue != null) {
statusValue.setText(selectedIssue.getStatus().toString());
}
if (descriptionValue != null) {
descriptionValue.selectAll();
descriptionValue.cut();
descriptionValue.setText(selectedIssue.getDescription());
}
} else {
displayedIssueLabel.setText("");
displayedBugId = null;
displayedBugProject = null;
}
if (details != null) {
details.setVisible(selectedIssue != null);
}
}
private boolean isVoid(Object o) {
if (o instanceof String) {
return isEmpty((String) o);
} else {
return o == null;
}
}
private boolean isEmpty(String s) {
return s == null || s.trim().isEmpty();
}
private boolean equal(Object o1, Object o2) {
if (isVoid(o1)) {
return isVoid(o2);
}
return o1.equals(o2);
}
private static enum SaveState {
INVALID, UNSAVED, UNCHANGED
}
private final class DetailsData implements Issue {
#Override
public String getId() {
if (displayedBugId == null || isEmpty(displayedIssueLabel.getText())) {
return null;
}
return displayedBugId;
}
#Override
public IssueStatus getStatus() {
if (statusValue == null || isEmpty(statusValue.getText())) {
return null;
}
return IssueStatus.valueOf(statusValue.getText().trim());
}
#Override
public String getProjectName() {
if (displayedBugProject == null || isEmpty(displayedIssueLabel.getText())) {
return null;
}
return displayedBugProject;
}
#Override
public String getSynopsis() {
if (synopsis == null || isEmpty(synopsis.getText())) {
return "";
}
return synopsis.getText();
}
#Override
public String getDescription() {
if (descriptionValue == null || isEmpty(descriptionValue.getText())) {
return "";
}
return descriptionValue.getText();
}
}
private SaveState computeSaveState(Issue edited, Issue issue) {
try {
// These fields are not editable - so if they differ they are invalid
// and we cannot save.
if (!equal(edited.getId(), issue.getId())) {
return SaveState.INVALID;
}
if (!equal(edited.getProjectName(), issue.getProjectName())) {
return SaveState.INVALID;
}
// If these fields differ, the issue needs saving.
if (!equal(edited.getStatus(), issue.getStatus())) {
return SaveState.UNSAVED;
}
if (!equal(edited.getSynopsis(), issue.getSynopsis())) {
return SaveState.UNSAVED;
}
if (!equal(edited.getDescription(), issue.getDescription())) {
return SaveState.UNSAVED;
}
} catch (Exception x) {
// If there's an exception, some fields are invalid.
return SaveState.INVALID;
}
// No field is invalid, no field needs saving.
return SaveState.UNCHANGED;
}
private void updateDeleteIssueButtonState() {
boolean disable = true;
if (deleteIssue != null && table != null) {
final boolean nothingSelected = table.getSelectionModel().getSelectedItems().isEmpty();
disable = nothingSelected;
}
if (deleteIssue != null) {
deleteIssue.setDisable(disable);
}
}
private void updateSaveIssueButtonState() {
boolean disable = true;
if (saveIssue != null && table != null) {
final boolean nothingSelected = table.getSelectionModel().getSelectedItems().isEmpty();
disable = nothingSelected;
}
if (disable == false) {
disable = computeSaveState(new DetailsData(), getSelectedIssue()) != SaveState.UNSAVED;
}
if (saveIssue != null) {
saveIssue.setDisable(disable);
}
}
// Configure the table widget: set up its column, and register the
// selection changed listener.
private void configureTable() {
colName.setCellValueFactory(new PropertyValueFactory<ObservableIssue, String>("id"));
colSynopsis.setCellValueFactory(new PropertyValueFactory<ObservableIssue, String>("synopsis"));
colStatus.setCellValueFactory(new PropertyValueFactory<ObservableIssue, IssueStatus>("status"));
// In order to limit the amount of setup in Getting Started we set the width
// of the 3 columns programmatically but one can do it from SceneBuilder.
colName.setPrefWidth(75);
colStatus.setPrefWidth(75);
colSynopsis.setPrefWidth(443);
colName.setMinWidth(75);
colStatus.setMinWidth(75);
colSynopsis.setMinWidth(443);
colName.setMaxWidth(750);
colStatus.setMaxWidth(750);
colSynopsis.setMaxWidth(4430);
table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
table.setItems(tableContent);
assert table.getItems() == tableContent;
final ObservableList<ObservableIssue> tableSelection = table.getSelectionModel().getSelectedItems();
tableSelection.addListener(tableSelectionChanged);
}
/**
* Return the name of the project currently selected, or null if no project
* is currently selected.
*
*/
public String getSelectedProject() {
if (model != null && list != null) {
final ObservableList<String> selectedProjectItem = list.getSelectionModel().getSelectedItems();
final String selectedProject = selectedProjectItem.get(0);
return selectedProject;
}
return null;
}
public ObservableIssue getSelectedIssue() {
if (model != null && table != null) {
List<ObservableIssue> selectedIssues = table.getSelectionModel().getSelectedItems();
if (selectedIssues.size() == 1) {
final ObservableIssue selectedIssue = selectedIssues.get(0);
return selectedIssue;
}
}
return null;
}
/**
* Listen to changes in the list selection, and updates the table widget and
* DeleteIssue and NewIssue buttons accordingly.
*/
private final ChangeListener<String> projectItemSelected = new ChangeListener<String>() {
#Override
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
projectUnselected(oldValue);
projectSelected(newValue);
}
};
// Called when a project is unselected.
private void projectUnselected(String oldProjectName) {
if (oldProjectName != null) {
displayedIssues.removeListener(projectIssuesListener);
displayedIssues = null;
table.getSelectionModel().clearSelection();
table.getItems().clear();
if (newIssue != null) {
newIssue.setDisable(true);
}
if (deleteIssue != null) {
deleteIssue.setDisable(true);
}
}
}
// Called when a project is selected.
private void projectSelected(String newProjectName) {
if (newProjectName != null) {
table.getItems().clear();
displayedIssues = model.getIssueIds(newProjectName);
for (String id : displayedIssues) {
final ObservableIssue issue = model.getIssue(id);
table.getItems().add(issue);
}
displayedIssues.addListener(projectIssuesListener);
if (newIssue != null) {
newIssue.setDisable(false);
}
updateDeleteIssueButtonState();
updateSaveIssueButtonState();
}
}
private void configureDetails() {
if (details != null) {
details.setVisible(false);
}
if (details != null) {
details.addEventFilter(EventType.ROOT, new EventHandler<Event>() {
#Override
public void handle(Event event) {
if (event.getEventType() == MouseEvent.MOUSE_RELEASED
|| event.getEventType() == KeyEvent.KEY_RELEASED) {
updateSaveIssueButtonState();
}
}
});
}
}
}

Related

AutoCompleteTextField list does not always scroll to top?

The AutoCompleteTextField seems to work exactly as intended until I start backspacing in the TextField. I am not sure what the difference is, but if I type in something like "123 M" then I get values that start with "123 M". If I backspace and delete the M leaving "123 " in the field, the list changes, but it does not scroll to the top of the list.
I should note that everything works fine on the simulator and that I am experiencing this behavior when running a debug build on my iPhone.
EDIT: So this does not only seem to happen when backspacing. This image shows the results I have when typing in an address key by key. In any of the pictures where the list isn't viewable or is clipped, I am able to drag down on the list to get it to then display properly. I have not tried this on an Android device.
EDIT2:
public class CodenameOneTest {
private Form current;
private Resources theme;
private WaitingClass w;
private String[] properties = {"1 MAIN STREET", "123 E MAIN STREET", "12 EASTER ROAD", "24 MAIN STREET"};
public void init(Object context) {
theme = UIManager.initFirstTheme("/theme");
// Enable Toolbar on all Forms by default
Toolbar.setGlobalToolbar(true);
}
public void start() {
if(current != null) {
current.show();
return;
}
Form form = new Form("AutoCompleteTextField");
form.setLayout(new BorderLayout());
final DefaultListModel<String> options = new DefaultListModel<>();
AutoCompleteTextField ac = new AutoCompleteTextField(options) {
protected boolean filter(String text) {
if(text.length() == 0) {
options.removeAll();
return false;
}
String[] l = searchLocations(text);
if(l == null || l.length == 0) {
return false;
}
options.removeAll();
for(String s : l) {
options.addItem(s);
}
return true;
};
};
Container container = new Container(BoxLayout.y());
container.setScrollableY(true); // If you comment this out then the field works fine
container.add(ac);
form.addComponent(BorderLayout.CENTER, container);
form.show();
}
String[] searchLocations(String text) {
try {
if(text.length() > 0) {
if(w != null) {
w.actionPerformed(null);
}
w = new WaitingClass();
String[] properties = getProperties(text);
if(Display.getInstance().isEdt()) {
Display.getInstance().invokeAndBlock(w);
}
else {
w.run();
}
return properties;
}
}
catch(Exception e) {
Log.e(e);
}
return null;
}
private String[] getProperties(String text) {
List<String> returnList = new ArrayList<>();
List<String> propertyList = Arrays.asList(properties);
for(String property : propertyList) {
if(property.startsWith(text)) {
returnList.add(property);
}
}
w.actionPerformed(null);
return returnList.toArray(new String[returnList.size()]);
}
class WaitingClass implements Runnable, ActionListener<ActionEvent> {
private boolean finishedWaiting;
public void run() {
while(!finishedWaiting) {
try {
Thread.sleep(30);
}
catch(InterruptedException ex) {
ex.printStackTrace();
}
}
}
public void actionPerformed(ActionEvent e) {
finishedWaiting = true;
return;
}
}
public void stop() {
current = Display.getInstance().getCurrent();
if(current instanceof Dialog) {
((Dialog)current).dispose();
current = Display.getInstance().getCurrent();
}
}
public void destroy() {
}
}
I used this code on an iPhone 4s:
public void start() {
if(current != null){
current.show();
return;
}
Form hi = new Form("AutoComplete", new BorderLayout());
if(apiKey == null) {
hi.add(new SpanLabel("This demo requires a valid google API key to be set in the constant apiKey, "
+ "you can get this key for the webservice (not the native key) by following the instructions here: "
+ "https://developers.google.com/places/web-service/get-api-key"));
hi.getToolbar().addCommandToRightBar("Get Key", null, e -> Display.getInstance().execute("https://developers.google.com/places/web-service/get-api-key"));
hi.show();
return;
}
Container box = new Container(new BoxLayout(BoxLayout.Y_AXIS));
box.setScrollableY(true);
for(int iter = 0 ; iter < 30 ; iter++) {
box.add(createAutoComplete());
}
hi.add(BorderLayout.CENTER, box);
hi.show();
}
private AutoCompleteTextField createAutoComplete() {
final DefaultListModel<String> options = new DefaultListModel<>();
AutoCompleteTextField ac = new AutoCompleteTextField(options) {
#Override
protected boolean filter(String text) {
if(text.length() == 0) {
return false;
}
String[] l = searchLocations(text);
if(l == null || l.length == 0) {
return false;
}
options.removeAll();
for(String s : l) {
options.addItem(s);
}
return true;
}
};
ac.setMinimumElementsShownInPopup(5);
return ac;
}
String[] searchLocations(String text) {
try {
if(text.length() > 0) {
ConnectionRequest r = new ConnectionRequest();
r.setPost(false);
r.setUrl("https://maps.googleapis.com/maps/api/place/autocomplete/json");
r.addArgument("key", apiKey);
r.addArgument("input", text);
NetworkManager.getInstance().addToQueueAndWait(r);
Map<String,Object> result = new JSONParser().parseJSON(new InputStreamReader(new ByteArrayInputStream(r.getResponseData()), "UTF-8"));
String[] res = Result.fromContent(result).getAsStringArray("//description");
return res;
}
} catch(Exception err) {
Log.e(err);
}
return null;
}
I was able to create this issue but not the issue you describe.

GWT- In celltable column checkboxcell select all records i want select display record

Frineds,
I am using celltable and their is one column which I put in table header for select all record option and also I am using pager which showing max 15 record in one page. when I clicked on selectall option it will select all records which are present page no 2,3,4,.... in short all records get selected(if total records is 100 it's selected 100 records).so i want only select display page records not all...
ref code is -
final SelectionModel < GenericFirewallRule > selectionModel =
new MultiSelectionModel < GenericFirewallRule > ();
deleteRuleCellTable.setSelectionModel(selectionModel,DefaultSelectionEventManager. < GenericFirewallRule > createCheckboxManager());
// CheckboxCell cbForHeader = new CheckboxCell();
Column < GenericFirewallRule, Boolean > checkColumn = new Column < GenericFirewallRule, Boolean > (
new CheckboxCell()) {#Override
public Boolean getValue(GenericFirewallRule object) {
if(object == null || object.getRuleNumber() == null){
return null;
}else{
if (selectionModel.isSelected(object)) {
if (!ruleListForDelete.contains(object)) {
ruleListForDelete.add(object);
}
} else {
if (ruleListForDelete.contains(object)) {
ruleListForDelete.remove(object);
}
}
System.out.println("ruleListForDelete : " + ruleListForDelete);
return selectionModel.isSelected(object);
}
}
};
Please suggest me solutions....
You can do something like this:
selectAllHeader = new Header<Boolean>(new HeaderCheckbox()) {
#Override
public Boolean getValue() {
for (T item : getVisibleItems()) {
if (!getSelectionModel().isSelected(item)) {
return false;
}
}
return getVisibleItems().size() > 0;
}
};
selectAllHeader.setUpdater(new ValueUpdater<Boolean>() {
#Override
public void update(Boolean value) {
for (T object : getVisibleItems()) {
getSelectionModel().setSelected(object, value);
}
}
});
public class HeaderCheckbox extends CheckboxCell {
private final SafeHtml INPUT_CHECKED = SafeHtmlUtils.fromSafeConstant("<input type=\"checkbox\" tabindex=\"-1\" checked/>");
private final SafeHtml INPUT_UNCHECKED = SafeHtmlUtils.fromSafeConstant("<input type=\"checkbox\" tabindex=\"-1\"/>");
public HeaderCheckbox() {
}
#Override
public void render(Context context, Boolean value, SafeHtmlBuilder sb) {
if (value != null && value) {
sb.append(INPUT_CHECKED);
} else {
sb.append(INPUT_UNCHECKED);
}
}
}

How can we get the item on which i am doing the drop on a treeviewer

I have created a jface treeviewer and i am adding drag and drop of elements into the treeviewer.So the items should be added on the the subchild of a tree.How can i get the subchildname on which i am dropping a element.
for eg:
tree->
A->
1
2
B
C
so when I drag and drop on 1 it should get the selecteditem as 1 how can we do it.
the code for drop is as follows
int operationsn = DND.DROP_COPY | DND.DROP_MOVE;
Transfer[] transferType = new Transfer[]{TestTransfer.getInstance()};
DropTarget targetts = new DropTarget(treeComposite, operationsn);
targetts.setTransfer(new Transfer[] { TestTransfer.getInstance() });
targetts.addDropListener(new DropTargetListener() {
public void dragEnter(DropTargetEvent event) {
System.out.println("dragEnter in target ");
if (event.detail == DND.DROP_DEFAULT) {
if ((event.operations & DND.DROP_COPY) != 0) {
event.detail = DND.DROP_COPY;
} else {
event.detail = DND.DROP_NONE;
}
}
}
public void dragOver(DropTargetEvent event) {
System.out.println("dragOver in target ");
event.feedback = DND.FEEDBACK_SELECT | DND.FEEDBACK_SCROLL;
}
public void dragOperationChanged(DropTargetEvent event) {
System.out.println("dragOperationChanged in target ");
if (event.detail == DND.DROP_DEFAULT) {
if ((event.operations & DND.DROP_COPY) != 0) {
event.detail = DND.DROP_COPY;
} else {
event.detail = DND.DROP_NONE;
}
}
}
public void dragLeave(DropTargetEvent event) {
System.out.println("dragLeave in target ");
}
public void dropAccept(DropTargetEvent event) {
System.out.println("dropAccept in target ");
}
public void drop(DropTargetEvent event) {
//if (textTransfer.isSupportedType(event.currentDataType))
if (event.data != null) {
Test tsType = (Test) event.data;
addItem(tsType);
System.out.println("test step name is" +tsType);
}
}
});
Here in the addItem function I have written the code to add item to the treeviewer on the selecteditem.but while dropping the item I am not able to select the item so how can we selected the item while dropping the elements into the tree.
When using JFace Viewers you can use the JFace ViewDropAdapter class rather than DropTargetListener.
This class does more work for you and has a getCurrentTarget() method to return the current target element.
More details on this here

Condition in Pick/PickBranch activities

I have a following scenario that I am trying to define in workflow foundation:
My workflow gets to a stage from which it can continue in 3 paths, each path has some conditions that must be satisfied before the path is taken. After each path is finished, a termination condition is checked, and if not terminated, the workflow gets back to the decision stage where the 3 paths are allowed.
I wanted to solve this with Pick activity, set up a branch with a trigger for each one (triggered by Receive), but I don't know how to add the conditions there (PickBranches have no conditions on them, just triggers).
You can implement your Custom Pick Activity to add new conditions.
namespace System.Activities.Statements
{
using System.Activities.DynamicUpdate;
using System.Activities.Validation;
using System.Collections.ObjectModel;
using System.Runtime;
using System.Runtime.Collections;
using System.Runtime.Serialization;
using System.Windows.Markup;
[ContentProperty("Branches")]
public sealed class Pick : NativeActivity
{
const string pickStateProperty = "System.Activities.Statements.Pick.PickState";
Collection<PickBranch> branches;
Variable<PickState> pickStateVariable;
Collection<Activity> branchBodies;
public Pick()
{
this.pickStateVariable = new Variable<PickState>();
}
protected override bool CanInduceIdle
{
get
{
return true;
}
}
public Collection<PickBranch> Branches
{
get
{
if (this.branches == null)
{
this.branches = new ValidatingCollection<PickBranch>
{
// disallow null values
OnAddValidationCallback = item =>
{
if (item == null)
{
throw FxTrace.Exception.ArgumentNull("item");
}
}
};
}
return this.branches;
}
}
protected override void OnCreateDynamicUpdateMap(NativeActivityUpdateMapMetadata metadata, Activity originalActivity)
{
metadata.AllowUpdateInsideThisActivity();
}
protected override void UpdateInstance(NativeActivityUpdateContext updateContext)
{
PickState pickState = updateContext.GetValue(this.pickStateVariable);
Fx.Assert(pickState != null, "Pick's Execute must have run by now.");
if (updateContext.IsCancellationRequested || pickState.TriggerCompletionBookmark == null)
{
// do not schedule newly added Branches once a Trigger has successfully completed.
return;
}
CompletionCallback onBranchCompleteCallback = new CompletionCallback(OnBranchComplete);
foreach (PickBranchBody body in this.branchBodies)
{
if (updateContext.IsNewlyAdded(body))
{
updateContext.ScheduleActivity(body, onBranchCompleteCallback, null);
}
}
}
protected override void CacheMetadata(NativeActivityMetadata metadata)
{
if (this.branchBodies == null)
{
this.branchBodies = new Collection<Activity>();
}
else
{
this.branchBodies.Clear();
}
foreach (PickBranch branch in this.Branches)
{
if (branch.Trigger == null)
{
metadata.AddValidationError(new ValidationError(SR.PickBranchRequiresTrigger(branch.DisplayName), false, null, branch));
}
PickBranchBody pickBranchBody = new PickBranchBody
{
Action = branch.Action,
DisplayName = branch.DisplayName,
Trigger = branch.Trigger,
Variables = branch.Variables,
};
this.branchBodies.Add(pickBranchBody);
metadata.AddChild(pickBranchBody, origin: branch);
}
metadata.AddImplementationVariable(this.pickStateVariable);
}
protected override void Execute(NativeActivityContext context)
{
if (this.branchBodies.Count == 0)
{
return;
}
PickState pickState = new PickState();
this.pickStateVariable.Set(context, pickState);
pickState.TriggerCompletionBookmark = context.CreateBookmark(new BookmarkCallback(OnTriggerComplete));
context.Properties.Add(pickStateProperty, pickState);
CompletionCallback onBranchCompleteCallback = new CompletionCallback(OnBranchComplete);
//schedule every branch to only run trigger
for (int i = this.branchBodies.Count - 1; i >= 0; i--)
{
context.ScheduleActivity(this.branchBodies[i], onBranchCompleteCallback);
}
}
protected override void Cancel(NativeActivityContext context)
{
context.CancelChildren();
}
void OnBranchComplete(NativeActivityContext context, ActivityInstance completedInstance)
{
PickState pickState = this.pickStateVariable.Get(context);
ReadOnlyCollection<ActivityInstance> executingChildren = context.GetChildren();
switch (completedInstance.State)
{
case ActivityInstanceState.Closed:
pickState.HasBranchCompletedSuccessfully = true;
break;
case ActivityInstanceState.Canceled:
case ActivityInstanceState.Faulted:
if (context.IsCancellationRequested)
{
if (executingChildren.Count == 0 && !pickState.HasBranchCompletedSuccessfully)
{
// All of the branches are complete and we haven't had a single
// one complete successfully and we've been asked to cancel.
context.MarkCanceled();
context.RemoveAllBookmarks();
}
}
break;
}
//the last branch should always resume action bookmark if it's still there
if (executingChildren.Count == 1 && pickState.ExecuteActionBookmark != null)
{
ResumeExecutionActionBookmark(pickState, context);
}
}
void OnTriggerComplete(NativeActivityContext context, Bookmark bookmark, object state)
{
PickState pickState = this.pickStateVariable.Get(context);
string winningBranch = (string)state;
ReadOnlyCollection<ActivityInstance> children = context.GetChildren();
bool resumeAction = true;
for (int i = 0; i < children.Count; i++)
{
ActivityInstance child = children[i];
if (child.Id != winningBranch)
{
context.CancelChild(child);
resumeAction = false;
}
}
if (resumeAction)
{
ResumeExecutionActionBookmark(pickState, context);
}
}
void ResumeExecutionActionBookmark(PickState pickState, NativeActivityContext context)
{
Fx.Assert(pickState.ExecuteActionBookmark != null, "This should have been set by the branch.");
context.ResumeBookmark(pickState.ExecuteActionBookmark, null);
pickState.ExecuteActionBookmark = null;
}
[DataContract]
internal class PickState
{
[DataMember(EmitDefaultValue = false)]
public bool HasBranchCompletedSuccessfully
{
get;
set;
}
[DataMember(EmitDefaultValue = false)]
public Bookmark TriggerCompletionBookmark
{
get;
set;
}
[DataMember(EmitDefaultValue = false)]
public Bookmark ExecuteActionBookmark
{
get;
set;
}
}
class PickBranchBody : NativeActivity
{
public PickBranchBody()
{
}
protected override bool CanInduceIdle
{
get
{
return true;
}
}
public Collection<Variable> Variables
{
get;
set;
}
public Activity Trigger
{
get;
set;
}
public Activity Action
{
get;
set;
}
protected override void OnCreateDynamicUpdateMap(NativeActivityUpdateMapMetadata metadata, Activity originalActivity)
{
PickBranchBody originalBranchBody = (PickBranchBody)originalActivity;
if ((originalBranchBody.Action != null && metadata.GetMatch(this.Trigger) == originalBranchBody.Action) || (this.Action != null && metadata.GetMatch(this.Action) == originalBranchBody.Trigger))
{
metadata.DisallowUpdateInsideThisActivity(SR.PickBranchTriggerActionSwapped);
return;
}
metadata.AllowUpdateInsideThisActivity();
}
protected override void CacheMetadata(NativeActivityMetadata metadata)
{
Collection<Activity> children = null;
if (this.Trigger != null)
{
ActivityUtilities.Add(ref children, this.Trigger);
}
if (this.Action != null)
{
ActivityUtilities.Add(ref children, this.Action);
}
metadata.SetChildrenCollection(children);
metadata.SetVariablesCollection(this.Variables);
}
protected override void Execute(NativeActivityContext context)
{
Fx.Assert(this.Trigger != null, "We validate that the trigger is not null in Pick.CacheMetadata");
context.ScheduleActivity(this.Trigger, new CompletionCallback(OnTriggerCompleted));
}
void OnTriggerCompleted(NativeActivityContext context, ActivityInstance completedInstance)
{
PickState pickState = (PickState)context.Properties.Find(pickStateProperty);
if (completedInstance.State == ActivityInstanceState.Closed && pickState.TriggerCompletionBookmark != null)
{
// We're the first trigger! We win!
context.ResumeBookmark(pickState.TriggerCompletionBookmark, context.ActivityInstanceId);
pickState.TriggerCompletionBookmark = null;
pickState.ExecuteActionBookmark = context.CreateBookmark(new BookmarkCallback(OnExecuteAction));
}
else if (!context.IsCancellationRequested)
{
// We didn't win, but we haven't been requested to cancel yet.
// We'll just create a bookmark to keep ourselves from completing.
context.CreateBookmark();
}
// else
// {
// No need for an else since default cancelation will cover it!
// }
}
void OnExecuteAction(NativeActivityContext context, Bookmark bookmark, object state)
{
if (this.Action != null)
{
context.ScheduleActivity(this.Action);
}
}
}
}
}

PropertyGrid Browsable not found for entity framework created property, how to find it?

Trying to remove or place items on a property grid by changing the Browsable attribute.
But unless browsable is set on object creation my code to change Browsable doesn't work. Now I can manually add browsable, but when I make a change to my entity (still developing project so lots of changes to entity) any additional attributes I add go away.
I attempted to set [Browsable(true)] two ways other ways: http://ardalis.com/adding-attributes-to-generated-classes and http://social.msdn.microsoft.com/Forums/en-US/adodotnetentityframework/thread/617ebfca-0f68-4b90-83fd-0da758fadbd0/
Both seem to actually set the Browsable correctly, but when I loop thru the Attributes in Property Descriptor it is not there (for me to change).
String fieldname = "browsable"; // I also edit "description"
PropertyDescriptor pd = TypeDescriptor.GetProperties(o.GetType())[propertyName];
object attrib = null;
AttributeCollection attribs = pd.Attributes;
foreach (Attribute a in attribs)
{
if (a.GetType() == attributeType)
{
attrib = a;
break;
}
}
// The microsoft documentation leads one to believe the following line of code would find the desired attribute,
// negating the need for the more complete foreach statement above.
// However, it appears to find attribute even when it does not exist. Setting value for "found" attribute
// will result in random memory being changed, which results in very unpredictable behavior.
// attrib = pd.Attributes[t];
if (attrib != null)
{
// locate field that contains value
FieldInfo field = attrib.GetType().GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Instance);
if (field != null)
{
if (field.FieldType == value.GetType())
{
// set field to desired value
field.SetValue(attrib, value);
}
}
}
else
{
throw new Exception("Attribute (" + attributeType.Name + ") does not exist for Property(" + propertyName + ")");
}
So I keep getting the Exception that I throw if it doesn't find "browsable" - but only if not set in Model.Designer.cs first.
Below is what my Model.Designer.cs looks like.
/// <summary>
/// No Metadata Documentation available.
/// </summary>
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)]
[DataMemberAttribute()]
[Browsable(false)] // this works, but goes away if change my entity
public Nullable<global::System.TimeSpan> SignoutAfter
{
get
{
return _SignoutAfter;
}
set
{
OnSignoutAfterChanging(value);
ReportPropertyChanging("SignoutAfter");
_SignoutAfter = StructuralObject.SetValidValue(value);
ReportPropertyChanged("SignoutAfter");
OnSignoutAfterChanged();
}
}
private Nullable<global::System.TimeSpan> _SignoutAfter;
partial void OnSignoutAfterChanging(Nullable<global::System.TimeSpan> value);
partial void OnSignoutAfterChanged();
So I need a way to either 1. add browsable to entity when I edit them so it is always on perhaps editing the t4, but I don't even know where to begin with that or 2. Another way to add or remove (and edit) the properties (see I might edit the description based on some logic) or 3 find the hole in my code so I can find and edit browsable (description and displayname).
Update The second link above, http://social.msdn.microsoft.com/Forums/en-US/adodotnetentityframework/thread/617ebfca-0f68-4b90-83fd-0da758fadbd0/ , has a lot of what I need, I think. Adding a Attribute array variable to the class and some code to see if that is set seems to have the effect that I am looking for. But leaving this open to find a better answer.
partial class Client : ICustomTypeDescriptor
{
public Attribute[] SignOutAttributes; // added this
#region ICustomTypeDescriptor Members
... // see the link for the other code
public PropertyDescriptorCollection GetProperties (Attribute[] attributes)
{
var propsColl = TypeDescriptor.GetProperties (this, attributes, true);
var props = new List<PropertyDescriptor> ();
foreach (PropertyDescriptor prop in propsColl)
{
String strUPPERCaseName = prop.Name.ToUpper (); // for my thick fingers
// make sure case values are upper case
switch (strUPPERCaseName)
{
case "SIGNOUTAFTER":
if (SignOutAttributes != null)
{
props.Add(new CustomPropertyDescriptor(prop, SignOutAttributes));
}
else
{
props.Add (new CustomPropertyDescriptor (prop, new Attribute[]
{
new CategoryAttribute("Settings"),
new DisplayNameAttribute("Signout After"),
new BrowsableAttribute(true),
new ReadOnlyAttribute(false)
}));
}
break;
default:
props.Add (prop);
break;
}
}
return new PropertyDescriptorCollection (props.ToArray ());
}
In my code I can change the Attribute Array to have what Attribute values I want.
_client.SignOutAttributes = new Attribute[]
{
new CategoryAttribute ("My Category"),
new DisplayNameAttribute("Signout After"),
new BrowsableAttribute(true),
new ReadOnlyAttribute(false)
};
I'm not 100% happy with this. I have to write code for each Property.
Using ICustomTypeDescriptor is definitely the good solution when you want dynamic (set at runtime) properties. Here is generic ICustomTypeDescriptor utility class that I've been using for this sort of property grid hacking, it's pretty straightforward to use:
public sealed class DynamicTypeDescriptor: ICustomTypeDescriptor, INotifyPropertyChanged
{
private Type _type;
private AttributeCollection _attributes;
private TypeConverter _typeConverter;
private Dictionary<Type, object> _editors;
private EventDescriptor _defaultEvent;
private PropertyDescriptor _defaultProperty;
private EventDescriptorCollection _events;
public event PropertyChangedEventHandler PropertyChanged;
private DynamicTypeDescriptor()
{
}
public DynamicTypeDescriptor(Type type)
{
if (type == null)
throw new ArgumentNullException("type");
_type = type;
_typeConverter = TypeDescriptor.GetConverter(type);
_defaultEvent = TypeDescriptor.GetDefaultEvent(type);
_defaultProperty = TypeDescriptor.GetDefaultProperty(type);
_events = TypeDescriptor.GetEvents(type);
List<PropertyDescriptor> normalProperties = new List<PropertyDescriptor>();
OriginalProperties = TypeDescriptor.GetProperties(type);
foreach (PropertyDescriptor property in OriginalProperties)
{
if (!property.IsBrowsable)
continue;
normalProperties.Add(property);
}
Properties = new PropertyDescriptorCollection(normalProperties.ToArray());
_attributes = TypeDescriptor.GetAttributes(type);
_editors = new Dictionary<Type, object>();
object editor = TypeDescriptor.GetEditor(type, typeof(UITypeEditor));
if (editor != null)
{
_editors.Add(typeof(UITypeEditor), editor);
}
editor = TypeDescriptor.GetEditor(type, typeof(ComponentEditor));
if (editor != null)
{
_editors.Add(typeof(ComponentEditor), editor);
}
editor = TypeDescriptor.GetEditor(type, typeof(InstanceCreationEditor));
if (editor != null)
{
_editors.Add(typeof(InstanceCreationEditor), editor);
}
}
public T GetPropertyValue<T>(string name, T defaultValue)
{
if (name == null)
throw new ArgumentNullException("name");
foreach (PropertyDescriptor pd in Properties)
{
if (pd.Name == name)
{
try
{
return (T)Convert.ChangeType(pd.GetValue(Component), typeof(T));
}
catch
{
return defaultValue;
}
}
}
return defaultValue;
}
public void SetPropertyValue(string name, object value)
{
if (name == null)
throw new ArgumentNullException("name");
foreach (PropertyDescriptor pd in Properties)
{
if (pd.Name == name)
{
pd.SetValue(Component, value);
break;
}
}
}
internal void OnValueChanged(PropertyDescriptor prop)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(prop.Name));
}
}
internal static T GetAttribute<T>(AttributeCollection attributes) where T : Attribute
{
if (attributes == null)
return null;
foreach (Attribute att in attributes)
{
if (typeof(T).IsAssignableFrom(att.GetType()))
return (T)att;
}
return null;
}
public sealed class DynamicProperty: PropertyDescriptor, INotifyPropertyChanged
{
private readonly Type _type;
private readonly bool _hasDefaultValue;
private readonly object _defaultValue;
private readonly PropertyDescriptor _existing;
private readonly DynamicTypeDescriptor _descriptor;
private Dictionary<Type, object> _editors;
private bool? _readOnly;
private bool? _browsable;
private string _displayName;
private string _description;
private string _category;
private List<Attribute> _attributes = new List<Attribute>();
public event PropertyChangedEventHandler PropertyChanged;
internal DynamicProperty(DynamicTypeDescriptor descriptor, Type type, object value, string name, Attribute[] attrs)
: base(name, attrs)
{
_descriptor = descriptor;
_type = type;
Value = value;
DefaultValueAttribute def = DynamicTypeDescriptor.GetAttribute<DefaultValueAttribute>(Attributes);
if (def == null)
{
_hasDefaultValue = false;
}
else
{
_hasDefaultValue = true;
_defaultValue = def.Value;
}
if (attrs != null)
{
foreach (Attribute att in attrs)
{
_attributes.Add(att);
}
}
}
internal static Attribute[] GetAttributes(PropertyDescriptor existing)
{
List<Attribute> atts = new List<Attribute>();
foreach (Attribute a in existing.Attributes)
{
atts.Add(a);
}
return atts.ToArray();
}
internal DynamicProperty(DynamicTypeDescriptor descriptor, PropertyDescriptor existing, object component)
: this(descriptor, existing.PropertyType, existing.GetValue(component), existing.Name, GetAttributes(existing))
{
_existing = existing;
}
public void RemoveAttributesOfType<T>() where T : Attribute
{
List<Attribute> remove = new List<Attribute>();
foreach (Attribute att in _attributes)
{
if (typeof(T).IsAssignableFrom(att.GetType()))
{
remove.Add(att);
}
}
foreach (Attribute att in remove)
{
_attributes.Remove(att);
}
}
public IList<Attribute> AttributesList
{
get
{
return _attributes;
}
}
public override AttributeCollection Attributes
{
get
{
return new AttributeCollection(_attributes.ToArray());
}
}
public object Value { get; set; }
public override bool CanResetValue(object component)
{
if (_existing != null)
return _existing.CanResetValue(component);
return _hasDefaultValue;
}
public override Type ComponentType
{
get
{
if (_existing != null)
return _existing.ComponentType;
return typeof(object);
}
}
public override object GetValue(object component)
{
if (_existing != null)
return _existing.GetValue(component);
return Value;
}
public override string Category
{
get
{
if (_category != null)
return _category;
return base.Category;
}
}
public void SetCategory(string category)
{
_category = category;
}
public override string Description
{
get
{
if (_description != null)
return _description;
return base.Description;
}
}
public void SetDescription(string description)
{
_description = description;
}
public override string DisplayName
{
get
{
if (_displayName != null)
return _displayName;
if (_existing != null)
return _existing.DisplayName;
return base.DisplayName;
}
}
public void SetDisplayName(string displayName)
{
_displayName = displayName;
}
public override bool IsBrowsable
{
get
{
if (_browsable.HasValue)
return _browsable.Value;
return base.IsBrowsable;
}
}
public void SetBrowsable(bool browsable)
{
_browsable = browsable;
}
public override bool IsReadOnly
{
get
{
if (_readOnly.HasValue)
return _readOnly.Value;
if (_existing != null)
return _existing.IsReadOnly;
ReadOnlyAttribute att = DynamicTypeDescriptor.GetAttribute<ReadOnlyAttribute>(Attributes);
if (att == null)
return false;
return att.IsReadOnly;
}
}
public void SetIsReadOnly(bool readOnly)
{
_readOnly = readOnly;
}
public override Type PropertyType
{
get
{
if (_existing != null)
return _existing.PropertyType;
return _type;
}
}
public override void ResetValue(object component)
{
if (_existing != null)
{
_existing.ResetValue(component);
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(Name));
}
_descriptor.OnValueChanged(this);
return;
}
if (CanResetValue(component))
{
Value = _defaultValue;
_descriptor.OnValueChanged(this);
}
}
public override void SetValue(object component, object value)
{
if (_existing != null)
{
_existing.SetValue(component, value);
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(Name));
}
_descriptor.OnValueChanged(this);
return;
}
Value = value;
_descriptor.OnValueChanged(this);
}
public override bool ShouldSerializeValue(object component)
{
if (_existing != null)
return _existing.ShouldSerializeValue(component);
return false;
}
public override object GetEditor(Type editorBaseType)
{
if (editorBaseType == null)
throw new ArgumentNullException("editorBaseType");
if (_editors != null)
{
object type;
if ((_editors.TryGetValue(editorBaseType, out type)) && (type != null))
return type;
}
return base.GetEditor(editorBaseType);
}
public void SetEditor(Type editorBaseType, object obj)
{
if (editorBaseType == null)
throw new ArgumentNullException("editorBaseType");
if (_editors == null)
{
if (obj == null)
return;
_editors = new Dictionary<Type, object>();
}
if (obj == null)
{
_editors.Remove(editorBaseType);
}
else
{
_editors[editorBaseType] = obj;
}
}
}
public PropertyDescriptor AddProperty(Type type, string name, object value, string displayName, string description, string category, bool hasDefaultValue, object defaultValue, bool readOnly)
{
return AddProperty(type, name, value, displayName, description, category, hasDefaultValue, defaultValue, readOnly, null);
}
public PropertyDescriptor AddProperty(
Type type,
string name,
object value,
string displayName,
string description,
string category,
bool hasDefaultValue,
object defaultValue,
bool readOnly,
Type uiTypeEditor)
{
if (type == null)
throw new ArgumentNullException("type");
if (name == null)
throw new ArgumentNullException("name");
List<Attribute> atts = new List<Attribute>();
if (!string.IsNullOrEmpty(displayName))
{
atts.Add(new DisplayNameAttribute(displayName));
}
if (!string.IsNullOrEmpty(description))
{
atts.Add(new DescriptionAttribute(description));
}
if (!string.IsNullOrEmpty(category))
{
atts.Add(new CategoryAttribute(category));
}
if (hasDefaultValue)
{
atts.Add(new DefaultValueAttribute(defaultValue));
}
if (uiTypeEditor != null)
{
atts.Add(new EditorAttribute(uiTypeEditor, typeof(UITypeEditor)));
}
if (readOnly)
{
atts.Add(new ReadOnlyAttribute(true));
}
DynamicProperty property = new DynamicProperty(this, type, value, name, atts.ToArray());
AddProperty(property);
return property;
}
public void RemoveProperty(string name)
{
if (name == null)
throw new ArgumentNullException("name");
List<PropertyDescriptor> remove = new List<PropertyDescriptor>();
foreach (PropertyDescriptor pd in Properties)
{
if (pd.Name == name)
{
remove.Add(pd);
}
}
foreach (PropertyDescriptor pd in remove)
{
Properties.Remove(pd);
}
}
public void AddProperty(PropertyDescriptor property)
{
if (property == null)
throw new ArgumentNullException("property");
Properties.Add(property);
}
public override string ToString()
{
return base.ToString() + " (" + Component + ")";
}
public PropertyDescriptorCollection OriginalProperties { get; private set; }
public PropertyDescriptorCollection Properties { get; private set; }
public DynamicTypeDescriptor FromComponent(object component)
{
if (component == null)
throw new ArgumentNullException("component");
if (!_type.IsAssignableFrom(component.GetType()))
throw new ArgumentException(null, "component");
DynamicTypeDescriptor desc = new DynamicTypeDescriptor();
desc._type = _type;
desc.Component = component;
// shallow copy on purpose
desc._typeConverter = _typeConverter;
desc._editors = _editors;
desc._defaultEvent = _defaultEvent;
desc._defaultProperty = _defaultProperty;
desc._attributes = _attributes;
desc._events = _events;
desc.OriginalProperties = OriginalProperties;
// track values
List<PropertyDescriptor> properties = new List<PropertyDescriptor>();
foreach (PropertyDescriptor pd in Properties)
{
DynamicProperty ap = new DynamicProperty(desc, pd, component);
properties.Add(ap);
}
desc.Properties = new PropertyDescriptorCollection(properties.ToArray());
return desc;
}
public object Component { get; private set; }
public string ClassName { get; set; }
public string ComponentName { get; set; }
AttributeCollection ICustomTypeDescriptor.GetAttributes()
{
return _attributes;
}
string ICustomTypeDescriptor.GetClassName()
{
if (ClassName != null)
return ClassName;
if (Component != null)
return Component.GetType().Name;
if (_type != null)
return _type.Name;
return null;
}
string ICustomTypeDescriptor.GetComponentName()
{
if (ComponentName != null)
return ComponentName;
return Component != null ? Component.ToString() : null;
}
TypeConverter ICustomTypeDescriptor.GetConverter()
{
return _typeConverter;
}
EventDescriptor ICustomTypeDescriptor.GetDefaultEvent()
{
return _defaultEvent;
}
PropertyDescriptor ICustomTypeDescriptor.GetDefaultProperty()
{
return _defaultProperty;
}
object ICustomTypeDescriptor.GetEditor(Type editorBaseType)
{
object editor;
if (_editors.TryGetValue(editorBaseType, out editor))
return editor;
return null;
}
EventDescriptorCollection ICustomTypeDescriptor.GetEvents(Attribute[] attributes)
{
return _events;
}
EventDescriptorCollection ICustomTypeDescriptor.GetEvents()
{
return _events;
}
PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[] attributes)
{
return Properties;
}
PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties()
{
return Properties;
}
object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd)
{
return Component;
}
}