I have a class that inherits from Java.IO.FileInputStream. It looks something like this:
public class DeviceInputStream : FileInputStream
{
private FileDescriptor descriptor = null;
private byte currentValue;
public DeviceInputStream(FileDescriptor fd) : base(fd)
{
descriptor = fd;
}
public DeviceInputStream(File file) : base(file){}
public DeviceInputStream(string fileName):base(fileName){}
public override int Read()
{
int byteRead = base.Read();
currentValue = (byte) byteRead;
return byteRead;
}
public byte CurrentValue
{
get { return currentValue; }
}
}
However, when I compile this I get the following error:
unreported exception FileNotFoundException; must be caught or declared to be thrown
super (p0);
DeviceInputStream.java:20
Any ideas as to what might be causing this problem? Thanks.
-Shaun
It seems this is an issue with Xamarin Monodroid and has been filed as a bug to extend the ExportAttribute to constructors. Details are from here:
http://forums.xamarin.com/discussion/500/inheriting-from-fileinputstream
At build time, Android Callable Wrappers (ACWs) are generated for each Java.Lang.Object subclass, which includes our DeviceInputStream type:
public class DeviceInputStream
extends java.io.FileInputStream
implements
mono.android.IGCUserPeer
{
static final String __md_methods;
static {
__md_methods =
"n_read:()I:GetReadHandler\n" +
"";
mono.android.Runtime.register ("Scratch.ContentProvidersHateApplications.DeviceInputStream, Scratch.ContentProvidersHateApplications, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", DeviceInputStream.class, __md_methods);
}
public DeviceInputStream (java.io.File p0)
{
super (p0);
if (getClass () == DeviceInputStream.class)
mono.android.TypeManager.Activate ("Scratch.ContentProvidersHateApplications.DeviceInputStream, Scratch.ContentProvidersHateApplications, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", "Java.IO.File, Mono.Android, Version=0.0.0.0, Culture=neutral, PublicKeyToken=c4c4237547e4b6cd", this, new java.lang.Object[] { p0 });
}
public DeviceInputStream (java.io.FileDescriptor p0)
{
super (p0);
if (getClass () == DeviceInputStream.class)
mono.android.TypeManager.Activate ("Scratch.ContentProvidersHateApplications.DeviceInputStream, Scratch.ContentProvidersHateApplications, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", "Java.IO.FileDescriptor, Mono.Android, Version=0.0.0.0, Culture=neutral, PublicKeyToken=c4c4237547e4b6cd", this, new java.lang.Object[] { p0 });
}
public DeviceInputStream (java.lang.String p0)
{
super (p0);
if (getClass () == DeviceInputStream.class)
mono.android.TypeManager.Activate ("Scratch.ContentProvidersHateApplications.DeviceInputStream, Scratch.ContentProvidersHateApplications, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", "System.String, mscorlib, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e", this, new java.lang.Object[] { p0 });
}
public int read ()
{
return n_read ();
}
private native int n_read ();
/* ... */
}
Since ACWs are Java code, they need to be valid Java code. Unfortunately, in this circumstance they're not, because the super(p0) invocation in e.g. the DeviceInputStream(String) constructor is FileInputStream(String), which throws a FileNotFoundException.
Since the DeviceInputStream(String) constructor invokes a method which may thrown an exception, DeviceInputStream(String) must either contain a throws clause or have a try/catch block around the super(p0) statement. Neither happens, hence the compiler error.
Unfortunately, there is no workaround at this time; there isn't a way to add a throws to the ACW on constructor bodies, and there is no other way to customize the ACW's constructor, so you're stuck. :-(
Support to extend ExportAttribute so that this could work has been filed at bug 8754.
Related
I am newbie in edi data. I am using smooks api to read the edi data and able to parse it into java object. I want to convert java object to edi data for that i am not getting much information. Here is the example i am trying to read from edi file and creating the java object -
customOrder.edi - COR*130*PINGPONG02*You got it to work*1230
---------------
POJO -
------
public class CustomOrder implements Serializable{
private int number;
private String sender;
private String message;
private int price;
// setter and getter
}
custom-order-mapping.xml -
-------------------------
<?xml version="1.0" encoding="UTF-8"?><medi:edimap xmlns:medi="http://www.milyn.org/schema/edi-message-mapping-1.3.xsd">
<medi:description name="DVD Order" version="1.0" />
<medi:delimiters segment="
" field="*" component="^" sub-component="~" />
<medi:segments xmltag="CustomOrder">
<medi:segment segcode="COR" xmltag="co">
<medi:field xmltag="number" />
<medi:field xmltag="sender" />
<medi:field xmltag="message" />
<medi:field xmltag="price" />
</medi:segment>
</medi:segments>
</medi:edimap>
smooks-config.xml -
------------------
<?xml version="1.0"?>
<smooks-resource-list
xmlns="http://www.milyn.org/xsd/smooks-1.1.xsd"
xmlns:edi="http://www.milyn.org/xsd/smooks/edi-1.1.xsd"
xmlns:jb="http://www.milyn.org/xsd/smooks/javabean-1.2.xsd"
xmlns:core="http://www.milyn.org/xsd/smooks/smooks-core-1.4.xsd">
<edi:reader mappingModel="/example/custom-order-mapping.xml" />
<jb:bean beanId="customer" class="example.model.CustomOrder" createOnElement="co">
<!-- Customer bindings... -->
<jb:value property="number" data="#/number" decoder="Integer"/>
<jb:value property="sender" data="#/sender" decoder="String"/>
<jb:value property="message" data="#/message" decoder="String"/>
<jb:value property="price" data="#/price" decoder="Integer"/>
</jb:bean>
</smooks-resource-list>
Main method -
--------------
Main smooksMain = new Main();
ExecutionContext executionContext = smooksMain.smooks.createExecutionContext();
org.milyn.payload.JavaResult result = smooksMain.runSmooksTransform(executionContext);
CustomOrder custOrder = (CustomOrder) result.getBean("customer");
// Need to get to edi data from java object custOrder
// Please help me - this part of code
I want to prepare edi data from java object. If any other api/framework apart from Smooks which will do the same, it will be fine for me.please let me know, Thanks.
I searched about it and get to know from smooks forum that to prepare edi data from java object, we have to use Edifact Java Compiler(EJC).
Above example is to prepare java object from edi data.
Pojo class have to implement EDIWritable and override the write method.Here is the changed Pojo class -
public class CustomOrder implements Serializable, EDIWritable{
private int number;
private IntegerDecoder numberDecoder;
private String sender;
private String message;
private int price;
private IntegerDecoder priceDecoder;
public CustomOrder() {
numberDecoder = new IntegerDecoder();
priceDecoder = new IntegerDecoder();
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public void setSender(String sender) {
this.sender = sender;
}
public String getSender() {
return sender;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public void write(Writer writer, Delimiters delimiters) throws IOException {
// TODO Auto-generated method stub
Writer nodeWriter = writer;
if(number != 0) {
nodeWriter.write(delimiters.escape(numberDecoder.encode(number)));
}
nodeWriter.write(delimiters.getField());
if(sender != null) {
nodeWriter.write(delimiters.escape(sender.toString()));
}
nodeWriter.write(delimiters.getField());
if(message != null) {
nodeWriter.write(delimiters.escape(message.toString()));
}
nodeWriter.write(delimiters.getField());
if(price != 0) {
nodeWriter.write(delimiters.escape(priceDecoder.encode(price)));
}
//nodeWriter.write(delimiters.getField());
writer.write(delimiters.getSegmentDelimiter());
writer.flush();
}
}
Next, we have to prepare the Factory of the pojo class -
CustomOrderFactory
public class CustomOrderFactory {
private Smooks smooks;
private Delimiters delimiters;
public static CustomOrderFactory getInstance() throws IOException, SAXException {
return new CustomOrderFactory();
}
public void addConfigurations(InputStream resourceConfigStream) throws SAXException, IOException {
smooks.addConfigurations(resourceConfigStream);
}
public void toEDI(CustomOrder instance, Writer writer) throws IOException {
instance.write(writer, delimiters);
}
private CustomOrderFactory() throws IOException, SAXException {
smooks = new Smooks(CustomOrderFactory.class.getResourceAsStream("smooks-config.xml"));
System.out.println("smooks is prepared");
try {
Edimap edimap = EDIConfigDigester.digestConfig(CustomOrderFactory.class.getResourceAsStream("custom-order-mapping.xml"));
System.out.println("ediMap is prepared");
delimiters = edimap.getDelimiters();
System.out.println("delimeter is prepared");
} catch(EDIConfigurationException e) {
IOException ioException = new IOException("Exception reading EDI Mapping model.");
ioException.initCause(e);
throw ioException;
}
}
}
Once CustomOrder object is ready, as shown above in Main class. We have to use this object to convert to edi data format. Here is the complete Main class -
Main class
----------
Main smooksMain = new Main();
ExecutionContext executionContext = smooksMain.smooks.createExecutionContext();
org.milyn.payload.JavaResult result = smooksMain.runSmooksTransform(executionContext);
CustomOrder custOrder = (CustomOrder) result.getBean("customer");
// Prepare edi data from java object custOrder
CustomOrderFactory customOrderFactory = CustomOrderFactory.getInstance();
OutputStream os = new FileOutputStream("createdEDIFile.edi");
customOrderFactory.toEDI(custOrder, new OutputStreamWriter(os));
System.out.println("Edi file is created from java object");
Thats it. Hope it would help. Thanks.
What is the easiest way to bind to View's (or any other Android control) weight? Because this property doesn't have a setter, I tried custom binding, but id doesn't seem to work:
public class ViewWeightCustomBinding : MvxAndroidTargetBinding
{
public ViewWeightCustomBinding(object target) : base(target)
{
}
public override Type TargetType
{
get { return typeof (int); }
}
protected override void SetValueImpl(object target, object value)
{
var realTarget = target as View;
if(target == null)
return;
ViewGroup.LayoutParams layoutParameters = realTarget.LayoutParameters;
realTarget.LayoutParameters = new LinearLayout.LayoutParams(layoutParameters.Width, layoutParameters.Height,
(int) value);
}
}
registration in setup:
protected override void FillTargetFactories(IMvxTargetBindingFactoryRegistry registry)
{
registry.RegisterFactory(new MvxSimplePropertyInfoTargetBindingFactory(typeof(ViewWeightCustomBinding), typeof(View), "ViewWeight"));
base.FillTargetFactories(registry);
}
And .axml
<View
android:layout_width="0dp"
android:layout_height="3dp"
android:background="#color/green_holo"
local:MvxBind="ViewWeight Id" />
I can see Waring in debug window:
[0:]
MvxBind:Warning: 5.20 Failed to create target binding for binding ViewWeight for Id
[0:] MvxBind:Warning: 5.20 Failed to create target binding for binding ViewWeight for Id
01-31 10:54:57.247 I/mono-stdout( 3795): MvxBind:Warning: 5.20 Failed to create target binding for binding ViewWeight for Id
MvxSimplePropertyInfoTargetBindingFactory can only be used for real C# properties.
For invented "pseudo" properties, you need to use a custom binding registration like that shown in the n=28 tutorial -
protected override void FillTargetFactories(Cirrious.MvvmCross.Binding.Bindings.Target.Construction.IMvxTargetBindingFactoryRegistry registry)
{
registry.RegisterCustomBindingFactory<BinaryEdit>(
"N28",
binary => new BinaryEditFooTargetBinding(binary) );
base.FillTargetFactories(registry);
}
https://github.com/MvvmCross/NPlus1DaysOfMvvmCross/blob/master/N-28-CustomBinding/CustomBinding.Droid/Setup.cs
Anyone knows how to develop an add-in for PowerDesigner? I was reading the document of PowerDesigner about how to create an ActiveX Add-in, it says "The ActiveX must implement a specific interface called IPDAddIn to become a PowerDesigner add-in.". But I don't know where the interface IPDAddIn is, and how to implement it ?
Here is the online document
I have this old example, which could give some ideas, even if not everything it up-to-date.
using PdAddInTypLib;
namespace MineSpace
{
[ComVisible(true)]
[Guid("A6FA0D26-77E8-4DD3-B27E-F4050C3D5188")]
public class Launcher : IPdAddIn {
// Main() manages the console or GUI interface
// the PdAddIn interface is managed by an instance of Launcher
[ComVisible(false)]
[STAThread]
public static void Main(String[] args) {
}
public Launcher() {
_app = null;
}
// IPdAddIn implementation
public void Initialize(Object anApplication) {
try {
_app = (PdCommon.Application)anApplication;
}
catch (Exception e) {
// process
}
}
public void Uninitialize() {
}
public String ProvideMenuItems(String aMenu, Object anObj) {
return "";
}
public int IsCommandSupported(String aMenu, Object anObj, String aCommand) {
return 0;
}
public void DoCommand(String aMenu, Object anObj, String aCommand) {
}
private PdCommon.Application _app;
}
}
with the corresponding part in the class declaration:
[HKEY_CLASSES_ROOT\MyPlugin.Launcher]
#="MyPlugin.Launcher"
[HKEY_CLASSES_ROOT\MyPlugin.Launcher\CLSID]
#="{13749EFC-1ADA-4451-8C47-FF0B545FF172}"
[HKEY_CLASSES_ROOT\CLSID\{13749EFC-1ADA-4451-8C47-FF0B545FF172}]
#="MyPlugin.Launcher"
[HKEY_CLASSES_ROOT\CLSID\{13749EFC-1ADA-4451-8C47-FF0B545FF172}\InprocServer32]
#="C:\windows\System32\mscoree.dll"
"ThreadingModel"="Both"
"Class"="MyPlugin.Launcher"
"Assembly"="MyPlugin, Version=1.0.1402.33688, Culture=neutral, PublicKeyToken=null"
"RuntimeVersion"="v1.0.3705"
[HKEY_CLASSES_ROOT\CLSID\{13749EFC-1ADA-4451-8C47-FF0B545FF172}\ProgId]
#="MyPlugin.Launcher"
[HKEY_CLASSES_ROOT\CLSID\{13749EFC-1ADA-4451-8C47-FF0B545FF172}\Implemented Categories\{62C8FE65-4EBB-45E7-B440-6E39B2CDBF29}]
And the corresponding code to declare the add-in in PowerDesigner. If the File value is present, PowerDesigner could call DllRegisterServer on it, if the component is not yet registered.
[HKEY_LOCAL_MACHINE\SOFTWARE\Sybase\PowerDesigner 10\Addins\MyPlugin Launcher]
"Enable"="No"
"Class"="MyPlugin.Launcher"
"Type"="ActiveX"
"File"="d:\\myplugin\\myplugin.exe"
Is it possible to instantiate a type, configured in UnityContainer, within the constructor of another type configured in UnityContainer? With my current solution, I'm getting a
ResolutionFailedException:
Resolution of the dependency failed, type = "Sample.IMyProcessor", name = "(none)".
Exception occurred while: while resolving.
Exception is: VerificationException - Operation could destabilize the runtime.
The Problem is that my second class (FileLoader) has an argument which should be evaluated in the first constructor:
The Constructor of the MyProcessor class:
public class MyProcessor : IMyProcessor
{
private readonly IFileLoader loader;
private readonly IRepository repository;
public MyProcessor(IRepository repository, string environment, Func<SysConfig, IFileLoader> loaderFactory)
{
this.repository = repository;
SysConfig config = repository.GetConfig(environment);
loader = loaderFactory(config);
}
public void DoWork()
{
loader.Process();
}
}
And here the Main function with the UnityContainer config:
public static void Run()
{
var unityContainer = new UnityContainer()
.RegisterType<IRepository, MyRepository>()
.RegisterType<IFileLoader, FileLoader>()
.RegisterType<IMyProcessor, MyProcessor>(new InjectionConstructor(typeof(IRepository), "DEV", typeof(Func<SysConfig, IFileLoader>)));
//Tests
var x = unityContainer.Resolve<IRepository>(); //--> OK
var y = unityContainer.Resolve<IFileLoader>(); //--> OK
var processor = unityContainer.Resolve<IMyProcessor>();
//--> ResolutionFailedException: "Operation could destabilize the runtime."
processor.DoWork();
}
And the FileLoader class:
public class FileLoader : IFileLoader
{
private readonly SysConfig sysConfig;
public FileLoader(SysConfig sysConfig, IRepository repository)
{
this.sysConfig = sysConfig;
}
public void Process()
{
//some sample implementation
if (sysConfig.IsProduction)
Console.WriteLine("Production Environement");
else
Console.WriteLine("Test Environment");
}
}
I assume the Problem is related to the Func which is passed to the MyProcessor class. Is there another way to pass the loaderFactory to the MyProcessor class?
Thanks!
The issue is that Unity automatic factories only support Func<T> and not any other of the Func generics.
You could register the Func you want with Unity and then it will be resolved:
Func<SysConfig, IFileLoader> func = config => container.Resolve<IFileLoader>();
container.RegisterType<Func<SysConfig, IFileLoader>>(new InjectionFactory(c => func));
var processor = container.Resolve<IMyProcessor>();
There are some other solutions out there such as this: Unity's automatic abstract factory
I'm trying to use the mvc-mini-profiler in my mvc application. I created a wrapper for my context and Castle Windsor creates the instance. However, I get the error "The space 'SSpace' has no associated collection". The edmx is in assembly A, DigidosEntities in assembly B and this is in assembly C. Any idea what can be the problem? I got the latest version of the profiler.
public interface IDataStore : IDisposable
{
int SaveChanges(int personId);
IObjectSet<TEntity> CreateObjectSet<TEntity>() where TEntity : class;
}
public class ProfiledDigidosEntities : IDataStore, IDisposable
{
private DigidosEntities _context = null;
public ProfiledDigidosEntities()
{
var connectionString = ConfigurationManager.ConnectionStrings["DigidosEntities"].ConnectionString;
var connection = new EntityConnection(connectionString);
var conn = ProfiledDbConnection.Get(connection);
_context = ObjectContextUtils.CreateObjectContext<DigidosEntities>(conn); /* Error: The space 'SSpace' has no associated collection */
}
public void Dispose()
{
if (_context != null)
_context.Dispose();
}
public int SaveChanges(int personId)
{
return _context.SaveChanges(personId);
}
public IObjectSet<TEntity> CreateObjectSet<TEntity>() where TEntity : class
{
return _context.CreateObjectSet<TEntity>();
}
}
Ok, here was my problem: The profiler wants a workspace to make a new profiled connection, the workspace is created through this method (in ObjectContextUtils.cs):
static MetadataCache()
{
workspace = new System.Data.Metadata.Edm.MetadataWorkspace(
new string[] { "res://*/" },
new Assembly[] { typeof(U).Assembly });
}
As you can see it will search in assembly of the type you want to create. Since in my case the type of the model was not in the same assembly, the creation of the workspace failed. Moving the DigidosEntities to the same assembly as the edmx fixed it.