Cannot use some methods in F# from C# class - f#

I am having hard time figuring out why I cannot see/use some methods from C# type in F# function.
public class KafkaBus : IKafkaBus
{
// this works and can be used
public IObservable<Shared.Model.Message<T>> CreateConsumer<T>(string topic, Func<byte[], T> deserialize = null)
// those cannot be found
public Task<Confluent.Kafka.CommittedOffsets> CommitAsync<T>(Message<T> message)
public Task<Confluent.Kafka.CommittedOffsets> CommitAsync(string topic, int partition, long offSet)
}
If I check object browser in F# solution under references, I see those methods listed:
I am using VS 2017 15.3, .NET Framework 4.6.1, library is referenced via nuget.

So in the end reopening project, rebuilding or simply restarting a machine helps the cause... Seems like a bug in Visual Studio. Got help on MSDN forums

Related

Switching from Rhino to Nashorn

I have a Java 7 project which makes a lot of use of Javascript for scripting various features. Until now I was using Rhino as script engine. I would now like to move to Java 8, which also means that I will replace Rhino by Nashorn.
How compatible is Nashorn to Rhino? Can I use it as a drop-in replacement, or can I expect that some of my scripts will not work anymore and will need to be ported to the new engine? Are there any commonly-used features of Rhino which are not supported by Nashorn?
One problem is that Nashorn can no longer by default import whole Java packages into the global scope by using importPackage(com.organization.project.package);
There is, however, a simple workaround: By adding this line to your script, you can enable the old behavior of Rhino:
load("nashorn:mozilla_compat.js");
Another problem I ran into is that certain type-conversions when passing data between java and javascript work differently. For example, the object which arrives when you pass a Javascript array to Java can no longer be cast to List, but it can be cast to a Map<String, Object>. As a workaround you can convert the Javascript array to a Java List in the Javascript code using Java.to(array, Java.type("java.util.List"))
To use the importClass method on JDK 8, we need to add the following command:
load("nashorn:mozilla_compat.js");
However, this change affect the execution on JDK 7 (JDK does not gives support to load method).
To maintain the compatibility for both SDKs, I solved this problem adding try/catch clause:
try{
load("nashorn:mozilla_compat.js");
}catch(e){
}
Nashorn can not access an inner class when that inner class is declared private, which Rhino was able to do:
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class Test {
public static void main(String[] args) {
Test test = new Test();
test.run();
}
public void run() {
ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName("JavaScript");
Inner inner = new Inner();
engine.put("inner", inner);
try {
engine.eval("function run(inner){inner.foo(\"test\");} run(inner);");
} catch (ScriptException e) {
e.printStackTrace();
}
}
private class Inner {
public void foo(String msg) {
System.out.println(msg);
}
}
}
Under Java8 this code throws following exception:
javax.script.ScriptException: TypeError: kz.test.Test$Inner#117cd4b has no such function "foo" in <eval> at line number 1
at jdk.nashorn.api.scripting.NashornScriptEngine.throwAsScriptException(NashornScriptEngine.java:564)
at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:548)
I noticed that Rhino didn't have a problem with a function called 'in()' (although 'in' is a reserved JavaScript keyword).
Nashorn however raise an error.
Nashorn cannot call static methods on instances! Rhino did this, therefore we had to backport Rhino to Java 8 (Here's a short summary: http://andreas.haufler.info/2015/04/using-rhino-with-java-8.html)
Nashorn on Java8 does not support AST. So if you have Java code that inspects the JS source tree using Rhino's AST mechanism , you may have to rewrite it (using regex maybe) once you port your code to use Nashorn.
I am talking about this API https://mozilla.github.io/rhino/javadoc/org/mozilla/javascript/ast/AstNode.html
Nashorn on Java9 supports AST though.
One feature that is in Rhino and not Nashorn: exposing static members through instances.
From http://nashorn-dev.openjdk.java.narkive.com/n0jtdHc9/bug-report-can-t-call-static-methods-on-a-java-class-instance : "
My conviction is that exposing static members through instances is a
sloppy mashing together of otherwise separate namespaces, hence I
chose not to enable it.
I think this is deeply wrong. As long as we have to use two different constructs to access the same java object and use package declarations unnecessarily in javascript, code becomes harder to read and write because cognitive load increases. I will rather stick to Rhino then.
I have not found a workaround for this obvious "design bug" yet.

MvvmCross vNext: ObservableColletion is defined in an assembly that is not referenced

I have got my PCL model to build now, which took a bit of time making plug-ins, however now in my Android UI project I get two errors when building it.
First error is:
The type 'System.Collections.ObjectModel.ObservableCollection`1<T0>' is defined in an assembly that is not referenced.
You must add a reference to assembly 'System.Windows, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e,
Retargetable=Yes'. C:\ENM\Main\src\prod\Mobile\Stakeholder\UI.Android.vNext\Views\LocationsMapView.cs 40 32 UI.Android.vNext
The second error is:
foreach statement cannot operate on variables of type
'System.Collections.ObjectModel.ObservableCollection`1<BK.EMS.Stakeholder.Model.ViewModels.LocationViewModel>'
because 'System.Collections.ObjectModel.ObservableCollection`1<BK.EMS.Stakeholder.Model.ViewModels.LocationViewModel>'
does not contain a public definition for 'GetEnumerator'
C:\ENM\Main\src\prod\Mobile\Stakeholder\UI.Android.vNext\Views\LocationsMapView.cs 40 32 UI.Android.vNext
I have referenced the System.Windows assembly from the System.Windows.Droid project, which is supposed to forward ObservableCollection<>.
The lines where the error occurs:
private void AddLocationOverlays()
{
if (_itemizedOverlay.Size() > 0) _itemizedOverlay.ClearOverlayItems();
RunOnUiThread(() =>
{
foreach (var location in ViewModel.Locations)
{
_itemizedOverlay.AddOverlayItem(location);
}
_mapView.Invalidate();
});
}
The Locations property in my ViewModel looks like this:
public ObservableCollection<LocationViewModel> Locations
{
get { return _locations; }
set
{
_locations = value;
RaisePropertyChanged(() => Locations);
}
}
Nothing too complicated and works fine in the non-PCL models...
So how do I get around and fix this?
We now have a solution to this problem - see fix from Daniel Plaisted in Portable Class Library strong assembly reference problems in MonoTouch/MonoDroid
This fix is checked in at https://github.com/slodge/MvvmCross/commit/f6a88048467838e5ac5ca687744dc0b2d1958aa8
Update : See other answer. It appears we now have a solution to this problem!
I believe this is linked to this problem - Portable Class Library strong assembly reference problems in MonoTouch/MonoDroid
Which is linked to: https://github.com/slodge/MvvmCross/issues/41
This is raised with Xamarin as a bug: https://bugzilla.xamarin.com/show_bug.cgi?id=8035 and
I'm afraid I don't understand the recommended Strong Signing solutions right now.
Please upvote the bug report to alert the Microsoft PCL and Xamarin teams about this. The MS and Xamarin teams are talking to each other on this (albeit through me!), and I am hopeful we will find a way for either Microsoft or Xamarin to ship some signed DLLs.
In the meantime, some possible workarounds are:
Use IEnumerable access instead of ObservableCollection - the collection can still be an ObservableCollection instance, just don't reference it as an ObservableCollection in the UI code.
Try putting your iterating code in a class library rather than in an application project - bizarre as it feels, the compiler seems perfectly happy building the same code when its in a library rather than in an application
Try building in MonoDevelop with the Mono compiler - this doesn't seem to have the same strong name reference checks.
Looking at your sample code I would just try:
private ObservableCollection<LocationViewModel> _locations;
public IEnumerable<LocationViewModel> Locations
{
get { return _locations; }
set
{
if (value != null && !(value is ObservableCollection<LocationViewModel>)
{
throw new Exception("You must Set an ObservableCollection");
}
_locations = (ObservableCollection<LocationViewModel>)value;
RaisePropertyChanged(() => Locations);
}
}
then AddLocationOverlays could stay the same.
The only problem with this would be if you then wanted to bind to INotifyCollectionChanged on this collection - but I think you can find a way around this too if needed - e.g. you could somehow expose another INotifyCollectionChanged hook, or you could try using a hack involving an intermediary class library.
I accept that for now these are workarounds not solutions :/

Resolving a type without registering first - prism 4 and Untiy

First of all I would like to remark I am new with the concept of prism, DI and containers. I am looking on one of the code samples provided with the Prism Library:
The code simply injects a view with the "Hello World" string (in a TextBlock element) to a region in the shell.
When the application starts-up, it creates a new BootStrapper instance, which creates and initializes the shell:
public class Bootstrapper : UnityBootstrapper
{
protected override DependencyObject CreateShell()
{
return Container.Resolve<Shell>();
}
protected override void InitializeShell()
{
base.InitializeShell();
Application.Current.RootVisual = (UIElement)this.Shell;
}
protected override void ConfigureModuleCatalog()
{
base.ConfigureModuleCatalog();
ModuleCatalog moduleCatalog = (ModuleCatalog)this.ModuleCatalog;
moduleCatalog.AddModule(typeof(HelloWorldModule.HelloWorldModule));
}
}
My question refers to the method CreateShell(). I couldnt find nowhere in the supplied code (including not in a configuration file or any xaml file...) where do they register the type Shell, and even if it was registered - the supplies Shell class doesnt implement any interface... what is the meaning of resolving a specific type?
the Shell implementation:
public partial class Shell : UserControl
{
public Shell()
{
InitializeComponent();
}
}
This looks like a magic to me, so I tried to create my own type (MyType) and resolve it the same way:
Container.Resolve<MyType>();
By setting a breakepoint inside MyType constructor, I saw that it DID resolved MyType. Can somebody please explain to me how does it work?
These couple of threads should answer your question:
http://compositewpf.codeplex.com/Thread/View.aspx?ThreadId=230051
Does unity just make clasess with out needing anything registered?
Additionally, if you are eager to get more detail into how Unity can do this, simple download Unity 2.0 and open the source code that is provided with the installer.
I hope this helps.
Thanks,
Damian
You do not need to register a type you want to resolve. You need to register the dependencies of a type, that you want to resolve. In this case, the Shell doesn't need any dependencies, so you can resolve it simply. But for an example (not really), if your shell getting an interface IService as a parameter, then you must register IService, before you resolve Shell.
Otherwise you will get Dependency Resolution Failed Exception. In Prism 4.1 it will be swallowed silently due to TryResolve.

What do I need to know to create a source code editor?

Say I want to create a source code editor for ocaml programming language, where do I start? I am looking to create an editor for the Windows platform as a hobby project. My primary skill is in web development. I have developed windows apps long time ago. I have no clue how it is done with todays available tools. I have visual studio 2008 and C# is my language of choice.
You need to know:
OCAML Syntax, Features, Keywords, Functions etc...
C# as this is your native language I guess
You need to know what features you wanna implement
...if it's using a GUI or just from a terminal like nano/vim
how syntax highlighting works
how to open and save files
how autocompletion works
etc..
You might want to take look at some open source editors like dev-c++ or gedit
Also, as you in person are more web-devvy, you might want to start creating one which runs in a web browser. This is often easier and helps you understand the basics of creating a code editor. Later you can always write one for desktops.
If you are most comfortable in Visual Studio, then you can use the Visual Studio Shell to create your own IDE based on that foundation.
Here is a podcast that gives a good overview:
http://www.code-magazine.com/codecast/index.aspx?messageid=32b9401a-140d-4acb-95bb-6accd3a3dafc
Also, as a reference, the IronPython Studio was created using the Visual Studio 2008 Shell:
http://ironpythonstudio.codeplex.com/
Browsing that source code should give you a good starting point.
a lighter-weight alternative is to use the RichEdit control
example:
http://www.codeproject.com/Messages/3401956/NET-Richedit-Control.aspx
// http://www.codeproject.com/Messages/3401956/NET-Richedit-Control.aspx
using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace RichEditor
{
public class RichTextBoxEx : RichTextBox
{
IntPtr mHandle = IntPtr.Zero;
protected override CreateParams CreateParams
{
get
{
// Prevent module being loaded multiple times.
if (this.mHandle == IntPtr.Zero)
{
// load the library to obtain an instance of the RichEdit50 class.
this.mHandle = LoadLibrary("msftedit.dll");
}
// If module loaded, reset ClassName.
if (this.mHandle != IntPtr.Zero)
{
CreateParams cParams = base.CreateParams;
// Check Unicode or ANSI system and set appropriate ClassName.
if (Marshal.SystemDefaultCharSize == 1)
{
cParams.ClassName = "RichEdit50A";
}
else
{
cParams.ClassName = "RichEdit50W";
}
return cParams;
}
else // Module wasnt loaded, return default .NET RichEdit20 CreateParams.
{
return base.CreateParams;
}
}
}
~RichTextBoxEx()
{
//Free loaded Library.
if (mHandle != IntPtr.Zero)
{
FreeLibrary(mHandle);
}
}
[DllImport("kernel32.dll", SetLastError = true)]
private static extern IntPtr LoadLibrary(String lpFileName);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool FreeLibrary(IntPtr hModule);
}
}
You could use Scintilla. It has syntax highlighting and some other features. Also, it has a .NET Version available here.
Another good tool is Alsing Syntax Box:
Powerful Syntax Highlight Windows
Forms Control for the Microsoft.NET
Platform. Written in 100% managed C#.
Supports syntax highlighting and code
folding for just about any programming
language.
With Alsing Syntax Box, you can define a syntax file (just like this one for C#) and later have a intellisense like feature.
You can start with one of them for your editor.

Error "More than one matching bindings are available" when using Ninject.Web.Mvc 2.0 and ASP.NET MVC 1.0

Recently I've switched to Ninject 2.0 release and started getting the following error:
Error occured: Error activating SomeController
More than one matching bindings are available.
Activation path:
1) Request for SomeController
Suggestions:
1) Ensure that you have defined a binding for SomeController only once.
However, I'm unable to find certain reproduction path. Sometimes it occurs, sometimes it does not.
I'm using NinjectHttpApplication for automatic controllers injection. Controllers are defined in separate assembly:
public class App : NinjectHttpApplication
{
protected override IKernel CreateKernel()
{
INinjectModule[] modules = new INinjectModule[] {
new MiscModule(),
new ProvidersModule(),
new RepositoryModule(),
new ServiceModule()
};
return new StandardKernel(modules);
}
protected override void OnApplicationStarted()
{
RegisterRoutes(RouteTable.Routes);
RegisterAllControllersIn("Sample.Mvc");
base.OnApplicationStarted();
}
/* ............. */
}
Maybe someone is familiar with this error.
Any advice?
I finally figured this issue out recently. Apparently, the NinjectHttpApplication.RegisterAllControllersIn() function doesn't do all of the proper bindings needed. It binds your concrete controller implementations to IController requests. For example, if you have a controller class called SampleMvcController, which inherits from System.Web.Mvc.Controller. It would do the following named binding during application start:
kernel.Bind<IController>().To(SampleMvcController).InTransientScope().Named("SampleMvc");
But when debugging the NinjectControllerFactory, I find that request are being made for the Ninject Kernel to return an object for the class "SampleMvcController", not for a concrete implementation of IController, using the named binding of "SampleMvc".
Because of this, when the first web request that involves the SampleMvcController is made, it creates a binding of SampleMvcController to itself. This is not thread safe though. So if you have several web requests being made at once, the bindings can potentially happen more than once, and now you are left with this error for having multiple bindings for the SampleMvcController.
You can verify this by quickly refreshing an MVC URL, right after causing your web application to restart.
The fix:
The simplest way to fix this issue is to create a new NinjectModule for your controller bindings, and to load this module during application start. Within this module, you self bind each of your defined controllers, like so:
class ControllerModule : StandardModule {
public override Load() {
Bind<SampleMvcController>().ToSelf();
Bind<AnotherMvcController>().ToSelf();
}
}
But if you don't mind changing the Ninject source code, you can modify the RegisterAllControllersIn() function to self bind each controller it comes across.
I have been dealing with this problem for months. I tried so many options but was unable to come to a solution. I knew that it was a threading problem because it would only occur when there was a heavy load on my site. Just recently a bug was reported and fixed in the ninject source code that solves this problem.
Here is a reference to the issue. It was fixed in build 2.1.0.70 of the Ninject source. The key change was in KernelBase.cs by removing the line
context.Plan = planner.GetPlan(service);
and replacing it with
lock (planner)
{
context.Plan = planner.GetPlan(service);
}
To use this new build with MVC you will need to get the latest build of Ninject then get the latest build of ninject.web.mvc. Build ninject.web.mvc with the new Ninject build.
I have been using this new build for about a week with a heavy load and no problems. That is the longest it has gone without a problem so I would consider this to be a solution.
Are you sure you really are creating a single completely new Kernel from scratch in your OnApplicationStarted every time it's invoked ? If you're not and you're actually creating it once but potentially running the registration bit twice. Remember that you're not guaranteed to only ever have one App class instantiated ever within a given AppDomain.
My answer was a bit more obvious.
I had declared the binding for one of my controllers more than once during refactor of my code.
I added this to my global.ascx.cs file:
public void RegisterAllControllersInFix(Assembly assembly)
{
RegisterAllControllersInFix(assembly, GetControllerName);
}
public void RegisterAllControllersInFix(Assembly assembly, Func<Type, string> namingConvention)
{
foreach (Type type in assembly.GetExportedTypes().Where(IsController))
Kernel.Bind(type).ToSelf();
}
private static bool IsController(Type type)
{
return typeof(IController).IsAssignableFrom(type) && type.IsPublic && !type.IsAbstract && !type.IsInterface;
}
private static string GetControllerName(Type type)
{
string name = type.Name.ToLowerInvariant();
if (name.EndsWith("controller"))
name = name.Substring(0, name.IndexOf("controller"));
return name;
}
Then called it from my OnApplicationStarted() method as follows:
RegisterAllControllersIn(Assembly.GetExecutingAssembly());
RegisterAllControllersInFix(Assembly.GetExecutingAssembly());
Difficult to know whether this fixed it though because it's so intermittent.

Resources