Modify a pictogram element in Eclipse RCP Graphiti - eclipse-rcp

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);

Related

Wagtail - how to get tags to work with `telepath` (tags in streamfield)?

I can use tags in regular page fields without any issue. When using tags within blocks (within a streamfield), the UI works and the tags are saved BUT the current page tags do not show up when loading the page in the admin. That's because the current value is not in the template anymore, it's in a JSON loaded via telepath.
I can confirm that the tags are saved and present in the data passed to initBlockWidget in the page source but these are ignored. Also, if I used a regular text field instead of the tag-widget, I can see the saved-values in the admin.
This is the code I have (which used to be enough before the refactor with telepath).
from wagtail.admin.widgets import AdminTagWidget
class TagBlock(TextBlock):
#cached_property
def field(self):
field_kwargs = {"widget": AdminTagWidget()}
field_kwargs.update(self.field_options)
return forms.CharField(**field_kwargs)
I think the following link is what I need to complete somehow to get it to work: https://docs.wagtail.io/en/stable/reference/streamfield/widget_api.html#form-widget-client-side-api
I've tried with this:
class AdminTagWidgetAdapter(WidgetAdapter):
class Media:
js = [
"wagtailadmin/js/vendor/tag-it.js",
"js/admin/admin-tag-widget-adapter.js",
]
register(AdminTagWidgetAdapter(), AdminTagWidget)
And under js/admin/admin-tag-widget-adapter.js:
console.log("adapter"); // this shows up in the console
class BoundWidget { // copied from wagtail source code
constructor(element, name, idForLabel, initialState) {
var selector = ':input[name="' + name + '"]';
this.input = element.find(selector).addBack(selector); // find, including element itself
this.idForLabel = idForLabel;
this.setState(initialState);
}
getValue() {
return this.input.val();
}
getState() {
return this.input.val();
}
setState(state) {
this.input.val(state);
}
getTextLabel(opts) {
const val = this.getValue();
if (typeof val !== 'string') return null;
const maxLength = opts && opts.maxLength;
if (maxLength && val.length > maxLength) {
return val.substring(0, maxLength - 1) + '…';
}
return val;
}
focus() {
this.input.focus();
}
}
// my code here:
class AdminTagWidget {
constructor(html, idPattern) {
this.html = html;
this.idPattern = idPattern;
}
boundWidgetClass = BoundWidget;
render(placeholder, name, id, initialState) {
console.log("RENDER", placeholder, name, id, initialState); // this does not show
var html = this.html.replace(/__NAME__/g, name).replace(/__ID__/g, id);
var idForLabel = this.idPattern.replace(/__ID__/g, id);
var dom = $(html);
$(placeholder).replaceWith(dom);
// eslint-disable-next-line new-cap
return new this.boundWidgetClass(dom, name, idForLabel, initialState);
}
}
console.log("here") // does show in the console
// variants I've tried:
//window.telepath.register('wagtail.admin.widgets.tags.AdminTagWidget', AdminTagWidget);
//window.telepath.register('wagtail.widgets.AdminTagWidget', AdminTagWidget);
window.telepath.register('path.where.its.used.AdminTagWidget', AdminTagWidget)
The log from my custom render method does not show. It seems that I'm not calling the right path within window.telepath.register but I don't know how what the string is supposed to be...
I'm not even sure if this is the right way forward.
Notes:
it works in regular field, the question is about tags in blocks
I'm using Wagtail version 2.13.2 but I've also tried with 2.15 without any difference.
In the console, I can log window.telepath and see my custom widget. It's just not "applied" to anything
Your WidgetAdapter class needs a js_constructor attribute:
class AdminTagWidgetAdapter(WidgetAdapter):
js_constructor = 'myapp.widgets.AdminTagWidget'
class Media:
js = [
"wagtailadmin/js/vendor/tag-it.js",
"js/admin/admin-tag-widget-adapter.js",
]
Any string value will work here - it just needs to uniquely identify the class, so it's recommended to use a dotted module-like path to avoid colliding with others. This then matches the string you pass to window.telepath.register on the Javascript side:
window.telepath.register('myapp.widgets.AdminTagWidget', AdminTagWidget)

Symfony: exclude empty values from form save

I have a many to many relation between Product and Properties. I'm using embedRelation() in my Product form to edit a Product and it's Properties. Properties includes images which causes my issue. Every time I save the form the updated_at column is updated for file properties even when no file is uploaded.
Therefore, I want to exclude empty properties when saving my form.
I'm using Symfony 1.4 and Doctrine 1.2.
I'm thinking something like this in my ProductForm.class.php, but I need some input on how to make this work.
Thanks
class ProductForm extends BaseProductForm
{
public function configure()
{
unset($this['created_at'], $this['updated_at'], $this['id'], $this['slug']);
$this->embedRelation('ProductProperties');
}
public function saveEmbeddedForms($con = null, $forms = null)
{
if (null === $forms)
{
$properties = $this->getValue('ProductProperties');
$forms = $this->embeddedForms;
foreach($properties as $p)
{
// If property value is empty, unset from $forms['ProductProperties']
}
}
}
}
I ended up avoiding Symfony's forms and saving models instead of saving forms. It can be easier when playing with embedded forms. http://arialdomartini.wordpress.com/2011/04/01/how-to-kill-symfony%E2%80%99s-forms-and-live-well/
Solved it by checking if posted value is a file, and if both filename and value_delete is null I unset from the array. It might not be best practice, but it works for now.
Solution based on http://www.symfony-project.org/more-with-symfony/1_4/en/06-Advanced-Forms
class ProductPropertyValidatorSchema extends sfValidatorSchema
{
protected function configure($options = array(), $messages = array())
{
// N0thing to configure
}
protected function doClean($values)
{
$errorSchema = new sfValidatorErrorSchema($this);
foreach($values as $key => $value)
{
$errorSchemaLocal = new sfValidatorErrorSchema($this);
if(array_key_exists('value_delete', $values))
{
if(!$value && !$values['value_delete'])
{
unset($values[$key]);
}
}
// Some error for this embedded-form
if (count($errorSchemaLocal))
{
$errorSchema->addError($errorSchemaLocal, (string) $key);
}
}
// Throws the error for the main form
if (count($errorSchema))
{
throw new sfValidatorErrorSchema($this, $errorSchema);
}
return $values;
}
}

DataSet does not support System.Nullable<>

i have an app which has btn to preview report made in crystal report. I added Dataset as datasource of the report and dragged datatable from the toolbox and added the fields I need as columns. I got the instruction from this link http://aspalliance.com/2049_Use_LINQ_to_Retrieve_Data_for_Your_Crystal_Reports.2. This is my 2nd report the first one works and did not encounter any prob at all that is why i am confused, not to mention it also has nullable column. the error says: DataSet does not support System.Nullable<>.
private void ShowReportView()
{
string reportFile = "JudgeInfoFMReport.rpt";
ObservableCollection<tblJudgeFileMaint> judgeFileMaintList;
judgeFileMaintList = GenerateReport();
if (judgeFileMaintList.Count > 0)
{
CrystalReportViewerUC crview2 = new CrystalReportViewerUC();
crview2.SetReportPathFile(reportFile, judgeFileMaintList);
crview2.ShowDialog();
}
else
{
System.Windows.MessageBox.Show("No record found.", module, MessageBoxButton.OK, MessageBoxImage.Information);
}
}
private ObservableCollection<tblJudgeFileMaint> GenerateReport()
{
var result = FileMaintenanceBusiness.Instance.GetAllJudgeInfoList();
return new ObservableCollection<tblJudgeFileMaint>(result);
}
The error is in the part where I set datasource report.SetDataSource
public bool SetReportPathFile(string reportPathFile, IEnumerable enumerable)
{
string reportFolder = #"\CrystalReportViewer\Reports\";
string filename = System.Windows.Forms.Application.StartupPath + reportFolder + reportPathFile; // "\\Reports\\CrystalReports\\DateWiseEmployeeInfoReport.rpt";
ReportPathFile = filename;
report.Load(ReportPathFile);
report.SetDataSource(enumerable);
report.SetDatabaseLogon("sa", "admin007");
bRet = true;
}
_IsLoaded = bRet;
return bRet;
}
I read some answers and says I should set the null value to DBNUll which I did in the properties window of each column if it is nullable. Can anyone help me please? thanks
Your question can be seen in this post, but in a generic way ... that way you can pass an Object to a DataSet typed!
.NET - Convert Generic Collection to DataTable
figured it out. by using a collectionextention, copied somewhere, I forgot the link. Os to whoever it is who made the class, credits to you.
class method looks like this.
public statis class CollectionExtension {
public static DataSet ToDataSet<T>(this IEnumerable<T> collection, string dataTableName)
{
if (collection == null)
{
throw new ArgumentNullException("collection");
}
if (string.IsNullOrEmpty(dataTableName))
{
throw new ArgumentNullException("dataTableName");
}
DataSet data = new DataSet("NewDataSet");
data.Tables.Add(FillDataTable(dataTableName, collection));
return data;
}
}
then you can use it by doing this in getting your source to your report:
private DataSet GenerateNeutralContEducReport(string dsName)
{
var contEduHistoryList = FileMaintenanceBusiness.Instance.GetManyNeutralFMContEducHistoryInfobyKeyword(CurrentNeutralFM.NeutralID, "NeutralID").ToList();
return CollectionExtensions.ToDataSet<tblContinuingEducationHistory>(contEduHistoryList, dsName);
}
I found little help from the other proposed answers but this solution worked.
A different way to solve this problem is to make the data column nullable.
DataColumn column = new DataColumn("column", Type.GetType("System.Int32"));
column.AllowDBNull = true;
dataTable.Columns.Add(column);
https://learn.microsoft.com/en-us/dotnet/api/system.data.datacolumn.allowdbnull?view=netcore-3.1
foreach (PropertyDescriptor property in properties)
{
dt.Columns.Add(property.Name, Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType);
}

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.

Syncfusion DocIO -- how to insert image (local file) at bookmark using BookmarksNavigator

I have been using Syncfusion DocIO for generating MS Word documents from my .net applications (winforms). So far I have dealt with plain text and it is fairly straightforward to insert text in a word document template where bookmarks serve as reference points for text insertion.
I am navigating the bookmarks using BookmarksNavigator.MoveToBookmark() . Now I need to insert an image at a bookmark but I am at a loss at how to go about it.
Please help...
Thanks.
Specifically for adding it to a bookmark :
//Move to the specified bookmark
bk.MoveToBookmark(bookmark);
//Insert the picture into the specified bookmark location
bk.DeleteBookmarkContent(true);
// we assume the text is a full pathname for an image file
// get the image file
System.Drawing.Image image = System.Drawing.Image.FromFile(sText);
IWParagraph paragraph = new WParagraph(document);
paragraph.AppendPicture(image);
bk.InsertParagraph(paragraph);
private System.Drawing.Image LoadSignature(string sFileName)
{
string sImagePath = sFileName;
System.Drawing.Image image = System.Drawing.Image.FromFile(sImagePath);
return image;
}
private void MergeSignature(WordDocument doc, string sFile, string sBalise)
{
System.Drawing.Image iSignature = LoadSignature(sFile);
WordDocument ImgDoc = new WordDocument();
ImgDoc.AddSection();
ImgDoc.Sections[0].AddParagraph().AppendPicture(iSignature);
if (iSignature != null)
{
TextSelection ts = null ;
Regex pattern = new Regex(sBalise);
ts = doc.Find(pattern);
if (ts != null)
{
doc.ReplaceFirst = true;
doc.Replace(pattern, ImgDoc, false);
}
}
iSignature.Dispose();
}
See here: https://help.syncfusion.com/file-formats/docio/working-with-mailmerge
1) You should create docx file with name "Template.docx". This file will use as template.
In your docx file create Field of type MergeField.
2) Create MergeFiled with name Image:Krishna
3)
using Syncfusion.DocIO.DLS;
using System.Drawing;
public class Source
{
public Image Krishna { get; set; } = Image.FromFile(#"C:\1.png");
}
and generating code:
public static void Generate()
{
WordDocument doc = new WordDocument("Template.docx");
Source data = new Source();
var dataTable = new MailMergeDataTable("", new Source[] { data });
doc.MailMerge.ExecuteGroup(dataTable);
doc.Save("result.docx");
doc.Close();
}