Broker xamarin что это
Перейти к содержимому

Broker xamarin что это

  • автор:

Languages and frameworks: Xamarin

JetBrains Rider supports creating and working with Xamarin applications for both Android and iOS. Although currently JetBrains Rider does not provide a designer or a previewer for Xamarin forms, you can still benefit from code analysis, coding assistance, and debugging features in C#, VB.NET, and other languages, as well as from general IDE features, such as the integrated VCS client.

If other tools that Xamarin relies on (for example, Android SDK, Android Emulator) are configured properly, you will be able to build and run your Xamarin application right from the JetBrains Rider IDE.

Xamarin SDK

To develop Xamarin Applications you need to have a Xamarin SDK on your machine. There are two different Xamarin SDKs — for iOS/Mac and for Android .

Xamarin SDK consists of two parts:

  • Assemblies with .NET types for the target platform. For example, a .NET type to represent the base OSX NSObject . Using these assemblies, IDE and compiler resolve and build user code.
  • Tools that transform .NET projects into native applications, which can be deployed and executed on the emulator or a physical device. For example, using these tools .apk packages for Android are built.

JetBrains Xamarin SDK

JetBrains Rider can use different Xamarin SDKs, for example the one from Visual Studio. However, if you do not have Visual Studio on your machine, you can use JetBrains Xamarin SDK prepared and packed by the JetBrains Rider team.

JetBrains Xamarin SDK is a custom build of Xamarin GitHub sources with some improvements and additional code.

Currently JetBrains Xamarin SDK lacks some features compared to Visual Studio Xamarin SDK, but it is in the process of constant improvement.

JetBrains Xamarin SDK is available for Windows and macOS:

There are two JetBrains Xamarin SDK builds available on Windows targeting the following platforms:

Apple platform (iOS, Mac, tvOS, watchOS)

JetBrains Xamarin SDK for iOS development provides a limited feature set on Windows. For example, currently it does not support connecting to a remote Mac and perform full build/deploy.

JetBrains Xamarin SDK for Apple platforms on Windows ships as a .zip file (~ 60Mb) and installs into the JetBrains MsBuild directory:

JetBrains Xamarin SDK for Android development provides a solid feature set. However, fast deployment is currently not supported.

JetBrains Xamarin SDK for Android platforms on Windows ships as a .zip file (~ 700Mb) and installs into the JetBrains MsBuild directory:

There are two JetBrains Xamarin SDK builds available on macOS targeting the following platforms:

Apple platform (iOS, Mac, tvOS, watchOS)

On macOS, JetBrains Xamarin SDK for Apple platforms provides almost the same feature set as Visual Studio SDK, all known scenarios are supported.

JetBrains Xamarin SDK for iOS development on macOS ships as a .dmg file (~ 700Mb) and installs into:

  • /Library/Frameworks/Xamarin.iOS.framework
  • /Library/Frameworks/Xamarin.Mac.framework
  • /Library/Frameworks/Mono.framework/External

JetBrains Xamarin SDK for Android development provides a solid feature set. However, fast deployment is currently not supported.

JetBrains Xamarin SDK for Android development on macOS ships as a .dmg file (~ 700Mb) and installs into:

  • /Library/Frameworks/Xamarin.Android.framework
  • /Library/Frameworks/Mono.framework/External

Before you start

Xamarin aims to be executed on a variety of different platforms and therefore Xamarin development relies on several different tools for building and running your applications.

On Windows, you can develop Xamarin applications for any platform, but local build and run/debug is limited to Android devices and emulators.

If you use Visual Studio Xamarin SDK, you will be able to build and run your application on iOS and macOS. To do so, configure a Mac agent accessible on the network, and then connect to it ( Tools | iOS | Xamarin Mac Agent ).

  1. Install a Xamarin SDK for iOS on your machine in one of the following ways.
    • Install Xamarin in Visual Studio. Note that you can use Visual Studio Community, which is free. If you already have Visual Studio installed, you have to add Xamarin support to it.
    • Start installation of Xamarin iOS & Mac on the Environment page of JetBrains Rider settings Control+Alt+S and follow the installation wizard. This way JetBrains Rider will automatically download and install JetBrains Xamarin SDK for iOS & Mac.
    • Alternatively you can clone the Xamarin open-source repo from GitHub, build it and install on the machine. This way is quite complicated and we do not recommend it.
  2. Install Android development tools in one of the following ways:
    • Start installation of Xamarin Android on the Environment page of JetBrains Rider settings Control+Alt+S and follow the installation wizard. This way JetBrains Rider will automatically download and install JetBrains Xamarin SDK for Android.
    • Alternatively, all components that are automatically installed on the the Environment page of JetBrains Rider settings Control+Alt+S , could be also installed manually:
      • Rider Xamarin Android Support plugin. It has all necessary features, like Android SDK manager.
      • Android SDK developed and provided by Google. You can install it from Visual Studio, Android Studio, Rider (with Rider Xamarin Android Support plugin), or downloaded as a set of command line tools.
      • Java SE Development Kit (JDK)

On macOS, you can develop, build and run fully cross-platform Xamarin applications.

  1. Install a Xamarin SDK on your machine in one of the following ways.
    • Install Visual Studio for Mac.
    • Start installation of Xamarin iOS & Mac on the Environment page of JetBrains Rider settings Control+Alt+S and follow the installation wizard. This way JetBrains Rider will automatically download and install JetBrains Xamarin SDK for iOS & Mac.
    • Alternatively you can clone the Xamarin open-source repo from GitHub, build it and install on the machine. This way is quite complicated and we do not recommend it.
  2. For iOS and Mac development, install Xcode. You will need an Apple ID for installing and signing into Xcode. If you do not already have it, you can create a new one at https://appleid.apple.com. JetBrains Rider will detect Xcode automatically. If you have several Xcode versions, you can choose which one to use on the Build, Execution, Deployment | iOS page of JetBrains Rider settings Control+Alt+S .
  3. Install Android development tools in one of the following ways:
    • Start installation of Xamarin Android on the Environment page of JetBrains Rider settings Control+Alt+S and follow the installation wizard. This way JetBrains Rider will automatically download and install JetBrains Xamarin SDK for Android.
    • Alternatively, all components that are automatically installed on the the Environment page of JetBrains Rider settings Control+Alt+S , could be also installed manually:
      • Rider Xamarin Android Support plugin. It has all necessary features, like Android SDK manager.
      • Android SDK developed and provided by Google. You can install it from Visual Studio, Android Studio, Rider (with Rider Xamarin Android Support plugin), or downloaded as a set of command line tools.
      • Java SE Development Kit (JDK)

You can check the status of Xamarin tools and install or update them on the Environment page of JetBrains Rider settings Control+Alt+S :

JetBrains Rider: Environment settings

Create and open Xamarin projects

JetBrains Rider supports creating new and working with existing projects. Project templates are available, too.

You can create a new Xamarin project in a new solution using File | New… or add a new Xamarin project to the existing solution by right-clicking the solution or solution folder node in the Solution Explorer, and choosing Add | New Project .

JetBrains Rider: New Solution wizard. Xamarin

Xcode integration on macOS

When developing Xamarin applications on macOS, it is recommended to edit resource files and connect resources to code using Xcode.

You can use context menus of .storyboard , .xib , .plist files or of the Xamarin macios project node to open them in Xcode.

If the file or project has never been opened in Xcode before, JetBrains Rider will generate an Xcode project as follows:

  • xcodeproj project specifications (a project descriptor similar to csproj but for Xcode) is generated
  • Source files for all user types inherited NSObject (forms, delegates, views, controls, and so on) in Objective C are generated
  • All resources (images, designer files) are copied

When the project structure is ready, Xcode will start automatically and you can use it to edit resources. Every time Rider receives focus, it looks for changes (edits in existing files, new files, removed files) and integrates these changes into the Xamarin .NET project. It modifies .designer.cs parts of user types (inherited from NSObject ) and copies back all changed resources.

All Xcode-related events are printed in the Xcode console tool window, which appears when you open resources or projects in Xcode:

Xamarin development in JetBrains Rider: Xcode console

How it works under the hood

When you create a new Xamarin macios project

  1. JetBrains Rider creates the corresponding xcodeproj project ( pbxproj and other necessary files) project in the obj\xcode subdirectory with all required settings and configurations.
  2. Copies of all content files (views, plist files, images, and so on) are created in that directory.
  3. For each ViewController type JetBrains Rider generates an objc class with actions and outlets.
  4. The generated project is opened automatically in Xcode.

When you made changes in Xcode and then switch to Rider

  1. All modified content files are copied back into .NET project.
  2. Settings are updated.
  3. objc files are parsed and *.designer.cs files are regenerated for view controllers. For all these files you will see a generated header:

// WARNING // // This file has been generated automatically by Rider IDE // to store outlets and actions made in Xcode. // If it is removed, they will be lost. // Manual changes to this file may not be handled correctly.

Run and debug Xamarin applications

When you create or open a Xamarin project, JetBrains Rider automatically creates run/debug configurations for each Xamarin project in the solution.

If you want to adjust something in the way your application starts and executes, you can edit and create new run/debug configurations. When you start a Xamarin application from the IDE, you can use the corresponding selector on the navigation bar to choose which configuration should be used:

JetBrains Rider: Choosing a run/debug configuration for Xamarin application

Debug a Xamarin project, which was not created with JetBrains Rider

  1. Press Control+Alt+S to open the IDE settings and then select Environment .
  2. Enable Xamarin Android and Xamarin iOS & Mac support. If you are on Windows and have Xamarin SDK installed via Visual Studio, it will be detected automatically. Otherwise, JetBrains Rider will suggest installing JetBrains Xamarin SDK. JetBrains Xamarin SDK cannot be installed alongside with Visual Studio Xamarin SDK.
  3. Once Xamarin SDK is installed, you can create Xamarin-specific run/debug configurations.
  4. Open the Run/Debug Configuration dialog in one of the following ways:
    • Select Run | Edit Configurations from the main menu.
    • With the Navigation bar visible ( View | Appearance | Navigation Bar ), choose Edit Configurations from the run/debug configuration selector.
    • Press Alt+Shift+F10 and then press 0 .
  5. In the Run/Debug Configuration dialog that opens, press Alt+Insert or click , then choose Xamarin.Android , Xamarin.iOS , or Xamarin.Mac from the list.
  6. Specify the target project and other parameters if necessary, then click OK .
  7. Use the newly created configuration to run and debug your Xamarin project.

Webinar recording: Better Xamarin Development with Rider for Mac

You can also watch this webinar recording where Dylan Berry explores the various ways Rider can help you improve your coding speed and quality when developing Xamarin apps.

  • 0:05 – Introduction
  • 1:22 – Tools are important
  • 11:00 – Get started with Rider on Mac
  • 13:43 – Exploring Rider
  • 1:04:46 – Plugins

Подробно о Xamarin

Вы неплохо владеете языком C# и платформой .NET в целом? Вам надоело стоять в стороне и смотреть, как кто-то другой пишет крутые мобильные приложения вместо вас? У меня есть для вас кое-что интересное! То, что поможет вам изменить сложившуюся ситуацию и позволит писать отличные мобильные приложения, не требуя отдельного изучения Objective-C и Java. Я расскажу вам о продукте Xamarin. Подробно и правдиво.

Что это?

Xamarin — это фреймворк для кроссплатформенной разработки мобильных приложений (iOS, Android, Windows Phone) с использованием языка C#. Идея очень простая. Вы пишете код на своем любимом языке, с применением всех привычных для вас языковых фич типо LINQ, лямбда-выражений, Generic`ов и async`ов. При этом вы имеете полный доступ ко всем возможностям SDK платформы и родному механизму создания UI, получая на выходе приложение, которое, строго говоря, ничем не отличается от нативных и (по крайней мере по заверениям) не уступает им в производительности.

  • Xamarin.IOS — библиотека классов для C#, предоставляющая разработчику доступ к iOS SDK;
  • Xamarin.Android — библиотека классов для C#, предоставляющая разработчику доступ к Android SDK;
  • Компиляторы для iOS и Android;
  • IDE Xamarin Studio;
  • Плагин для Visual Studio.

Давай подробнее

Некоторое время назад достаточно широкую известность получили ряд фреймворков(например PhoneGap), которые предлагают разработку кроссплатформенных мобильных приложений на HTML5 с использованием JavaScript. Идея заключается в том, что приложение разрабатывается как обычный сайт для мобильных устройств с использованием соответствующих js-библиотек, например, Jquery Mobile. Затем все это упаковывается в некий контейнер, который для пользователя выглядит как нативное приложение. Минусы этих фреймворков очевидны: во-первых, вы не имеете доступа к нативным элементам UI. То есть даже если вы хотите использовать стандартную кнопку «Назад» для iPhone, вы должны ее нарисовать и сверстать. Во-вторых, вы получаете урезанный и обобщенный API для работы с платформой. Таким образом, те или иные фичи, присущие какой-то отдельной платформе будут вам недоступны. Ну и третье и самое важное — такое приложение физически запускается внутри браузера телефона (точнее внутри контрола WebView). Не нужно расписывать долго, что это значит: низкая производительность (особенно «хорош» WebView на старых версиях Android) и огромные проблемы с отображением (ну, господа, это же — браузер). Хотя, конечно, в определенных случаях эти фреймворки могут оказаться очень уместны.

Xamarin — это про другое. Т.к. я надеюсь, что мы здесь все — неглупые пацаны разработчики, я расскажу о том, как он устроен внутри. Это позволит понять потенциал данной технологии. Xamarin основан на open-source реализации платформы .NET — Mono. Эта реализация включает в себя собственный компилятор C#, среду выполнения, а так же основные .NET библиотеки. Цель проекта — позволить запускать программы, написанные на C#, на операционных системах, отличных от Windows — Unix-системах, Mac OS и других. Важно, что разработкой Xamarin занимаются те же люди, что и разработкой Mono. И (тут внимание) — это НЕ Microsoft со всеми вытекающими плюсами и минусами.

С точки зрения исполнения приложений между iOS и Android есть одно ключевое различие — способ их предварительной компиляции. Как известно, для выполнения приложений в Android используется виртуальная Java-машина Dalvik. Нативные приложения, которые пишутся на Java, компилируются в некий промежуточный байт-код, который интерпретируется Dalvik`ом в команды процессора в момент исполнения программы(т.е. аналогично тому, как работает CLR в .NET). Это так называемая Just-in-time компиляция (компиляция на лету). В iOS используется другая модель компиляции — Ahead-of-Time (компиляция перед исполнением). Xamarin учитывает это различие, предоставляя отдельные компиляторы для каждой из этих платформ, которые позволяют на выходе получать настоящие, нативные приложения, которые выполняются вне контекста браузера и могут использовать все аппаратные и программные ресурсы платформы.
Для iOS ситуация простая — никакой виртуальной машины нет и программный код должен быть просто заранее скомпилирован в машинный. Для этой цели используется AOT компилятор Mono.
Для Android интереснее. При компиляции приложения происходит перевод кода на C# в промежуточный байт-код, понятный виртуальной машине Mono и сама эта виртуальная машина также добавляется в упакованное приложение. И Mono и Dalvik написаны на Си и работают поверх ядра Linux (а мы помним, что Android основана на Linux). Вы уже понимаете, что происходит. При запуске приложения на Android обе виртуальные машины начинают работать бок о бок и обмениваются данными через специальный механизм wrapper`ов.

Это все хорошо, но давай ближе к разработке

Расскажу подробнее о самих библиотеках на примере Xamarin.iOS (Monotouch), т.к. опыта работы с ней гораздо больше, чем с Xamarin.Android (но там все аналогично).
Библиотека классов Monotouch.dll предоставляет доступ ко всем возможностям iOS SDK. Для разработчика — это просто набор C#-классов с хорошей аннотацией. Внутри эти классы используют разработанные инженерами Xamarin механизмы биндинга на нативные классы и методы. Важно, что этот же механизм можно использовать для биндинга любых библиотек, написанных на objective-c. Большинство классов и методов называются так же, как в оригинальном iOS SDK, хотя бывают исключения (в этом случае приходится использовать поиск в документации Xamarin по оригинальному названию, т.к. оно фигурирует в атрибутах биндинга). В классах активно используется механизм C# event`ов, что позволяет писать красивый и компактный код обработчиков с использованием лямбда-выражений:

button.TouchUpInside += (s, o) => < message.Text = "Hello!"; >; 

Да и в целом код, написанный на C# выглядит гораздо читабельней и приятней. Посмотрите разницу на примере кода, создающего строку с атрибутами:

Для асинхронной разработки Xamarin предоставляет возможность использовать как классы из пространства имен System.Threading.Thread и System.Threading.ThreadPool, так и полный спектр возможностей, предоставляемых Task Parallel Library. Использование последней, однако, считается предпочтительным. Кроме того, на момент написания статьи вышла очередная Stable версия, в которой появилась поддержка .NET 4.5, в частности, теперь можно использовать ключевые слова async/await. Хотя эта возможность была доступна и ранее, но для этого приходилось использовать beta-канал обновлений.

Что с ограничениями?

Ограничения в Xamarin.iOS связаны в основном с тем, что в iOS, как было сказано выше, в отличии от .NET и Mono нет виртуальной машины. Поэтому возникают трудности с поддержкой Generic. Причина ясна — на компилятор ложится задача проанализировать код и определить все возможные конкретизации в том или ином классе и методе. Отсюда возникают такие ограничения:

  • Не рекомендуется использовать Virtual Generic методы, т.к компилятор не всесилен и может не учесть все возможные варианты использования;
  • Нельзя создавать Generic-наследников от класса NSObject, который является базовым в иерархии Objective-C. Достаточно серьезное ограничение, которое может некоторым образом испортить вашу стройную и красивую архитектуру.
Разработка UI

Для каждой платформы Xamarin предоставляет возможность использовать нативные средства разработки UI и нативные элементы пользовательского интерфейса. Для Android создание UI может происходить непосредственно в коде или же при помощи декларативного подхода с описанием интерфейса в XML. Для iOS это также либо код, либо использование нативных средств проектирования интерфейса — отдельные xib-файлы или же один большой Storyboard. Редактирование этих файлов происходит в привычной для iOS-разработчика среде XCode. И это означает, что вам потребуется Mac. Да, для разработки iOS-приложений вам в любом случае потребуется Mac по двум причинам:
Во-первых, как я уже сказал, для редактирования UI в среде XCode. Во-вторых, для отладки приложений требуется симулятор iPhone/iPad, который также доступен только на Mac.

Переносимость кода

Xamarin, по заявлениям разработчиков, является средством кроссплатформенной разработки, т.е. ожидаемо, что приложение, написанное один раз, может быть запущено на различных мобильных платформах. Но, в этом случае возникает конфликт с предыдущим пунктом. Как же так?

На самом деле ситуация обстоит следующим образом. Для каждой из платформы вам потребуется реализовать собственный слой UI. Т.е код, который отвечает за внешний вид приложения, вам придется написать для каждой платформы отдельно. Это цена за возможность использования нативных механизмов работы с UI. Если разбивать приложение на слои, то получается такая схема:

  • Data Layer (DL) – Хранилище данных, например, база SqlLite или xml-файлы;
  • Data Access Layer (DAL) – Обертка над хранилищем для осуществления CRUD-операций;
  • Business Layer (BL) – Слой, содержащий бизнес-логику приложения;
  • Service Access Layer (SAL) – Слой, отвечающий за взаимодействие с удаленными сервисами (Rest, Json, WCF);
  • Application Layer (AL) – Слой, содержащий платформозависимый код, другими словами, это код, который зависит от библиотек monotouch.dll или monodroid.dll;
  • User Interface Layer (UI) – Слой пользовательского интерфейса.
Сторонние компоненты

У Xamarin существует собственный магазин сторонних компонентов Xamarin Components.Он интегрируется в IDE и позволяет в несколько кликов подключать к вашему проекту различные компоненты, написанные как инженерами Xamarin, так и сторонними разработчиками. Количество компонентов, кстати, растет как на дрожжах. Есть как платные, так и бесплатные(на данный момент их большинство). Все компоненты можно разделить на две части. Одни предоставляют дополнительные элементы пользовательского интерфейса, другие являются библиотеками классов. Например вариант для Mono известной библиотеки для работы с Json — Json.NET или же библиотека для взаимодействия с Rest-сервисами — RestSharp. Не все компоненты кроссплатформенные, многие доступны только для конкретной платформы. Как я упоминал выше, Xamarin использует механизм биндингов для связывания с нативными библиотеками классов, что позволяет портировать на C# любые нативные библиотеки классов. Кроме того, для Xamarin.iOS, например, существует специальная утилита, которая умеет генерировать такие биндинги автоматически. Собственно это позволяет инженерам Xamarin поспевать за всеми нововведениями iOS. Так, в частности, в Xamarin.iOS практически сразу после выхода появилась возможность использовать Dropbox API, а так же новые фичи iOS 7.

Документация и комьюнити

Xamarin имеет отличную документацию, содержащую подробные руководства, сниппеты, а также внушительную базу примеров. Документация непосредственно по всем классам библиотек Monotouch и Monodroid являются частью общей документации Mono. Но, к сожалению, этого все равно недостаточно, чтобы покрыть весь пласт вопросов, которые могут возникать в процессе разработки. У Xamarin существует комьюнити разработчиков, которое сконцентировано на официальном форуме и на StackOverlow. Активностью и инициативностью людей в комьюнити похвастаться не могу. Из пяти вопросов, заданных на официальном форуме, ответ я получил только на один. Может быть, не то спрашивал. В этом плане неоценимую помощь оказала приватная тех. поддержка с инженерами по электронной почте, доступная в business-лицензии. Отвечают, как правило, в течении нескольких часов и не стандартными отписками «попробуйте выключить и включить», а действительно разбираются в проблеме и помогают ее решить. Следует понимать, что база вопросов и ответов, накопленная для нативной разработки гораздо шире, чем для Xamarin, поэтому, как бы вы ни хотели, вам придется разобраться в специфическом синтаксисе objective-c (c Java проблем быть не должно), чтобы понимать примеры кода на том же StackOverflow. Кроме того, это откроет вам доступ к прочтению и пониманию официальной документации для платформы, что на определенном этапе может стать очень важно. С другой стороны, в этом есть и положительный момент: получив такой базис, вам будет проще перейти к нативной разработке при необходимости.

Среда разработки

Разработчики Xamarin в качестве среды разработки предлагают использовать либо собственную IDE — Xamarin Studio, либо Visual Studio (в business-лицензии, об этом ниже).

Xamarin Studio
  • Приятная подсветка синтаксиса;
  • Автодополнение кода (включая возможность одновременного импорта namespaces);
  • Удобный универсальный поиск по названиям файлов, типам, членам классов и т.п;
  • Развитые возможности навигации по проекту: Быстрый переход к описанию класса, переход к базовому классу, список мест использования класса и т.д.;
  • Различные механизмы рефакторинга и быстрая подсказка (как alt+Enter в Resharper);
  • Достаточно развитые механизмы дебага, включая слежение, просмотр текущего значения переменной при наведении, визуализацию потоков и аналог Immediate window в VS;
  • Встроенная интеграция с системами контроля версий: SVN, Git и TFS (для TFS, правда, нужны сторонние утилиты);
  • Горячие клавиши (включая copy-paste) работают только в английской раскладке. Разработчикам известно об этой проблеме. Баг в багтрекере заведен;
  • Периодически, при попытке поставить breakpoint студия виснет. Несмотря на наличие механизма автосохранения, это немного расстраивает.
  • При использовании встроенной интеграции с SVN добавление новых файлов в проект не отслеживается автоматически. Т.е. изменение в файле .csproj зачекинятся, а сами файлы — нет. По каждому файлу нужно кликать правой кнопкой и добавлять его в репозиторий. Техподдержка сообщила, что им известно об этом баге и они исправят его в одном из ближайших обновлений.
  • Иногда проект перестает компилироваться. Лечится перезапуском студии.
Visual Studio

Xamarin предлагает возможность вести разработку в Visual Studio после установки специального плагина, который доступен в business-лицензии (на момент выхода статьи — 999$), но есть месяц триала. Плюсы очевидны: вы становитесь разработчиком мобильных приложений, не меняя места дислокации, и можете использовать всю тяжелую артиллерию в лице Resharper и других ваших любимых плагинов. После установки плагина для Visual Studio вам потребуется настроить соединение с вашим Mac, которое будет использовано при запуске проекта на выполнение. Т.е. после запуска, приложение автоматически пересылается на Mac, где компилируется и загружается либо на симулятор либо на устройство, при этом сам процесс процесс отладки, расстановка брейкпоинтов и т.д. будет происходить в Visual Studio.
Вариантов работы в Visual Studio несколько. Либо вы используется виртуальную машину внутри Mac (например Parallels), куда ставите Windows и Visual Studio. Либо используете две разные физические машины, при этом использовать один Mac для нескольких PC-разработчиков затруднительно, т.к. отладка требует манипуляций с симулятором. И последний вариант — использовать виртуальную машину с Mac OS X (так называемый hackintosh). Вполне себе жизнеспособный вариант, хотя и есть некоторые ограничения. Например, в Xcode придется перемещаться по Storyboard только с использованием полос прокрутки, т.к. windows-мышь не очень похожа на настоящую мышь от Mac со всеми вытекающими.

Время горькой правды. С отладкой в Visual Studio периодически возникали проблемы. Самая заметная — это то, что при удаленной сборке приложения, процесс отладки мог отвалиться по таймауту. Хотя, опять же, стоит отдать должное разработчикам — они исправляют ошибки достаточно интенсивно, и вот уже на момент написания этой статьи, процесс отладки стал стабильным. Хотя и стоит заметить, что на текущий момент, времени между запуском приложения и появлением его на экране симулятора при использовании Visual Studio требуется несколько больше, чем при использовании Xamarin Studio на Mac.

Лицензии

На момент написания статьи Xamarin имеет следующие типы лицензий:

  • Starter — Бесплатно. Рассчитан скорее для ознакомления, т.к. имеет ограничение на размер приложения (по ощущениям очень не большой, т.к. не компилировались даже некоторые sample-проекты) и на использование сторонних компонентов;
  • Indie — 299$ на одно рабочее место. Снимается ограничение на размер приложения. Разработка возможна только в Xamarin Studio;
  • Business — 999$ на одно рабочее место. Появляется возможность разработки в Visual Studio и приватная тех. поддержка от инженеров Xamarin;
  • Enterprise -1899$ на одно рабочее место. В рамках этой лицензии предоставляется возможность получения Hotfixes (не вижу особого смысла, т.к. обновления и так выходят очень часто), а так же возможность отправить инженерам проект с исходным кодом и сказать «Что-то у меня не получается поменять ширину ячейки в таблице, помогите!». Плюс ряд не слишком полезных, на мой взгляд, опций.

Заключение

На текущий момент технология Xamarin является серьезным инструментом для решения сложных задач в области разработки мобильных приложений. Несмотря на это, команда разработчиков не останавливается и продолжает его активное развитие и улучшение. За последние два месяца заметны серьезные улучшения в общей стабильности продукта. На мой взгляд у технологии большое будущее и с каждым днем число разработчиков, использующих ее в качестве основного фреймворка для разработки будет неуклонно расти. Однако довольно высокая стоимость лицензии может стать препятствием для использования на пути indie-разработчиков. В целом свой опыт работы с данным фреймворком считаю положительным и продолжу его использование.

Instrument Xamarin Applications

Before you can monitor your Xamarin application, you will need to instrument your application to enable the Xamarin Agent to collect mobile metrics.

After you have set up and accessed Mobile RUM, follow these instructions:

  1. Confirm that the Xamarin Agent supports your platform
  2. Understand the limitations of the Xamarin Agent
  3. Instrument a Xamarin Application
  4. Customize the Xamarin Instrumentation (Optional)

Xamarin Agent Support

Supported Platforms

The Xamarin Agent can only be used with iOS and Android platforms. All other platforms will build and run without errors, but no monitoring will occur.

Supported Libraries

  • .NET Standard 2.0 (with Xamarin Agent >= 20.10.0)
Recommendations

The Xamarin = 50.3, the Xamarin Agent only supports the .NET Standard library and the instrumentation of applications that reference the .NET Standard library. If you still need PCL support, you are recommended to use Xamarin

Limitations

The Xamarin Agent has these limitations:

  • Automatic instrumentation is not supported, so you will need to manually report events and metrics.
  • Symbolication is not supported, although the Xamarin Agent does report uncaught exceptions and native application crashes.

Instrument Xamarin Applications

Follow the steps below to manually instrument your Xamarin iOS, Android, and Forms apps.

Add the Xamarin Agent Package

You obtain the Xamarin Agent from the NuGet Gallery. Follow the instructions given in Adding a Package to add the package AppDynamics Xamarin Agent from nuget.org.

Get Your Application Key

Complete the Getting Started Wizard to get an EUM App Key. You will need this key when you modify the source code. In some cases, multiple mobile applications can share the same key.

Because there is no Xamarin platform option, you will need to choose either Android or iOS. For Android, you will need to select Manual.

If you have completed the Getting Started Wizard, but don’t have your EUM App Key, see Get Your Application Key.

Add the Required Permissions (Android Deployments Only)

Open the file Properties/AndroidManifest.xml and verify that it has these permissions:

If these permissions are not present, add them.

Link the AppDynamics Agent Assembly

Forms Solution

Xamarin Forms is the unified development environment for running all platforms. If you try to run something on an unsupported platform, linking our agent won’t allow you to monitor the application, but it also will not cause any errors.

To use the Xamarin Agent for your iOS/Android apps, add the using directive at the top of the App.xaml.cs file:

using Xamarin.Forms; using AppDynamics.Agent; namespace  < public partial class App : Application < . >>
iOS Solution

To use the Xamarin Agent in iOS apps, add the using directive at the top of the AppDelegate.cs file:

using Foundation; using UIKit; using AppDynamics.Agent; public class AppDelegate : UIApplicationDelegate
Android Solution

To use the Xamarin Agent in Android apps, add the using directive at the top of the MainActivity.cs file:

using Android.App; using Android.Widget; using Android.OS; using System; using Android.Content; using AppDynamics.Agent; namespace  < [Activity(Label = "Phoneword", MainLauncher = true, Icon = "@mipmap/icon")] public class MainActivity : Activity < . >. >

Initialize the Agent

To initialize the Xamarin Agent, you use the code below for iOS and Android. Use the EUM app key (enter as a string) that you received after completing step 2.

var config = AppDynamics.Agent.AgentConfiguration.Create(); AppDynamics.Agent.Instrumentation.InitWithConfiguration(config);

If you are running an on-premises EUM Server, you need to specify the URL to the EUM Server. See Point to an On-Premises EUM Server (Optional) to learn how.

Forms Solution

For Forms Solutions, you only need to place the initialize code in the constructor of t he App.xaml.cs file for the Xamarin Agent to instrument both Android and iOS applications.

public App() < InitializeComponent(); // This initialization code is used by both iOS and Android apps. var config = AppDynamics.Agent.AgentConfiguration.Create(); AppDynamics.Agent.Instrumentation.InitWithConfiguration(config); MainPage = new FormsExamplePage(); >

If you have application code in the MainActivity.cs file for Android or AppDelegate.cs for iOS that you want to instrument, however, you should initialize the Xamarin Agent in those files as you would do for iOS Solutions and Android Solutions .

iOS Solution

For iOS apps, you place the initialize code In the AppDelegate.cs file in the method FinishedLaunching of the class AppDelegate as shown below.

public class AppDelegate : UIApplicationDelegate < // class-level declarations public override UIWindow Window < get; set; >public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) < // The two lines below initialize the AppDynamics instrumentation. var config = AppDynamics.Agent.AgentConfiguration.Create(); AppDynamics.Agent.Instrumentation.InitWithConfiguration(config); . return true; > . >

You may also consider placing it in the Main.cs int the method Main.

Android Solution

In the MainActivity.cs file, place the initialization code in the method OnCreate:

class MainActivity < protected override void OnCreate(Bundle savedInstanceState) < // The two lines below initialize the AppDynamics instrumentation. var config = AppDynamics.Agent.AgentConfiguration.Create(); AppDynamics.Agent.Instrumentation.InitWithConfiguration(config); . > >

Build the Application

Run and build your application from Visual Studio. From the Getting Started Wizard, you should see that the application has connected and the instrumentation has been verified.

For iOS projects with the Xamarin Agent >=20.10.0, you must add the additional MtouchExtraArgs argument —gcc_flags «-ObjC -lz» for each build configuration, such as the debug and release builds. If the iOS project file is edited directly, the build configuration should contain the MtouchExtraArgs element:

 true full false bin\iPhoneSimulator\Debug DEBUG;ENABLE_TEST_CLOUD; prompt 4 iPhone Developer true true SdkOnly x86_64 HttpClientHandler Default false --gcc_flags "-ObjC -lz" 

Customize Your Instrumentation (Optional)

The Xamarin SDK has additional classes to allow you to extend the kinds of application data you can collect and aggregate using Mobile RUM. See Customize the Xamarin Instrumentation.

Point to an On-Premises EUM Server (Optional)

To use an on-premises EUM Server, you pass the URL to the on-premises EUM Server when you initialize the instrumentation with the EUM App Key from Get Your Application Key:

var config = AppDynamics.Agent.AgentConfiguration.Create(); config.CollectorURL = ; AppDynamics.Agent.Instrumentation.InitWithConfiguration(config);

Upgrade the Xamarin Agent

As new features are added to the agent, you will need to upgrade the Xamarin Agent package in your app.

AppDynamics Packages

  1. From Visual Studio, open the Xamarin application that has the AppDynamics Agent package.
  2. From the Packages folder, select the AppDynamics Agent.
  3. Right-click and click Update.

Dynatrace. OneAgent. Xamarin 8.277.1

This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module’s version of Install-Package.

For projects that support PackageReference, copy this XML node into the project file to reference the package.

paket add Dynatrace.OneAgent.Xamarin --version 8.277.1

The NuGet Team does not provide support for this client. Please contact its maintainers for support.

#r "nuget: Dynatrace.OneAgent.Xamarin, 8.277.1"

#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.

// Install Dynatrace.OneAgent.Xamarin as a Cake Addin #addin nuget:?package=Dynatrace.OneAgent.Xamarin&version=8.277.1 // Install Dynatrace.OneAgent.Xamarin as a Cake Tool #tool nuget:?package=Dynatrace.OneAgent.Xamarin&version=8.277.1

The NuGet Team does not provide support for this client. Please contact its maintainers for support.

Dynatrace OneAgent for Xamarin

Use the Dynatrace Xamarin NuGet package to instrument your Xamarin apps with the OneAgent for Android or iOS.

After the project setup, OneAgent monitors all user actions, lifecycle events, web requests, and crashes. Using manual instrumentation, you can additionally create custom actions, tag users, and report values, events, and errors.

Licenses for libraries used:

Changelog

  • Updated Android (8.277.1.1003) & iOS Agent (8.277.1.1004)
  • Updated iOS Agent (8.275.1.1006)
  • Updated Android (8.273.1.1003) & iOS Agent (8.273.1.1006)
  • Removed Instant crash reporting from iOS agent
  • Updated Android (8.271.1.1003) & iOS Agent (8.271.2.1007)
  • Improved empty request tag handling for webrequest timing
  • Updated Android (8.267.1.1005) & iOS Agent (8.267.1.1006)
  • Updated Android (8.265.1.1002) & iOS Agent (8.265.1.1003)
  • Updated Manifest instrumentation to support msbuild CLI
  • Updated Android (8.263.1.1002) & iOS Agent (8.263.2.1005)
  • Fixed null value for GetRequestTagHeader
  • Updated iOS targets file to better support Pair to Mac builds
  • Updated Android (8.261.2.1013) & iOS Agent (8.261.1.1006)
  • Minimum Java Version was raised to 11
  • Fixed issue when using DTXAutoStart on iOS
  • Updated Android (8.259.1.1008) & iOS Agent (8.259.1.1009)
  • Minimum iOS Version has been raised to 11
  • Added Business event capturing API
  • Updated Android (8.253.1.1003) & iOS Agent (8.253.1.1006)
  • Updated Android (8.249.1.1004) & iOS Agent (8.249.1.1007)
  • Updated Documentation (fixed supported iOS version)
  • Updated Android (8.247.1.1003) & iOS Agent (8.247.1.1007)
  • Raised Minimum Android API level to 21
  • Net Version auto detection via MSBuild
  • Removing Dynatrace_Net_Version property
  • Fixed requesting a tag with not valid URL
  • Fixed crash for when API is called when agent is not available
  • Added Cancel API for actions
  • Added version compatability with net6.0 and others
  • Deprecated SetupHttpClient
  • Target file automatically resolves path for older projects
  • Fixed crash handler bug with null or empty crash message/stacktrace values
  • ReportCrash is now ending the session
  • Added ReportError to API to use exception objects
  • Fixes Android Startup Issue
  • Updated Documentation (added link)
  • Changed API
  • Changed Configuration Format
  • Added new Android instrumentation
Product Versions Compatible and additional computed target framework versions.
.NET net5.0 net5.0 was computed. net5.0-windows net5.0-windows was computed. net6.0 net6.0 was computed. net6.0-android net6.0-android was computed. net6.0-ios net6.0-ios was computed. net6.0-maccatalyst net6.0-maccatalyst was computed. net6.0-macos net6.0-macos was computed. net6.0-tvos net6.0-tvos was computed. net6.0-windows net6.0-windows was computed. net7.0 net7.0 was computed. net7.0-android net7.0-android was computed. net7.0-ios net7.0-ios was computed. net7.0-maccatalyst net7.0-maccatalyst was computed. net7.0-macos net7.0-macos was computed. net7.0-tvos net7.0-tvos was computed. net7.0-windows net7.0-windows was computed.
.NET Core netcoreapp1.0 netcoreapp1.0 was computed. netcoreapp1.1 netcoreapp1.1 was computed. netcoreapp2.0 netcoreapp2.0 was computed. netcoreapp2.1 netcoreapp2.1 was computed. netcoreapp2.2 netcoreapp2.2 was computed. netcoreapp3.0 netcoreapp3.0 was computed. netcoreapp3.1 netcoreapp3.1 was computed.
.NET Standard netstandard1.1 netstandard1.1 is compatible. netstandard1.2 netstandard1.2 was computed. netstandard1.3 netstandard1.3 was computed. netstandard1.4 netstandard1.4 was computed. netstandard1.5 netstandard1.5 was computed. netstandard1.6 netstandard1.6 was computed. netstandard2.0 netstandard2.0 was computed. netstandard2.1 netstandard2.1 was computed.
.NET Framework net45 net45 was computed. net451 net451 was computed. net452 net452 was computed. net46 net46 was computed. net461 net461 was computed. net462 net462 was computed. net463 net463 was computed. net47 net47 was computed. net471 net471 was computed. net472 net472 was computed. net48 net48 was computed. net481 net481 was computed.
MonoAndroid monoandroid monoandroid was computed. monoandroid11 monoandroid11 is compatible.
MonoMac monomac monomac was computed.
MonoTouch monotouch monotouch was computed.
Tizen tizen30 tizen30 was computed. tizen40 tizen40 was computed. tizen60 tizen60 was computed.
Universal Windows Platform uap uap was computed. uap10.0 uap10.0 was computed.
Windows Phone wpa81 wpa81 was computed.
Windows Store netcore netcore was computed. netcore45 netcore45 was computed. netcore451 netcore451 was computed.
Xamarin.iOS xamarinios xamarinios was computed. xamarinios10 xamarinios10 is compatible.
Xamarin.Mac xamarinmac xamarinmac was computed.
Xamarin.TVOS xamarintvos xamarintvos was computed.
Xamarin.WatchOS xamarinwatchos xamarinwatchos was computed.

Compatible target framework(s)
Additional computed target framework(s)
Learn more about Target Frameworks and .NET Standard.

.NETStandard 1.1
  • No dependencies.
MonoAndroid 1.1
  • No dependencies.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *