Getting exception during unbind of key - eclipse-plugin

In my perspective plugin, I have written some code to unbind F2 key. But activating bindingManager or saving the active binding throws this exception:
Cannot get the parent identifier from an undefined scheme. org.eclipse.ui.defaultAcceleratorConfiguration
My code:
ContextManager contextManager = new ContextManager();
BindingManager bindingManager = new BindingManager(contextManager,
commandManager);
IBindingService bindingService = (IBindingService) PlatformUI.
getWorkbench().getAdapter(IBindingService.class);
Binding[] bindings = bindingService.getBindings();
for (Binding binding : bindings) {
if(binding.getTriggerSequence().format().equals("F2"))
{
KeyBinding keyBinding = (KeyBinding) binding;
String contextId = binding.getContextId();
String schemeId = binding.getSchemeId();
KeySequence triggerSequence = keyBinding.getKeySequence();
ParameterizedCommand parameterizedCommand = binding
.getParameterizedCommand();
Command command = parameterizedCommand.getCommand();
KeyBinding deleteBinding = new KeyBinding(triggerSequence,
null, schemeId, contextId, null, null, null,
Binding.USER);
bindingManager.addBinding(deleteBinding);
}
}
try {
bindingManager
.setActiveScheme(bindingService.getActiveScheme());
} catch (final NotDefinedException e) {
throw new Error(
"Error"); //$NON-NLS-1$
}
try {
bindingService.savePreferences(
bindingManager .getActiveScheme(), bindingManager
.getBindings());
} catch (IOException e) {
e.printStackTrace();
}

Related

How can I change the title of the welcomepage programatically?

The code below is not working. (no exceptions thrown). Totally clueless why is not changed When I check in the GUI, there is a new version, with no changes!
public static void SetEntityWebName(ProcessEntity entity, SPWeb entityWeb)
{
try
{
entityWeb.AllowUnsafeUpdates = true;
var welcomePageListItem = entityWeb.GetFile(entityWeb.RootFolder.WelcomePage).Item;
var welcomePage = entityWeb.GetFile(entityWeb.RootFolder.WelcomePage);
welcomePage.CheckOut();
if (entity.Type == Entity.Job)
{
entityWeb.Title = ((SyncJobs_Result)entity.Entity).JobName;
welcomePageListItem["Title"] = ((SyncJobs_Result)entity.Entity).JobName;
welcomePage.Update();
}
if (entity.Type == Entity.Client)
{
entityWeb.Title = ((SyncClients_Result)entity.Entity).ClientName;
welcomePageListItem["Title"] = ((SyncClients_Result)entity.Entity).ClientName;
welcomePage.Update();
}
if (entity.Type == Entity.Opportunity)
{
entityWeb.Title = ((SyncOpportunities_Result)entity.Entity).OpportunityName;
welcomePageListItem["Title"] = ((SyncOpportunities_Result)entity.Entity).OpportunityName;
welcomePage.Update();
}
welcomePage.CheckIn(string.Empty);
welcomePage.Publish(string.Empty);
entityWeb.Update();
}
catch (Exception ex)
{
}
}
I think you also have to update the welcomePageListItem list item .
I am not sure but , give it a try

Null reference exception during selection of comboboxes

Let me explain my case. I have wpf user control in which I dynamically generate comboboxes. For this purposes I use class Control Service from which I create the comboboxes with their comboboxitems and also manage selection change event for each of them.
Everthing work great until I try to raise up second event on first combobox. There is coming problem when I try to clear items of the second combobox. I did debubugg and there is not problem with reference of combobox which I have already checked (childCmB != null), but after to try clear items of this combobox. the exception is thrown.
I try find many cases on forums but with any success, so I would appreciate any suggestion to resolve this problem.
Thank you
ControlService.class:
static class ControlService
{
private static ObservableDictionary<String, System.Windows.UIElement> controls = new ObservableDictionary<String, System.Windows.UIElement>();
private static Grid expanderContent;
public static Expander createExpander(String header, String name, String code)
{
header = manageControlName(header);
ExpanderModelView expanderModelView = new ExpanderModelView(name);
//Recieve template grid
expanderContent = expanderModelView.getExpanderContent();
//Add in static collection
Expander expander = new Expander() { Header = header };
//Code of provider service
expander.Uid = code;
expander.Name = name;
//Set up handler
expanderContent.AddHandler(System.Windows.Controls.ComboBox.SelectionChangedEvent, new SelectionChangedEventHandler(cmb_SelectionChanged));
//Insert data
expander.Content = expanderContent;
controls.Add(header, expander);
return expander;
}
public static void cleanUIElementCollection()
{
controls.Clear();
}
private static string manageControlName(string name)
{
int counter = 1;
if (controls.Count != 0)
{
foreach (String value in controls.Keys)
{
if (value.Equals(name))
{
if (name.Any(char.IsDigit))
name = name.Substring(0, name.IndexOf("("));
name = String.Format(name + "({0})", counter);
counter++;
}
}
}
return name;
}
private static void cmb_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Grid currentContent = sender as Grid;
String selectedItemId = ((e.Source as System.Windows.Controls.ComboBox).SelectedItem as ComboBoxItem).Uid;
IEnumerable<Parameter> childCmBs = DataService.getServiceParametersByParentId((e.Source as System.Windows.Controls.ComboBox).Uid);
if (childCmBs.Any())
{
foreach (Parameter param in childCmBs)
{
try
{
System.Windows.Controls.ComboBox childCmB = currentContent.FindName(param.Key) as System.Windows.Controls.ComboBox;
if (childCmB != null)
{
childCmB.Items.Clear();
addComboBoxItems(DataService.getChildrenParameterValuesByParentId(selectedItemId), childCmB);
}
}
catch (Exception ex)
{
System.Windows.MessageBox.Show(String.Format("Happen some problem during creating comboboxes: {0}", ex.Message));
}
}
}
}
public static void createComboBoxes(IEnumerable<Parameter> parameters, System.Windows.Controls.Panel panel)
{
foreach (Parameter parameter in parameters)
{
TextBlock cmbLabel = new TextBlock() { Text = parameter.Caption };
System.Windows.Controls.ComboBox cmb = new System.Windows.Controls.ComboBox() { Name = parameter.Key, Uid = parameter.ID };
panel.Children.Add(cmbLabel);
panel.Children.Add(cmb);
addComboBoxItems(parameter.ParameterValue, cmb);
}
}
public static void addComboBoxItems(IEnumerable<ParameterValue> parameterValues, System.Windows.Controls.ComboBox cmb)
{
foreach (ParameterValue value in parameterValues)
{
ComboBoxItem item = new ComboBoxItem()
{
Content = value.Caption,
Uid = value.ID,
Name = value.Key
};
cmb.Items.Add(item);
}
}
}
I am not sure but I think the problem is this line :
String selectedItemId = ((e.Source as System.Windows.Controls.ComboBox).SelectedItem as ComboBoxItem).Uid;
When you clear items of the combobox,
e.Source as System.Windows.Controls.ComboBox).SelectedItem as ComboBoxItem) is null.
so, when you try to get Uid of a null item, it throws an exception.
There is no SelectedItem when you clear the ComboBox.
Nevertheless you should always check that a reference is valid before you try to use it. So your method should be implemented something like this:
private static void cmb_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Grid currentContent = sender as Grid;
if (currentContent != null)
{
ComboBox comboBox = e.Source as ComboBox;
if (comboBox != null)
{
ComboBoxItem selectedItem = comboBox.SelectedItem as ComboBoxItem;
if (selectedItem != null)
{
String selectedItemId = selectedItem.Uid;
IEnumerable<Parameter> childCmBs = DataService.getServiceParametersByParentId(selectedItemId);
if (childCmBs != null && childCmBs.Any())
{
foreach (Parameter param in childCmBs)
{
try
{
System.Windows.Controls.ComboBox childCmB = currentContent.FindName(param.Key) as System.Windows.Controls.ComboBox;
if (childCmB != null)
{
childCmB.Items.Clear();
addComboBoxItems(DataService.getChildrenParameterValuesByParentId(selectedItemId), childCmB);
}
}
catch (Exception ex)
{
System.Windows.MessageBox.Show(String.Format("Happen some problem during creating comboboxes: {0}", ex.Message));
}
}
}
}
}
}
}

Entity Framework is not saving data

I am trying to save data to SQL Server from Entity Framework; this normally works and I don't know what I doing wrong here it's not throwing an error at all.
try
{
tblPortalCustomerInfo _custInfo = new tblPortalCustomerInfo();
_custInfo = _da.GetCustById(new Guid("397E4A4B-CD89-43DC-9E70-C19FC27EE6E4"));
_custInfo.addressLine1 = tbaddress1.Text;
_custInfo.addressLine2 = tbaddress2.Text;
_custInfo.town = tbtown.Text;
_custInfo.county = "test";
_custInfo.postcode = tbpostCode.Text;
_custInfo.email = tbEmail.Text;
_custInfo.phone = tbDayPhone.Text;
if(_custInfo.EntityState == System.Data.EntityState.Detached)
{
_da.portalEntities.tblPortalCustomerInfoes.AddObject(_custInfo);
}
_da.SaveChanges();
}
catch (Exception ex)
{
throw;
}
I have step through the code and no error is produced and it is getting attached ok here is my GetCustById function
// <returns></returns>
public tblPortalCustomerInfo GetCustById(Guid id)
{
try
{
tblPortalCustomerInfo _customerInfo;
_customerInfo = (from _custInfo in _dal.portalEntities.tblPortalCustomerInfoes
where _custInfo.id == id
select _custInfo).FirstOrDefault();
//If the empNotes entity is null create a new one and attach it to the context.
if (_customerInfo == null)
{
_customerInfo = new tblPortalCustomerInfo();
_dal.portalEntities.tblPortalCustomerInfoes.AddObject(_customerInfo);
}
return _customerInfo;
}
catch (Exception ex)
{
string inner = string.Empty;
if (ex.InnerException != null)
{
inner = ex.InnerException.ToString();
}
return null;
}
}
My portal entities is just off my context base
public portalEntities1 _portalEntities;
public portalEntities1 portalEntities
{
get
{
if (_portalEntities == null)
{
try
{
_portalEntities = new portalEntities1();
}
catch (Exception ex)
{
}
}
return _portalEntities;
}
}
Before you say am I doing a postback check yes I am here on my page load
protected void Page_Load(object sender, EventArgs e)
{
/****** Script for SelectTopNRows command from SSMS ******/
/****** Script for SelectTopNRows command from SSMS ******/
tblPortalCustomerInfo _myCustomerInfo = _da.GetCustById(new Guid("397E4A4B-CD89-43DC-9E70-C19FC27EE6E4"));
if (!IsPostBack)
{
tbaddress1.Text = _myCustomerInfo.addressLine1;
tbaddress2.Text = _myCustomerInfo.addressLine2;
tbtown.Text = _myCustomerInfo.town;
tbpostCode.Text = _myCustomerInfo.postcode;
tbMobile.Text = _myCustomerInfo.mobile;
tbEmail.Text = _myCustomerInfo.email;
tbLandLine.Text = _myCustomerInfo.phone;
}
}
My portal entities property which is in my context base
public portalEntities1 _portalEntities;
public portalEntities1 portalEntities
{
get
{
if (_portalEntities == null)
{
try
{
_portalEntities = new portalEntities1();
}
catch (Exception ex)
{
}
}
return _portalEntities;
}
}
I get no error the information is just not saved to the db some reason anyone got any ideas
Note 1
Ok so I am using ef5 is this the right method to change a object state it seemed logical to me
protected void btnSave_Click(object sender, EventArgs e)
{
try
{
tblPortalCustomerInfo _custInfo = new tblPortalCustomerInfo();
_custInfo = _da.GetCustById(new Guid("397E4A4B-CD89-43DC-9E70-C19FC27EE6E4"));
_custInfo.addressLine1 = tbaddress1.Text;
_custInfo.addressLine2 = tbaddress2.Text;
_custInfo.town = tbtown.Text;
_custInfo.county = "test";
_custInfo.postcode = tbpostCode.Text;
_custInfo.email = tbEmail.Text;
_custInfo.phone = tbDayPhone.Text;
_da.portalEntities.ObjectStateManager.ChangeObjectState(_custInfo, System.Data.EntityState.Modified); ----> is this correct for ef5
_da.SaveChanges();
}
}
When I try the above method I am presented with
Exception thrown: 'System.InvalidOperationException' in System.Data.Entity.dll Additional information: The ObjectStateManager does not contain an ObjectStateEntry with a reference to an object of type 'portalef.tblPortalCustomerInfo'.
Inside the function called GetCustById you search for a customer with a specific id and if the customer doesn't exist you create it and then return it to the calling code.Either way the customer already exists in the database and calling AddObject() will only create an entry in the database if it does not yet exist

Get all regestired listeners to an observable value

How to get all listeners to an observable value? I could extend the class and override addListener and removeListener methods to store them in a set. But the set should already be stored somehow inside observable value. How could I get that set?
I find a way around it, you can't get direct access to the Listeners list but if you use a debugger(I use IntelliJ) you can see it if you look inside your ObservableProprty like this:(I hope this is clear enough)
another way:(You're a smart guy, you'll know how to fit into your case)
//SimpleFloatProperty we want to find its Listeners
FloatPropertyBase f=ampPS.currentProperty();
Object value;
ChangeListener[] list;
ChangeListener changeListener=null;
Field field = null;
try {
field = FloatPropertyBase.class.getDeclaredField("helper");
field.setAccessible(true);
value = field.get(f);
try {
field = value.getClass().getDeclaredField("listener");
field.setAccessible(true);
changeListener =(WeakChangeListener)field.get(value);
}catch (NoSuchFieldException e) {
e.printStackTrace();
}
try {
field = value.getClass().getDeclaredField("changeListeners");
field.setAccessible(true);
list =(ChangeListener[])field.get(value);
}catch (NoSuchFieldException e) {
e.printStackTrace();
}
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
the result:
(Notice the difference between 1 listener or more than 1)
I I'm adding Example for several types of values
public static ChangeListener[] getChangeListeners(ObservableValue observableValue){
Object value;
ChangeListener[] list=null;
ChangeListener changeListener=null;
Field field = null;
try {
if(observableValue instanceof SimpleFloatProperty ){
field = FloatPropertyBase.class.getDeclaredField("helper");
}
else if(observableValue instanceof SimpleBooleanProperty ){
field = BooleanPropertyBase.class.getDeclaredField("helper");
}
else if(observableValue instanceof SimpleIntegerProperty ){
field = IntegerPropertyBase.class.getDeclaredField("helper");
}
field.setAccessible(true);
value = field.get(observableValue);
try {
field = value.getClass().getDeclaredField("listener");
field.setAccessible(true);
changeListener =(ChangeListener)field.get(value);
}catch (NoSuchFieldException e) {
//e.printStackTrace();
}
try {
field = value.getClass().getDeclaredField("changeListeners");
field.setAccessible(true);
list =(ChangeListener[])field.get(value);
}catch (NoSuchFieldException e) {
//e.printStackTrace();
}
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
if(list!=null){
return list;
}
else {
ChangeListener[] changeListeners = new ChangeListener[1];
changeListeners[0]=changeListener;
return changeListeners;
}
}
and I call it:
SimpleBooleanProperty booleanProperty = new SimpleBooleanProperty(true);
SimpleFloatProperty simpleFloatProperty = new SimpleFloatProperty(0);
SimpleIntegerProperty simpleIntegerProperty = new SimpleIntegerProperty(1);
booleanProperty.addListener(changeListener);
simpleFloatProperty.addListener(changeListener);
simpleIntegerProperty.addListener(changeListener);
simpleIntegerProperty.addListener(changeListener);
System.out.println(getChangeListeners(booleanProperty).length);
System.out.println(getChangeListeners(simpleFloatProperty).length);
System.out.println(getChangeListeners(simpleIntegerProperty).length);
the result:
so I do get warnings, but the job is done!

LayoutSerializationCallback not be called

I'm using AvalonDock and I would serialize and deserialize my layout. But the callback (where I use the ContentId for create an instance of correct object) is not always called. For this reason the loaded not work correctly. I have tried to add one "try-catch", but not thrown exception.
This is my code:
` var layoutSerializer = new XmlLayoutSerializer(manager);
layoutSerializer.LayoutSerializationCallback += (s, e) =>
{
MyClass item;
if (items.TryGetValue(e.Model.ContentId, out item))
{
e.Content = item;
var tool = item as IMyClassToolApp;
var anchorable = e.Model as LayoutAnchorable;
var document = item as IMyClassDocumentApp;
var layoutDocument = e.Model as LayoutDocument;
if (tool != null && anchorable != null)
{
addToolCallback(tool);
tool.IsVisible = anchorable.IsVisible;
tool.IsSelected = e.Model.IsSelected;
return;
}
if (document != null && layoutDocument != null)
{
addDocumentCallback(document);
// Nasty hack to get around issue that occurs if documents are loaded from state,
// and more documents are opened programmatically.
layoutDocument.GetType().GetProperty("IsLastFocusedDocument").SetValue(layoutDocument, false, null);
document.IsVisible = true;
document.IsSelected = layoutDocument.IsSelected;
return;
}
}
e.Cancel = true;
};
try
{
layoutSerializer.Deserialize(stream);
}
catch
{
return false;
}`
Thank you for your help!
Are you sure your stream is O.K? If for example configuration file does not exist LayoutSerializationCallback method will not be called.
private void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
try
{
MainWindow.logger.Debug("Entering: {0}", "MainWindow_Loaded");
string filePath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
#"Jofta\Analyzer\configs\AvalonDock.config");
if (!string.IsNullOrEmpty(filePath) && File.Exists(filePath))
{
XmlLayoutSerializer serializer = new XmlLayoutSerializer(this.dockingManager);
serializer.LayoutSerializationCallback += this.Serializer_LayoutSerializationCallback;
serializer.Deserialize(filePath);
}
MainWindow.logger.Debug("Exiting: {0}", "MainWindow_Loaded");
}
catch (Exception ex)
{
MainWindow.logger.Error("Exception in: {0}", "MainWindow_Loaded");
MainWindow.logger.Error("Message: {0}", ex.Message);
}
}
private void Serializer_LayoutSerializationCallback(object sender, LayoutSerializationCallbackEventArgs e)
{
try
{
MainWindow.logger.Debug("Entering: {0}", "serializer_LayoutSerializationCallback");
if (e.Model.ContentId == ObjectExplorerViewModel.AnchorableContentId)
{
e.Content = Workspace.Instance.ObjectExplorer;
return;
}
// ...
// ...
MainWindow.logger.Debug("Exiting: {0}", "serializer_LayoutSerializationCallback");
}
catch (Exception ex)
{
MainWindow.logger.Error("Exception in: {0}", "serializer_LayoutSerializationCallback");
MainWindow.logger.Error("Message: {0}", ex.Message);
}
}

Resources