How to install Xamarin plugin in Visual Studio

how to install xamarin plugin in visual studio 2013 and how to install marinara profiler and how to install package xamarin and how to install xamarin without visual studio
Dr.KiranArora Profile Pic
Dr.KiranArora,Canada,Teacher
Published Date:26-10-2017
Your Website URL(Optional)
Comment
;DPDULQDQG0RQR±D This chapter provides an overview of the Mono project and the suite of Mono-based commercial products offered by Xamarin. To begin this pathway into the unknown, this chapter will cover the following topics: ‡ Understanding Mono ‡ Why you should use Xamarin ‡ Installation of Xamarin.Android and Xamarin.iOS ‡ Using Xamarin Studio and Visual Studio for development ‡ Options for source control Understanding Mono Before we jump straight into a conversation about Xamarin, let's discuss a related topic: Mono. Mono is an open source cross-platform implementation of the .NET platform. This includes a Common Language Runtime (CLR) that is binary compatible with Microsoft .NET, a set of compilers for languages such as C, and an implementation of the .NET runtime libraries. The Mono CLR has been ported to many platforms, which include the Linux and BSD-based operating systems (which are not limited to just Android, iOS, and OS X), Windows-based systems, and even some game consoles such as the Wii, Xbox 360, and PS4. The Mono project was started by a Ximian, which was purchased by Novell. Xamarin now leads Mono.Xamarin and Mono – a Pathway to the Unnatural The Xamarin product suite Xamarin is a software company that offers a suite of commercial Mono-based products that allow developers to create apps for Android, iOS, and OS X using C and the .NET framework. Xamarin's cofounder, Miguel de Icaza, has directed the Mono project since its inception in 2001. Xamarin's primary product offerings are: ‡ Xamarin.Android (formerly Mono for Android) ‡ Xamarin.iOS (formerly MonoTouch) ‡ Xamarin.Mac Each of these products is licensed through an annual subscription with the following levels being available: ‡ Starter: This subscription is actually free, but restricts the size of apps. ‡ Indie: This subscription provides everything needed to build and deploy full-featured mobile apps, but can only be purchased by companies with ÀYHRUOHVVHEPSOR\HHVQ7KLVVXVQVFFOXGHWKHXVHRWLULSWLRQDOVRGRH of the Visual Studio add-in discussed in the Using the Visual Studio environment section. ‡ Business: This subscription adds the use of the Visual Studio add-in as well as e-mail support. ‡ Enterprise: This subscription adds access to a set of prime components, WÀKRHVDQDQFHGVXSSRGHKUWQ A link for the pricing information can be found at the end of this section. For quick reference, please visithttps://store.xamarin.com. Xamarin also hosts a component store; a market place to buy and sell components that can be used in Xamarin apps. The components in this store can be distributed for free or sold, and Xamarin pays component vendors a percentage of the revenue collected from the sales. 8 Chapter 1 Another service that Xamarin offers is the Test Cloud. As the name implies, this is a cloud-based testing service that allows teams to create automated testing capabilities for their apps that can be run against a plethora of physical devices. This is particularly important for Android developers as there are far more devices that need to be considered. The following table provides useful links to additional information about the Xamarin suite: Type of information URL to access it Product information http://xamarin.com/tour http://xamarin.com/csharp http://xamarin.com/products http://xamarin.com/faq https://store.xamarin.com Product pricing https://components.xamarin.com Component store http://xamarin.com/test-cloud Xamarin Test Cloud Evaluating whether Xamarin is the right tool Now that you have some background on Mono and the Xamarin suite of products, SFKDULQKURMHW"\OIRUHULJWWRR,V;DPPWWWRDVN\RXUVHO\RXPLJKWZDQI EHQ7KHJ;HÀWVRIXVLQOORZVDPDULQDUHDVIR ‡ It builds on your existing skills of using C and .NET: Because of the huge number of features available to both the C language and the .NET framework, it requires a huge investment of time and energy for developers to master them. Although you can argue that Java and Objective-C have similarities (being object-oriented languages), there is a real cost associated LQDQVIHUULQ&DQHFODLPJ\RXUSURÀFLHQFWUHWKHVDPP\G1(7ZLWKDNWR regarding Java or Objective-C. This is where Xamarin comes to your rescue; QLQJQLÀFDQGLYLPDGHDVLYHVWPHQWLQWLGXDORXSVWKGVDQJUDWKDYH&DQG .NET might turn to it if they wish to develop iOS and Android apps due to the requirement of these skills. 9 Xamarin and Mono – a Pathway to the Unnatural ‡ Allows for reusability of code in cross-platform development: Although the Xamarin suite prevents you to create an app that can also be deployed to Android, iOS, and WP8, it compensates for this by providing you with the capability to recycle huge portions of your code base across all of these platforms. The general process that makes this all so much easier for you is that the user interface code and the code that deals with the device capabilities tend to be written for each platform. With this, things such as client-side logic (proxies and caching), client-side validation, data caching, and client-side data storage can potentially be reused, saving you a huge amount of time and energy. I have personally seen Android and iOS apps share as much as 50 percent of the code base and some report as high as 80 percent. The more you invest in the approach to reuse, the more likely you will achieve a higher percentage. However, there are some drawbacks when it comes to using Xamarin: ‡ Costs due to licensing requirements: The Xamarin suite or tools are all commercial tools and must be licensed, meaning there is a tangible cost of HFN;XDQFKHQDPDU\RWUFLQ VZHEVLWHIRUWKHFXUUQWSUFHLQJL ‡ Waiting for updatesZHQHEHWHDQHZODJWLPOÀQGWKDWWKHUHLVVRPHRXZLO release of a platform (Android/iOS) and the corresponding release of the Xamarin products that support it. Xamarin has done a great job of releasing Xamarin.iOS on the same day when the new versions of the OS are made available. Xamarin.Android generally lags behind because Google does not make beta/preview versions available. In some ways, this delay is not a big issue at least for phone apps; the telecoms generally take some period of time before they provide the newest Android versions to be downloaded. ‡ Performance and memory management: This is probably more of a concern for Xamarin.Android than Xamarin.iOS. As you will see in Chapter 2, Demystifying Xamarin.iOS, Xamarin.iOS essentially builds a binary executable much like those produced by using just Xcode and the iOS SDK. However, as we will see in Chapter 3, Demystifying Xamarin.Android, Xamarin.Android relies on deploying the Mono CLR and the communications between the Mono CLR and the Dalvik VM. In some cases, Xamarin.Android will allocate Java and C objects to achieve some of the "magic" and "sorcery" behind developing in C or .NET on an Android device. As a result of this, Xamarin. Android will affect both the memory footprint and execution performance. 10 Chapter 1 ‡ Distribution size: There are a number of runtime libraries that must be distributed or linked with Xamarin apps. A discussion of the actual size and strategies to minimize the distribution size is reserved for the last chapter. While the list of drawbacks might seem extensive, in most cases, the impact of each can be minimized. I have chosen to build out a Xamarin consulting practice because HPDQJURXSVWKDWKDYHHGDQ\OLNHGIHHOHHÀWVLGHQWLÀQY,SODFHDKEWKDOXHRQLJK UIRXDUHDJRXSHYDOXH,\WLQDQG1(7VHHWKHVDPY&DVLJQLÀFDQLZLOOQHVWPHQW DULQÀWVWKHQ\RXVKROG VEHQXHRQ;DPGLLYLGXDWSOQRUDQHDFHVDJUHDWYDODOWKX certainly consider using it. Learning C This book assumes that you have a working knowledge of C and .NET. Since this might not be the case for some readers, we have included a few links to help you get up to speed. Xamarin provides the following link which presents C from an Objective-C perspective:http://docs.xamarin.com/guides/ios/advanced_ topics/xamarin_for_objc/primer Microsoft provides a set of tutorials for learning C available at:http://msdn. microsoft.com/en-us/library/aa288436(v=vs.71).aspx. Installing Xamarin Before moving on, we need to install Xamarin. This section will show you the steps to install Xamarin on both the Android and iOS platforms, notably Xamarin.Android and Xamarin.iOS, on both OS X and Windows. Since Xamarin.iOS is dependent on the latest iOS SDK and the latest Xcode, both of these should be installed prior to starting the OS X install. Both Xcode and the iOS SDK are free and you can download these installs from:https://developer.apple.com/devcenter/ios/ index.actiondownloads. Also, note that you can install Xcode from the OS X App Store. 11 Xamarin and Mono – a Pathway to the Unnatural Likewise, Xamarin.Android is dependent on the latest Android SDK; however, the difference being that the Xamarin install will automatically download the Android SDK and install it as part of the overall install process. So, no separate steps need to be taken. If you already have installed the Android SDK, you have just been handed the opportunity to use it. Installing Xamarin on OS X To install Xamarin on OS X, go towww.Xamarin.com, download the OS X installer to launch it, and follow the directions. Be sure to choose to install both Xamarin. Android and Xamarin.iOS; Xamarin.Mac is optional. The Xamarin.iOS Visual Studio plugin uses the build server calledmtbserver to compile the iOS code on your Mac. If you plan to use the Visual Studio plugin, be sure to choose to allow network connections. Installing Xamarin on Windows Now, we move on to the Windows installation process. If you plan on using the Visual Studio add-in, Visual Studio will need to be installed prior to installing Xamarin. To install Xamarin on Windows, you need to visitwww.Xamarin.com, download the Windows installer, launch it, and then follow the directions. Be sure to install both Xamarin.Android and Xamarin.iOS. Development environments Developers have two options when it comes to IDEs: Xamarin Studio or Visual Studio. This section will show you how to develop apps for both Android and iOS through both of these studios. Using the Xamarin Studio environment Xamarin Studio is a customized version of the MonoDevelop IDE and this can be used to develop applications for Android, iOS, and OS X. Xamarin Studio is available on both OS X and Windows with highly advanced and useful features such as: ‡ Code completion ‡ Smart syntax highlighting ‡ Code navigation 12 Chapter 1 ‡ Code tooltips ‡ Integrated debugging for mobile apps running in emulators or on devices ‡ Source control integration with Git and Subversion built-in If you look at the following screenshot, you will see how Xamarin Studio is shown with the Android user interface designer opened: = a s PCUfp Pnuuiirt'JoyauriPOflirKilaiinl Xomcnn Studio G it Pnj«t File He Sccrch DuM Run VentenCentral Tech Wmden Help (tmann StuAo Q. tn«s to watch Dete9 © o 'Control.' 3 7 Solution 4 PCOjstArtMtv POIDruMc«r.(3 POlDctcSefve a PCCJMreevce a a PGQanrewidJpto PCOUI art POUpp (New One) A A (vlS) (Al lonyuepes; (AC Layout 1.7m WVGA Pettioft Android 4.0.1 A deck modes; On A Mere AR Ovfoult Theme (1 i POlApp  FonnWtdgm O Reference 7 Q Q Q Convener Button ' Asets »  ChedUhn POIApp IReUMcet. CheckedeOVtew _ drawabl _ ; layout ProgressSv (Homontal) Name (large) Progress Bar POBeM.axm POllSt-SUTi Progrox Bar (Normal) POIrt»t»mcn Pregroxx Bar (Small) Description .menu a QwckCentactBadoe ivahm — AboutResource  KodwButlcn ftetw«e.desgn Address IPODxtService.a RadtoCroup POO«aActMPr;c; RabngBar PODeonSatvtc i POUUcMty.a Property Docjmont CX»na Latitude Longitude POttWVtwuAdopt tortOftittffiLo POrtrSApp Source Eiton Tatht J Q Using Xamarin Studio to develop Android apps Xamarin Studio and the Xamarin.Android add-in allow the complete development and debugging of Android apps without use of any other IDEs. The Android UI designer can also be used from within Xamarin Studio. 13 Xamarin and Mono – a Pathway to the Unnatural Using Xamarin Studio to develop iOS apps Xamarin Studio and the Xamarin.iOS add-in allow the development and testing of iOS apps when installed on a Mac with Xcode and the iOS SDK. All code can be written, compiled, and debugged from within Xamarin Studio. In general, the user Q6WXGLRDULHVPXVWEHEXLOWZLWKLQ;FRGH;DPRDUGÀOU\EIDFH;,%RUVWRGLDQQWHU SURYLGHVDOLGH;QNWRLFHGRQFRVXFKWKDWZFNKHQDOEUHLVGRXEOHRLVWRU\ERDUGÀO Xcode will be launched. There is a caveat to this; Xamarin has an iOS UI designer built for Xamarin Studio, yet it has remained in an alpha status for almost a year. I have seen a number of posts on various forums indicating it is stable and safe to use, but Xamarin has been slow to clarify why it is still in alpha status and when it will move to a stable status. We will discuss the use of the iOS UI designer in more detail in Chapter 4, Developing Your First iOS App with Xamarin.iOS. Using the Visual Studio environment Xamarin for Visual Studio is an add-in that supports the development of the Xamarin.Android and Xamarin.iOS apps and is available to business and enterprise subscribers. This add-in can be used with any non-Express edition of Visual Studio 2010 through to Version 2013. Android apps can be completely developed using Visual Studio. In order to develop iOS apps, you will still need a Mac with the iOS 6'.DQG;FRGHWRFRPSLWKXVHULQUOHDQGFUWHHEDQHDWHIDFHGRUVLRUW\ERDUOHVGÀ I If you already have a license for Visual Studio and are comfortable with the environment, this add-in will be better suited to you than Xamarin Studio due to it being simple to use. The following screenshot shows Visual Studio 2012 with the Android user interface designer opened: 14 Chapter 1 _ ft (Administrator) launch (ClrtQ fi X crotch Visual Studio Quick 10IT V/t MU VSW PPOJtCT 8UU0 OfBIX. HAM SQl T001S VMIA1SYN TIST ANAl DtVtXPfittt VMNOOW WHP Start  0tn« Any CPU  M - y Teolboi J X x Solution trptorer » X - Swch Todbci fi’   p p Win WVSA (News One) A' Portrait A AndroidtflJ MS) A (Aft languages) lAJIPort mcdesl A Mere Ah layouts Oft Q o o a s D», -  a Images & Media SaaiehSoMan tiptoe (CM;) fi P Pornr» Q SoMion POtApp (2 projects) ® IT u a jT POtApp ImageBuitcn i 1 P A Properties n ImagcView l RHttmn MediaCotHroller P Q P y Assets n VideoView a fi Resomccs a Layouts Name P dranablr m h Pointer a layout » L i Framclayout AddrestPicfcerOiAlcg amJ i I lmeart a,out (Morcontafl POIDcUilaaM (Vertical) nl aiml Imaaileyout POtt U Description POft.ntfeent.aunl Ratatwelayout Q menu » m L. i Tableta,-cut si value AboutRevomcrvM Q a Composite Address c» Resoune.deugntr.es P Pomtt t P f PODetaSer.icecs tiparvdableUtVie-. P C» PCdOetadAetenty ct LI GrxMti» P C» POUtonWvK».ct P C POfeistActi.h).ct MowontalScrollVin Latitude Longitude \l e» P Adapter P CftistVie cs LnlVirw P C« Pemtonntrrrstet 4_j SoeWi a POIIaUApp T i.l SliditvgC’ianef P A Propettiet TaWtest Sotutrenbplc'er Tcaenbpioicr l_) TibiV.dget X Properties » Webttc - a Ad.a«l Pointer h a ? L I Oialerfihei I I GesturrOvertayYirw I 1 SurtaeeVww tnctminlliin Q View Q V«wStut Q Drw Source r. tl Zoomftutten Find SymbolResults I I ZoemContreH Code Metrics Results list find 5ymbct Pcsuhs CipAorer bplorer Dw Test Server Toolt-oi Ready The Android user interface designer Using Visual Studio to develop Android apps The Visual Studio add-in for Xamarin.Android allows the full development and debugging of Android apps without the use of any other IDE. This add-in provides the usage of the Android UI designer from within Visual Studio. For those that have the appropriate licenses and are comfortable with Visual Studio, this might be the best option for Android development. Using Visual Studio to develop iOS apps The Visual Studio add-in for Xamarin.iOS allows you to develop and test iOS apps, but only in conjunction with the use of a Mac with both Xcode and the iOS SDK installed. The iOS code must be compiled and executed on a Mac using the Xamarin's mtbserver. Xcode on a Mac must also be used to develop the user interface xib and/ WKXUDWLRQLQVFPRQÀJLRUGHWDLOHVGÀOHVWRU\ERDURUVFXVVIRUDQL26DSS:HZLOOGL in Chapter 4, Developing Your First iOS App with Xamarin.iOS. 15 Xamarin and Mono – a Pathway to the Unnatural Solution andHSURM\;DPFWÀVGDQGXFUHDWDULQ6OHHGEWXDUHVGLRH completely compatible with Visual Studio. This gives teams the ÁHLEKRRVZKLLOLW\WDQRFHFK,'(WGWKFLFXVHH\HO\RKDQDQHDVJ throughout the duration of a project. Comparing IDEs The advantages and disadvantages of adopting each IDE are shown in the following table: IDE Pros Cons Xamarin Studio Available for all Xamarin Limited number of subscription levels productivity add-ins available Runs on Windows and OS X Does not offer support for the use of TFS for source control Visual Studio Most C developers are Requires a business or already familiar and enterprise subscription of comfortable with Visual Xamarin Studio Requires a license of VS Allows the use of popular Runs on Windows only productivity add-ins such For iOS development, as ReShaper and CodeRush requires a more complex Allows the use of TFS for configuration in which VS source control and issue must communicate with tracking a Mac running Xcode to perform builds and UI development must be done with Xcode 16 Chapter 1 Version control Version control can be a challenge anytime you have a diverse set of development tools, and Xamarin certainly adds diversity to most shops. The challenge is making it easy to share and manage code from all of the different IDEs and client apps that folks will be working with; many times they do not have access to HWRDULQL;DPDUHYHU\DWWUDFWLYWKHVDPHUHSRVLWRUHV6LWVRIXVLQQFHWKJQHÀHEH QVWLQJVHOYHVHL1(7RSVPVKDQ\;DPDULQGHYHORSHUVZLOOÀGWKHP working in environments already committed to using Microsoft Team Foundation Server (TFS). Unfortunately, it's not always easy to connect to TFS from non-Microsoft tools. In the case of Xamarin Studio, there is an open source add-in that cannot be directly VXSSRUWHGE\;DPDULXUQDQGLQJWRFRQÀJHHQFDQEHFKDOOJ Other version control systems to consider include Git and Subversion. Xamarin Studio contains built-in support for both Git and Subversion, and add-ins for both of these tools exist for Visual Studio. The following table contains useful URLs to download and read about the various add-ins: Add-in URL to access it https://github.com/Indomitable/monodevelop-tfs- TFS add-in for addin Xamarin Studio http://www.teamaddins.com/blog Git for Visual (VS2013 has built-in support) Studio http://msdn.microsoft.com/en-us/library/hh850437. aspx (VS2012 requires a free plugin) http://visualstudiogallery.msdn.microsoft.com/ abafc7d6-dcaa-40f4-8a5e-d6724bdb980c http://www.visualsvn.com/visualsvn/?gclid=CMmSnY- Subversion add- opL0CFa07MgodDksA5g in for Visual Studio (by VisualSVN) 17 Xamarin and Mono – a Pathway to the Unnatural 7KWVDOOHVLHÀVQRQUHQWWKSRWDHLHHORPDUHGHYH\DVSHFWVRVRIWZ/LNHPDQI following table outlines some of the pros and cons to consider when deciding on a source control solution for Xamarin projects: VCS Tool Pros Cons TFS Already in use by many Xamarin Studio add-in shops that will consider has been known to be Xamarin. problematic to use in the past. Free add-in for Xamarin Studio. Git Built-in support in Xamarin. Difficult to share and synchronize code with other Free add-in available for teams in a large organization Visual Studio 2012 and 2013. that might be using TFS for their C code. Subversion Built-in support in Xamarin Difficult to share and Studio. synchronize code with other teams in a large organization Commercial add-in for that might be using TFS for Visual Studio. their C code. WRPDNHWKDWZRU76WU\IHQWLQXVLQ,I\RXDOUHDG\KWLQYHVWP)DYHDVLLNRUJJQÀFDQ your Xamarin development as well. This can be done by either having developers use Visual Studio or trying your luck with the TFS add-in for Xamarin Studio. Summary In this chapter, we provided an introduction to Mono and the suite of commercial products offered by Xamarin and considered the pros and cons of using Xamarin. (RS,DWLRQWLRQ'DWWKHRXJKWKHVLQVWDOOHWWKUDÀUVWORRNOSURFVQVRZ:HDHVDQGWRRN available to developers. In the next chapter, we will take a look at the architecture of the Xamarin.iOS product. 18 'HP\VWL;DPDU\LIQJLQL26 Xamarin.iOS and Ahead-of-Time compilation Unlike most Mono or .NET apps, Xamarin.iOS apps are statically compiled, where compilation is accomplished through the Mono Ahead-of-Time (AOT) compilation facilities. AOT is used to comply with Apple's requirements, for example, the use of iOS apps to compile, refraining from Just-in-Time compilation facilities, or running on virtual machines. Use of AOT compilation comes with some limitations regarding the C language. These limitations will be easier to discuss after discussing the approach to binding iOS to C and .NET. This is why we have pushed this topic to the Limitations of using the AOT compilation section in the later part of this chapter.Demystifying Xamarin.iOS Additional information about Mono AOT compilation can be found at the following link: http://www.mono-project.com/AOTFull_AOT Understanding Mono assemblies Xamarin.iOS ships with an extended subset of Silverlight and desktop .NET assemblies. These libraries provide the .NET runtime library support for developers, including namespaces such asSystem.IO andSystem.Threading. Xamarin.iOS is not binary compatible with assemblies compiled for a different LQSURÀOHJ\RXUPHDQ code must be recompiled to generate assemblies that WKLQHFLÀVSFDOO\WDUJHWWKHDOO\H7VHVDPHWKQSJL;DPDULVHQ26KLVLVHURÀOWL UKWK\RXKDYHWRGRLI\RXDUHDUJH1(7WRHUSUOHVVXFKLOYHUOLJWWLQJRDV6RÀ For a complete list of assemblies that ship with Xamarin.iOS, please refer to the following link: http://docs.xamarin.com/guides/ios/under_the_hood/ assemblies Xamarin.iOS bindings In this section, you will discover one of the main sources of power behind Xamarin. iOS. This ships with a set of binding libraries that provides support for iOS development. What will follow are some details into each of these bindings. The design principles A number of goals or design principles guided the development of the binding libraries. These principles are critical to make C developers productive in an iOS development. The following represents a summary of the design principles: ‡ Allow developers to subclass Objective-C classes in the same way as they subclass other .NET classes ‡ Provide a way to call arbitrary Objective-C libraries ‡ Transform the common Objective-C tasks into something much easier SWHZKLFVSEYOHHWRFRPOHPDNLOW2EQJWKHGLÀIO&WDVNFXWLHRVVLMH 20 Chapter 2 ‡ Expose Objective-C properties as C properties as well as expose a strongly typed API ‡ Use Native C types in lieu of Objective-C types when possible ‡ Support both C events and Objective-C Delegation as well as expose C delegates to Object-C APIs This section has provided you with a general idea of the principles to WLG,I\RXDUHFXQEHDULQPULRXVRÀQGDFPSOHWLRHGVFXXVVLRQ\RFDQ RIÀFLDOIUWRWKHUHH documentation available at the following link: http://docs.xamarin.com/guides/ios/under_the_hood/ api_design/ C types and type safety The Xamarin.iOS bindings are designed to use types familiar to C developers and to increase type safety when possible. For example, the API uses C string instead ofNSString, meaning the text property inUILabelRZLQLVIKPDQQ.HGGHÀQHUROOQLQWKH66'LHJWL2 property(nonatomic, copy) NSString text Also, this is exposed in Xamarin.iOS as follows: public string Text get; set; Behind the scenes, the framework takes care of marshaling C types to the appropriate type expected by the iOS SDK. Another example is the treatment ofNSArray. Rather than exposing weakly typed arrays, Xamarin.iOS exposes strongly typed arrays to the following Object-C property onUIView: property(nonatomic, readonly, copy) NSArray subviews This is exposed as a C property in the following manner: UIView Subviews get; Use of inheritance Xamarin.iOS allows you to extend any Objective-C type in the same manner you will extend any C type and features like calling "base" from overridden methods work as predicted. 21 Demystifying Xamarin.iOS Mapping Objective-C delegates In Objective-C, the delegation design pattern is used extensively to allocate responsibility to various objects. Xamarin faced a few inherent challenges in mapping iOS delegates to C and .NET. In Objective-C, delegates in Objective-C are implemented as objects that respond to WRIPHWKQGDVHV7RKLVQ\GHÀHGDVDSUODWRFVHWRIPHKRHUDOORWKRGVLVJHQGDOWKRXJ LWUHVHPEOHLWHUIDFHWKHUHLVLQIDFVD&JQLÀFDQQQD&WGLIIHUHQWDVLFHEHWZHH interface and an Objective-C protocol: ‡ In C, an object that implements an interface is required to implement all the LQWHUIGHVGHÀPHWKRDFHWKQHGRQ ‡ On the other hand, objects in Objective-C that adopt a protocol are not required to implement the methods of the protocol for the given circumstance Another challenge is that, in many ways, traditional .NET frameworks have relied more heavily on events to accomplish similar capabilities, and the event model is much more familiar to .NET developers. With these differences in mind and hoping to make Xamarin.iOS as intuitive to C developers as possible without compromising the iOS architecture, Xamarin.iOS provides four different ways to implement delegate functionality: ‡ Via .NET events ‡ Via .NET properties ‡ Via strongly typed delegates ‡ Via weakly typed delegates Via .NET events For many types, Xamarin.iOS automatically creates an appropriate delegate and forwards delegate calls to corresponding .NET events. This makes the development experience very natural to C and .NET developers. UIWebView is a goodGHÀQHV2VHDPSO6LHRIWKL UIWebViewDelegate, which contains a number of methods that aUIWebView will forward if a delegate is assigned that includes the following: ‡ webViewDidStartLoad ‡ webViewDidFinishLoad ‡ webView:didFailLoadWithError 22 Chapter 2 ZHÀ:KDWQGLQWKH Xamarin.iOS classMonoTouch.UIKit.UIWebView are three events that correspond to the following methods: ‡ LoadStarted ‡ LoadFinished ‡ LoadError Via .NET properties Although events have the advantage of having multiple subscribers, they come with RZQOLPLWDWLRQV6SHFLWKHLUÀFDOO\WKLVFUXOGEHZKHRH events cannot have a return type. In situations where a delegate method must return a value, delegate properties are used. The following example shows you how to use a delegate property for UITextField. In this example, an anonymous method is assigned to the delegate propertyShouldReturn onUITextField: firstNameTextField.ShouldReturn = delegate (textfield) textfield.ResignFirstResponder (); return true; Via strongly typed delegates If events or delegate properties have not been provided or if you would just rather work with a delegate, you will be pleased to hear that Xamarin.iOS provides a set of .NET classes that correspond to each iOSRQQLWLH7KHVHFODVVHVFRQWDLQDGHÀHJDWGHO IRUHDFKPHWKRGGHÀQHKGRQWUHFRUHVSRQHWKRGVWKDWUHTXLUHGLQJSURWRFRO0 HLPSOPHQWDWLRQVDUHGHÀQHGDVDEVUWDFWDQGHÀQHGGPHWKRGVWKDWDUHRSWLRQDODUH as virtual. To use one of these delegates, a developer simply creates a new class that inherits from the desired delegate and overrides the methods that need to be implemented. For an example of using strongly typed delegate, we will turn to UITableViewDataSourceHVWRSRSXODWHDSÀQ7KLVLVWKHURWRFROL26GH UITableView instance. The following example demonstrates a data source that can be used to populateUITableView with phone numbers: public class PhoneDataSource : UITableViewDataSource Liststring_phoneList; public PhoneDataSource (Liststring phoneList) _phoneList = phoneList; 23 Demystifying Xamarin.iOS public override int RowsInSection(UITableView tableView, int section) return _phoneList.Count; public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) ... // create and populate UITableViewCell return cell; Now that we have created the delegate, we need to assign it to aUITableView instance. The property for theUITableViewDataSource delegate is namedSource with the following code that shows you how to make the assignment: phoneTableView.Source = new PhoneDataSource(phoneList); Via weakly typed delegates Lastly, Xamarin.iOS provides you with a way to use weakly typed delegates. Unfortunately, this method requires a bit more work for the developer. In Xamarin.iOS, weak delegates can be created using any class that inherits from NSObject. When creating a weak delegate, you are being handed the responsibility to properly decorate your class using theExport attribute, which effectively teaches iOS how the methods are mapped. The following example shows a weak delegate LDWHULQÀFDWWURSUHEXWHVSFLWKWKDSSZLDWLRVH public class WeakPhoneDataSource : NSObject ... Export ("tableView:numberOfRowsInSection:") public override int RowsInSection(UITableView tableView, int section) ... Export ("tableView:cellForRowAtIndexPath:") public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) ... 24 Chapter 2 The last few steps assign the weak delegate to aUITableView instance. By Xamarin. iOS convention, weak delegate property names always begin withWeak. The following example shows you how to assign the weak data source delegate: phoneTableView.WeakSource = new WeakPhoneDataSource(...); Once a weak delegate has been assigned, any assigned strong delegates will cease to receive calls. Creating binding libraries There might be times when you are required to create your own binding library for an Objective-C library that is not delivered as part of Xamarin.iOS and can't be found in the Xamarin component store. Xamarin provides a great deal of guidance to create bindings as well as an automated tool to help with some of the drudgery work. The following links provide guidance to create custom bindings for Objective-C libraries: Type of information URL to access it http://docs.xamarin.com/guides/ios/ General binding information advanced_topics/binding_objective-c/ Use of the Objective Sharpie http://docs.xamarin.com/guides/ios/ advanced_topics/binding_objective-c/ automation tool objective_sharpie/ http://docs.xamarin.com/guides/ios/ Binding types reference advanced_topics/binding_objective-c/ binding_types_reference_guide/ Memory management When it comes to releasing resources, Xamarin.iOS has this covered for you through garbage collector (GC), which does this on your behalf. On top of this, all objects that are derived fromNSObject utilize theSystem.IDisposable interface so that developers have some control over it when the memory is released. NSObject not only implements theIDisposable interface, but also follows the .NET dispose pattern. TheIDisposable interface only requires a single method to be implemented,Dispose(). The dispose pattern requires an additional method to be implemented,Dispose(bool disposing). The disposing parameter indicates whether the method is being called from theDispose() method, in which case the value istrue, or from theFinalize method, in which case the value isfalse. 25 Demystifying Xamarin.iOS The disposing parameter is intended to be used to determine if managed objects should be freed. If the value istrue, the managed objects should be released. Unmanaged objects should be released regardless of the value. The following code demonstrates what should be present in theDispose() method: public void Dispose () this.Dispose (true); GC.SuppressFinalize (this); Take note of the call toDispose(bool disposing) with a value oftrue. Conveniently, theDispose() method is implemented for you by the framework as a virtual method onNSObject. The following code demonstrates an implementation of theDispose(bool disposing) method: class MyViewController : UIViewController UIImagemyImage; . . . public override void Dispose (bool disposing) if (disposing) if (myImage= null) myImage.Dispose (); myImage = null; // Free unmanaged objects regardless of value. base.Dispose (disposing) Again, notice the call tobase.Dispose(disposing). This call is very important as it deals with resources managed within the framework itself. 26