This commit is contained in:
David Britch 2020-12-08 10:00:32 +00:00
Родитель 6c47645a17
Коммит d3900c4aca
74 изменённых файлов: 3271 добавлений и 0 удалений

Просмотреть файл

@ -0,0 +1,294 @@
---
title: "Callbacks on Android"
ms.prod: xamarin
ms.assetid: F3A7A4E6-41FE-4F12-949C-96090815C5D6
author: davidortinau
ms.author: daortin
ms.date: 11/14/2017
---
# Callbacks on Android
Calling to Java from C# is somewhat a *risky business*. That is to say there is a *pattern* for callbacks from C# to Java; however, it is more complicated than we would like.
We'll cover the three options for doing callbacks that make the most sense for Java:
- Abstract classes
- Interfaces
- Virtual methods
## Abstract Classes
This is the easiest route for callbacks, so I would recommend using `abstract` if you are just trying to get a callback working in the simplest form.
Let's start with a C# class we would like Java to implement:
```csharp
[Register("mono.embeddinator.android.AbstractClass")]
public abstract class AbstractClass : Java.Lang.Object
{
public AbstractClass() { }
public AbstractClass(IntPtr handle, JniHandleOwnership transfer) : base(handle, transfer) { }
[Export("getText")]
public abstract string GetText();
}
```
Here are the details to make this work:
- `[Register]` generates a nice package name in Java--you will get an auto-generated package name without it.
- Subclassing `Java.Lang.Object` signals to .NET Embedding to run the class through Xamarin.Android's Java generator.
- Empty constructor: is what you will want to use from Java code.
- `(IntPtr, JniHandleOwnership)` constructor: is what Xamarin.Android will use for creating the C#-equivalent of Java objects.
- `[Export]` signals Xamarin.Android to expose the method to Java. We can also change the method name, since the Java world likes to use lower case methods.
Next let's make a C# method to test the scenario:
```csharp
[Register("mono.embeddinator.android.JavaCallbacks")]
public class JavaCallbacks : Java.Lang.Object
{
[Export("abstractCallback")]
public static string AbstractCallback(AbstractClass callback)
{
return callback.GetText();
}
}
```
`JavaCallbacks` could be any class to test this, as long as it is a `Java.Lang.Object`.
Now, run .NET Embedding on your .NET assembly to generate an AAR. See the [Getting Started guide](~/tools/dotnet-embedding/get-started/java/android.md) for details.
After importing the AAR file into Android Studio, let's write a unit test:
```java
@Test
public void abstractCallback() throws Throwable {
AbstractClass callback = new AbstractClass() {
@Override
public String getText() {
return "Java";
}
};
assertEquals("Java", callback.getText());
assertEquals("Java", JavaCallbacks.abstractCallback(callback));
}
```
So we:
- Implemented the `AbstractClass` in Java with an anonymous type
- Made sure our instance returns `"Java"` from Java
- Made sure our instance returns `"Java"` from C#
- Added `throws Throwable`, since C# constructors are currently marked with `throws`
If we ran this unit test as-is, it would fail with an error such as:
```csharp
System.NotSupportedException: Unable to find Invoker for type 'Android.AbstractClass'. Was it linked away?
```
What is missing here is an `Invoker` type. This is a subclass of `AbstractClass` that forwards C# calls to Java. If a Java object enters the C# world and the equivalent C# type is abstract, then Xamarin.Android automatically looks for a C# type with the suffix `Invoker` for use within C# code.
Xamarin.Android uses this `Invoker` pattern for Java binding projects among other things.
Here is our implementation of `AbstractClassInvoker`:
```csharp
class AbstractClassInvoker : AbstractClass
{
IntPtr class_ref, id_gettext;
public AbstractClassInvoker(IntPtr handle, JniHandleOwnership transfer) : base(handle, transfer)
{
IntPtr lref = JNIEnv.GetObjectClass(Handle);
class_ref = JNIEnv.NewGlobalRef(lref);
JNIEnv.DeleteLocalRef(lref);
}
protected override Type ThresholdType
{
get { return typeof(AbstractClassInvoker); }
}
protected override IntPtr ThresholdClass
{
get { return class_ref; }
}
public override string GetText()
{
if (id_gettext == IntPtr.Zero)
id_gettext = JNIEnv.GetMethodID(class_ref, "getText", "()Ljava/lang/String;");
IntPtr lref = JNIEnv.CallObjectMethod(Handle, id_gettext);
return GetObject<Java.Lang.String>(lref, JniHandleOwnership.TransferLocalRef)?.ToString();
}
protected override void Dispose(bool disposing)
{
if (class_ref != IntPtr.Zero)
JNIEnv.DeleteGlobalRef(class_ref);
class_ref = IntPtr.Zero;
base.Dispose(disposing);
}
}
```
There is quite a bit going on here, we:
- Added a class with the suffix `Invoker` that subclasses `AbstractClass`
- Added `class_ref` to hold the JNI reference to the Java class that subclasses our C# class
- Added `id_gettext` to hold the JNI reference to the Java `getText` method
- Included a `(IntPtr, JniHandleOwnership)` constructor
- Implemented `ThresholdType` and `ThresholdClass` as a requirement for Xamarin.Android to know details about the `Invoker`
- `GetText` needed to lookup the Java `getText` method with the appropriate JNI signature and call it
- `Dispose` is just needed to clear the reference to `class_ref`
After adding this class and generating a new AAR, our unit test passes. As you can see this pattern for callbacks is not *ideal*, but doable.
For details on Java interop, see the amazing [Xamarin.Android documentation](~/android/platform/java-integration/working-with-jni.md) on this subject.
## Interfaces
Interfaces are much the same as abstract classes, except for one detail: Xamarin.Android does not generate Java for them. This is because before .NET Embedding, there are not many scenarios where Java would implement a C# interface.
Let's say we have the following C# interface:
```csharp
[Register("mono.embeddinator.android.IJavaCallback")]
public interface IJavaCallback : IJavaObject
{
[Export("send")]
void Send(string text);
}
```
`IJavaObject` signals to .NET Embedding that this is a Xamarin.Android interface, but otherwise this is exactly the same as an `abstract` class.
Since Xamarin.Android will not currently generate the Java code for this interface, add the following Java to your C# project:
```java
package mono.embeddinator.android;
public interface IJavaCallback {
void send(String text);
}
```
You can place the file anywhere, but make sure to set its build action to `AndroidJavaSource`. This will signal .NET Embedding to copy it to the proper directory to get compiled into your AAR file.
Next, the `Invoker` implementation will be quite the same:
```csharp
class IJavaCallbackInvoker : Java.Lang.Object, IJavaCallback
{
IntPtr class_ref, id_send;
public IJavaCallbackInvoker(IntPtr handle, JniHandleOwnership transfer) : base(handle, transfer)
{
IntPtr lref = JNIEnv.GetObjectClass(Handle);
class_ref = JNIEnv.NewGlobalRef(lref);
JNIEnv.DeleteLocalRef(lref);
}
protected override Type ThresholdType
{
get { return typeof(IJavaCallbackInvoker); }
}
protected override IntPtr ThresholdClass
{
get { return class_ref; }
}
public void Send(string text)
{
if (id_send == IntPtr.Zero)
id_send = JNIEnv.GetMethodID(class_ref, "send", "(Ljava/lang/String;)V");
JNIEnv.CallVoidMethod(Handle, id_send, new JValue(new Java.Lang.String(text)));
}
protected override void Dispose(bool disposing)
{
if (class_ref != IntPtr.Zero)
JNIEnv.DeleteGlobalRef(class_ref);
class_ref = IntPtr.Zero;
base.Dispose(disposing);
}
}
```
After generating an AAR file, in Android Studio we could write the following passing unit test:
```java
class ConcreteCallback implements IJavaCallback {
public String text;
@Override
public void send(String text) {
this.text = text;
}
}
@Test
public void interfaceCallback() {
ConcreteCallback callback = new ConcreteCallback();
JavaCallbacks.interfaceCallback(callback, "Java");
assertEquals("Java", callback.text);
}
```
## Virtual Methods
Overriding a `virtual` in Java is possible, but not a great experience.
Let's assume you have the following C# class:
```csharp
[Register("mono.embeddinator.android.VirtualClass")]
public class VirtualClass : Java.Lang.Object
{
public VirtualClass() { }
public VirtualClass(IntPtr handle, JniHandleOwnership transfer) : base(handle, transfer) { }
[Export("getText")]
public virtual string GetText() { return "C#"; }
}
```
If you followed the `abstract` class example above, it would work except for one detail: _Xamarin.Android won't lookup the `Invoker`_.
To fix this, modify the C# class to be `abstract`:
```csharp
public abstract class VirtualClass : Java.Lang.Object
```
This is not ideal, but it gets this scenario working. Xamarin.Android will pick up the `VirtualClassInvoker` and Java can use `@Override` on the method.
## Callbacks in the Future
There are a couple of things we could to do improve these scenarios:
1. `throws Throwable` on C# constructors is fixed on this [PR](https://github.com/xamarin/java.interop/pull/170).
1. Make the Java generator in Xamarin.Android support interfaces.
- This removes the need for adding Java source file with a build action of `AndroidJavaSource`.
1. Make a way for Xamarin.Android to load an `Invoker` for virtual classes.
- This removes the need to mark the class in our `virtual` example `abstract`.
1. Generate `Invoker` classes for .NET Embedding automatically
- This is going to be complicated, but doable. Xamarin.Android is already doing something similar to this for Java binding projects.
There is a lot of work to be done here, but these enhancements to .NET Embedding are possible.
## Further Reading
- [Getting Started on Android](~/tools/dotnet-embedding/get-started/java/android.md)
- [Preliminary Android Research](~/tools/dotnet-embedding/android/index.md)
- [.NET Embedding Limitations](~/tools/dotnet-embedding/limitations.md)
- [Error codes and descriptions](~/tools/dotnet-embedding/errors.md)

Просмотреть файл

@ -0,0 +1,116 @@
---
title: ".NET Embedding on Android"
ms.prod: xamarin
ms.assetid: EB2F967A-6D95-4448-994B-6D5C7BFAC2C7
author: davidortinau
ms.author: daortin
ms.date: 06/15/2018
---
# .NET Embedding on Android
In some cases, you may want to add a Xamarin .NET library to an
existing native Android project. To do this, you can use the
[Embeddinator-4000](https://www.nuget.org/packages/Embeddinator-4000/)
tool to turn your .NET library into a native library that can be
incorporated into a native Java-based Android app.
# [Visual Studio](#tab/windows)
## Xamarin.Android Requirements
For Xamarin.Android to work with .NET Embedding, you need the following:
- **Xamarin.Android** &ndash;
[Xamarin.Android 7.5](https://visualstudio.microsoft.com/xamarin/)
or later must be installed.
- **Android Studio** &ndash;
[Android Studio 3.x](https://developer.android.com/studio/) or
later must be installed.
- **Java Developer Kit** &ndash;
[Java 1.8](https://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html)
or later must be installed.
## Using Embeddinator-4000
To consume a .NET library in a native Android project, use the
following steps:
1. Create a C# Android Library project.
2. Install [Embeddinator-4000](https://www.nuget.org/packages/Embeddinator-4000/).
3. Locate **Embeddinator-4000.exe** and add it to your **PATH**. For example:
```cmd
set PATH=%PATH%;C:\Users\USERNAME\.nuget\packages\embeddinator-4000\0.4.0\tools
```
4. Run Embeddinator-4000 on the library assembly. For example:
```cmd
Embeddinator-4000.exe -gen=Java -out=foo Xamarin.Foo.dll
```
5. Use the generated AAR file in a Java project in Android Studio.
# [Visual Studio for Mac](#tab/macos)
## Xamarin.Android Requirements
For Xamarin.Android to work with .NET Embedding, you need the following:
- **Xamarin.Android** &ndash;
[Xamarin.Android 7.5](https://visualstudio.microsoft.com/xamarin/)
or later must be installed.
- **Android Studio** &ndash;
[Android Studio 3.x](https://developer.android.com/studio/) or
later must be installed.
- **Java Developer Kit** &ndash;
[Java 1.8](https://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html)
or later must be installed.
- **Mono** &ndash;
[Mono 5.0](https://www.mono-project.com/download/) or later must be
installed (mono is installed with Visual Studio for Mac).
## Using Embeddinator-4000
To consume a .NET library in a native Android project, use the following steps:
1. Create a C# Android Library project.
2. Install [Embeddinator-4000](https://www.nuget.org/packages/Embeddinator-4000/).
3. Locate **Embeddinator-4000.exe** and add **mono** to your path. For example:
```bash
export TOOLS=~/.nuget/packages/embeddinator-4000/0.4.0/tools
export PATH=$PATH:/Library/Frameworks/Mono.framework/Commands
```
4. Run Embeddinator-4000 on the library assembly. For example:
```bash
mono $TOOLS/Embeddinator-4000.exe -gen=Java -out=foo Xamarin.Foo.dll
```
5. Use the generated AAR file in a Java project in Android Studio.
-----
Usage and command line options are described in the
[Embeddinator-4000](https://github.com/mono/Embeddinator-4000/blob/master/Usage.md#java--c)
documentation.
## Callbacks
Learn about [making calls between C# and Java](callbacks.md).
## Samples
- [Weather sample app](https://github.com/jamesmontemagno/embeddinator-weather)

Просмотреть файл

@ -0,0 +1,299 @@
---
title: ".NET Embedding errors"
description: "This document describes errors generated by .NET Embedding. Errors are listed by code and given a description to assist with troubleshooting."
ms.prod: xamarin
ms.assetid: 932C3F0C-D968-42D1-BB14-D97C73361983
author: davidortinau
ms.author: daortin
ms.date: 04/11/2018
---
# .NET Embedding errors
## EM0xxx: Binding error messages
E.g. parameters, environment
<!-- 0xxx: the generator itself, e.g. parameters, environment -->
<a name="EM0000"></a>
### EM0000: Unexpected error - Please fill a bug report at https://github.com/mono/Embeddinator-4000/issues
An unexpected error condition occurred. Please [file an issue](https://github.com/mono/Embeddinator-4000/issues) with as much information as possible, including:
* Full build logs with maximum verbosity
* A minimal test case that reproduce the error
* All version information
The easiest way to get exact version information is to use the **Xamarin Studio** menu, **About Xamarin Studio** item, **Show Details** button and then copy/paste the version information (you can use the **Copy Information** button).
<a name="EM0001"></a>
### EM0001: Could not create Output directory `X`
The directory name specified by `-o=DIR` does not exist and could not be created. It might be an invalid name for the file system.
<a name="EM0002"></a>
### EM0002: Option `X` is not supported
The tool does not support the option `X`. It is possible that another version of the tool supports it or the `X` option does not apply in this environment.
<a name="EM0003"></a>
### EM0003: The platform `X` is not valid.
The tool does not support the platform `X`. It is possible that another version of the tool supports it or the `X` platform does not apply in this environment.
<a name="EM0004"></a>
### EM0004: The target `X` is not valid.
The tool does not support the target `X`. It is possible that another version of the tool supports it or the `X` target does not apply in this environment.
<a name="EM0005"></a>
### EM0005: The compilation target `X` is not valid.
The tool does not support the compilation target `X`. It is possible that another version of the tool supports it or the `X` compilation target does not apply in this environment.
<a name="EM0006"></a>
### EM0006: Could not find the Xcode location.
The tool could not find the currently selected Xcode location using the `xcode-select -p` command. Please verify that you can successfully run this command and it returns the correct Xcode location.
<a name="EM0007"></a>
### EM0007: Could not get the sdk version for '{sdk}'.
The tool could not get the SDK version using the `xcrun --show-sdk-version --sdk {sdk}` command. Please verify that you can successfully run this command and it returns the SDK version.
<a name="EM0008"></a>
### EM0008: The architecture '{arch}' is not valid for '{platform}'. Valid architectures for '{platform}' are: '{architectures}'.
The architecture in the error message is not valid for the targeted platform. Please verify that a valid architecture is passed for the `--abi` option.
<a name="EM0009"></a>
### EM0009: The feature `X` is not currently implemented by the generator
This is a known issue that we intend to fix in a future release of the generator. Contributions are welcome.
<a name="EM0010"></a>
### EM0010: Can't merge the frameworks '{simulatorFramework}' and '{deviceFramework}' because the file '{file}' exists in both.
The tool could not merge the frameworks mentioned in the error message because there is a common file between them.
This might indicate a bug in .NET Embedding; please file a bug report at [https://github.com/mono/Embeddinator-4000/issues](https://github.com/mono/Embeddinator-4000/issues) with a test case.
<a name="EM0011"></a>
### EM0011: The assembly `X` does not exist.
The tool could not find the assembly `X` specified in the arguments.
<a name="EM0012"></a>
### EM0012: The assembly name `X` is not unique
More than one assembly supplied have the same internal name and it would not be possible to distinguish between them at runtime.
The most likely cause is that an assembly is specified more than once in the command-line arguments. However, a renamed assembly keeps its original name and multiple copies cannot coexist.
<a name="EM0013"></a>
### EM0013: Can't find the assembly 'X', referenced by 'Y'.
The tool could not find the assembly 'X', referenced by the assembly 'Y'. Please make sure all referenced assemblies are in the same directory as the assembly to be bound.
<a name="EM0014"></a>
### EM0014: Could not find {product} ({product} {min_version} is required).
The dependency mentioned in the error message could not be found on the system.
<a name="EM0015"></a>
### EM0015: Could not find a valid version of {product} (found {version}, but at least {min_version} is required).
The dependency mentioned in the error message was found on the system but it's too old. Please update to a newer version.
<a name="EM0016"></a>
### EM0016: Could not create symlink '{file}' -> '{target}': error {number}
Could not create the symlink mentioned in the error message.
<a name="EM0026"></a>
### EM0026 Could not parse the command line argument 'A': *
The syntax given for the command line option `A` could not be parsed by the tool. Please check the documentation for the correct syntax.
<a name="EM0099"></a>
### EM0099: Internal error *. Please file a bug report with a test case (https://github.com/mono/Embeddinator-4000/issues).
This error message is reported when an internal consistency check in .NET Embedding fails.
This indicates a bug in .NET Embedding; please file a bug report at [https://github.com/mono/Embeddinator-4000/issues](https://github.com/mono/Embeddinator-4000/issues) with a test case.
<!-- 1xxx: code processing -->
## EM1xxx: Code processing
<a name="EM1010"></a>
### EM1010: Type `T` is not generated because `X` are not supported.
This is a **warning** that the type `T` will be ignored (i.e. nothing will be generated) because it uses `X`, a feature that is not supported.
Note: Supported features will evolve with new versions of the tool.
<a name="EM1011"></a>
### EM1011: Type `T` is not generated because it lacks marshaling code with a native counterpart.
This is a **warning** that the type `T` will be ignored (i.e. nothing will be generated) because it exposes something from the .NET framework that requires extra marshaling.
Note: This is something that might get supported, with some limitations, in a future version of the tool.
<a name="EM1020"></a>
### EM1020: Constructor `C` is not generated because of parameter type `T` is not supported.
This is a **warning** that the constructor `C` will be ignored (i.e. nothing will be generated) because a parameter of type `T` is not supported.
There should be an earlier warning giving more information why type `T` is not supported.
Note: Supported features will evolve with new versions of the tool.
<a name="EM1021"></a>
### EM1021: Constructor `C` has default values for which no wrapper is generated.
This is a **warning** that the default parameters of constructor `C` are not generating any extra code. The most common cause is that an existing method already has the same signature. For example, in .NET it's possible to have:
```csharp
public class MyType {
public MyType () { ... }
public MyType (int i = 0) { ... }
}
```
In such cases only two generated `init` selectors will be created, both calling into Mono, but no wrapper for the latter will exist.
<a name="EM1030"></a>
### EM1030: Method `M` is not generated because return type `T` is not supported.
This is a **warning** that the method `M` will be ignored (i.e. nothing will be generated) because its return type `T` is not supported.
There should be an earlier warning giving more information why type `T` is not supported.
Note: Supported features will evolve with new versions of the tool.
<a name="EM1031"></a>
### EM1031: Method `M` is not generated because of parameter type `T` is not supported.
This is a **warning** that the method `M` will be ignored (i.e. nothing will be generated) because a parameter of type `T` is not supported.
There should be an earlier warning giving more information why type `T` is not supported.
Note: Supported features will evolve with new versions of the tool.
<a name="EM1032"></a>
### EM1032: Method `M` has default values for which no wrapper is generated.
This is a **warning** that the default parameters of method `M` are not generating any extra code. The most common cause is that an existing method already has the same signature. For example, in .NET it's possible to have:
```csharp
public class MyType {
public int Increment () { ... }
public int Increment (int i = 0) { ... }
}
```
In such cases only two generated `Increment` selectors will be created, both calling into Mono, but no wrapper for the latter will exist.
<a name="EM1033"></a>
### EM1033: Method `M` is not generated because another method exposes the operator with a friendly name.
This is a **warning** that the method `M` is not generated because another method exposes the operator with a friendly name. (https://msdn.microsoft.com/library/ms229032(v=vs.110).aspx)
<a name="EM1034"></a>
### EM1034: Extension method `M` is not generated inside a category because they cannot be created on primitive type `T`. A normal, static method was generated.
This is a **warning** that an extension method on a primivite type (e.g. `System.Int32`) was found. In Objective-C it is not possible to create categories on a primitive type. Instead, the generator will produce a normal static method.
<a name="EM1040"></a>
### EM1040: Property `P` is not generated because of parameter type `T` is not supported.
This is a **warning** that the property `P` will be ignored (i.e. nothing will be generated) because the exposed type `T` is not supported.
There should be an earlier warning giving more information why type `T` is not supported.
Note: Supported features will evolve with new versions of the tool.
<a name="EM1041"></a>
### EM1041: Indexed properties on `T` is not generated because multiple indexed properties are not supported.
This is a **warning** that the indexed properties on `T` will be ignored (i.e. nothing will be generated) because multiple indexed properties are not supported.
<a name="EM1050"></a>
### EM1050: Field `F` is not generated because of field type `T` is not supported.
This is a **warning** that the field `F` will be ignored (i.e. nothing will be generated) because the exposed type `T` is not supported.
There should be an earlier warning giving more information why type `T` is not supported.
Note: Supported features will evolve with new versions of the tool.
<a name="EM1051"></a>
### EM1051: Element `E` is generated instead as `F` because its name conflicts with an important objective-c selector.
This is a **warning** that the element `E` will be generated as `F` because its name conflicts with an important objective-c selector.
Selectors on the [NSObjectProtocol](https://developer.apple.com/reference/objectivec/1418956-nsobject?language=objc) have important meaning in objective-c and must be overridden carefully.
Note: The list of reserved selectors will evolve with new versions of the tool.
<a name="EM1052"></a>
### EM1052: Element `E` is not generated its name conflicts with other elements on the same class.
This is a **warning** that Element `E` is not generated as its name conflicts with other elements on the same class.
<a name="EM1053"></a>
### EM1053: Target `E` is not supported for Xamarin.iOS and Xamarin.Mac. Only the `framework` option is considered supported and should be used.
This is a **warning** that target `E` is considered unsupported for Xamarin.iOS and Xamarin.Mac use cases.
Consumption of static or dynamic .NET Embedding libraries may require additional work steps or tweaks and should be avoided in most use cases.
Consider removing your `--target` parameter or pass `--target=framework` instead.
<!-- 2xxx: code generation -->
## EM2xxx: Code generation
<!-- 3xxx: reserved -->
<!-- 4xxx: reserved -->
<!-- 5xxx: reserved -->
<!-- 6xxx: reserved -->
<!-- 7xxx: reserved -->
<!-- 8xxx: reserved -->
<!-- 9xxx: reserved -->

Просмотреть файл

@ -0,0 +1,77 @@
---
title: "Getting started with C"
description: "This document describes how to use .NET Embedding to embed .NET code in a C application. It discusses how to use .NET Embedding in both Visual Studio 2019 and Visual Studio for Mac."
ms.prod: xamarin
ms.assetid: 2A27BE0F-95FB-4C3A-8A43-72540179AA85
author: davidortinau
ms.author: daortin
ms.date: 04/19/2018
---
# Getting started with C
## Requirements
To use .NET Embedding with C, you'll need a Mac or Windows machine running:
### macOS
* macOS 10.12 (Sierra) or later
* Xcode 8.3.2 or later
* [Mono](https://www.mono-project.com/download/)
### Windows
* Windows 7, 8, 10 or later
* Visual Studio 2015 or later
## Installing .NET Embedding from NuGet
Follow these [instructions](~/tools/dotnet-embedding/get-started/install/install.md) to install and configure .NET Embedding for your project.
The command invocation you should configure will look like (possibly with different version numbers and paths):
### Visual Studio for Mac
```shell
mono {SolutionDir}/packages/Embeddinator-4000.0.4.0.0/tools/Embeddinator-4000.exe --gen=c --outdir=managed_c --platform=macos --compile managed.dll
```
### Visual Studio 2017
```shell
$(SolutionDir)\packages\Embeddinator-4000.0.2.0.80\tools\Embeddinator-4000.exe --gen=c --outdir=managed_c --platform=windows --compile managed.dll
```
## Generation
### Output files
If all goes well, you will be presented with the following output:
```shell
Parsing assemblies...
Parsed 'managed.dll'
Processing assemblies...
Generating binding code...
Generated: managed.h
Generated: managed.c
Generated: mscorlib.h
Generated: mscorlib.c
Generated: embeddinator.h
Generated: glib.c
Generated: glib.h
Generated: mono-support.h
Generated: mono_embeddinator.c
Generated: mono_embeddinator.h
```
Since the `--compile` flag was passed to the tool, .NET Embedding should also have compiled the output files into a shared library, which you can find next to the generated files, a **libmanaged.dylib** file on macOS, and **managed.dll** on Windows.
To consume the shared library, you can include the **managed.h** C header file, which provides the C declarations corresponding to the respective managed library APIs and link with the previously mentioned compiled shared library.
## Further Reading
* [.NET Embedding Limitations](~/tools/dotnet-embedding/limitations.md)
* [Contributing to the open source project](https://github.com/mono/Embeddinator-4000/blob/master/Contributing.md)
* [Error codes and descriptions](~/tools/dotnet-embedding/errors.md)

Просмотреть файл

@ -0,0 +1,35 @@
---
title: "Getting started with .NET Embedding"
description: "This document links to various guides that describe how to use .NET Embedding in C, Java, Android, Objective-C, iOS, and macOS projects."
ms.prod: xamarin
ms.assetid: AF8A4798-EBDD-4E73-997B-C3D4FC5E9685
author: davidortinau
ms.author: daortin
ms.date: 11/14/2017
---
# Getting started with .NET Embedding
## [C](c.md)
Embed .NET code in your C apps.
## [Java](java/index.md)
How to embed in Java apps on various platforms.
### [Android](java/android.md)
Android-specific advice for embedding .NET code.
## [Objective-C](objective-c/index.md)
How to embed in Objective-C.
### [iOS](objective-c/ios.md)
iOS-specific tips for embedding .NET code.
### [macOS](objective-c/macos.md)
macOS-specific tips for embedding .NET code.

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 244 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 202 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 12 KiB

Просмотреть файл

@ -0,0 +1,107 @@
---
title: "Installing .NET Embedding"
description: "This document describes how to install .NET Embedding. It discusses how to run the tooling by hand, how to generate bindings automatically, how to use custom MSBuild targets, and necessary post-build steps."
ms.prod: xamarin
ms.assetid: 47106AF3-AC6E-4A0E-B30B-9F73C116DDB3
author: chamons
ms.author: chhamo
ms.date: 04/18/2018
---
# Installing .NET Embedding
## Installing .NET Embedding from NuGet
Choose **Add > Add NuGet Packages...** and install **Embeddinator-4000** from the NuGet package manager:
![NuGet Package Manager](images/visualstudionuget.png)
This will install **Embeddinator-4000.exe** and **objcgen** into the **packages/Embeddinator-4000/tools** directory.
In general, the latest release of the Embeddinator-4000 should be selected for downloading. Objective-C support requires 0.4 or later.
## Running manually
Now that the NuGet is installed, you can run the tooling by hand.
- Open a Terminal (macOS) or Command Prompt (Windows)
- Change directory to your solution root
- The tooling is installed in:
- **./packages/Embeddinator-4000.[VERSION]/tools/objcgen** (Objective-C)
- **./packages/Embeddinator-4000.[VERSION]/tools/Embeddinator-4000.exe** (Java/C)
- On macOS, **objcgen** can be run directly.
- On Windows, **Embeddinator-4000.exe** can be run directly.
- On macOS, **Embeddinator-4000.exe** needs to be run with **mono**:
- `mono ./packages/Embeddinator-4000.[VERSION]/tools/Embeddinator-4000.exe`
Each command invocation will need a number of paramaters listed in the platform-specific documentation.
## Automatic binding generation
There are two approaches for automatically running .NET Embedding part of your build process.
- Custom MSBuild targets
- Post-build steps
While this document will describe both, using a custom MSBuild target is preferred. Post Build Steps will not necessarily run when building from the command line.
### Custom MSBuild targets
To customize your build with MSbuild targets, first create a **Embeddinator-4000.targets** file next to your csproj similar to the following:
```xml
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Target Name="RunEmbeddinator" AfterTargets="AfterBuild" Inputs="$(OutputPath)/$(AssemblyName).dll" Outputs="$(IntermediateOutputPath)/Embeddinator/$(AssemblyName).framework/$(AssemblyName)">
<Exec Command="" />
</Target>
</Project>
```
Here, the command's text should be filled in with one of the .NET Embedding invocations listed in the platform-specific documentation.
To use this target:
- Close your project in Visual Studio 2017 or Visual Studio for Mac
- Open the library csproj in a text editor
- Add this line at the bottom, above the final `</Project>` line:
```xml
<Import Project="Embeddinator-4000.targets" />
```
- Reopen your project
### Post-build steps
The steps to add a post-build step to run .NET Embedding vary depending on the IDE:
#### Visual Studio for Mac
In Visual Studio for Mac, go to **Project Options > Build > Custom Commands** and add an **After Build** step.
Set up the command listed in the platform-specific documentation.
> [!NOTE]
> Make sure to use the version number you installed from NuGet
If you are going to be doing ongoing development on the C# project, you might also add a custom command to clean the **output** directory prior to running .NET Embedding:
```shell
rm -Rf '${SolutionDir}/output/'
```
![Custom Build Action](images/visualstudiocustombuild.png)
> [!NOTE]
> The generated binding will be placed in the directory indicated by the
> `--outdir` or `--out` parameter. The generated binding name may vary as
> some platforms have limitations on package names.
#### Visual Studio 2017
We will essentially set up the same thing, but the menus in Visual Studio 2017 are a bit different. The shell commands are also slightly different.
Go to **Project Options > Build Events** and enter the command listed in the platform-specific documentation into the **Post-build event command line** box. For example:
![.NET Embedding on Windows](images/visualstudiowindows.png)

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 33 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 46 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 9.5 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 54 KiB

Просмотреть файл

@ -0,0 +1,287 @@
---
title: "Getting started with Android"
description: "This document describes how to get started using .NET Embedding with Android. It discusses installing .NET Embedding, creating an Android library project, using generated output in an Android Studio project, and other considerations."
ms.prod: xamarin
ms.assetid: 870F0C18-A794-4C5D-881B-64CC78759E30
author: davidortinau
ms.author: daortin
ms.date: 03/28/2018
---
# Getting started with Android
In addition to the requirements from the [Getting started with Java](~/tools/dotnet-embedding/get-started/java/index.md) guide you'll also need:
- [Xamarin.Android 7.5](https://visualstudio.microsoft.com/xamarin/) or later
- [Android Studio 3.x](https://developer.android.com/studio/index.html) with Java 1.8
As an overview, we will:
- Create a C# Android Library project
- Install .NET Embedding via NuGet
- Run .NET Embedding on the Android library assembly
- Use the generated AAR file in a Java project in Android Studio
## Create an Android Library Project
Open Visual Studio for Windows or Mac, create a new Android Class Library project, name it **hello-from-csharp**, and save it to **~/Projects/hello-from-csharp** or **%USERPROFILE%\Projects\hello-from-csharp**.
Add a new Android Activity named **HelloActivity.cs**, followed by an Android Layout at **Resource/layout/hello.axml**.
Add a new `TextView` to your layout, and change the text to something enjoyable.
Your layout source should look something like this:
```xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:minWidth="25px"
android:minHeight="25px">
<TextView
android:text="Hello from C#!"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center" />
</LinearLayout>
```
In your activity, make sure you are calling `SetContentView` with your new layout:
```csharp
[Activity(Label = "HelloActivity"),
Register("hello_from_csharp.HelloActivity")]
public class HelloActivity : Activity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.hello);
}
}
```
> [!NOTE]
> Don't forget the `[Register]` attribute. For details, see
> [Limitations](#current-limitations-on-android).
Build the project. The resulting assembly will be saved in `bin/Debug/hello-from-csharp.dll`.
## Installing .NET Embedding from NuGet
Follow these [instructions](~/tools/dotnet-embedding/get-started/install/install.md) to install and configure .NET Embedding for your project.
The command invocation you should configure will look like this:
### Visual Studio for Mac
```shell
mono '${SolutionDir}/packages/Embeddinator-4000.0.4.0.0/tools/Embeddinator-4000.exe' '${TargetPath}' --gen=Java --platform=Android --outdir='${SolutionDir}/output' -c
```
#### Visual Studio 2017
```shell
set E4K_OUTPUT="$(SolutionDir)output"
if exist %E4K_OUTPUT% rmdir /S /Q %E4K_OUTPUT%
"$(SolutionDir)packages\Embeddinator-4000.0.2.0.80\tools\Embeddinator-4000.exe" "$(TargetPath)" --gen=Java --platform=Android --outdir=%E4K_OUTPUT% -c
```
## Use the generated output in an Android Studio project
1. Open Android Studio and create a new project with an **Empty Activity**.
2. Right-click on your **app** module and choose **New > Module**.
3. Select **Import .JAR/.AAR Package**.
4. Use the directory browser to locate **~/Projects/hello-from-csharp/output/hello_from_csharp.aar** and click **Finish**.
![Import AAR into Android Studio](android-images/androidstudioimport.png)
This will copy the AAR file into a new module named **hello_from_csharp**.
![Android Studio Project](android-images/androidstudioproject.png)
To use the new module from your **app**, right-click and choose **Open Module Settings**. On the **Dependencies** tab, add a new **Module Dependency** and choose **:hello_from_csharp**.
![Android Studio Dependencies](android-images/androidstudiodependencies.png)
In your activity, add a new `onResume` method, and use the following code to launch the C# activity:
```java
import hello_from_csharp.*;
public class MainActivity extends AppCompatActivity {
//... Other stuff here ...
@Override
protected void onResume() {
super.onResume();
Intent intent = new Intent(this, HelloActivity.class);
startActivity(intent);
}
}
```
### Assembly compression (*IMPORTANT*)
One further change is required for .NET Embedding in your Android Studio project.
Open your app's **build.gradle** file and add the following change:
```groovy
android {
// ...
aaptOptions {
noCompress 'dll'
}
}
```
Xamarin.Android currently loads .NET assemblies directly from the APK, but it requires the assemblies to not be compressed.
If you do not have this setup, the app will crash on launch and print something like this to the console:
```shell
com.xamarin.hellocsharp A/monodroid: No assemblies found in '(null)' or '<unavailable>'. Assuming this is part of Fast Deployment. Exiting...
```
## Run the app
Upon launching your app:
![Hello from C# sample running in the emulator](android-images/hello-from-csharp-android.png)
Note what happened here:
- We have a C# class, `HelloActivity`, that subclasses Java
- We have Android Resource files
- We used these from Java in Android Studio
For this sample to work, all the following are set up in the final APK:
- Xamarin.Android is configured on application start
- .NET assemblies included in **assets/assemblies**
- **AndroidManifest.xml** modifications for your C# activities, etc.
- Android resources and assets from .NET libraries
- [Android Callable Wrappers](~/android/platform/java-integration/android-callable-wrappers.md) for any `Java.Lang.Object` subclass
If you are looking for an additional walkthrough, check out the following
video, which demonstrates embedding Charles Petzold's
[FingerPaint demo](/samples/xamarin/monodroid-samples/applicationfundamentals-fingerpaint) in an Android Studio project:
[![Embeddinator-4000 for Android](https://img.youtube.com/vi/ZVcrXUpCNpI/0.jpg)](https://www.youtube.com/watch?v=ZVcrXUpCNpI)
## Using Java 1.8
As of writing this, the best option is to use Android Studio 3.0 ([download here](https://developer.android.com/studio/index.html)).
To enable Java 1.8 in your app module's **build.gradle** file:
```groovy
android {
// ...
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
```
You can also take a look at an [Android Studio test
project](https://github.com/mono/Embeddinator-4000/blob/master/tests/android/app/build.gradle) for more details.
If you are wanting to use Android Studio 2.3.x stable, you will have to enable the deprecated Jack toolchain:
```groovy
android {
// ..
defaultConfig {
// ...
jackOptions.enabled true
}
}
```
## Current limitations on Android
Right now, if you subclass `Java.Lang.Object`, Xamarin.Android will generate the Java stub (Android Callable Wrapper) instead of .NET Embedding. Because of this, you must follow the same rules for exporting C# to Java as Xamarin.Android. For example:
```csharp
[Register("mono.embeddinator.android.ViewSubclass")]
public class ViewSubclass : TextView
{
public ViewSubclass(Context context) : base(context) { }
[Export("apply")]
public void Apply(string text)
{
Text = text;
}
}
```
- `[Register]` is required to map to a desired Java package name
- `[Export]` is required to make a method visible to Java
We can use `ViewSubclass` in Java like so:
```java
import mono.embeddinator.android.ViewSubclass;
//...
ViewSubclass v = new ViewSubclass(this);
v.apply("Hello");
```
Read more about [Java integration with Xamarin.Android](~/android/platform/java-integration/index.md).
## Multiple assemblies
Embedding a single assembly is straightforward; however, it is much more likely you will have more than one C# assembly. Many times you will have dependencies on NuGet packages such as the Android support libraries or Google Play Services that further complicate things.
This causes a dilemma, since .NET Embedding needs to include many types of files into the final AAR such as:
- Android assets
- Android resources
- Android native libraries
- Android java source
You most likely do not want to include these files from the Android support library or Google Play Services into your AAR, but would rather use the official version from Google in Android Studio.
Here is the recommended approach:
- Pass .NET Embedding any assembly that you own (have source for) and want to call from Java
- Pass .NET Embedding any assembly that you need Android assets, native libraries, or resources from
- Add Java dependencies like the Android support library or Google Play Services in Android Studio
So your command might be:
```shell
mono Embeddinator-4000.exe --gen=Java --platform=Android -c -o output YourMainAssembly.dll YourDependencyA.dll YourDependencyB.dll
```
You should exclude anything from NuGet, unless you find out it contains Android assets, resources, etc. that you will need in your Android Studio project. You can also omit dependencies that you do not need to call from Java, and the linker _should_ include the parts of your library that are needed.
To add any Java dependencies needed in Android Studio, your **build.gradle** file might look like:
```groovy
dependencies {
// ...
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.google.android.gms:play-services-games:11.0.4'
// ...
}
```
## Further reading
- [Callbacks on Android](~/tools/dotnet-embedding/android/callbacks.md)
- [Preliminary Android Research](~/tools/dotnet-embedding/android/index.md)
- [.NET Embedding Limitations](~/tools/dotnet-embedding/limitations.md)
- [Contributing to the open source project](https://github.com/mono/Embeddinator-4000/blob/master/Contributing.md)
- [Error codes and descriptions](~/tools/dotnet-embedding/errors.md)
## Related links
- [Weather Sample (Android)](https://github.com/jamesmontemagno/embeddinator-weather)

Просмотреть файл

@ -0,0 +1,76 @@
---
title: "Getting started with Java"
description: "This document describes how to get started using .NET Embedding with Java. It discusses system requirements, installation, and supported platforms."
ms.prod: xamarin
ms.assetid: B9A25E9B-3EC2-489A-8AD3-F78287609747
author: davidortinau
ms.author: daortin
ms.date: 03/28/2018
---
# Getting started with Java
This is the getting started page for Java, which covers the basics for all supported platforms.
## Requirements
To use .NET Embedding with Java you will need:
* Java 1.8 or later
* [Mono 5.0](https://www.mono-project.com/download/)
For Mac:
* Xcode 8.3.2 or later
For Windows:
* Visual Studio 2017 with C++ support
* Windows 10 SDK
For Android:
* [Xamarin.Android 7.5](https://visualstudio.microsoft.com/xamarin/) or later
* [Android Studio 3.x](https://developer.android.com/studio/index.html) with Java 1.8
You can use [Visual Studio for Mac](https://visualstudio.microsoft.com/vs/mac/) to edit and compile your C# code.
> [!NOTE]
> Earlier versions of Xcode, Visual Studio, Xamarin.Android, Android Studio, and Mono _might_ work, but are untested and unsupported.
## Installation
.NET Embedding is currently available on [NuGet](https://www.nuget.org/packages/Embeddinator-4000/):
```shell
nuget install Embeddinator-4000
```
This will place **Embeddinator-4000.exe** into the **packages/Embeddinator-4000/tools** directory.
Additionally, you can build .NET Embedding from source, see our [git repository](https://github.com/mono/Embeddinator-4000/) and the [contributing](https://github.com/mono/Embeddinator-4000/blob/master/Contributing.md) document for instructions.
## Platforms
Java is currently in a preview state for macOS, Windows, and Android.
The platform is selected by passing the `--platform=<platform>` command-line argument to the .NET Embedding tool. Currently `macOS`, `Windows`, and `Android` are supported.
### macOS and Windows
For development, you should be able to use any Java IDE that supports Java 1.8. You can even use Android Studio for this if desired, [see here](https://stackoverflow.com/questions/16626810/can-android-studio-be-used-to-run-standard-java-projects). You can use the JAR file output as you would any standard Java jar file.
### Android
Please make sure you are already set up to develop Android applications before trying to create one using .NET Embedding. The [following instructions](~/tools/dotnet-embedding/get-started/java/android.md) assume that you have already successfully built and deployed an Android application from your computer.
Android Studio is recommended for development, but other IDEs should work as long as there is support for the [AAR file format](https://developer.android.com/studio/projects/android-library.html).
## Further reading
* [Getting Started on Android](~/tools/dotnet-embedding/get-started/java/android.md)
* [Callbacks on Android](~/tools/dotnet-embedding/android/callbacks.md)
* [Preliminary Android Research](~/tools/dotnet-embedding/android/index.md)
* [.NET Embedding Limitations](~/tools/dotnet-embedding/limitations.md)
* [Contributing to the open source project](https://github.com/mono/Embeddinator-4000/blob/master/Contributing.md)
* [Error codes and descriptions](~/tools/dotnet-embedding/errors.md)

Двоичные данные
Docs/Tools/dotnet-embedding/get-started/objective-c/images/install1.png Executable file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 53 KiB

Двоичные данные
Docs/Tools/dotnet-embedding/get-started/objective-c/images/install2.png Executable file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 60 KiB

Двоичные данные
Docs/Tools/dotnet-embedding/get-started/objective-c/images/install3.png Executable file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 56 KiB

Просмотреть файл

@ -0,0 +1,69 @@
---
title: "Getting started with Objective-C"
description: "This document describes how get started using .NET Embedding with Objective-C. It discusses requirements, installing .NET Embedding from NuGet, and supported platforms."
ms.prod: xamarin
ms.assetid: 4ABC0247-B608-42D4-89CB-D2E598097142
author: davidortinau
ms.author: daortin
ms.date: 11/14/2017
---
# Getting started with Objective-C
This is the getting started page for Objective-C, which covers the basics for all supported platforms.
## Requirements
To use .NET Embedding with Objective-C, you'll need a Mac running:
- macOS 10.12 (Sierra) or later
- Xcode 8.3.2 or later
- [Mono 5.0](https://www.mono-project.com/download/)
You can install [Visual Studio for Mac](https://visualstudio.microsoft.com/vs/mac/) to edit and compile your C# code.
> [!NOTE]
>
> - Earlier versions of macOS, Xcode, and Mono _might_ work, but are
> untested and unsupported
> - Code generation can be done on Windows, but it is only possible to
> compile it on a Mac computer where Xcode is installed
## Installing .NET Embedding from NuGet
Follow these [instructions](~/tools/dotnet-embedding/get-started/install/install.md) to install and configure .NET Embedding for your project.
A sample command invocation is listed in the [macOS](~/tools/dotnet-embedding/get-started/objective-c/macos.md)
and
[iOS](~/tools/dotnet-embedding/get-started/objective-c/ios.md) getting started guides.
## Platforms
Objective-C is a language that is most commonly used to write applications for macOS, iOS, tvOS and watchOS; .NET Embedding supports all of those platforms. Working with each platform implies some [key differences and these are explained here](~/tools/dotnet-embedding/objective-c/platforms.md).
### macOS
[Creating a macOS application](~/tools/dotnet-embedding/get-started/objective-c/macos.md) is easiest since it does not involve as many additional steps, like setting up identity, provisining profiles, simulators and devices. You are encouraged to start with the macOS document before the one for iOS.
### iOS / tvOS
Please make sure you are already set up to develop iOS applications before trying to create one using .NET Embedding. The [following instructions](~/tools/dotnet-embedding/get-started/objective-c/ios.md) assume that you have already successfully built and deployed an iOS application from your computer.
Support for tvOS is analogous to how iOS works, by just using tvOS projects in the IDEs (both Visual Studio and Xcode) instead of iOS projects.
> [!NOTE]
> Support for watchOS will be available in a future release and will be
> very similar to iOS/tvOS.
## Further reading
- [.NET Embedding features specific to Objective-C](~/tools/dotnet-embedding/objective-c/index.md)
- [Best Practices for Objective-C](~/tools/dotnet-embedding/objective-c/best-practices.md)
- [.NET Embedding Limitations](~/tools/dotnet-embedding/limitations.md)
- [Contributing to the open source project](https://github.com/mono/Embeddinator-4000/blob/master/Contributing.md)
- [Error codes and descriptions](~/tools/dotnet-embedding/errors.md)
- [Target platforms](~/tools/dotnet-embedding/objective-c/platforms.md)
## Related links
- [Weather Sample (iOS & macOS)](https://github.com/jamesmontemagno/embeddinator-weather)

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 633 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 109 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 702 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 39 KiB

Просмотреть файл

@ -0,0 +1,102 @@
---
title: "Getting started with iOS"
description: "This document describes how to get started using .NET Embedding with iOS. It discusses requirements and presents a sample app to demonstrate how to bind a managed assembly and use the output in an Xcode project."
ms.prod: xamarin
ms.assetid: D5453695-69C9-44BC-B226-5B86950956E2
author: davidortinau
ms.author: daortin
ms.date: 11/14/2017
---
# Getting started with iOS
## Requirements
In addition to the requirements from our [Getting started with Objective-C](~/tools/dotnet-embedding/get-started/objective-c/index.md) guide, you'll also need:
* [Xamarin.iOS 10.11](https://visualstudio.microsoft.com/xamarin/) or later
## Hello world
First, build a simple hello world example in C#.
### Create C# sample
Open Visual Studio for Mac, create a new iOS Class Library project, name it **hello-from-csharp**, and save it to **~/Projects/hello-from-csharp**.
Replace the code in the **MyClass.cs** file with the following snippet:
```csharp
using UIKit;
public class MyUIView : UITextView
{
public MyUIView ()
{
Text = "Hello from C#";
}
}
```
Build the project, and the resulting assembly will be saved as **~/Projects/hello-from-csharp/hello-from-csharp/bin/Debug/hello-from-csharp.dll**.
### Bind the managed assembly
Once you have a managed assembly, bind it by invoking .NET Embedding.
As described in the
[installation](~/tools/dotnet-embedding/get-started/install/install.md)
guide, this can be done as post-build step in your project, with a
custom MSBuild target, or manually:
```shell
cd ~/Projects/hello-from-csharp
objcgen ~/Projects/hello-from-csharp/hello-from-csharp/bin/Debug/hello-from-csharp.dll --target=framework --platform=iOS --outdir=output -c --debug
```
The framework will be placed in **~/Projects/hello-from-csharp/output/hello-from-csharp.framework**.
### Use the generated output in an Xcode project
Open Xcode, create a new iOS Single View Application, name it **hello-from-csharp**, and select the **Objective-C** language.
Open the **~/Projects/hello-from-csharp/output** directory in Finder, select **hello-from-csharp.framework**, drag it to the Xcode project and drop it just above the **hello-from-csharp** folder in the project.
![Drag and drop framework](ios-images/hello-from-csharp-ios-drag-drop-framework.png)
Make sure **Copy items if needed** is checked in the dialog that pops up, and click **Finish**.
![Copy items if needed](ios-images/hello-from-csharp-ios-copy-items-if-needed.png)
Select the **hello-from-csharp** project and navigate to the **hello-from-csharp** target's **General tab**. In the **Embedded Binary** section, add **hello-from-csharp.framework**.
![Embedded binaries](ios-images/hello-from-csharp-ios-embedded-binaries.png)
Open **ViewController.m**, and replace the contents with:
```objective-c
#import "ViewController.h"
#include "hello-from-csharp/hello-from-csharp.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
MyUIView *view = [[MyUIView alloc] init];
view.frame = CGRectMake(0, 200, 200, 200);
[self.view addSubview: view];
}
@end
```
.NET Embedding does not currently support bitcode on iOS, which is enabled for some Xcode project templates.
Disable it in your project settings:
![Bitcode Option](../../images/ios-bitcode-option.png)
Finally, run the Xcode project, and something like this will show up:
![Hello from C# sample running in the simulator](ios-images/hello-from-csharp-ios.png)

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 166 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 31 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 186 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 21 KiB

Просмотреть файл

@ -0,0 +1,94 @@
---
title: "Getting started with macOS"
description: "This document describes how get started using .NET Embedding with macOS. It discusses requirements, and presents a sample application to demonstrate how to bind the managed assembly and use the generated output in an Xcode project."
ms.prod: xamarin
ms.assetid: AE51F523-74F4-4EC0-B531-30B71C4D36DF
author: davidortinau
ms.author: daortin
ms.date: 11/14/2017
---
# Getting started with macOS
## What you will need
* Follow instructions in the [Getting started with Objective-C](~/tools/dotnet-embedding/get-started/objective-c/index.md) guide.
## Hello world
First, build a simple hello world example in C#.
### Create C# sample
Open Visual Studio for Mac, create a new Mac Class Library project named **hello-from-csharp**, and save it to **~/Projects/hello-from-csharp**.
Replace the code in the **MyClass.cs** file with the following snippet:
```csharp
using AppKit;
public class MyNSView : NSTextView
{
public MyNSView ()
{
Value = "Hello from C#";
}
}
```
Build the project. The resulting assembly will be saved as **~/Projects/hello-from-csharp/hello-from-csharp/bin/Debug/hello-from-csharp.dll**.
### Bind the managed assembly
Once you have a managed assembly, bind it by invoking .NET Embedding.
As described in the
[installation](~/tools/dotnet-embedding/get-started/install/install.md)
guide, this can be done as post-build step in your project, with a
custom MSBuild target, or manually:
```shell
cd ~/Projects/hello-from-csharp
objcgen ~/Projects/hello-from-csharp/hello-from-csharp/bin/Debug/hello-from-csharp.dll --target=framework --platform=macOS-modern --abi=x86_64 --outdir=output -c --debug
```
The framework will be placed in **~/Projects/hello-from-csharp/output/hello-from-csharp.framework**.
### Use the generated output in an Xcode project
Open Xcode and create a new Cocoa Application. Name it **hello-from-csharp** and select the **Objective-C** language.
Open the **~/Projects/hello-from-csharp/output** directory in Finder, select **hello-from-csharp.framework**, drag it to the Xcode project and drop it just above the **hello-from-csharp** folder in the project.
![Drag and drop framework](macos-images/hello-from-csharp-mac-drag-drop-framework.png)
Make sure **Copy items if needed** is checked in the dialog that pops up, and click **Finish**.
![Copy items if needed](macos-images/hello-from-csharp-mac-copy-items-if-needed.png)
Select the **hello-from-csharp** project and navigate to the **hello-from-csharp** target's **General** tab. In the **Embedded Binary** section, add **hello-from-csharp.framework**.
![Embedded binaries](macos-images/hello-from-csharp-mac-embedded-binaries.png)
Open **ViewController.m**, and replace the contents with:
```objc
#import "ViewController.h"
#include "hello-from-csharp/hello-from-csharp.h"
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
MyNSView *view = [[MyNSView alloc] init];
view.frame = CGRectMake(0, 200, 200, 200);
[self.view addSubview: view];
}
@end
```
Finally, run the Xcode project, and something like this will show up:
![Hello from C# sample running in the simulator](macos-images/hello-from-csharp-mac.png)

Двоичные данные
Docs/Tools/dotnet-embedding/images/ios-bitcode-option.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 16 KiB

Просмотреть файл

@ -0,0 +1,57 @@
---
title: ".NET Embedding"
description: ".NET Embedding allows your existing .NET Code (C#, F#, and others) to be consumed by code written in other programming languages."
ms.prod: xamarin
ms.assetid: 617C38CA-B921-4A76-8DFC-B0A3DF90E48A
author: davidortinau
ms.author: daortin
ms.date: 11/14/2017
---
# .NET Embedding
![Preview](~/media/shared/preview.png)
.NET Embedding allows your existing .NET Code (C#,
F#, and others) to be consumed from other programming languages and in
various different environments.
This means that if you have a .NET library that you want to use from
your existing iOS app, you can do that. Or if you want to link it
with a native C++ library, you can also do that. Or consume .NET
code from Java.
.NET Embedding is based on the [Embeddinator-4000](https://github.com/mono/Embeddinator-4000)
open source project.
## Environments and Languages
The tool is both aware of the environment it will use, as well as the
language that will consume it. For example, the iOS platform does
not allow just-in-time (JIT) compilation, so .NET Embedding will
statically compile your .NET code into native code that can be used in
iOS. Other environments do allow JIT compilation, and in those
environments, we opt to JIT compile.
It supports various language consumers, so it surfaces .NET code as
idiomatic code in the target language. This is the list of supported
languages at present:
- [**Objective-C**](objective-c/index.md) – mapping .NET to idiomatic Objective-C APIs
- [**Java**](android/index.md) – mapping .NET to idiomatic Java APIs
- [**C**](get-started/c.md) – mapping .NET to object-oriented like C APIs
More languages will come later.
## Getting Started
To get started, check one of our guides for each of the currently
supported languages:
- [**Objective-C**](get-started/objective-c/index.md) – covers macOS and iOS
- [**Java**](get-started/java/index.md) – covers macOS and Android
- [**C**](get-started/c.md) – covers C language on desktop platforms
## Related Links
- [Embeddinator-4000 on GitHub](https://github.com/mono/Embeddinator-4000)

Просмотреть файл

@ -0,0 +1,53 @@
---
title: ".NET Embedding Limitations"
description: "This document describes limitations of .NET Embedding, the tool that allows you to consume .NET code in other programming languages."
ms.prod: xamarin
ms.assetid: EBBBB886-1CEF-4DF4-AFDD-CA96049F878E
author: davidortinau
ms.author: daortin
ms.date: 11/14/2017
---
# .NET Embedding Limitations
This document explains the limitations of .NET Embedding and, whenever possible, provides workarounds for them.
## General
### Use more than one embedded library in a project
It is not possible to have two Mono runtimes co-existing inside the same application. This means you cannot use two different .NET Embedding-generated libraries inside the same application.
**Workaround:** You can use the generator to create a single library that includes several assemblies (from different projects).
### Subclassing
.NET Embedding eases the integration of the Mono runtime inside applications by exposing a set of ready-to-use APIs for the target language and platform.
However this is not a two-way integration, e.g. you cannot subclass a managed type and expect managed code to call back inside your native code, since your managed code is unaware of this co-existence.
Depending on your needs, it might be possible to workaround parts of this limitation, e.g.
* your managed code can p/invoke into your native code. This requires customizing your managed code to allow customization from native code;
* use products like Xamarin.iOS and expose a managed library that would allow Objective-C (in this case) to subclass some managed NSObject subclasses.
## Objective-C generated code
### Nullability
There is no metadata in .NET that tell us if a null reference is acceptable or not for an API. Most APIs will throw `ArgumentNullException` if they cannot cope with a `null` argument. This is problematic as Objective-C handling of exceptions is something better avoided.
Since we cannot generate accurate nullability annotations in the header files and wish to minimize managed exceptions we default to non-null arguments (`NS_ASSUME_NONNULL_BEGIN`) and add some specific, when precision is possible, nullability annotations.
### Bitcode (iOS)
Currently .NET Embedding does not support bitcode on iOS, which is enabled for some Xcode project templates. This will have to be disabled to successfully link generated frameworks.
* For iOS, bitcode is optional to submit apps to Apple's AppStore. Xamarin.iOS does not support it for iOS since the generated bitcode is “inline assembly”. This provides no benefit on the iOS platform because it cant be optimized server-side, but makes binaries larger and build times longer.
* For tvOS and watchOS, bitcode is required for submitting apps to Apple's AppStore. Xamarin.iOS supports bitcode on tvOS (as "inline assembly") and watchOS (as "LLVM/IR") to fulfill this requirement.
* For macOS, bitcode support is currently not required, nor supported by Xamarin.Mac.
![Bitcode Option](images/ios-bitcode-option.png)

Просмотреть файл

@ -0,0 +1,139 @@
---
title: ".NET Embedding best practices for Objective-C"
description: "This document describes various best practices for using .NET Embedding with Objective-C. It discusses exposing a subset of the managed code, exposing a chunkier API, naming, and more."
ms.prod: xamarin
ms.assetid: 63C7F5D2-8933-4D4A-8348-E9CBDA45C472
author: davidortinau
ms.author: daortin
ms.date: 11/14/2017
---
# .NET Embedding best practices for Objective-C
This is a draft and might not be in-sync with the features presently supported by the tool. We hope that this document will evolve separately and eventually match the final tool, i.e. we'll suggest long term best approaches - not immediate workarounds.
A large part of this document also applies to other supported languages. However all provided examples are in C# and Objective-C.
## Exposing a subset of the managed code
The generated native library/framework contains Objective-C code to call each of the managed APIs that is exposed. The more API you surface (make public) then larger the native _glue_ library will become.
It might be a good idea to create a different, smaller assembly, to expose only the required APIs to the native developer. That facade will also allow you more control over the visibility, naming, error checking... of the generated code.
## Exposing a chunkier API
There is a price to pay to transition from native to managed (and back). As such, it's better to expose _chunky instead of chatty_ APIs to the native developers, e.g.
**Chatty**
```csharp
public class Person {
public string FirstName { get; set; }
public string LastName { get; set; }
}
```
```objc
// this requires 3 calls / transitions to initialize the instance
Person *p = [[Person alloc] init];
p.firstName = @"Sebastien";
p.lastName = @"Pouliot";
```
**Chunky**
```csharp
public class Person {
public Person (string firstName, string lastName) {}
}
```
```objc
// a single call / transition will perform better
Person *p = [[Person alloc] initWithFirstName:@"Sebastien" lastName:@"Pouliot"];
```
Since the number of transitions is smaller the performance will be better. It also requires less code to be generated, so this will produce a smaller native library as well.
## Naming
Naming things is one of two hardest problems in computer science, the others being cache invalidation and off-by-1 errors. Hopefully .NET Embedding can shield you from all but naming.
### Types
Objective-C does not support namespaces. In general, its types are prefixed with a 2 (for Apple) or 3 (for 3rd parties) character prefix, like `UIView` for UIKit's View, which denotes the framework.
For .NET types skipping the namespace is not possible as it can introduce duplicated, or confusing, names. This makes existing .NET types very long, e.g.
```csharp
namespace Xamarin.Xml.Configuration {
public class Reader {}
}
```
would be used like:
```objc
id reader = [[Xamarin_Xml_Configuration_Reader alloc] init];
```
However you can re-expose the type as:
```csharp
public class XAMXmlConfigReader : Xamarin.Xml.Configuration.Reader {}
```
making it more Objective-C friendly to use, e.g.:
```objc
id reader = [[XAMXmlConfigReader alloc] init];
```
### Methods
Even good .NET names might not be ideal for an Objective-C API.
Naming conventions in Objective-C are different than .NET (camel case instead of pascal case, more verbose).
Please read the [coding guidelines for Cocoa](https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CodingGuidelines/Articles/NamingMethods.html#//apple_ref/doc/uid/20001282-BCIGIJJF).
From an Objective-C developer's point of view, a method with a `Get` prefix implies you do not own the instance, i.e. the [get rule](https://developer.apple.com/library/content/documentation/CoreFoundation/Conceptual/CFMemoryMgmt/Concepts/Ownership.html#//apple_ref/doc/uid/20001148-SW1).
This naming rule has no match in the .NET GC world; a .NET method with a `Create` prefix will behave identically in .NET. However, for Objective-C developers, it normally means you own the returned instance, i.e. the [create rule](https://developer.apple.com/library/content/documentation/CoreFoundation/Conceptual/CFMemoryMgmt/Concepts/Ownership.html#//apple_ref/doc/uid/20001148-103029).
## Exceptions
It's quite common in .NET to use exceptions extensively to report errors. However, they are slow and not quite identical in Objective-C. Whenever possible you should hide them from the Objective-C developer.
For example, the .NET `Try` pattern will be much easier to consume from Objective-C code:
```csharp
public int Parse (string number)
{
return Int32.Parse (number);
}
```
versus
```csharp
public bool TryParse (string number, out int value)
{
return Int32.TryParse (number, out value);
}
```
### Exceptions inside `init*`
In .NET a constructor must either succeed and return a (_hopefully_) valid instance or throw an exception.
In contrast, Objective-C allows `init*` to return `nil` when an instance cannot be created. This is a common, but not general, pattern used in many of Apple's frameworks. In some other cases an `assert` can happen (and kill the current process).
The generator follow the same `return nil` pattern for generated `init*` methods. If a managed exception is thrown, then it will be printed (using `NSLog`) and `nil` will be returned to the caller.
## Operators
Objective-C does not allow operators to be overloaded as C# does, so these are converted to class selectors.
["Friendly"](/dotnet/standard/design-guidelines/operator-overloads) named methods are generated in preference to the operator overloads when found, and can produce an easier to consume API.
Classes that override the operators `==` and\or `!=` should override the standard Equals (Object) method as well.

Просмотреть файл

@ -0,0 +1,249 @@
---
title: "Objective-C Support"
description: "This document provides a description of the support for Objective-C in .NET Embedding. It discusses Automatic Reference Counting, NSString, Protocols, NSObject protocol, exceptions, and more."
ms.prod: xamarin
ms.assetid: 3367A4A4-EC88-4B75-96D0-51B1FCBCE614
author: davidortinau
ms.author: daortin
ms.date: 11/14/2017
---
# Objective-C Support
## Specific features
The generation of Objective-C has a few special features that are worth noting.
### Automatic Reference Counting
The use of Automatic Reference Counting (ARC) is **required** to call the generated bindings. Project using a .NET Embedding-based library must be compiled with `-fobjc-arc`.
### NSString support
APIs that expose `System.String` types are converted into `NSString`. This makes memory management easier than when dealing with `char*`.
### Protocols support
Managed interfaces are converted into Objective-C protocols where all members are `@required`.
### NSObject protocol support
By default, the default hashing and equality of both .NET and the Objective-C runtime are assumed to be interchangeable, as they share similar semantics.
When a managed type overrides `Equals(Object)` or `GetHashCode`, it generally means that the default (.NET) behavior was not sufficient; this implies that the default Objective-C behavior is likely not sufficient either.
In such cases, the generator overrides the [`isEqual:`](https://developer.apple.com/reference/objectivec/1418956-nsobject/1418795-isequal?language=objc) method and [`hash`](https://developer.apple.com/reference/objectivec/1418956-nsobject/1418859-hash?language=objc) property defined in the [`NSObject` protocol](https://developer.apple.com/reference/objectivec/1418956-nsobject?language=objc). This allows the custom managed implementation to be used from Objective-C code transparently.
### Exceptions support
Passing `--nativeexception` as an argument to `objcgen` will convert managed exceptions into Objective-C exceptions that can be caught and processed.
### Comparison
Managed types that implement `IComparable` (or its generic version `IComparable<T>`) will produce Objective-C friendly methods that return a `NSComparisonResult` and accept a `nil` argument. This makes the generated API more friendly to Objective-C developers. For example:
```objc
- (NSComparisonResult)compare:(XAMComparableType * _Nullable)other;
```
### Categories
Managed extensions methods are converted into categories. For example, the following extension methods on `Collection`:
```csharp
public static class SomeExtensions {
public static int CountNonNull (this Collection collection) { ... }
public static int CountNull (this Collection collection) { ... }
}
```
would create an Objective-C category like this one:
```objc
@interface Collection (SomeExtensions)
- (int)countNonNull;
- (int)countNull;
@end
```
When a single managed type extends several types, multiple Objective-C categories are generated.
### Subscripting
Managed indexed properties are converted into object subscripting. For example:
```csharp
public bool this[int index] {
get { return c[index]; }
set { c[index] = value; }
}
```
would create Objective-C similar to:
```objc
- (id)objectAtIndexedSubscript:(int)idx;
- (void)setObject:(id)obj atIndexedSubscript:(int)idx;
```
which can be used via the Objective-C subscripting syntax:
```objc
if ([intCollection [0] isEqual:@42])
intCollection[0] = @13;
```
Depending on the type of your indexer, indexed or keyed subscripting will be generated where appropriate.
This [article](https://nshipster.com/object-subscripting/) is a great introduction to subscripting.
## Main differences with .NET
### Constructors vs initializers
In Objective-C, you can call any of the initializer prototypes of any of the parent classes in the inheritance chain, unless it is marked as unavailable (`NS_UNAVAILABLE`).
In C# you must explicitly declare a constructor member inside a class, which means constructors are not inherited.
To expose the right representation of the C# API to Objective-C, `NS_UNAVAILABLE` is added to any initializer that is not present in the child class from the parent class.
C# API:
```csharp
public class Unique {
public Unique () : this (1)
{
}
public Unique (int id)
{
}
}
public class SuperUnique : Unique {
public SuperUnique () : base (911)
{
}
}
```
Objective-C surfaced API:
```objc
@interface SuperUnique : Unique
- (instancetype)initWithId:(int)id NS_UNAVAILABLE;
- (instancetype)init;
@end
```
Here, `initWithId:` has been marked as unavailable.
### Operator
Objective-C does not support operator overloading as C# does, so operators are converted to class selectors:
```csharp
public static AllOperators operator + (AllOperators c1, AllOperators c2)
{
return new AllOperators (c1.Value + c2.Value);
}
```
to
```objc
+ (instancetype)add:(Overloads_AllOperators *)anObjectC1 c2:(Overloads_AllOperators *)anObjectC2;
```
However, some .NET languages do not support operator overloading, so it is common to also include a ["friendly"](/dotnet/standard/design-guidelines/operator-overloads) named method in addition to the operator overload.
If both the operator version and the "friendly" version are found, only the friendly version will be generated, as they will generate to the same Objective-C name.
```csharp
public static AllOperatorsWithFriendly operator + (AllOperatorsWithFriendly c1, AllOperatorsWithFriendly c2)
{
return new AllOperatorsWithFriendly (c1.Value + c2.Value);
}
public static AllOperatorsWithFriendly Add (AllOperatorsWithFriendly c1, AllOperatorsWithFriendly c2)
{
return new AllOperatorsWithFriendly (c1.Value + c2.Value);
}
```
becomes:
```objc
+ (instancetype)add:(Overloads_AllOperatorsWithFriendly *)anObjectC1 c2:(Overloads_AllOperatorsWithFriendly *)anObjectC2;
```
### Equality operator
In general operator `==` in C# is handled as a general operator as noted above.
However, if the "friendly" Equals operator is found, both operator `==` and operator `!=` will be skipped in generation.
### DateTime vs NSDate
From the [`NSDate`](https://developer.apple.com/reference/foundation/nsdate?language=objc) documentation:
> `NSDate` objects encapsulate a single point in time, independent of any particular calendrical system or time zone. Date objects are immutable, representing an invariant time interval relative to an absolute reference date (00:00:00 UTC on 1 January 2001).
Due to `NSDate` reference date, all conversions between it and `DateTime` must be done in UTC.
#### DateTime to NSDate
When converting from `DateTime` to `NSDate`, the `Kind` property on `DateTime` is taken into account:
|Kind|Results|
|---|---|
|`Utc`|Conversion is performed using the provided `DateTime` object as is.|
|`Local`|The result of calling `ToUniversalTime()` in the provided `DateTime` object is used for conversion.|
|`Unspecified`|The provided `DateTime` object is assumed to be UTC, so same behavior when `Kind` is `Utc`.|
The conversion uses the following formula:
```
TimeInterval = DateTimeObjectTicks - NSDateReferenceDateTicks / TicksPerSecond
```
In this formula:
- `NSDateReferenceDateTicks` is calculated based on the `NSDate` reference date of 00:00:00 UTC on 1 January 2001:
```csharp
new DateTime (year:2001, month:1, day:1, hour:0, minute:0, second:0, kind:DateTimeKind.Utc).Ticks;
```
- [`TicksPerSecond`](/dotnet/api/system.timespan.tickspersecond) is defined on [`TimeSpan`](/dotnet/api/system.timespan)
To create the `NSDate` object, the `TimeInterval` is used with the `NSDate` [dateWithTimeIntervalSinceReferenceDate:](https://developer.apple.com/reference/foundation/nsdate/1591577-datewithtimeintervalsincereferen?language=objc) selector.
#### NSDate to DateTime
The conversion from `NSDate` to `DateTime` uses the following formula:
```
DateTimeTicks = NSDateTimeIntervalSinceReferenceDate * TicksPerSecond + NSDateReferenceDateTicks
```
In this formula:
- `NSDateReferenceDateTicks` is calculated based on the `NSDate` reference date of 00:00:00 UTC on 1 January 2001:
```csharp
new DateTime (year:2001, month:1, day:1, hour:0, minute:0, second:0, kind:DateTimeKind.Utc).Ticks;
```
- [`TicksPerSecond`](/dotnet/api/system.timespan.tickspersecond) is defined on [`TimeSpan`](/dotnet/api/system.timespan)
After calculating `DateTimeTicks`, the `DateTime` [constructor](/dotnet/api/system.datetime.-ctor#System_DateTime__ctor_System_Int64_System_DateTimeKind_) is invoked, setting its `kind` to `DateTimeKind.Utc`.
> [!NOTE]
> `NSDate` can be `nil`, but a `DateTime` is a struct in .NET, which by definition can't be `null`. If you give a `nil` `NSDate`, it will be translated to the default `DateTime` value, which maps to `DateTime.MinValue`.
`NSDate` supports a higher maximum and a lower minimum value than `DateTime`. When converting from `NSDate` to `DateTime`, these higher and lower values are changed to the `DateTime` [MaxValue](/dotnet/api/system.datetime.maxvalue) or [MinValue](/dotnet/api/system.datetime.minvalue), respectively.

Просмотреть файл

@ -0,0 +1,43 @@
---
title: "Objective-C Platforms"
description: "This document describes the various platforms that .NET Embedding can target when working with Objective-C code. It discusses macOS, iOS, tvOS, and watchOS."
ms.prod: xamarin
ms.assetid: 43253BE4-A03A-4646-9A14-32C05174E672
author: davidortinau
ms.author: daortin
ms.date: 11/14/2017
---
# Objective-C Platforms
.NET Embedding can target various platforms when generating Objective-C code:
* macOS
* iOS
* tvOS
* watchOS [not implemented yet]
The platform is selected by passing the `--platform=<platform>` command-line
argument to .NET Embedding.
When building for the iOS, tvOS and watchOS platforms, .NET Embedding will
always create a framework that embeds Xamarin.iOS, since Xamarin.iOS contains
a lot of runtime support code which is required on these platforms.
However, when building for the macOS platform, it's possible to choose whether
the generated framework should embed Xamarin.Mac or not. It's possible to not
embed Xamarin.Mac if the bound assembly does not reference Xamarin.Mac.dll
(either directly or indirectly), and this is selected by passing
`--platform=macOS` to the .NET Embedding tool.
If the bound assembly contains a reference to Xamarin.Mac.dll, it's necessary
to embed Xamarin.Mac, and additionally the embeddinator must know which target
framework to use.
There are three possible Xamarin.Mac target frameworks: `modern` (previously
called `mobile`), `full` and `system` (the difference between each is
described in Xamarin.Mac's [target framework][1] documentation), and each is
selected by passing `--platform=macOS-modern`, `--platform=macOS-full` or
`--platform=macOS-system` to the .NET Embedding tool.
[1]: ~/mac/platform/target-framework.md

Двоичные данные
Docs/Tools/workbooks/images/azure-workbook-small.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 154 KiB

Двоичные данные
Docs/Tools/workbooks/images/azure-workbook.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 551 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 844 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 728 KiB

Двоичные данные
Docs/Tools/workbooks/images/workbook-small.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 837 KiB

Двоичные данные
Docs/Tools/workbooks/images/workbook.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 1.7 MiB

Просмотреть файл

@ -0,0 +1,46 @@
---
title: "Xamarin Workbooks"
description: "Xamarin Workbooks provide a blend of documentation and code that is perfect for experimentation, learning, and creating guides and teaching aids."
ms.prod: xamarin
ms.assetid: 04275482-0488-4F1C-8808-D03A8E21BE62
author: davidortinau
ms.author: daortin
ms.date: 10/23/2018
---
# Xamarin Workbooks
Xamarin Workbooks provide a blend of documentation and code that is perfect for
experimentation, learning, and creating guides and teaching aids.
Create a rich C# workbook for Android, iOS, Mac, WPF, or Console, and get instant live
results as you learn these APIs.
Xamarin Workbooks is open source software. Development happens in the open
on GitHub. We invite interested users and developers to get involved with the
project.
[Join us on GitHub!](https://github.com/Microsoft/workbooks)
Give it a try and let us know what you think, or if
you [run into any bugs](~/tools/workbooks/install.md#reporting-bugs). We have a
[forum](https://forums.xamarin.com/categories/inspector) too!
[![A sample UrhoSharp based workbook](images/interactive-1.0.0-urho-planet-earth-small.png)](images/interactive-1.0.0-urho-planet-earth.png#lightbox)
## [Installation and Requirements](install.md)
Information on getting Workbooks installed on your Mac or Windows computer.
## [Interactive Workbooks](workbook.md)
An introduction to how to use Xamarin Workbooks.
## Samples
There are a wide variety of [sample workbooks available on GitHub](https://github.com/xamarin/workbooks).
## [Integration SDK](sdk/index.md)
It is possible to extend Xamarin Workbooks with custom data representations
and renderers. Integrations are written with C# and TypeScript/JavaScript.

Двоичные данные
Docs/Tools/workbooks/install-images/windows-remove.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 27 KiB

Просмотреть файл

@ -0,0 +1,181 @@
---
title: "Workbooks Installation and Requirements"
description: "This document describes how to download and install Xamarin Workbooks, discussing supported platforms and system requirements."
ms.prod: xamarin
ms.assetid: 9D4E10E8-A288-4C6C-9475-02969198C119
author: davidortinau
ms.author: daortin
ms.date: 06/19/2018
---
# Workbooks Installation and Requirements
<a name="install"></a>
## Download and Install
<!-- markdownlint-disable MD001 -->
# [Windows](#tab/windows)
1. Check the [requirements](#requirements) below.
2. Download and install [Xamarin Workbooks for Windows](https://dl.xamarin.com/interactive/XamarinInteractive.msi).
3. Start [playing around](~/tools/workbooks/workbook.md) with workbooks.
# [macOS](#tab/macos)
1. Check the [requirements](#requirements) below.
2. Download and install [Xamarin Workbooks for Mac](https://dl.xamarin.com/interactive/XamarinInteractive.pkg).
3. Start [playing around](~/tools/workbooks/workbook.md).
-----
## Requirements
#### Supported Operating Systems
- **Mac** - OS X 10.11 or greater
- **Windows** - Windows 7 or greater (with Internet Explorer 11 or greater and
.NET 4.6.1 or greater)
#### Supported App Platforms
|App Platform|OS Support|Notes|
|--- |--- |--- |
|Mac|Only supported on Mac|
|iOS|Supported on Mac and Windows|Xamarin.iOS 11.0 and Xcode 9.0 or greater must be installed on Mac. Running iOS workbooks on Windows requires a Mac build host running all of the above, and the [Remoted iOS Simulator](~/tools/ios-simulator/index.md) installed on Windows.|
|Android|Supported on Mac and Windows|Must use Google, Visual Studio or Xamarin Android emulator, with a virtual device >= 5.0|
|WPF|Only supported on Windows|
|Console (.NET Framework)|Supported on Mac and Windows|
|Console (.NET Core)|Supported on Mac and Windows|
## Reporting Bugs
Please [report issues on GitHub][bugs], and include all of the following information:
### Log Files
Always attach Workbooks client log files:
- Mac: `~/Library/Logs/Xamarin/Workbooks/Xamarin Workbooks {date}.log`
- Windows: `%LOCALAPPDATA%\Xamarin\Workbooks\logs\Xamarin Workbooks {date}.log`
1.4.x also features the ability to select the log file in Finder (macOS) or
Explorer (Windows) directly from the main menu:
- **Help > Reveal Log File**
#### Log paths for Workbooks 1.3 and earlier:
- Mac: `~/Library/Logs/Xamarin/Inspector/Xamarin Inspector {date}.log`
- Windows: `%LOCALAPPDATA%\Xamarin\Inspector\logs\Xamarin Inspector {date}.log`
### Platform Version Information
It is very helpful to know details about your Operating System and installed Xamarin products.
From the main menu in Workbooks:
- **Help > Copy Version Information**
#### Instructions for Workbooks 1.3 and earlier:
Visual Studio For Mac
- **Visual Studio > About Visual Studio > Show Details > Copy Information**
- Paste into bug report
Visual Studio
- **Help > About Visual Studio > Copy Info**
- Let us know your Operating System version and whether you are running 32-bit or 64-bit Windows.
### Samples
If you can attach or link to the **.workbooks** file you are having trouble with,
that might help solve your bug more quickly.
### Devices
If you are having trouble connecting your iOS or Android workbook, and have
already checked [our troubleshooting page](~/tools/workbooks/troubleshooting/index.md),
we'll need to know:
- Name of device you are trying to connect to
- OS version of your device
- Android: Verify that you are using an x86 emulator
- Android: What emulator platform are you using? Google Emulator?
Visual Studio Android Emulator? Xamarin Android Player?
- iOS on Windows: What version of the Xamarin Remote iOS Simulator do you have
installed (check **Add/Remove Programs** in **Control Panel**)?
- iOS on Windows: Please also provide Platform Version Information for your Mac
build host
- Does the device have network connectivity (check via web browser)?
[bugs]: https://github.com/Microsoft/workbooks/issues/new
## Uninstall
### Windows
Depending on how you acquired Workbooks, you may have to perform
two uninstallation procedures. Please check both of these to completely
uninstall the software.
#### Visual Studio Installer
If you have Visual Studio 2017, open **Visual Studio Installer**, and look in
**Individual Components** for **Xamarin Workbooks**. If it is checked, uncheck it
and then click **Modify** to uninstall.
#### System Uninstall
If you installed Workbooks yourself with a downloaded installer,
it will need to be uninstalled via the **Apps & features**
system settings page on Windows 10 or via **Add/Remove Programs** in the
Control Panel on older versions of Windows.
> **Start > Settings > System > Apps & features**
![Xamarin Workbooks as listed in &quot;Apps &amp; features&quot;](install-images/windows-remove.png)
**You should still follow the procedure for the Visual Studio Installer to make
sure Workbooks does not get reinstalled without your knowledge.**
<a name="uninstall-macos"></a>
### macOS
Starting with [1.2.2](https://github.com/xamarin/release-notes-archive/blob/master/release-notes/interactive/interactive-1.2.md),
Xamarin Workbooks can be uninstalled from a terminal by running:
```bash
sudo /Library/Frameworks/Xamarin.Interactive.framework/Versions/Current/uninstall
```
The uninstaller will detail the files and directories it will remove and
ask for confirmation before proceeding.
Pass the `-help` argument to the `uninstall` script for more advanced
scenarios.
For older versions, you will need to manually remove the following:
1. Delete the Workbooks app at `"/Applications/Xamarin Workbooks.app"`
2. Delete the Inspector app at `"Applications/Xamarin Inspector.app"`
3. Delete the add-ins: `"~/Library/Application Support/XamarinStudio-6.0/LocalInstall/Addins/Xamarin.Interactive"` and `"~/Library/Application Support/XamarinStudio-6.0/LocalInstall/Addins/Xamarin.Inspector"`
4. Delete Inspector and supporting files here: `/Library/Frameworks/Xamarin.Interactive.framework` and `/Library/Frameworks/Xamarin.Inspector.framework`
## Downgrading
The bundle identifier for **/Applications/Xamarin Workbooks.app** changed from
`com.xamarin.Inspector` to `com.xamarin.Workbooks` in the 1.4 release, as
Workbooks and Inspector are now fully split.
Because of a bug in older installers, it is not possible to downgrade 1.4 or
newer releases using the 1.3.2 or older installers.
To downgrade from 1.4 or newer to 1.3.2 or older:
1. [Uninstall Workbooks & Inspector manually](#uninstall-macos)
2. Run the 1.3.2 or older `.pkg` installer

Просмотреть файл

@ -0,0 +1,24 @@
---
title: "Xamarin Workbooks Editor Keyboard Shortcuts"
description: "This document describes keyboard shortcuts available for use in the Xamarin Workbooks editor. In particular, it looks at various ways the Return key is used."
ms.prod: xamarin
ms.assetid: 6375A371-3215-4A7C-B97B-A19E58BE96D6
author: davidortinau
ms.author: daortin
ms.date: 03/30/2017
---
# Xamarin Workbooks Editor Keyboard Shortcuts
## The Return Key, and its nuances
The following table describes the various key bindings for executing code
and authoring markdown. We have taken great care to choose sensible and
consistent key bindings that are both familiar and fluid.
|Key Binding|Code Cell|Markdown Cell|
|--- |--- |--- |
|<kbd>Return</kbd>|<p>If the caret is at the end of the cell buffer and the cell can be successfully parsed, it will be executed and results will be displayed below the buffer, and a new code cell will be inserted and focused cell after the executed cell.</p><p>If parsing is not successful, a new line will be inserted into the buffer. Compiler diagnostics will not be produced if parsing is not successful.</p>|<p><kbd>Return</kbd> exhibits different behavior depending on the Markdown context at the caret.</p><ul><li>If the caret is in a Markdown code block, a literal new line is inserted.</li><li>If the caret is in a Markdown list block, create a new list item or split the current list item.</li><li>If the caret is in any other type of Markdown block, create a new paragraph block or split the current block.</li></ul>|
|<dl><dt>Mac</dt><dd><kbd>CommandReturn</kbd></dd><dt>Win</dt><dd><kbd>ControlReturn</kbd></dd></dl>|<p>Always attempts to parse and execute the cell contents. If compilation is successful, results (including execution exceptions) will be displayed below the buffer, and if there are no subsequent cells, a new one will be created and focused.</p><p>If there are any compilation errors, diagnostics will be displayed and the buffer will remain focused with the caret position unchanged.</p>|Inserts and focuses a new code cell after the current markdown cell.|
|<dl><dt>Mac</dt><dd><kbd>CommandShiftReturn</kbd><dd><dt>Win</dt><dd><kbd>ControlShiftReturn</kbd></dd></dl>|Inserts and focuses a new markdown cell after the current cell.|Same behavior as <kbd>Return</kbd>|
|<kbd>ShiftReturn</kbd>|Always inserts a new line, regardless of caret location or content.|Inserts a hard line break within the current Markdown block.|

Просмотреть файл

@ -0,0 +1,42 @@
---
title: "Architecture Overview"
description: "This document describes the architecture of Xamarin Workbooks, examining how the interactive agent and interactive client work together."
ms.prod: xamarin
ms.assetid: 6C0226BE-A0C4-4108-B482-0A903696AB04
author: davidortinau
ms.author: daortin
ms.date: 03/30/2017
---
# Architecture Overview
Xamarin Workbooks features two main components which must work in conjunction
with each other: _Agent_ and _Client_.
## Interactive Agent
The Agent component is a small platform-specific assembly which runs in the
context of a .NET application.
Xamarin Workbooks provides pre-built "empty" applications for a number of
platforms, such as iOS, Android, Mac, and WPF. These applications explicitly
host the agent.
During live inspection (Xamarin Inspector), the agent is injected via the
IDE debugger into an existing application as part of the regular development &
debugging workflow.
## Interactive Client
The client is a native shell (Cocoa on Mac, WPF on Windows) that hosts a web
browser surface for presenting the workbook/REPL interface. From an SDK
perspective, all client integrations are implemented in JavaScript and CSS.
The client is responsible (via Roslyn) for compiling source code into small
assemblies and sending them over to the connected agent for execution. Results
of execution are sent back to the client for rendering. Each cell in a workbook
yields one assembly which references the assembly of the previous cell.
Because an agent can be running on any type of .NET platform and has access to
anything in the running application, care must be taken to serialize results in
a platform-agnostic manner.

Двоичные данные
Docs/Tools/workbooks/sdk/debugging-images/developer-pane-small.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 51 KiB

Двоичные данные
Docs/Tools/workbooks/sdk/debugging-images/developer-pane.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 51 KiB

Двоичные данные
Docs/Tools/workbooks/sdk/debugging-images/mac-dev-tools.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 594 KiB

Двоичные данные
Docs/Tools/workbooks/sdk/debugging-images/windows-dev-tools.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 106 KiB

Просмотреть файл

@ -0,0 +1,83 @@
---
title: "Debugging integrations"
description: "This document describes how to debug Xamarin Workbooks integrations, both agent-side and client-side on Windows and Mac."
ms.prod: xamarin
ms.assetid: 90143544-084D-49BF-B44D-7AF943668F6C
author: davidortinau
ms.author: daortin
ms.date: 06/19/2018
---
# Debugging integrations
## Debugging agent-side integrations
Debugging agent-side integrations is best done by using the logging methods
provided by the `Log` class in `Xamarin.Interactive.Logging`.
On macOS, log messages appear in both the log viewer menu (**Window > Log Viewer**)
and in the client log. On Windows, messages only appear in the client log,
as there is no log viewer there.
The client log is at the following locations on macOS and Windows:
- Mac: `~/Library/Logs/Xamarin/Workbooks/Xamarin Workbooks {date}.log`
- Windows: `%LOCALAPPDATA%\Xamarin\Workbooks\logs\Xamarin Workbooks {date}.log`
One thing to be aware of is that when loading integrations via the usual `#r` mechanism
during development, the integration assembly will be picked up as a _dependency_ of the
workbook and packaged with it if an absolute path is not used. This can cause changes to
appear to not propagate, as if rebuilding the integration did nothing.
## Debugging client-side integrations
As client-side integrations are written in JavaScript and loaded into our
web browser surface (see the [architecture](~/tools/workbooks/sdk/architecture.md) documentation), the best
way to debug them is using the WebKit developer tools on Mac, or using F12
Chooser on Windows.
Both sets of tools allow you to view JavaScript/TypeScript source, set breakpoints,
view console output, and inspect and modify the DOM.
### Mac
To enable the developer tools for Xamarin Workbooks on Mac, run the following
command in your terminal:
```shell
defaults write com.xamarin.Workbooks WebKitDeveloperExtras -bool true
```
and then restart Xamarin Workbooks. Once you do so, you should see **Inspect Element**
appear in your right-click context menu, and a new **Developer** pane
will be available in Workbooks preferences. This option allows you to choose if you want
the developer tools opened at startup:
[![Developer pane](debugging-images/developer-pane-small.png)](debugging-images/developer-pane.png#lightbox)
This preference is restart-only as well—you'll need to restart the Workbooks client
in order for it to take effect on new workbooks. Activating the developer tools via
the context menu or the preferences will show the familiar Safari UI:
[![Safari dev tools](debugging-images/mac-dev-tools.png)](debugging-images/mac-dev-tools.png#lightbox)
For information about using the Safari developer tools, see the
[WebKit inspector documentation][webkit-docs].
### Windows
On Windows, the IE team provides a tool known as "F12 Chooser" that is a remote
debugger for embedded Internet Explorer instances. You can find the tool in the
following location:
```shell
C:\Windows\System32\F12\F12Chooser.exe
```
Run F12 Chooser, and you should see the embedded instance that powers the Workbooks
client surface in the list. Choose it, and the familiar F12 debugging tools from Internet
Explorer will appear, attached to the client:
[![F12 tools](debugging-images/windows-dev-tools.png)](debugging-images/windows-dev-tools.png#lightbox)
[webkit-docs]: https://trac.webkit.org/wiki/WebInspector

Двоичные данные
Docs/Tools/workbooks/sdk/images/mac-workbooks-integrated.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 193 KiB

Двоичные данные
Docs/Tools/workbooks/sdk/images/visual-studio-nuget.png Executable file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 15 KiB

Двоичные данные
Docs/Tools/workbooks/sdk/images/visual-studio-pcl-platforms.png Executable file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 7.4 KiB

Двоичные данные
Docs/Tools/workbooks/sdk/images/visual-studio-pcl.png Executable file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 50 KiB

Двоичные данные
Docs/Tools/workbooks/sdk/images/windows-workbooks-integrated.png Executable file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 16 KiB

Двоичные данные
Docs/Tools/workbooks/sdk/images/xamarin-studio-nuget.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 475 KiB

Двоичные данные
Docs/Tools/workbooks/sdk/images/xamarin-studio-pcl.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 515 KiB

Просмотреть файл

@ -0,0 +1,207 @@
---
title: "Getting Started with the Xamarin Workbooks SDK"
description: "This document describes how to get started with the Xamarin Workbooks SDK, which can be used to develop integrations for Xamarin Workbooks."
ms.prod: xamarin
ms.assetid: FAED4445-9F37-46D8-B408-E694060969B9
author: davidortinau
ms.author: daortin
ms.date: 03/30/2017
---
# Getting Started with the Xamarin Workbooks SDK
This document provides a quick guide to getting started with developing
integrations for Xamarin Workbooks. Much of this will work with the stable
Xamarin Workbooks, but **loading integrations via NuGet packages is only
supported in Workbooks 1.3**, in the alpha channel at the time of writing.
## General Overview
Xamarin Workbooks integrations are small libraries that use the
[`Xamarin.Workbooks.Integrations` NuGet][nuget] SDK to integrate with the Xamarin
Workbooks and Inspector agents to provide enhanced experiences.
There are 3 major steps to getting started with developing an
integration—we'll outline them here.
## Creating the Integration Project
Integration libraries are best developed as multiplatform libraries. Because you
want to provide the best integration on all the available agents, past and
future, you'll want to choose a broadly supported set of libraries. We recommend
using the "Portable Library" template for the broadest support:
# [Visual Studio for Mac](#tab/macos)
[![Portable Library Template Visual Studio for Mac](images/xamarin-studio-pcl.png)](images/xamarin-studio-pcl.png#lightbox)
# [Visual Studio](#tab/windows)
[![Portable Library Template Visual Studio](images/visual-studio-pcl.png)](images/visual-studio-pcl.png#lightbox)
In Visual Studio, you'll want to make sure you select the following target
platforms for your portable library:
[![Portable Library Platforms Visual Studio](images/visual-studio-pcl-platforms.png)](images/visual-studio-pcl-platforms.png#lightbox)
-----
Once you create the library project, add a reference to our
`Xamarin.Workbooks.Integration` NuGet library via the NuGet Package Manager.
# [Visual Studio for Mac](#tab/macos)
[![NuGet Visual Studio for Mac](images/xamarin-studio-nuget.png)](images/xamarin-studio-nuget.png#lightbox)
# [Visual Studio](#tab/windows)
[![NuGet Visual Studio](images/visual-studio-nuget.png)](images/visual-studio-nuget.png#lightbox)
-----
You'll want to delete the empty class that's created for you as part of the
project—you won't be needing it for this. Once you've done these steps,
you're ready to begin building your integration.
## Building an Integration
We'll build a simple integration. We really love the color green, so we'll
add the color green as a representation to each object. First, create a new
class called `SampleIntegration`, and make it implement our
`IAgentIntegration` interface:
```csharp
using Xamarin.Interactive;
public class SampleIntegration : IAgentIntegration
{
public void IntegrateWith (IAgent agent)
{
}
}
```
What we want to do is add a [representation](~/tools/workbooks/sdk/representations.md) for every object that is a
green color. We'll do this using a representation provider. Providers inherit
from the `RepresentationProvider` class—for ours, we just need to
override `ProvideRepresentations`:
```csharp
using Xamarin.Interactive.Representations;
class SampleRepresentationProvider : RepresentationProvider
{
public override IEnumerable<object> ProvideRepresentations (object obj)
{
// This corresponds to Pantone 2250 XGC, our favorite color.
yield return new Color (0.0, 0.702, 0.4314);
}
}
```
We're returning a `Color`, a pre-built representation type in our SDK.
You'll notice that the return type here is an `IEnumerable<object>`&mdash;one
representation provider may return many representations for an object! All
representation providers are called for every object, so it's important to not
make any assumptions about what objects are being passed to you.
The final step is to actually register our provider with the agent and tell
Workbooks where to find our integration type. To register the provider, add this
code to the `IntegrateWith` method in the `SampleIntegration` class we created
earlier:
```csharp
agent.RepresentationManager.AddProvider (new SampleRepresentationProvider ());
```
Setting the integration type is done via an assembly-wide attribute. You can put
this in your AssemblyInfo.cs, or in the same class as your integration type for
convenience:
```csharp
[assembly: AgentIntegration (typeof (SampleIntegration))]
````
During development, you may find it more convenient to
use `AddProvider` overloads on `RepresentationManager` that allow
you to register a simple callback to provide representations inside a workbook,
and then move that code into your `RepresentationProvider` implementation once
you're finished. An example for rendering an [`OxyPlot`][oxyplot] `PlotModel`
might look like this:
```csharp
InteractiveAgent.RepresentationManager.AddProvider<PlotModel> (
plotModel => Image (new SvgExporter {
Width = 300,
Height = 250
}.ExportToString (plotModel)));
```
> [!NOTE]
> These APIs give you a quick way to get up and running, but we would not
> recommend shipping an entire integration only using them&mdash;they provide very
> little control over how your types are processed by the client.
With the representation registered, your integration is ready to ship!
## Shipping your integration
To ship your integration, you'll need to add it to a NuGet package.
You can ship it with your existing library's NuGet, or if you're creating a
new package, you can use this template .nuspec file as a starting point.
You'll need to fill out the sections relevant to your integration. The most
important part is that all of the files for your integration must be in a
`xamarin.interactive` directory at the root of the package. This enables us
to easily find all the relevant files for your integration, regardless of
whether you use an existing package or create a new one.
```xml
<?xml version="1.0"?>
<package xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd">
<metadata>
<id>$YourNuGetPackage$</id>
<version>$YourVersion$</version>
<authors>$YourNameHere$</authors>
<projectUrl>$YourProjectPage$</projectUrl>
<description>A short description of your library.</description>
</metadata>
<files>
<file src="Path\To\Your\Integration.dll" target="xamarin.interactive" />
</files>
</package>
```
Once you've created the .nuspec file, you can pack your NuGet like so:
```csharp
nuget pack MyIntegration.nuspec
```
and then publish it to [NuGet][nugetorg]. Once it's there, you'll be able to
reference it from any workbook and see it in action. In the screenshot below,
we've packaged the sample integration that we built in this document and
installed the NuGet package in a workbook:
# [Visual Studio for Mac](#tab/macos)
[![Workbook with Integration](images/mac-workbooks-integrated.png)](images/mac-workbooks-integrated.png#lightbox)
# [Visual Studio](#tab/windows)
[![Workbook with Integration](images/windows-workbooks-integrated.png)](images/windows-workbooks-integrated.png#lightbox)
-----
Notice that you don't see any `#r` directives or anything to initialize the
integration—Workbooks has taken care of all of that for you behind the scenes!
## Next Steps
Check out our other documentation for more information about the
moving pieces that make up the SDK, and our [sample integrations](~/tools/workbooks/samples/index.md) for
additional things you can do from your integration, like providing custom
JavaScript that is run in the Workbooks client.
[nugetorg]: https://nuget.org
[nuget]: https://nuget.org/packages/Xamarin.Workbooks.Integration
[oxyplot]: http://www.oxyplot.org/

Просмотреть файл

@ -0,0 +1,81 @@
---
title: "Advanced Integration Topics"
description: "This document describes advanced topics related to Xamarin Workbooks integrations. It discusses the Xamarin.Workbook.Integrations NuGet package and API exposure within a Xamarin Workbook."
ms.prod: xamarin
ms.assetid: 002CE0B1-96CC-4AD7-97B7-43B233EF57A6
author: davidortinau
ms.author: daortin
ms.date: 03/30/2017
---
# Advanced Integration Topics
Integration assemblies should reference
the [`Xamarin.Workbooks.Integrations` NuGet][nuget]. Check out
our [quick-start documentation](~/tools/workbooks/sdk/index.md) for more information about getting
started with the NuGet package.
Client integrations are also supported, and are initiated by placing JavaScript
or CSS files with the same name as the agent integration assembly in the same
directory. For example, if the agent integration assembly (which references the
NuGet) is named `SampleExternalIntegration.dll`, then `SampleExternalIntegration.js`
and `SampleExternalIntegration.css` will be integrated into the client as well if
they exist. Client integrations are optional.
The external integration itself can be packaged as a NuGet, provided and
referenced directly inside the application that is hosting the agent, or simply
placed alongside a `.workbook` file that wishes to consume it.
External integrations (agent and client) in NuGet packages will be automatically
loaded when the package is referenced, as per the quick-start documentation,
while integration assemblies shipped alongside the workbook will need to reference
it as so:
```csharp
#r "SampleExternalIntegration.dll"
```
When referencing an integration this way, it will not be loaded by the client
right away&mdash;you'll need to call some code from the integration to have it
load. We'll be addressing this bug in the future.
The `Xamarin.Interactive` PCL provides a few important integration APIs. Every
integration must at least provide an integration entry point:
```csharp
using Xamarin.Interactive;
[assembly: AgentIntegration (typeof (AgentIntegration))]
class AgentIntegration : IAgentIntegration
{
const string TAG = nameof (AgentIntegration);
public void IntegrateWith (IAgent agent)
{
// hook into IAgent APIs
}
}
```
At this point, once the integration assembly is referenced, the client will
implicitly load JavaScript and CSS integration files.
## APIs
As with any assembly that is referenced by a workbook or live inspect session,
any of its public APIs are accessible to the session. Therefore it is
important to have a safe and sensible API surface for users to explore.
The integration assembly is effectively a bridge between an application or
SDK of interest and the session. It can provide new APIs that make sense
specifically in the context of a workbook or live inspect session, or provide
no public APIs and simply perform "behind the scenes" tasks like yielding
object [representations](~/tools/workbooks/sdk/representations.md).
> [!NOTE]
> APIs which must be public but should not be surfaced via IntelliSense
> can be marked with the usual `[EditorBrowsable (EditorBrowsableState.Never)]`
> attribute.
[nuget]: https://nuget.org/packages/Xamarin.Workbooks.Integration

Просмотреть файл

@ -0,0 +1,117 @@
---
title: "Representations in Xamarin Workbooks"
description: "This document describes the Xamarin Workbooks representation pipeline, which enables the rendering of rich results for any code that returns a value."
ms.prod: xamarin
ms.assetid: 5C7A60E3-1427-47C9-A022-720F25ECB031
author: davidortinau
ms.author: daortin
ms.date: 03/30/2017
---
# Representations in Xamarin Workbooks
## Representations
Within a workbook or inspector session, code that is executed and yields a
result (e.g. a method returning a value or the result of an expression) is
processed through the representation pipeline in the agent. All objects, with
the exception of primitives such as integers, will be reflected to produce
interactive member graphs and will go through a process to provide alternate
representations that the client can render more richly. Objects of any size and
depth are safely supported (including cycles and infinite enumerables) due to
lazy and interactive reflection and remoting.
Xamarin Workbooks provides a few types common to all agents and clients that
allow for rich rendering of results. `Color` is one example of such a type,
where for example on iOS, the agent is responsible for converting `CGColor` or
`UIColor` objects into a `Xamarin.Interactive.Representations.Color` object.
In addition to common representations, the integration SDK provides APIs for
serializing custom representations in the agent and rendering representations
in the client.
## External Representations
`Xamarin.Interactive.IAgent.RepresentationManager` provides the ability to
register a `RepresentationProvider`, which an integration must implement to
convert from an arbitrary object to an agnostic form to render. These agnostic
forms must implement the `ISerializableObject` interface.
Implementing the `ISerializableObject` interface adds a Serialize method
that precisely controls how objects are serialized. The `Serialize`
method expects that a developer will exactly specify which properties
are to be serialized, and what the final name will be. Looking at the
`Person` object in our [`KitchenSink` sample][sample], we can see how
this works:
```csharp
public sealed class Person : ISerializableObject
{
public string Name { get; }
// Rest of the code is omitted…
void ISerializableObject.Serialize (ObjectSerializer serializer)
=> serializer.Property (nameof (Name), Name);
}
```
If we wanted to provide a superset or subset of properties from the
original object, we can do that with `Serialize`. For example, we might
do something like this to provide a pre-computed `Age` property on `Person`:
```csharp
public sealed class Person : ISerializableObject
{
public string Name { get; set; }
public DateTime DateOfBirth { get; set; }
// <snip>
void ISerializableObject.Serialize (ObjectSerializer serializer)
{
serializer.Property (nameof (Name), Name);
serializer.Property (nameof (DateOfBirth), DateOfBirth);
// Let's pre-compute an Age property that's the person's age in years,
// so we don't have to compute it in the renderer.
var age = (DateTime.MinValue + (DateTime.Now - DateOfBirth)).Year - 1;
serializer.Property ("Age", age)
}
}
```
> [!NOTE]
> APIs that produce `ISerializableObject` objects directly do
> not need to be handled by a `RepresentationProvider`. If the object you
> want to display is **not** an `ISerializableObject`, you will want to
> handle wrapping it in your `RepresentationProvider`.
### Rendering a Representation
Renderers are implemented in JavaScript and will have access to a JavaScript
version of the object represented via `ISerializableObject`. The JavaScript
copy will also have a `$type` string property that indicates the .NET type
name.
We recommend using TypeScript for client integration code, which of course
compiles to vanilla JavaScript. Either way, the SDK provides [typings][typings]
which can be referenced directly by TypeScript or simply referred to manually
if writing vanilla JavaScript is preferred.
The main integration point for rendering is
`xamarin.interactive.RendererRegistry`:
```js
xamarin.interactive.RendererRegistry.registerRenderer(
function (source) {
if (source.$type === "SampleExternalIntegration.Person")
return new PersonRenderer;
return undefined;
}
);
```
Here, `PersonRenderer` implements the `Renderer` interface. See the [typings][typings] for more details.
[typings]: https://github.com/xamarin/Workbooks/blob/master/SDK/typings/xamarin-interactive.d.ts

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 174 KiB

Просмотреть файл

@ -0,0 +1,31 @@
---
title: "Sample Integrations"
description: "This document links to samples that demonstrate Xamarin Workbooks integrations. Linked samples work with representation rendering and SkiaSharp."
ms.prod: xamarin
ms.assetid: 327DAD2E-1F76-4EB5-BCD0-9E7384D99E48
author: davidortinau
ms.author: daortin
ms.date: 03/30/2017
---
# Sample Integrations
See the [Kitchen Sink][KitchenSink] sample for a working example of an
integration. Simply build `KitchenSink.sln` in Visual Studio for Mac or
Visual Studio and then open `KitchenSink.workbook`.
[![Kitchen Sink Integration Screenshot](samples-images/kitchensinkintegrationscreenshot.png)](samples-images/kitchensinkintegrationscreenshot.png#lightbox)
The Kitchen Sink sample demonstrates both sets of concepts:
* The representation pieces demonstrate how to use `RepresentationManager` to
enhance rendering by using the built-in representations.
* The `Person` object and its associated JavaScript renderer demonstrate using
`ISerializableObject` without going through a representation provider.
Also see [SkiaSharp][skiasharp] for a real-world example of an integration
that uses the existing [representations](~/tools/workbooks/sdk/representations.md) provided by Xamarin Workbooks to render
its types.
[KitchenSink]: https://github.com/xamarin/Workbooks/tree/master/SDK/Samples/KitchenSink
[skiasharp]: https://github.com/mono/SkiaSharp/tree/master/source/SkiaSharp.Workbooks

Просмотреть файл

@ -0,0 +1,62 @@
---
title: "Troubleshooting Xamarin Workbooks on Android"
description: "This document provides troubleshooting tips for working with Xamarin Workbooks on Android. It discusses emulator support, workbooks that won't load, and other topics."
ms.prod: xamarin
ms.assetid: F1BD293B-4EB7-4C18-A699-718AB2844DFB
author: davidortinau
ms.author: daortin
ms.date: 03/30/2017
---
# Troubleshooting Xamarin Workbooks on Android
## Emulator Support
To run an Android workbook, an Android emulator must be available for
use. Physical Android devices are not supported.
We recommend Google's emulator along with HAXM if your computer supports it.
If you must have Hyper-V enabled on your system, go with the Visual Studio
Android Emulator instead.
You must have an emulator that runs Android 5.0 or later. ARM emulators are
not supported. Use `x86` or `x86_64` devices only.
Please read [our documentation on setting up Android emulators][android-emu]
if you are not familiar with the process.
> [!NOTE]
> Workbooks 1.1 and earlier will try (and fail!) to use ARM emulators
> if they are available. To work around this, launch the x86 emulator of your
> choice before opening or creating an Android workbook. Workbooks will always
> prefer to connect to a running emulator, as long as it is compatible.
## Workbooks Won't Load
### Workbook window spins forever, never loads (Windows)
First, check that your emulator has fully-working network access by testing any
website in the emulator's web browser.
### Visual Studio Android Emulator cannot connect to the internet
If your emulator does not have network access, you may need to follow these
steps to fix your Hyper-V network switch. If you switch between Wi-Fi networks
frequently you may need to repeat this periodically:
1. **Make sure any critical network operations are complete, as this may
temporarily disconnect Windows from the internet.**
1. Close emulators.
1. Open `Hyper-V Manager`.
1. Under `Actions`, open `Virtual Switch Manager...`.
1. Delete all virtual switches.
1. Click `OK`.
1. Launch VS Android Emulator. You will probably be prompted to recreate
virtual network switch.
1. Test that VS Android Emulator's browser can access the internet.
[android-emu]: ~/android/deploy-test/debugging/debug-on-emulator.md
## Related Links
- [Reporting Bugs](~/tools/workbooks/install.md#reporting-bugs)

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 13 KiB

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 11 KiB

Просмотреть файл

@ -0,0 +1,83 @@
---
title: "Known Issues & Workarounds"
description: "This document describes known issues and workarounds for Xamarin Workbooks. It discusses CultureInfo issues, JSON issues, and more."
ms.prod: xamarin
ms.assetid: 495958BA-C9C2-4910-9BAD-F48A425208CF
author: davidortinau
ms.author: daortin
ms.date: 03/30/2017
---
# Known Issues & Workarounds
## Persistence of CultureInfo across cells
Setting `System.Threading.CurrentThread.CurrentCulture` or
`System.Globalization.CultureInfo.CurrentCulture` does not persist across
workbook cells on Mono-based Workbooks targets (Mac, iOS, and Android) due to
a [bug in Mono's `AppContext.SetSwitch`][appcontext-bug] implementation.
### Workarounds
- Set the application-domain-local `DefaultThreadCurrentCulture`:
```csharp
using System.Globalization;
CultureInfo.DefaultThreadCurrentCulture = new CultureInfo("de-DE")
```
- Or, update to Workbooks 1.2.1 or newer , which will rewrite
assignments to `System.Threading.CurrentThread.CurrentCulture` and
`System.Globalization.CultureInfo.CurrentCulture` to provide for
the desired behavior (working around the Mono bug).
## Unable to use Newtonsoft.Json
### Workaround
- Update to Workbooks 1.2.1, which will install Newtonsoft.Json 9.0.1.
Workbooks 1.3, currently in the alpha channel, supports versions 10
and newer.
### Details
Newtonsoft.Json 10 was released which bumped its dependency on
Microsoft.CSharp which conflicts with the version Workbooks ships
to support `dynamic`. This is addressed in the Workbooks 1.3 preview
release, but for now we have worked around this by pinning
Newtonsoft.Json specifically to version 9.0.1.
NuGet packages explicitly depending on Newtonsoft.Json 10 or newer
are only supported in Workbooks 1.3, currently in the alpha channel.
## Code Tooltips are Blank
There is a [bug in the Monaco editor][monaco-bug] in Safari/WebKit,
which is used in the Mac Workbooks app, that results in code
tooltips rendering without text.
![Monaco tooltips rendering without text](general-images/monaco-signature-help-bug.png)
### Workaround
- Clicking on the tooltip after it appears will force the text to render.
- Or update to Workbooks 1.2.1 or newer
[appcontext-bug]: https://bugzilla.xamarin.com/show_bug.cgi?id=54448
[monaco-bug]: https://github.com/Microsoft/monaco-editor/issues/408
## SkiaSharp renderers are missing in Workbooks 1.3
Starting in Workbooks 1.3, we've removed the SkiaSharp renderers that we shipped
in Workbooks 0.99.0, in favor of SkiaSharp providing the renderers itself, using
our [SDK](~/tools/workbooks/sdk/index.md).
### Workaround
- Update SkiaSharp to the latest version in NuGet. At the time of writing, this
is 1.57.1.
## Related Links
- [Reporting Bugs](~/tools/workbooks/install.md#reporting-bugs)

Просмотреть файл

@ -0,0 +1,21 @@
---
title: "Troubleshooting Xamarin Workbooks"
description: "This document links to various guides that provide troubleshooting information for working with Xamarin Workbooks. Linked content discusses general known issues, issues with Android workbooks, and provides support-related resources."
ms.prod: xamarin
ms.assetid: 1706EA2C-7A94-4E30-BD4D-A2F31070554F
author: davidortinau
ms.author: daortin
ms.date: 03/30/2017
---
# Troubleshooting Xamarin Workbooks
## [General Known Issues & Workarounds](general.md)
## [Issues with Android Workbooks](android.md)
## [Discuss Issues on the Forums][forums]
## [File a Bug Report](~/tools/workbooks/install.md#reporting-bugs)
[forums]: https://forums.xamarin.com/categories/inspector

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 121 KiB

Двоичные данные
Docs/Tools/workbooks/workbook-images/inspector-0.6.0-repl.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 278 KiB

Двоичные данные
Docs/Tools/workbooks/workbook-images/inspector-0.6.2-editing.gif Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 459 KiB

Двоичные данные
Docs/Tools/workbooks/workbook-images/skia0-sml.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 36 KiB

Двоичные данные
Docs/Tools/workbooks/workbook-images/skia0.png Normal file

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 164 KiB

Просмотреть файл

@ -0,0 +1,196 @@
---
title: "Interactive Workbooks"
description: "This document describes how to use Xamarin Workbooks to create live documents containing C# code for experimenting, teaching, training, or exploring."
ms.prod: xamarin
ms.assetid: B79E5DE9-5389-4691-9AA3-FF4336CE294E
author: davidortinau
ms.author: daortin
ms.date: 03/30/2017
---
# Interactive Workbooks
You can use Workbooks as a standalone application, separate from your IDE.
To start creating a new workbook, run the Workbooks app. If you haven't installed this already, visit the [Installation](~/tools/workbooks/install.md#install) page. You will be prompted to create a workbook in your platform of choice, which will automatically connect to an agent app allowing you to visualize your document in real time.
If the Workbooks app is already running, you can create a new document by browsing to **File > New**.
Workbooks can be saved and opened again later within the application. You can then share them with others to demonstrate ideas, explore new APIs, or teach new concepts.
## Code Editing
The code editing window provides code completion, syntax coloring,
inline live-diagnostics, and multi-line statement support.
[![The code editing window provides code completion, syntax coloring, inline live-diagnostics, and multi-line statement support](workbook-images/inspector-0.6.0-repl-small.png)](workbook-images/inspector-0.6.0-repl.png#lightbox)
Xamarin Workbooks are saved in a `.workbook` file, which is a CommonMark
file with some metadata at the top (see [Workbooks File Types](#workbooks-files-types) for more
details on how workbooks can be saved).
### NuGet Package Support
Many popular NuGet packages are supported directly in Xamarin Workbooks. You can
search for packages by browsing to **File > Add Package**. Adding a package will
automatically bring in `#r` statements referencing package assemblies, allowing
you to use them right away.
When you save a workbook with package references, those references are saved as
well. If you share the workbook with another person, it will automatically
download the referenced packages.
There are some known limitations with NuGet package support in Workbooks:
- Native libraries are supported only on iOS, and only when linked with
the managed library.
- Packages which depend on `.targets` files or PowerShell scripts will likely
fail to work as expected.
- To remove or modify a package dependency, edit the workbook's manifest with
a text editor. Proper package management is on the way.
### Xamarin.Forms Support
If you reference the Xamarin.Forms NuGet package in your workbook, the workbook
app will change its main view to be Xamarin.Forms-based. You can access it through
`Xamarin.Forms.Application.Current.MainPage`.
The View Inspector tab also has special support for showing the Xamarin.Forms
view hierarchy to help you understand your layouts.
## Rich Text Editing
You can edit the text around your code using the rich text editor included, as illustrated below:
![Edit the text around the code using the built-in rich text editor](workbook-images/inspector-0.6.2-editing.gif)
### Markdown Authoring
Workbook authors may sometimes find it easier to directly edit the CommonMark "source"
of the workbook with their favorite editor.
Be aware that if you then edit and save your workbook within the Workbooks client,
your CommonMark text may be reformatted.
Please note that due to the CommonMark extension we use to enable YAML metadata in
workbook files, `---` is reserved for that purpose. If you wish to create
[thematic breaks](https://spec.commonmark.org/0.27/#thematic-break) in your text,
you should use `***` or `___` instead. Such breaks should be avoided in Workbooks 1.2
and earlier due to a bug during save.
### Improvements in Workbooks 1.3
We've also extended the Markdown block quote syntax slightly to improve presentation. By
adding an emoji as the first character in your block quote, you can influence the background
color of the quote:
- `> [!NOTE]`
> will render as a note with a blue background
- `> [!IMPORTANT]`
> will render as a warning with a yellow background
- `> [!WARNING]`
> will render as a problem with a red background
You can also link to headers in the Workbook document. We generate anchors for each header,
with the anchor ID being the header text, processed as follows:
1. The header is lower-cased.
1. All characters except for alphanumerics and dashes are removed.
1. All spaces are replaced with dashes.
This means that a header like "Important Header" gets an id of `important-header` and can be
linked to by inserting a link to `#important-header` in the workbook.
## Document Structure
### Cell
A discrete unit of content, representing either executable code
or markdown. A code cell is comprised of up to four sub-components:
- Editor
- Buffer
- Compiler Diagnostics
- Console Output
- Execution Results
### Editor
The interactive text component of a cell. For code cells, this is
the actual code editor with syntax highlighting, etc. For markdown
cells this is a rich-text content editor with a context sensitive
formatting and authoring toolbar.
### Buffer
The actual text content of an editor.
### Compiler Diagnostics
Any diagnostics produced when compiling code, rendered only when
explicit execution is requested. Displayed immediately below the
cell editor.
### Console Output
Any output written to standard out or standard error during the
execution of the cell. Standard out will be rendered in black
text and standard error will be rendered in red text.
### Execution Results
Rich and potentially interactive representations of results for
a cell will be rendered upon successful compilation, provided
a result is actually produced by execution. Exceptions are
considered results in this context, since they are produced
as a result of actually executing the compilation.
## Workbooks Files Types
### Plain Files
By default, a workbook saves as a plain text `.workbook` file containing
CommonMark-formatted text.
### Packages
A workbook package is a directory that is named with the `.workbook` extension.
On Mac's Finder and in the Xamarin Workbooks open dialog and recent
files menu, this directory will be recognized as if it were a file.
The directory must contain an `index.workbook` file, which is the actual plain
text workbook that will be loaded in Xamarin Workbooks. The directory can also
contain resources required by `index.workbook`, including images or other
files.
If a plain text `.workbook` file that references resources from its same
directory is opened in Workbooks 0.99.3 or later, when it is saved, it will be
converted into a `.workbook` package. This is true on both Mac and Windows.
> [!NOTE]
> Windows users will open the `package.workbook\index.workbook` file
directly, but otherwise the package will behave the same as on Mac.
### Archives
Workbook packages, being directories, can be hard to distribute easily over the
internet. The solution is workbook archives. A workbook archive is a
zip-compressed workbook package, named with the `.workbook` extension.
Starting in Workbooks 1.1, when saving a workbook package, the Save dialog
offers the choice of saving as an archive instead. Workbooks 1.0 had no
built-in way of creating or saving archives.
In Workbooks 1.0, when a workbook archive was opened, it was transparently
converted into a workbook package, and the zip file was lost. In Workbooks 1.1,
the zip file remains. When the user saves the archive, it is replaced with a
new zip file.
You can create a workbook archive manually by right-clicking a workbook package
and selecting **Compress** on Mac, or **Send To > Compressed (zipped) folder**
on Windows. Then rename the zip file to have a `.workbook` file extension. This
only works with workbook packages, not plain workbook files.
## Related Links
- [Welcome to Workbooks](https://developer.xamarin.com/workbooks/workbooks/getting-started/welcome.workbook)