How do I get the selected file's filesystem path using ResourceNavigator in RCP? - eclipse

This is what I tried, but it failed.And it alerted that 'org.eclipse .core .internal.File cannot be cast to org.eclipse.core.resource.IProject'.
public void runDefaultAction(IStructuredSelection selection) {
Object element = selection.getFirstElement();
if (element instanceof IFile) {
openFileAction.selectionChanged(selection);
openFileAction.run();
String selectedPathString = ((IFile) element).getFullPath().toString();
System.out.println(selectedPathString);
//get project absolute path
ISelectionService service = navigator.getSite().getWorkbenchWindow()
.getSelectionService();
IStructuredSelection selection1 = (IStructuredSelection) service
.getSelection("BIT_DEC.myNavigator");
IProject iproject = (IProject) selection1.getFirstElement();
String real_file_path = iproject.getLocation().toString();
System.out.println(real_file_path);
.....

it alerted that 'org.eclipse .core .internal.File cannot be cast to org.eclipse.core.resource.IProject'.
Because:
Corrected last 3 lines of your code.
if(selection1.getFirstElement() instanceof IFile) {
IFile file = (IFile) selection1.getFirstElement();
String real_file_path = file.getLocation().toString();
System.out.println(real_file_path);
}

IFile has a getLocation() method that gives you the full path directly.
Note: The selection returned by the selection service will generally be the same as the selection you are given. You can get the project from an IFile by calling its getProject() method.

Related

Modify a pictogram element in Eclipse RCP Graphiti

I tried the solution provided here:
automatic update of graphiti diagrams in case of changes in the datamodel
I am trying to call the Upadate feature in the UpdateNeeded function of my class which implements AbstractUpdateFeature:
TransactionalEditingDomain domain = TransactionUtils.getEditingDomain(diagram);
domain.getCommandStack().execute(new RecordingCommand(domain) {
public void doExecute() {
UpdateContext updateContext = new
UpdateContext(getDiagram().getChildren().get(0). getGraphicsAlgorithm().getPictogramElement( ));
IUpdateFeature updateFeature = getFeatureProvider().getUpdateFeature(updateContext);
updateFeature.update(updateContext);
}});
In the Update function I am trying to change the value of the text field of a Pictogram element:
// Set name in pictogram model
if (pictogramElement instanceof ContainerShape) {
ContainerShape cs = (ContainerShape) pictogramElement;
for (Shape shape : cs.getChildren()) {
if (shape.getGraphicsAlgorithm() instanceof Text) {
Text text = (Text) shape.getGraphicsAlgorithm();
text.setValue("aaa");
return true;
}
}
}
But I am getting the Exception:
java.lang.IllegalStateException: Cannot modify resource set without a write transaction
at org.eclipse.emf.transaction.impl.TransactionChangeRecorder.assertWriting(TransactionChangeRecorder.java:348)
at org.eclipse.emf.transaction.impl.TransactionChangeRecorder.appendNotification(TransactionChangeRecorder.java:302)
at org.eclipse.emf.transaction.impl.TransactionChangeRecorder.processObjectNotification(TransactionChangeRecorder.java:284)
at org.eclipse.emf.transaction.impl.TransactionChangeRecorder.notifyChanged(TransactionChangeRecorder.java:240)
Try executing the feature using DiagramBehavior
getDiagramBehavior().executeFeature(feature, context);

How to programmatically find a .java file in an Eclipse plugin from full classname?

Inside an Eclipse plugin, I'd like to open a file in editor.
I know the full package and class name
How can I determine the path of the .java file from this?
Take a look at IJavaProject.findType( name ) method. Once you have an IType, you can use getPath or getResource methods to locate the file. This method searches across a project and everything visible from that project.
To search the whole workspace, iterate through all the Java projects in the workspace, calling the findType method on each in turn.
You also need to know the source folder.
IProject prj = ResourcePlugin.getWorkspace().getRoot().getProject("project-name");
IFile theFile = prj.getFile(sourceFolder + packageName.replace('.','/') + className + ".java");
Generally you specify the file for an editor with an IFile. You can also ask an IFile for variants of the file's path.
I know this is a bit old but I had the same need and I had a look at how eclipse does it for stack trace elements (they have a hyperlink on them). The code is in org.eclipse.jdt.internal.debug.ui.console.JavaStackTraceHyperlink (the link is "lazy" so the editor to open is resolved only when you click on it).
What it does is it first searches for the type in the context of the launched application, then for in the whole workspace (method startSourceSearch) :
IType result = OpenTypeAction.findTypeInWorkspace(typeName, false);
And then opens the associated editor (method processSearchResult, source is the type retrieved above) :
protected void processSearchResult(Object source, String typeName, int lineNumber) {
IDebugModelPresentation presentation = JDIDebugUIPlugin.getDefault().getModelPresentation();
IEditorInput editorInput = presentation.getEditorInput(source);
if (editorInput != null) {
String editorId = presentation.getEditorId(editorInput, source);
if (editorId != null) {
try {
IEditorPart editorPart = JDIDebugUIPlugin.getActivePage().openEditor(editorInput, editorId);
if (editorPart instanceof ITextEditor && lineNumber >= 0) {
ITextEditor textEditor = (ITextEditor)editorPart;
IDocumentProvider provider = textEditor.getDocumentProvider();
provider.connect(editorInput);
IDocument document = provider.getDocument(editorInput);
try {
IRegion line = document.getLineInformation(lineNumber);
textEditor.selectAndReveal(line.getOffset(), line.getLength());
} catch (BadLocationException e) {
MessageDialog.openInformation(JDIDebugUIPlugin.getActiveWorkbenchShell(), ConsoleMessages.JavaStackTraceHyperlink_0, NLS.bind("{0}{1}{2}", new String[] {(lineNumber+1)+"", ConsoleMessages.JavaStackTraceHyperlink_1, typeName})); //$NON-NLS-2$ //$NON-NLS-1$
}
provider.disconnect(editorInput);
}
} catch (CoreException e) {
JDIDebugUIPlugin.statusDialog(e.getStatus());
}
}
}
}
Code has copyright from eclipse. Hopfully I'm allowed to reproduced it if this is mentionned.

dynamic connection string with EF4, get metadata path is not valid

Here is my problem.
I use a dynamic connection string for my Entity Framework context.
//In Web Config
add key="DataSource" value="WIN-QBRH0MJL8IT\ISS" />
//In my EntityFactory.cs
public static DBEntities GetEntity()
{
var scsb = new SqlConnectionStringBuilder();
scsb.DataSource = ConfigurationManager.AppSettings["DataSource"];
scsb.InitialCatalog = "db1";
scsb.MultipleActiveResultSets = true;
scsb.IntegratedSecurity = true;
if (HttpContext.Current.Session["DBName"] == null)
{
HttpContext.Current.Response.Redirect("/Account/Step1");
}
else
{
scsb.InitialCatalog = HttpContext.Current.Session["DBName"].ToString();
}
var builder = new EntityConnectionStringBuilder();
builder.Metadata = "metadata=~/bin/Models/DBModel.csdl|~/bin/Models/DBModel.ssdl|~/bin/Models/DBModel.msl";
builder.Provider = "System.Data.SqlClient";
builder.ProviderConnectionString = scsb.ConnectionString;
DBEntities db = new DBEntities(builder.ConnectionString);
return db;
}
I Know the problem is for this line :
builder.Metadata =
"metadata=~/bin/Models/DBModel.csdl|~/bin/Models/DBModel.ssdl|~/bin/Models/DBModel.msl";
I check and the csdl, ssdl, msl are in /mvcinfosite/bin/Models/.csdl,.ssdl,.msl
The configuration for my edmx is:
Metadata Artifact Processing : Copy to Output Directory
Here is the full error
The specified metadata path is not valid. A valid path must be either
an existing directory, an existing file with extension '.csdl',
'.ssdl', or '.msl', or a URI that identifies an embedded resources
Thanks
Try to remove ~ character and use valid relative path to your app root. I think it is not able to work with this special character used on in ASP.NET application.

In an Eclipse plugin, how can I make a DirectoryFieldEditor start with a particular path?

I am making an Eclipse plugin which on right clicking a project produces a UI.
In this UI I have used DirectoryFieldEditor. This produces directory dialog starting at "MyComputer" as root. What i want is it to show paths starting at the project which i right clicked. how can this be achieved?
I am trying to mimic when you right click a project and say "new package" - the source folder browse give a directory dialog with only those folders which are open projects.... I want a similar directory dialog.
Can somebody help and give me some code snippets or suggestions?
Well, considering the "new package" is actually the class:
org.eclipse.jdt.internal.ui.wizards.NewPackageCreationWizard
which uses NewPackageWizardPage (source code), you will see:
public void init(IStructuredSelection selection) {
IJavaElement jelem = getInitialJavaElement(selection);
initContainerPage(jelem);
String pName = ""; //$NON-NLS-1$
if (jelem != null) {
IPackageFragment pf = (IPackageFragment) jelem
.getAncestor(IJavaElement.PACKAGE_FRAGMENT);
if (pf != null && !pf.isDefaultPackage())
pName = pf.getElementName();
}
setPackageText(pName, true);
updateStatus(new IStatus[] { fContainerStatus, fPackageStatus });
}
With the getInitialJavaElement() being part of superclass NewContainerWizardPage:
/**
* Utility method to inspect a selection to find a Java element.
*
* #param selection the selection to be inspected
* #return a Java element to be used as the initial selection, or <code>null</code>,
* if no Java element exists in the given selection
*/
protected IJavaElement getInitialJavaElement(
IStructuredSelection selection) {
IJavaElement jelem = null;
if (selection != null && !selection.isEmpty()) {
Object selectedElement = selection.getFirstElement();
if (selectedElement instanceof IAdaptable) {
IAdaptable adaptable = (IAdaptable) selectedElement;
jelem = (IJavaElement) adaptable
.getAdapter(IJavaElement.class);
if (jelem == null) {
IResource resource = (IResource) adaptable
.getAdapter(IResource.class);
if (resource != null
&& resource.getType() != IResource.ROOT) {
while (jelem == null
&& resource.getType() != IResource.PROJECT) {
resource = resource.getParent();
jelem = (IJavaElement) resource
.getAdapter(IJavaElement.class);
}
if (jelem == null) {
jelem = JavaCore.create(resource); // java project
}
}
}
}
}
if (jelem == null) {
IWorkbenchPart part = JavaPlugin.getActivePage()
.getActivePart();
if (part instanceof ContentOutline) {
part = JavaPlugin.getActivePage().getActiveEditor();
}
if (part instanceof IViewPartInputProvider) {
Object elem = ((IViewPartInputProvider) part)
.getViewPartInput();
if (elem instanceof IJavaElement) {
jelem = (IJavaElement) elem;
}
}
}
if (jelem == null
|| jelem.getElementType() == IJavaElement.JAVA_MODEL) {
try {
IJavaProject[] projects = JavaCore.create(
getWorkspaceRoot()).getJavaProjects();
if (projects.length == 1) {
jelem = projects[0];
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
}
return jelem;
}
Between those two methods, you should be able to initialize your custom UI with the exact information (i.e., "relative source path") you want.
If you look at the source of DirectoryFieldEditor, you will see it open its directory chooser dialog based on the value if its main Text field defined in StringFieldEditor:doLoad():
String JavaDoc value = getPreferenceStore().getString(getPreferenceName());
textField.setText(value);
That means you need, in your custom UI, to get the preference store and associate the right path with an id. You will use that id for your DirectoryFieldEditor initialization. Y oucan see an example here.
public static final String MY_PATH = "my.init.path";
IPreferenceStore store = myPlugin.getDefault().getPreferenceStore();
store.setValue(MY_PATH, theRightPath);
myDirFieldEditor = new DirectoryFieldEditor(MY_PATH, "&My path", getFieldEditorParent());
As you mention in the comments, all this will only initialize the eclipse-part GUI, not the native windows explorer launched by a DirectoryDialog:
this (the native interface) is based on:
parameters stored in BROWSEINFO Structure
used by the actual GUI SHBrowseForFolder Function, which actually displays a dialog box that enables the user to select a Shell folder.
That GUI initialize a root path based on filter path, so you need to also initialize (on eclipse side) that filter field with a path in order to get it pick up by the Windows-GUI SHBrowseForFolder.
According to DirectoryFieldEditor, that is exactly what getTextControl() (the field you initialized above) is for.
But the problem comes from the fact that field has been initialized with a relative path. Since that path is unknown by the underlying OS, it defaults back to root OS path.
You need to find a way to store the full system path of the project, not the relative path.
That way, that full path will be recognized by the Os and used as initial path.
For instance, from a IJavaElement, you can get its associated resource, and try to get the (full system) path from there.
Actually, from the IPackageFragment you should be able to call getPath(), and check if the IPath returned contains the full system path.

CommandBars.FindControl throwing an exception

I am trying to use the FindControl Method of the CommandBars object in a VSTO Word addin to get what else a command bar object
Code is as follows
private void WireContextMenu(string MenuID,string Tag, string ID, ref Office.CommandBarButton Control)
{
try
{
object missing = System.Type.Missing;
Control = (Office.CommandBarButton)this.Application.CommandBars[MenuID].FindControl((object)Office.MsoControlType.msoControlButton, ID, Tag, missing, missing);
if (Control == null)
{
Control = (Office.CommandBarButton)this.Application.CommandBars[MenuID].Controls.Add(Office.MsoControlType.msoControlButton, ID, missing, missing, missing);
Control.Caption = "Biolit Markup Selection";
Control.Tag = Tag;
}
Control.Click += new Microsoft.Office.Core._CommandBarButtonEvents_ClickEventHandler(this.cb_Click);
}
catch (Exception Ex)
{
}
}
The FindControl method is throwing a Type Mismatch Exception (-2147352571)
Any ideas
is this the right way anyhow to add a item to the right click menu of word and then make sure you dont add it if it already exists
Thanks
you are using Missing where Missing is not allowed as parameter
ref: link text
http://msdn.microsoft.com/en-us/library/system.type.missing.aspx
use code like this:
object type = MsoControlType.msoControlPopup;
object id = 1;
object tag = null;
object visible = 1;
object recusive = false;
//object missing = System.Type.Missing;
CommandBarControl barControl = popParent.FindControl(type, id, tag, visible, recusive);