Intellij IDEA Plugin Gradle development - generating code to an existing class - gradle

I'm working on my IDEA IntelliJ Plugin with gradle and I am trying to create a button that adds a function to the current class, or a given class.
I saw an example in Eclipse but couldn't find the equivalent libraries.
I've tried to seek for an equivalent library to ICompilationUnit in Eclipse but couldn't find anything
ICompilationUnit unit = compilationUnit(activeEditor());
final String messageName = inputBox("Create New Message",
"Message Name");
if (messageName == null)
return null;
String camel = camelCase(messageName);
final String methodName = "handle" + camel;
IType type = null;
try {
unit.createImport(Global.WHEN_RECEIVED_CLASS_NAME.<String>data(), null, null);
type = unit.getType(drop(unit.getElementName(), 4));
if (!type.getSuperclassName().equals("SimpleAgent")) {
msgbox("cannot create message - unrecognized agent type");
return null;
}
IMethod mtd = method(type, methodName);
if (mtd == null) {
mtd = type
.createMethod(
"#WhenReceived(\""
+ messageName
+ "\")\npublic void "
+ methodName
+ "(){\n\t//TODO: Add Message Handling Code Here.\n\t"
+ "//you can add any parameters to the method in order to receive them within the message.\n}\n",
null, false, null);
}
CompilationUnitEditor editor = activeCompilationUnitEditor();
editor.setSelection(mtd);
My main goal is to add a button that once it's clicked it opens a text box, than it adds a function with the given text to the current class.
Error if nothing has been typed.
Thank you very much in advanced.

Related

How do you programmatically run Static Code Analysis in Visual Studio 2017?

I'm working on a solution to localize legacy applications. I've written a Visual studio add-in using EnvDte that automates the process of setting the "Localizable" flag for every form in the solution to true, which is a critical step for extracting resources on form designers. I am now trying to deal with any text that is set programmatically, text that trigger the Globalization (CA13##) warnings.
designer.Visible = true;
var host = (IDesignerHost)designer.Object;
var provider = TypeDescriptor.GetProvider(host.RootComponent);
var typeDescriptor = provider.GetExtendedTypeDescriptor(host.RootComponent);
if (typeDescriptor == null)
continue;
var propCollection = typeDescriptor.GetProperties();
var propDesc = propCollection["Localizable"];
if (propDesc != null && host.RootComponent != null &&
(bool?)propDesc.GetValue(host.RootComponent) != true)
{
try
{
propDesc.SetValue(host.RootComponent, true);
}
catch (Exception ex)
{
// log the error
}
// save changes
}
I've been able to run it manually from the menu using: Analyze -> Run Code Analysis -> On Solution to get a list of issues, but I would like to automate this step with another add-in that runs and extracts the results.
Are there any resources that point to accessing the build warnings or the results of the code analysis?
Are there any solutions that already do this using EnvDte or Roslyn?
Ok, I've managed to glean enough information to put together the add-in. Put simply, you use _dte.ExecuteCommand()
Initialize the command:
// nothing to see here...
_package = package ?? throw new ArgumentNullException(nameof(package));
var commandService = ServiceProvider.GetService(typeof(IMenuCommandService)) as OleMenuCommandService;
if (commandService == null)
return;
_dte = (DTE2)ServiceProvider.GetService(typeof(DTE));
var menuCommandId = new CommandID(CommandSet, CommandId);
var menuItem = new MenuCommand(MenuItemCallback, menuCommandId);
commandService.AddCommand(menuItem);
_events = _dte.Events.BuildEvents;
// since static code analysis is a sort of build you need to hook into OnBuildDone
_events.OnBuildDone += OnBuildDone;
Trigger the analysis
private void MenuItemCallback(object sender, EventArgs e)
{
_dte.ExecuteCommand("Build.RunCodeAnalysisonSolution");
}
Extract errors in the OnBuildDone event
private void OnBuildDone(vsBuildScope scope, vsBuildAction action)
{
Dispatcher.CurrentDispatcher.InvokeAsync(new Action(() =>
{
_dte.ExecuteCommand("View.ErrorList", " ");
var errors = _dte.ToolWindows.ErrorList.ErrorItems;
for (int i = 1; i <= errors.Count; i++)
{
ErrorItem error = errors.Item(i);
var code = error.Collection.Item(1);
var item = new
{
error.Column,
error.Description,
error.ErrorLevel,
error.FileName,
error.Line,
error.Project
};
error.Navigate(); // you can navigate to the error if you wanted to.
}
});
}

Getting native device information from BluetoothLE device

I'm using the Plugin.BLE nuget package in my Xamarin project to interrogate the BLE devices I have. It seems to be working fine, but there is an object returned as part of the overall device object when the found device event is triggered. The object is called NativeDevice.
Intellisense is showing that this is an object which can be manipulated on the platform which is what I am trying to do so I can store and handle within my mvvm framework.
The problem is that if I cast the object as a Device on the platform and store that in a var, the var is always null.
How am I supposed to get the values from the object on the platform so I can pass these back to my view model?
My code looks like this
(in the forms project)
adapter.DeviceDiscovered += (s, a) =>
{
var adList = new List<AdvertisingRecords>();
foreach (var r in a.Device.AdvertisementRecords)
{
adList.Add(new AdvertisingRecords { Data = r.Data, Type = (AdvertisingRecordType)r.Type });
}
var newbtd = new BluetoothDevice
{
AdvertisementRecords = adList,
NativeDevice = DependencyService.Get<INativeDevice>().ConvertToNative(a.Device.NativeDevice),
Name = a.Device.Name,
Rssi = a.Device.Rssi,
Id = a.Device.Id,
State = (BluetoothStates)a.Device.State
};
btd.Add(newbtd);
};
On the platform
[assembly: Xamarin.Forms.Dependency(typeof(NativeDeviceConverter))]
namespace MyApp.Droid.Injected
{
public class NativeDeviceConverter : INativeDevice
{
public NativeDevice ConvertToNative(object device)
{
var dev = device as Device;
if (dev != null)
return new NativeDevice { Name = !string.IsNullOrEmpty(dev.BluetoothDevice.Name) ? dev.BluetoothDevice.Name : string.Empty, Address = dev.BluetoothDevice.Address, Type = dev.BluetoothDevice.Type.ToString() };
else
return new NativeDevice();
}
}
}
NativeDevice is my abstracted class that I used within the VM
The Reason why device value null is that the type of a.Device.NativeDevice is not of Device type. It is NativeObject so for android it is of type BluetoothDevice and for ios, it is CBPeripheral.
As I understand from your code you want to pass a.Device which is in turn of type Device. So you just need to replace it this line
NativeDevice = DependencyService.Get<INativeDevice>().ConvertToNative(a.Device.NativeDevice)
with
NativeDevice = DependencyService.Get<INativeDevice>().ConvertToNative(a.Device)
Now you can use Device.BluethoothDevice in android.

how to convert beloved android code into nativescript

i try to convert beloved code same into nativescript but i am new i have no idea for this please tell me how to convert android code to nativescript ...
private void createWebPrintJob() {
// Get a PrintManager instance
PrintManager printManager = (PrintManager)
getSystemService(Context.PRINT_SERVICE);
// Get a print adapter instance
PrintDocumentAdapter printAdapter = webView.createPrintDocumentAdapter();
// Create a print job with name and adapter instance
String jobName = getString(R.string.app_name) + " Document";
PrintJob printJob = printManager.print(jobName, printAdapter,
new PrintAttributes.Builder().build());
// Save the job object for later status checking
// mPrintJobs.add(printJob);
}
May be something like this,
var application = require('application');
var utils = require('utils/utils');
function createWebPrintJob() {
var printManager = application.android.context
.getSystemService(android.content.Context.PRINT_SERVICE);
var printAdapter = webView.createPrintDocumentAdapter();
var jobName = getString(utils.ad.getStringId("app_name")) + " Document";
var printJob = printManager.print(jobName, printAdapter, new namespace.to.PrintAttributes.Builder().build());
mPrintJobs.add(printJob);
}
The above is just puedo code, end of the day it's JavaScript nothing super special.

How to get IEditorOperations from IVsTextView?

I'm developing my first Visual Studio (2015 Community) Command Menu and I'm trying to get access to IEditorOperations to delete text, send backspace etc. but I'm not sure how to. I can do:
var Service = Provider.GetService(typeof(IEditorOperationsFactoryService)) as IEditorOperationsFactoryService;
Service.GetEditorOperations(???);
I'm not sure what to pass in the ??? since I don't have access to an ITextView instead what I have is a IVsTExtView via:
IVsTextView View;
IVsTextManager Manager = (IVsTextManager)ServiceProvider.GetService(typeof(SVsTextManager));
int MustHaveFocus = 1;
Manager.GetActiveView(MustHaveFocus, null, out View);
When creating the Command Menu, VS generates a template for me with a private ctor creating the command service, binding it to the command set id etc. An overridden Initialize method, and a bunch of properties.
Any ideas?
EDIT: After help from Sergey, I managed to get a bit further. But now I get a null when I try to get the IEditorOperationsFactoryService, all the other values are valid.
static IEditorOperations GetEditorService(IServiceProvider Provider, IVsTextView VsView)
{
IEditorOperations Result;
try
{
var Model = (IComponentModel)Provider.GetService(typeof(SComponentModel));
var Editor = (IEditorOperationsFactoryService)Provider.GetService(typeof(IEditorOperationsFactoryService)); // returns null
var Adaptor = Model.GetService<IVsEditorAdaptersFactoryService>();
IWpfTextView TextView = Adaptor.GetWpfTextView(VsView);
Result = Editor.GetEditorOperations(TextView);
}
catch (Exception e)
{
System.Windows.Forms.MessageBox.Show(e.ToString());
Result = null;
}
return (Result);
}
You can get IEditorOperationsFactoryService instance from variable named Model, like this:
var Model = (IComponentModel)this.ServiceProvider.GetService(typeof(SComponentModel));
var Editor = (IEditorOperationsFactoryService)Model.GetService<IEditorOperationsFactoryService>();
You can get IWpfTextView (that implements ITextView) from IVsTextView using:
IVsTextView textView = ...;
IWpfTextView v = GetEditorAdaptersFactoryService().GetWpfTextView(textView);
private Microsoft.VisualStudio.Editor.IVsEditorAdaptersFactoryService GetEditorAdaptersFactoryService()
{
Microsoft.VisualStudio.ComponentModelHost.IComponentModel componentModel =
(Microsoft.VisualStudio.ComponentModelHost.IComponentModel)serviceProvider.GetService(
typeof(Microsoft.VisualStudio.ComponentModelHost.SComponentModel));
return componentModel.GetService<Microsoft.VisualStudio.Editor.IVsEditorAdaptersFactoryService>();
}

How to remove Objects from PDF File using PDFClown

I have a pdf which contains a lot of invisible paths. Since the amount of path produces problems later on, I would like to remove the ones that have white colors.
So far I am trying to do this with a ContentScanner:
public class FilterWhitePathScanner implements Scanner {
private static final Logger LOG = LoggerFactory.getLogger(FilterWhitePathScanner.class);
private int count = 0;
public void scan(ContentScanner level) {
if (level == null)
return;
while (level.moveNext()) {
ContentObject object = level.getCurrent();
if (object instanceof ContainerObject) {
// Scan the inner level!
scan(level.getChildLevel());
} else if (object instanceof org.pdfclown.documents.contents.objects.Path) {
AffineTransform ctm = level.getState().getCtm();
Color<?> strokeColor = level.getState().getStrokeColor();
Color<?> fillColor = level.getState().getFillColor();
if (checkWhite(fillColor) && checkWhite(strokeColor)) {
level.remove();
} else {
LOG.info("Stroke Color " + strokeColor + " - Fill Color " + fillColor);
}
} else {
LOG.info("Object:" + object);
}
}
}
It recognizes the paths correctly, but in the end these are not removed from the PDF. Here the code handling the PDF (it extracts only one page from the source pdf):
Document targetDoc = new File().getDocument();
targetDoc.getPages().add(sourceDoc.getPages().get(pageNum).clone(targetDoc));
Page page = targetDoc.getPages().get(0);
Contents contents = page.getContents();
FilterWhitePathScanner filterWhitePathScanner = new FilterWhitePathScanner();
filterWhitePathScanner.scan(new ContentScanner(contents));
LOG.info("White Paths: " + filterWhitePathScanner.getCount());
targetDoc.getFile().save(tempFilePath.toFile(), SerializationModeEnum.Standard);
The saved PDF file still contains the paths I tried to remove. How can I remove objects from the PDF finally?
Thanks,
Thomas
Finally found the solution in the Java doc:
You have to call contents.flush(); to persist the changes into the pdf file.
So I added this line to the PDF handling code before calling save and it works!

Resources