Archive for the ‘Development’ Category

I recently read a “Coding Question” thread, and a developer was asking what we all thought about this article. I wanted to hold on to my replies, so I’m posting it here for posterity 🙂

Auri:

Only a Sith deals in absolutes. There are use cases for everything, with exceptions.

Auri:

Seriously, though, I’d write tests to ensure the states that you want work as expected.

Auri:

And now that I’ve had my coffee:

Exceptions are a necessary construct. If something doesn’t go as planned, we need a way to handle it. In his article, he’s against blindly swallowing exceptions. That’s generally sound advice. Ask yourself: “Is this an expected exception? If so, do I have a specific exception handler for it, or am I just using the generic catch-all? Have other exceptions occurred? If so, is this one expected? Didn’t I read about C# support for exception switch statements? Did I just shiver?”

Like I was explaining before, only a Sith deals in absolutes. The way I see it, if an error is unexpected, I should have specific use cases for how to handle that exception. I should, generally, never blindly swallow with no logging, or simply re-throw and assume the code above will address. At least, not without a custom/known/non-generic exception I can check up the chain, or include in an integration test. Good article about testing [written by a friend] here, btw: https://arktronic.com/weblog/2015-11-01/automated-software-testing-part-1-reasoning/
At the very least, and I try to follow this rule as much as possible, LOG in any exception for tracking and pro-active/offensive development. Better that you can read logs, or run scripts to let you know about exceptions, and help things go right, than to be blind with a “well, the code seems to work, so let it be” approach. That’s the key goal, really: Help things go right. There are exceptions [heh] to this rule, like simple utility apps whose job is to bulk process data, and exceptions are part of the game. Still, I try to make sure to log, even with those. Unexpected/unintended bugs tend to appear when you’re dealing with massive amounts of data, and logs give a perspective you can’t see from debugging.
Ok, next cup of coffee.

As part of my .NET 301 Advanced class at the fantastic Eleven Fifty Academy, I teach Xamarin development. It’s sometimes tough, as every student has a different machine. Some have PCs, others have Macs running Parallels or Bootcamp. Some – many – have Intel processors, while others have AMD. I try to recommend students come to the class with Intel processors, due to the accelerated Android emulator benefit Intel’s HAXM – Hardware Acceleration Manager – provides. This blog entry is a running list of how I’ve solved getting the emulator running on so many machines. I hope the list helps you, too.

This list will be updated from time to time, as I find new bypasses. At this time, the list is targeted primarily for machines with an Intel processor. Those with AMD and Windows are likely stuck with the ARM emulators. Umm, sorry. I welcome solutions, there, too, please!

Last updated: December 4, 2017

Make sure you’re building from a path that’s ultimate length is less than 248 characters.

That odd Windows problem of long file paths bites us again here. Many new developers tend to build under c:\users\username\documents\Visual Studio 2017\projectname. Add to that the name of the project, and all its subfolders, and the eventual DLLs and executable are out of reach of various processes.

I suggest in this case you have a folder such as c:\dev\ and build your projects under there. That’s solved many launch and compile issues.

Use the x86 emulators.

If you have an Intel processor, then use the x86 and x64 based emulators instead of ARM. They’re considerably faster, as long as you have a) an Intel processor with virtualization abilities, which I believe all or most modern Intel processors do, and b) Intel’s HAXM installed.

Make sure VTI-X / Hardware Virtualization is enabled.

Intel’s HAXM – which you can download here – won’t run if the processor’s virtualization is disabled. You need to tackle this in the BIOS. That varies per machine. Many devices seem to chip with the feature disabled. Enabling it will enable HAXM to work.

Uninstall the Mobile Development with .NET Workload using the Visual Studio Installer, and reinstall.

Yes, I’m suggesting Uninstall + Reinstall. This has worked well in the class. Go to Start, then Visual Studio Installer, and uncheck the box. Restart afterwards. Then reinstall, and restart.

Mobile Development Workload Screenshot

Use the Xamarin Android SDK Manager.

The Xamarin team has built a much better Android SDK Manager than Google’s. It’s easy to install HAXM, update Build Tools and Platforms, and so forth. Use it instead and dealing with tool version conflicts may be a thing of the past.

Make sure you’re using the latest version of Visual Studio.

Bugs are fixed all the time, especially with Xamarin. Make sure you’re running the latest bits and your problems may be solved.

Experiment with Hyper-V Enabled and Disabled.

I’ve generally had issues with virtualization when Hyper-V is enabled. If you’re having trouble with it enabled, try with it disabled.

To enable/disable Hyper-V, go to Start, then type Windows Features. Choose Turn Windows Features On or Off. When the selection list comes up, toggle the Hyper-V feature accordingly.

Note: You may need to disable Windows Device Guard before you can disable Hyper-V. Thanks to Matt Soucoup for this tip.

Use a real device.

As a mobile developer, you should never trust the emulators to reflect the real thing. If you can’t get the emulators to work, and even if you can, you have the option of picking up an Android phone or tablet for cheap. Get one and test with it. If you’re not clear on how to set up Developer Mode on Android devices, it’s pretty simple. Check out Google’s article on the subject.

Try Xamarin’s HAXM and emulator troubleshooting guide.

The Xamarin folks have a guide, too.

If all else fails, use the ARM processors.

This is your last resort. If you don’t have an Intel processor, or a real device available, use the ARM processors. They’re insanely slow. I’ve heard there’s an x86 emulator from AMD, yet it’s supposedly only available for Linux. Not sure why that decision was made, but moving on… 🙂

Have another solution?

Have a suggestion, solution, or feature I’ve left out? Let me know and I’ll update!

 

My latest Visual Studio extension is now available! Get it here: 2017, 2015

So what is CodeLink?

Getting two developers on the same page over chat can be time consuming. I work remote, so I can’t just walk to someone’s desk. I often find myself saying “go to this file” and “ok, now find function <name>”. Then I wait. Most of the time it’s only 10-20 seconds lost. If it’s a common filename or function, it takes longer. Even then, mistakes can be made.

So I asked myself: Self, wouldn’t it be great if I could send them a link to the place / cursor location in the solution I’m at? Just like a web link?

CodeLink was born.

So here’s what a CodeLink looks like:

codelink://[visualstudio]/[AurisIdeas.Common.Security\AurisIdeas.Common.Security.csproj]/[ParameterFactory.cs]/[9]

I would simply share that CodeLink with a fellow developer. They’d select “Open CodeLink…” in VisualStudio, paste it in, and be brought to that line of code in that project. No more walking them through it, much less waiting.

Technically, the format is:

codelink://[Platform]/[Project Unique Path]/[File Unique Path]/[LineNumber]

What’s it good for?

Other than what I’ve suggested, and what you come up with, I’m thinking CodeLink will help you, teams, teachers, and students with:

  • Include CodeLinks in bugs, code reviews to highlight what needs to be reviewed
  • Share CodeLinks on Git repos, pointing to specific code examples, points of interest, and so forth
  • Share CodeLinks with students so they can continue referring / reviewing useful code

So what’s next?

When I was thinking of the link format, I figured I may end up extending this to VS Code and other editors in the future. After all, not everyone uses VS. Why not XCode, Visual Studio Mac, Atom? So, I added a type identifier.

As always, I look forward to your feedback. Hit me up on Twitter or LinkedIn.

 

Micro Adventure was a series books in the 1980s where you had to write computer programs to get from chapter to chapter. It was a great way to learn coding for a geeky kid looking for a good story related to computers. A few months ago, I was granted rights to use the books on a website, and now it’s in beta! Check out the site and let me know what you think!

https://microadventure.net

 

I’m continuing my resolution to record as many of my programming and technical presentations as possible. I recently spoke at the inaugural Indy.Code() conference. It was excellent, with an incredible speaker line-up. I hope they, too, post some of their presentations online!

Watch the Video on YouTube

From the synopsis:

Should you write your app “native”Âť or use a “cross-platform”Âť solution like React Native, Xamarin, or NativeScript? The new wave of native-cross-compiling solutions provide significant cost savings, code reuse opportunities, and lower technical debt. Does wholly native, per platform development, still play a role in future mobile development? Let’s discuss together.

In this presentation, we’ll discuss:

  • The growth of native, hybrid, and cross-platform mobile development solutions
  • Cost analysis of multiple native and cross-platform apps
  • Considerations for each native and cross-platform solution
  • Lessons learned

Slides are available here: https://t.co/5iLhEoEfen

If you have any questions, I’m happy to answer them! Please email me or ask on Twitter.

 

I’ve been struggling with carrying a Mac and PC for Xamarin development for a couple years now. Wouldn’t it be nice to just run OS X in a VM so I could use my Surface Book and not mess with the Apple ecosystem more than necessary? Well, I finally got it working, thanks in large part to the work that’s been done by many people, links of which I’ll credit in this article. Thanks, all!

vm

Requirements

  • macOS X Sierra Installer, or a machine with Sierra installed – extraction details below
  • Intel powered machine, preferably i5 or higher
  • 16GB or larger thumb drive, preferably USB 3
  • VirtualBox 5.x
  • Visual Studio 2015 or higher
  • If on a laptop, you’re plugged in

Create the OS X Installer USB Drive

First things first – you’ll need a Mac running Sierra and at least a 16 GB USB thumb drive. We’ll be using Unibeast, Multibeast, and the Clover bootloader. I imagine you own both Mac OS and the drive. I’d go the USB 3.0 or higher route so things run a bit faster. We’ll be extracting a Sierra installer in a moment. If you’re all set with the above, follow the instructions at the awesome Tony Mac x86 website. Special thanks to the Hackintosh website. When asked whether to use UEFI or Legacy boot mode, choose Legacy. Here is a marked-up PDF of the article in case the link doesn’t work.

In a nutshell, here’s what you’ll be doing in this step:

  1. Insert the thumb drive into the Mac. Launch Disk Utility and format the USB drive with the name USB and the format of GUID Partition Map.
  2. Download the macOS Sierra installer via the App Store. The installer will be saved in your Applications folder. Make a copy of it somewhere, just in case it gets deleted and you need it again. Don’t move the installer.
  3. Download and Run Unibeast and follow the prompts. Use Legacy boot mode. You’ll need a [free] account on the Tony Mac x86 site to download, fyi.
  4. Let Unibeast create the thumb drive. This will take about 10 minutes on a USB 3 drive.
  5. Download and Copy Multibeast to the newly created Unibeast drive.
  6. You’re now ready to start configuring VirtualBox.

Create the VirtualBox USB Drive Shim

You have a USB thumb drive, but VirtualBox doesn’t make it easy to boot from such a device. You’ll need to create a fake virtual disk that points to the USB drive. This tutorial walks you through it. Here’s a PDF if that link doesn’t work.

In a nutshell, here’s what you’ll be doing in this step:

  1. Open Disk Management and get the Disk Number of the thumb drive, as shown below
  2. Open command prompt as an administrator
  3. Navigate to %programfiles%\oracle\virtualbox
  4. Run the command
    VBoxManage internalcommands createrawvmdk -filename C:\usb.vmdk -rawdisk \\.\PhysicalDrive#

    to create the virtual drive pointer

  5. You’re now ready to create the VirtualBox virtual machine.

disk-number

Create the VM

Windows won’t allow VirtualBox to use the USB shim you just created unless you launch with administrator privileges. Right-click VirtualBox and select Run as Administrator. VirtualBox should open. Then, follow the instructions on this page. Ignore the download portion – you already have an install thumb drive, and you just want the VM configuration steps. If that link doesn’t work, here’s a PDF.

In a nutshell, here’s what you’ll be doing in this step:

  1. Create a new Virtual Machine, name it Sierra – although that’s not a requirement – and choose OS X 64-bit as the guest OS. VirtualBox’s settings aren’t fully correct, but we’ll get there.
  2. Choose 4 GB of RAM. I didn’t test with any other memory configs. So, YMMV if you go another route.
  3. When asked which drive to use, choose an existing drive, and select the USB shim you created in the previous section. The example above saved the file as usb.vmdk at the root of C:
  4. You should now have a VM, like every other time you’ve used VirtualBox 🙂
  5. Add another Virtual Disk to stand in as your Mac’s hard drive. I suggest VDI format, dynamically sized, and 60 GB in size. Ignore that my screen shot shoes 40 GB <grin> In future steps you’ll need to install XCode and Xamarin Studio. Don’t skimp on size here or you’ll be reinstalling later. Much sad.

Note: XCode uses a lot of space when it updates. Don’t skimp on virtual disk size. If that’s a big deal, save the VM’s drive to a location that will have enough space.

Once you’ve added the hard drive, you’ll need to finish configuring the VM. You already have an installer on the thumb drive.

Aside from the defaults, confirm the settings you have match settings below. I’ve also included some screen shots a little further down.

  1. After performing the steps above, you’ll be using the following settings in your VM:
    • System, Motherboard, Base Memory: 4096 MB
    • System, Motherboard, Boot Order: Only Optical and Hard Disk checked
    • System, Motherboard, Pointing Device: USB Tablet
    • System, Motherboard, Chipset: ICH9
    • System, Motherboard, Extended Features: Enable I/O APIC, Enable EFI, Hardware Clock in UTC Time, all checked
    • System, Processor, Processors: 2 CPUs
    • System, Processor, Execution Cap: 100%
    • System, Processor, Enable PAE/NX: Checked
    • Display, Screen, Video Memory: 128 MB
    • Display, Screen, Monitor Count: 1
    • Display, Screen, Scale Factor: 100% (you can change this later if you’re on a high-res display)
    • Display, Screen, Accelerator: 3D and 2D both unchecked
    • Storage: One controller, first item is USB shim, then the hard drive and “Empty” optical drive. The order of those two don’t matter.

After configuring the VM in the UI, close VirtualBox and run the following commands, of which I’ve created a convenient all-in-one script here. You may need to edit it depending on what you named your VM.

These make the appropriate settings to fool OS X to thinking you’re on a real Mac.

cd "C:\Program Files\Oracle\VirtualBox\"

VBoxManage modifyvm "Your VM Name" --cpuidset 00000001 000106e5 00100800 0098e3fd bfebfbff

VBoxManage setextradata "Your VM Name" "VBoxInternal/Devices/efi/0/Config/DmiSystemProduct" "iMac11,3"

VBoxManage setextradata "Your VM Name" "VBoxInternal/Devices/efi/0/Config/DmiSystemVersion" "1.0"

VBoxManage setextradata "Your VM Name" "VBoxInternal/Devices/efi/0/Config/DmiBoardProduct" "Iloveapple"

VBoxManage setextradata "Your VM Name" "VBoxInternal/Devices/smc/0/Config/DeviceKey" "ourhardworkbythesewordsguardedpleasedontsteal(c)AppleComputerInc"

VBoxManage setextradata "Your VM Name" "VBoxInternal/Devices/smc/0/Config/GetKeyFromRealSMC" 1

Boot the VM and Install Sierra

Alright, we’re ready to boot! Re-launch VirtualBox as an administrator and start up. After a bunch of Unix style text scrolling, you should see the Apple logo appear and begin to load macOS. If not, something’s configured wrong.  Read through the above steps and see what you missed. Of course, things may have changed over time, and this tutorial may no longer be valid. Bummer if that’s the case! Much sad. I want you to be much happy.

NOTE: If things appear frozen during boot, wait a minute. In sanity checking this on another machine with a friend, his seemed to be frozen, and then resumed. A watched installer never boils… [terrible joke]

The instructions for installing Sierra are pretty straightforward:

  1. When the installer appears, select the Utilities menu on top, then Disk Utility.
  2. Format the Virtual Hard Disk. I named mine VBox, but that doesn’t matter. Make sure the format is GUID Partition Map and Mac OS Journaled. Do not select the case sensitive option.
  3. When formatting is complete, quit Disk Utility and you’ll be back at the installer.
  4. Select the freshly formatted hard drive and start the install process.
  5. Wait. It took about 20 minutes to install on my 6th Gen Core i7 SSD Surface Book. YMMV.
  6. Keep an eye on the installer. When it’s done, remove the thumb drive. Otherwise, it’ll boot back into the installer. If that happens, wait for the installer to boot so you don’t corrupt anything, then remove the thumb drive, and restart the VM.
  7. When the Mac boots back up, follow the prompts. Do *not* use an Apple account – it won’t let you. Make note of the username – it will be in lowercase – you’ll need that when you enter a username and password for Visual Studio later. Don’t worry about the Apple Account issue, though – this won’t affect your ability to install XCode or use the App Store.
  8. Once setup is complete, shut down the Mac.
  9. In the VM’s settings, remove the USB shim.
  10. OS X is now installed.

From this point forward, you no longer need to run VirtualBox as an administrator. Yay!

NOTE: After configuring OS X, you may be presented with a dialog stating the keyboard cannot be identified. Don’t worry – just follow the prompts and you’ll be all set.

Install Xcode

For OS X to act as a build server, you must have Xcode and Xamarin Studio installed. Let’s install and configure Xcode first.

To complete this step, do the following:

  1. Open the App Store on the Mac
  2. Search for Xcode
  3. Click Get to install it. You’ll need to enter your Apple account credentials.
  4. Wait a while – it’s big and takes a while to install. About 30 minutes on my machine.
  5. Once installed, Launch Xcode, agree to any terms, and let it finish installing components.
  6. When Xcode is finished configuring, open the Xcode menu, select Preferences, then Accounts, and click the + symbol. Enter your Apple Developer Account details.
  7. Great! Xcode is configured! Time to get Xamarin set up.

virtualbox_sierra_20_11_2016_08_48_44

Install Xamarin Studio

Xamarin Studio handles installing the OS X build agent so you can debug apps with Visual Studio, while performing the necessary build and simulation tasks on the Mac. This is required for licensing reasons, and Apple being a closed system for iOS developers. Boo.

Note: Xamarin Studio may be called Visual Studio for Mac by the time you read this.

  1. First, open Safari – unless you installed something else on the Mac already – and download Xamarin Studio for Mac. This is simple – go to Xamarin.com, and download the installer.
  2. Open the installer on your Mac from the Downloads folder, and click Open when it warns you that it’s an application downloaded from the Internet.
  3. Install everything except Android. You can do Android dev on your PC, so I feel there’s no reason to install it again here. Again, YMMV – do as you wish 🙂 This process can take a while due to downloading and installing many items.
    • Note: I’m not sure if you need Profiler or Workbooks, so I kept them in there. I’m thinking it’s an insignificant difference.
    • Another Note: The installer will say it’s installing Android SDK anyway, not sure why! 🙂 I complained to Microsoft about this – it didn’t make sense to me.
  4. Once Xamarin Studio is installed, start it and make sure it comes up.
  5. Under the Xamarin Studio menu item – which may be Visual Studio by the time you read this – select Check for Updates and make sure everything’s up to date.
  6. Note to Visual Studio 2017 Release Candidate Users: If you’re running Visual Studio 2017 Release Candidate, it [annoyingly] installs and targets the alpha channel of Xamarin. You’ll need to switch to the Alpha channel in Xamarin Studio to match this, otherwise Visual Studio will refuse to compile/build/debug through the Mac instance. A channel switching option is available in the Check for Updates menu to address this issue.

virtualbox_sierra_20_11_2016_09_23_19

Configure the Mac for Remote Login

In order to connect to the Mac from Visual Studio, we’ll need to open a port on the Mac side. The process is described in this article.

In a nutshell, here’s what you’ll be doing in this step:

  1. Press Windows-Space, which translates to Apple-Space, and type remote login to open the Sharing control panel.
  2. Check the box for Remote Login, and select All Users, or at least ensure your user account is in there. You’re on a private network only accessible by your machine, so I see few security issues here. Behind the scenes, this is opening Port 22 for SSH access to your Mac.

virtualbox_sierra_20_11_2016_10_01_03

Alright, we should be all configured! Let’s switch back to Windows!

Configure VirtualBox Networking and Port Forwarding for Remote Debugging

Now that the Mac is configured, we have to tell VirtualBox how to allow your computer to talk with it. We do this by configuring Port Forwarding in VirtualBox.

  1. Open command prompt and type ipconfig.
  2. Take note of the Ethernet adapter VirtualBox Host-Only Network, which may be #2, #3 etc. You want the one with an IP address. Copy that IP address to the clipboard.
  3. In VirtualBox, open the Settings of your VM, and select Network, then Advanced, then Port Forwarding.
  4. Add a new rule. I named mine Remote Access.
  5. For Protocol, choose TCP.
  6. For Host IP, paste in your host adapter IP.
  7. For Host Port, enter 22.
  8. For Guest Port, enter 22.
  9. For Guest IP, go to your Mac, use Windows-Space to search for Network Utility, and type in the IP that appears there.

getting-host-ip

port-forwarding

port-forwarding

Note: It’s possible the Guest IP will change from time to time. This is especially true if the Mac isn’t the only virtual machine you run. If you can no longer connect, check whether you need to update the Guest IP.

VirtualBox is now configured! If you want to verify this, you can launch bash shell on your Windows 10 machine and type ssh username@ipaddress, accept the certificate, and enter your password when prompted. If you can type ls and see your Mac’s files, all is good in the world.

Link Visual Studio to macOS

Alright, hard part’s over. Now we need to configure Visual Studio. The steps for accomplishing this can be found at the same link above, or you can just click here if you don’t want to scroll. There’s also a tutorial in Visual Studio.

In a nutshell, here’s what you’ll be doing in this step:

  1. Launch Visual Studio.
  2. Type Control-Q to access the Quick Access Menu, and type iOS Settings. This will take you to the Xamarin iOS settings pane.
  3. Choose Find Xamarin Mac Agent, follow the prompts to ensure you’ve configured everything properly.
  4. In Enter Mac name or IP address enter your VirtualBox host adapter’s IP. If everything’s configured properly, you should be prompted to enter your Mac’s username and password.
  5. If all went well, a lock-like icon should appear next to the IP address, as shown below. If not, make sure the version of Xamarin installed in Visual Studio is the same as that on the Mac. See my note above about Visual Studio 2017 and its Xamarin Alpha Channel issue.

And, Go!

If everything went well, you should now be able to do all your Windows and Xamarin / Mac development on one machine!

Please provide feedback in the comments. Enjoy!

Tips / Updates

  • If you’d like to tweak the video resolution, you can follow this article. The command is:
VBoxManage setextradata "VM name" VBoxInternal2/EfiGopMode N

Where N can be one of 0,1,2,3,4,5 referring to the 640x480, 800x600, 1024x768, 1280x1024, 1440x900, 1920x1200 screen resolution respectively
  • My goal with this article is to build a machine for building a build/test VM. I am not trying to replace a Mac environment for doing lots of work on the Mac side of things.

 

 

I recently purchased an LG UltraWide 21:9 display. Why an ultra-wide and not 4K? a) I write code for a living and this is a great way to get two windows full size side-by-side without an extra monitor. b) It was only $130 instead of $400 due to a Best Buy sale. Sold!

I get home, connect it to my Surface Book, and nothing works. The screen just blinks on and off, on and off, blinkety blink, blinkety blink. No Bueno. Changing the cable made the blinkety blink go away, but the display control panel would suggest trying different settings, and wouldn’t light things up.

My friend Shane recommended I get an Active MiniDP to HDMI adapter. So I bought one on Amazon. Still, I didn’t want to wait… that’s 2 days with Prime shipping, and not fast enough.

So, I looked into the MiniDP adapter I was using. I found out it only supports up to 1080P! Maybe it’s DP 1.1 or something. Whatever it is, it couldn’t support a 2560×1440 or thereabouts display.

Fry’s had the answer – I made sure I found a MiniDP to HDMI adapter that clearly stated it supports 4K and MiniDP 1.2. The particular product I purchased was the Cirago Mini DisplayPort to HDMI Display Adapter.

I got home and the adapter worked flawlessly.

I hope that helps anyone having a similar issue!

 

The built-in Facebook OWIN provider in ASP.NET MVC can open your website to the benefits of logging in via the social networking behemoth. Still, it’s limited when it comes to pulling in profile details such as photo, birthdate, gender, and so forth. I recently implemented retrieval of those profile properties, and will explain how you can do it, too! I feel the obvious benefit is your users don’t need to manually type in their profile details, should you have similar fields in your system.

I’m assuming you’ve created and configured a Facebook app via Facebook’s Dev center, and won’t be going into that process in this article.

Determine Which Profile Fields You Need

Before we write any code, you need to know to which profile details you desire access. Facebook used to be relatively open. Not anymore! Now you need to ask permission for a ton of items, and many are no longer available. Make sure you check permissions at least every 3 months, otherwise you may find your granted permissions are no longer, well, granted, or even accessible.

Here’s a link to everything you can get: https://developers.facebook.com/docs/facebook-login/permissions/

In my case, to access the Profile photo, name information, and some other basic items, I chose:

  • public_profile
  • email
  • user_photos
  • user_about_me

I probably don’t need all these right now, but I may in the future. I figured I’d ask ahead of time.

Once you have your list, continue to the fun coding part…

Enable the Facebook Provider in Startup.Auth.cs

If you haven’t already, you’ll need to enable the Facebook provider via Startup.Auth.cs. Make sure you do this *after* any cookie authentication, so “normal” username/password logins are serviced before Facebook takes over. This should already be the case, as the default ASP.NET MVC template includes the many optional providers afterwards by default.

I suggest keeping the App ID and Secret in your config file – or at least out of code – so you can swap for differing environments as necessary. The code snippet below enables Facebook authentication, and specifies the profile fields for which we’ll be asking read permission:

You don’t have to use what I chose – it’s just what I needed for my particular case. Facebook *does* change allowed permissions and profile item visibility somewhat often. Stay on top of their developer changes – otherwise your site login may unexpectedly break.

// Enable Facebook authentication with permission grant request.
// Otherwise, you just get the user's name.
var options = new FacebookAuthenticationOptions();
options.AppId = ConfigurationManager.AppSettings["Facebook.AppId"];
options.AppSecret = ConfigurationManager.AppSettings["Facebook.AppSecret"];
options.Scope.Add("public_profile");
options.Scope.Add("email");
options.Scope.Add("user_photos");
options.Scope.Add("user_about_me");
app.UseFacebookAuthentication(options);

Install the Facebook NuGet Package

In order to easily get access to the Facebook data, I used the Facebook.NET library. It’s easy enough to install:

Install-Package Facebook

Note: I used version 7.0.6 in this example. You should be able to find the latest version and changelog at https://www.nuget.org/packages/Facebook/7.0.10-beta

Handle the Facebook External Login Callback in AccountController.cs

Once Facebook has been configured, all requests from your website will direct to Facebook, where it will ask permission, and, if granted, will redirect back to the ExternalLoginCallback action in the Account controller. It is here that I suggest you retrieve the data you’ve requested from Facebook. You’ll then modify the associated ExternalLoginConfirmation View with fields to correct or remove any information from Facebook, then continue with the account creation process on your website. That’s the part where you’ll populate the ApplicationUser entity, or whatever you decided to call it.

It’s relatively simple, as shown in the code below. The steps are as follows:

  1. Get the Facebook OAuth token with a simple HttpClient call
  2. Make the request for Profile details using the Facebook.NET library
  3. Optionally, download the Profile photo and save it somewhere

Yes, I could split this out – refactor as you see fit, and feel free to share any optimizations.

Below is the change to ExternalLoginCallback to grab the data from Facebook after the redirect:

ExternalLoginCallback Code

If you’d like to get the profile image, below is an example:

GetProfileImage Code

 

Moving Forward

I hope this article has helped answer your Facebook integration questions. If you would like additional details, please post in the comments, or message me on Twitter: @Auri

Thank you!

I went back and forth between my code and various Telerik and Stack Overflow demos of how the Kendo grid is supposed to refresh its datasource without reloading the entire grid. Finally, Telerik sent me a code example that included a function that’s not in their API documentation, but darn well should be. So, if you’re having the same issue I did, where you want to call read() on your grid’s datasource, but it simply isn’t working, here’s an example from Telerik that may help you.

The function: getKendoGrid()

Now, I keep my createDataSource() function around so I can swap out the data I’m paging. Their example uses some sample data, but you could simply use their example of creating a datasource to call your back-end JsonResult action in MVC and things can still work magically.

I hope this helps others Smile

<body>
  <div id="grid" />
  <script>
    function createDataSource() {
      return new kendo.data.DataSource({
        transport: {
          read: {
            url: "/echo",
            dataType: "json",
            method: "POST",
           
            // Simulate response
            data: {
              "json": JSON.stringify([{
                firstName: "John",
                lastName: "Smith",
                age: 25
              }])
            }
          }
        },
        pageSize: 10
      });
    }
   
    var ds = createDataSource();
   
    $("#grid").kendoGrid({
      dataSource: ds,
      autobind: false,
      scrollable: false,
      columns: ["firstName", "lastName", "age"]
    });
   
    $("#grid").getKendoGrid().dataSource.read();
  </script>
</body>
</html>

And here’s a colorized version:

image

I know it may be an act of pure sadism, but I see value in having a full development environment available in a package that weighs less than a pound. My Dell Venue 8 Pro runs full Windows 8.1, so why not write code on it? Well, there’s a limitation. I’m chea… err, frugal. So, I bought the 32GB device, on sale for $99 during Microsoft’s “12 Days of Deals” event. After clearing out a lot of space, and after installing all my Windows Store apps, I had just under 6 gigs free. Visual Studio takes roughtly 5.38 gigs for a base install, and more than 7 for a full. I still want to download apps, so using all that precious main storage space isn’t an option.

So, why not use the MicroSD expansion, you say? Great idea! Oh, wait… Visual Studio won’t install on removable media unless it’s Windows To Go certified, which only a handful of USB drives, and no MicroSD cards, can claim privileged membership. What is a developer to do?

Mount Points

It turns out there’s a workaround, but it requires you to “trick” Windows. I want to use that MicroSD and all its 16 gigs of practically unused storage. (Yes, I could have used a 32, but I didn’t have one handy at the time. Anyway…)

Using a feature in NTFS that allows you to permanently point the contents of an empty folder to another drive, in this case the MicroSD, you can install anything you want in that folder, and it won’t affect the available drive space on C:, safely keeping everything in the “remote” storage location. These remote locations are called NTFS Mount Points.

Now, there’s a catch… Even if you have a 32 GB MicroSD, that doesn’t increase your primary drive’s capacity by 32 GB. If your C: drive, in this case, only has 6 gigs free, then that’s what any Windows Installer will see as available. Now, once the installation is underway, it won’t run out of space when installing. However, if you don’t have enough space on C: to install in the first place, it won’t continue. So, before you try this process, make sure you have enough room on the drive for installation as if you were installing without the remote storage location!

Ready? Let’s Go

The entire process is very simple. We’ll start at the Desktop, which you can access on the All Programs menu.

  1. First, make sure you have enough space free on your C: drive, since that’s where Visual Studio will want to install on your tablet.
  2. Open Explorer, go to your C: drive, and create an empty folder. I named mine MicroSD, so I know the contents are on the removable media. You might ask why I simply didn’t redirect my Program Files folder. Here’s the reason: That’s a risky move, and the MicroSD card is slower than the built-in SSD. Also, if the MicroSD fails, I can simply reinstall the non-essential programs in that folder, without affecting all my primary apps and overall tablet usability.

    image

  3. Long-tap This PC in the side panel, and select Manage.

    image

  4. When the Computer Management window appears, tap Disk Management under Storage.
  5. Long-tap your MicroSD card in the list of Volumes on the top, and select Change Drive Letter and Paths.
  6. Tap Add, then tap the option for Mount in the following empty NTFS folder, and select your folder by tapping Browse.

    image

  7. That’s it, now you can install Visual Studio! Simply set the install location to the new folder you created instead of the standard Program Files folder.

A few notes when installing:

  • Remember, this is a tablet with 2 gigs of RAM. Don’t install SQL Server and the like.
  • Don’t run servers on your Venue Pro unless you want to kill the battery. Yeah, it’s Quad Core, but it’s also a low power processor built for on-the-go computing.
  • Visual Studio still installs a lot on your C: drive in the Program Files and Windows folders. It’s a development system, after all. So, be prepared to sacrifice 2-3 gigs of available space there.
  • As you develop, Visual Studio still has its little droppings of temp files. Clean up a bit more often if you’re doing a lot of dev.

What about a keyboard?

That’s what I was thinking… I just ordered the Dell Tablet Wireless Keyboard accessory from Dell’s site. It’s still pending shipping, so once I receive it, I’ll post a review.

I have a link to the accessory in this post.