Posts Tagged ‘c#’

So I had to deal with this recently. There were many examples out there, many of which didn’t work. Sooo, I’m blogging my code example so others don’t remain stuck 🙂

In short:

  1. In the XAML, add a CommandParameter binding, and wire up the Clicked event handler.
  2. In the C# Event Handler: Read the (sender as Button).CommandParameter and it’ll be the bound object. Cast / parse accordingly.

XAML (condensed):

<ListView x:Name=”LocationsListView”
ItemsSource=”{Binding Items}”
VerticalOptions=”FillAndExpand”
HasUnevenRows=”true”
RefreshCommand=”{Binding LoadLocationsCommand}”
IsPullToRefreshEnabled=”true”
IsRefreshing=”{Binding IsBusy, Mode=OneWay}”
Refreshing=”LocationsListView_OnRefreshing”
CachingStrategy=”RecycleElement”>
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Orientation=”Horizontal” Padding=”5″>
<StackLayout WidthRequest=”64″>
<Button
CommandParameter=”{Binding Id}”
BackgroundColor=”#4CAF50″
Clicked=”MapButtonClicked”
Text=”Map”
HorizontalOptions=”FillAndExpand”></Button>
</StackLayout>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>

C#:

protected void MapButtonClicked(object sender, EventArgs e)
{
var selectedLocation = _viewModel.Items.First(item =>
item.Id == int.Parse((sender as Button).CommandParameter.ToString()));

Utility.LaunchMapApp(selectedLocation.Latitude, selectedLocation.Longitude);
}

I’m pretty proud of this. Working on the app with the City of Fishers’ support, we’ve brought home a Mira Honorable Mention. After less than a year, we have thousands of users and two six arrests, with hundreds of incidents reported by Fishers residents. Pretty cool. Our team deserves it for all their hard work! Special thanks to Ed Gebhart, Mayor Scott Fadness, Chiefs Mitch Thompson and George Kehl, and the officers and citizens who continue to provide feedback to make this service even better for our community. 🙂

IBJ Article: https://www.techpoint.org/2017/04/mira-awards-winners-2017/

Mira Award Plaques

A little technical detail on the app, for those who are interested:

Platform: Xamarin with Xamarin.Forms, so we only had to write it once to deploy to iOS and Android. Yes, it really works.

Development Window: 18 months. Includes test runs with officers and the community.

Language: C#.

Time to Deploy to Google Play Store: Less than 15 minutes.

Time to Deploy to Approve Apple Developer Account: 3 months. They wouldn’t believe we were the City. Even with a phone call from the Mayor. That was an experience!

Time to Approve App, once we were in: 3 days. They were pretty cool after we were approved. 🙂

 

Want to learn all about Xamarin and how you can use it, while not spending most of your time watching code scroll by in a video? I figured there was room for an explainer without being a close-captioner for a code tutorial. Enjoy my latest video!

https://www.youtube.com/edit?video_id=AhvofyQCrhw

From the description, along with links:

Have you been considering Xamarin for your cross-platform mobile app? This presentation will help.

In this non-code-heavy presentation, we’ll discuss:

* What is Xamarin
* Development Environment Gotchas
* Creating a Sample To Do List App without writing any code
* Reviewing a real Xamarin app that’s “in the wild”
* Review native, platform-specific integrations
* Discuss gotchas when using Xamarin, and mobile apps in general
* Answer audience questions

Why not code-heavy? Because there are many examples you can follow online. This presentation will provide valuable information you can consider while reviewing the myriad of tutorials available to you with a simple Bing or Google search, or visiting Pluralsight, Microsoft Virtual Academy, or Xamarin University.

If you have any feedback, please leave in the comments, or ask me on Twitter: @Auri

Here are the links relevant for this presentation:

Slides: https://1drv.ms/p/s!AmKBMqPeeM_1-Zd7Y…

Indy.Code Slides with Cost and Performance Figures: https://1drv.ms/p/s!AmKBMqPeeM_1-JZR4…
(you can find the Indy.Code() presentation on my YouTube channel)

Google Xamarin vs. Native iOS with Swift/Objective C vs. Android with Java Performance Article: https://medium.com/@harrycheung/mobil…

Example code for push notifications, OAuth Twitter/Facebook/Google authentication, and more: https://github.com/codemillmatt/confe…

Link to Microsoft Dev Essentials for $30/month free Azure credit and free Xamarin training: https://aka.ms/devessentials

Microsoft Virtual Academy Multi-Threading Series: https://mva.microsoft.com/en-us/train…

 

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 noticed students feel learning object oriented programming appears tough when first exposed to structured development practices. To add insult to injury, boring example relationships like “people” and “students” and even types of fruit and their plant family relationships are used to show how objects relate to each other. I’m more in the camp believing learning “scary” new concepts should be fun, even memorable. People tend to remember good jokes, and forget dull experiences. I experimented with an approach to OOP. I used the old children’s storybook, Everybody POOPs.

We’re all human beings. All Humans eat and drink, and everybody poops. It takes a system to get to the pooping stage. We also fart. Adults fart and say excuse me!, while children fart and giggle. They’re still Human. Hopefully you can see how these related entities can be turned into computer classes.

I finally got around to recording a video of my teaching this concept, as it relates to classes in Microsoft’s C#. Student reactions are always enjoyable. Most of the time, they laugh, and have fun. I usually get compliments that it’s a lot easier to remember because it’s funny. Some people are disgusted I would talk about such a topic in class – I’m thinking those people don’t have a sense of humor. No photos are involved, so what’s the big deal?

Watch the Video

Here’s my original Blog Post about it

I was challenged last year to write a JavaScript version of Everybody Poops. I finally got around to that this year, explaining objects to students at the TeKY Initiative. That was a bit tougher, since JavaScript isn’t really object oriented. Still, it was fun. The students even got me a poop emoji mug 🙂 You can view the code here. You’ll need to use the console to play with the object.

I’m continuing to teach concepts in [what I feel are] fun, real world ways. My first step has been to create “Real World Programming” videos on YouTube. Two are complete as of this article – OOP (link above) and Inversion of Control + Dependency Injection. I hope to do a few more in 2017 as time permits. If you have a suggestion, please let me know!

I’ve been using this example for a couple years now – explaining Object Oriented Programming with a cute example based on the book Everybody Poops. It’s fun, and much less bland than the other OOP examples I’ve seen 🙂

Here’s the link: https://www.youtube.com/watch?v=_0PFHaX04mo

In case you missed the first video on Inversion of Control and Dependency Injection: https://www.youtube.com/watch?v=HcJN1XCs8t0

This is the second video in my Real World Programmer series. I hope you enjoy!

 

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 recently ran into a need to use the LAME MP3 encoder in a customer’s website. Problem was, once I deployed to Azure, I received an error of “Unable to load DLL libmp3lame.32.dll”. Uh oh! “But it’s in the bin folder!” I screamed silently at Starbucks. So, I binged the issue and found a good answer on StackOverflow. I’m sharing here because it helped unstick me, and I imagine others may be running to this issue with libraries other than LAME.

I ended up adding the function to my Global.asax, in addition to importing namespaces System.IO and System.Linq:

/// <summary>
/// Updates PATH variable in hosting instance to allow referring to items in this project's /bin folder.
/// Very helpful with Azure.
/// </summary>
public static void CheckAddBinPath()
{
    // find path to 'bin' folder
    var binPath = Path.Combine(new string[] { AppDomain.CurrentDomain.BaseDirectory, "bin" });
    // get current search path from environment
    var path = Environment.GetEnvironmentVariable("PATH") ?? "";
 
    // add 'bin' folder to search path if not already present
    if (!path.Split(Path.PathSeparator).Contains(binPath, StringComparer.CurrentCultureIgnoreCase))
    {
        path = string.Join(Path.PathSeparator.ToString(), new string[] { path, binPath });
        Environment.SetEnvironmentVariable("PATH", path);
    }
}

Then in Application start I simply added:

// Sometimes files aren't loaded properly from bin. Hint to the app to load from /bin, too.
CheckAddBinPath();

I hope that helps!