Multi-Line Code Editing in Visual Studio 2017

Here’s a quick tip if you’ve ever wanted to edit multiple lines of code at once in Visual Studio. Simply position your cursor at a point in your code, then press and hold SHIFT and ALT.  Next, press the up or down arrow to select the lines you want to edit.  When you begin typing you will behold a gift from the gods – editing multiple lines at once!

Multi Select Visual Studio
Multi Select Visual Studio

How to make a tappable frame in Xamarin Forms

To make an entire Xamarin Forms frame tappable, use a FrameGestureRecognizer, and set the Tapped property to your handler.  now the whole thing is tappable!   Inside your Frame Content, you can place a ListView that has multiple components.  For a visual cue, set an outline color on your Frame.  Place multiple Frames in a StackLayout or a Grid and you have a nice set of call to actions.

 <Frame Grid.Row="0" Grid.Column="0" OutlineColor="Gray">
          <Frame.GestureRecognizers>
            <TapGestureRecognizer Tapped="OnFrameTapped" />
          </Frame.GestureRecognizers>
          <Frame.Content>
            <StackLayout Orientation="Vertical" HorizontalOptions="Center">
              <ContentView HeightRequest="80" >
                <Image Source="image.png">
                </Image>
              </ContentView>
              <Label Text="My Frame" HorizontalOptions="Center"></Label>
            </StackLayout>
          </Frame.Content>
 </Frame>

Gorilla player for Xamarin – XAML Preview!

The new Gorilla Player is out, and its great!  What is it?  Its an instant XAML previewer for Xamarin Forms projects!  (There is also a XAML previewer that was announced during the Microsoft Build 2016 conference currently only available in Xamarin Studio).  If you’re tired of the long cycle of designing your XAML then having to compile and deploy to your device or emulator just so you can view your XAML, then this is for you.  Gorilla Player allows you to view your XAML without compiling.  To get set up, all you have to do is complete their BETA registration form then download their package that contains the player source files and app.  The app is a desktop app that runs as a service in the background, acting as a server that listens for connections from your emulator.  After you have the desktop app up and running, navigate to the directory of the player solution project, and open it in Visual Studio.  Build the project and deploy it to your emulator.  Start the player app on your emulator.  It will try to automatically connect to your desktop app.  If it can’t find it, you can optionally connect manually.   In Visual Studio you will see a new toolbar option in Tools > Gorilla Player > Connect to Gorilla Player.  Now when you open XAML files in Visual Studio, you will see a Gorilla Player icon on the source page.

GorillaVS

You should now be able to see your XAML in the emulator!  That’s it for simple XAML.  If you have Xamarin Forms ListViews with bindings, then you can set design time data a number of ways, the simplest I’ve found is to include a JSON file in the root of your project called “SampleData.json”.  In the file, set your design time data by including a JSON object with multiple name value pairs, each with their value set to an array.  The name in each name value pair is the title of your XAML page.  Set the value of the name value pair to an array of objects with properties that conform to your model.  This will be the design time data you see in the XAML previewer.  Don’t forget to set the binding in your ListView to  ItemsSource=”{Binding}” instead of ItemsSource=”{Binding Items}” or whatever your model is bound to in the code behind, when you want to preview using the sample data.

{
  "BlogPage.xaml": [
    {
      "Title": "Blog Post 1",
      "Link": "http://www.example.com",
      "PublishDate": "4/01/2016",
      "XamImageSource": "NoImageAvailable.png",
      "Caption": "This blog post is nice"
    },
    {
      "Title": "Blog Post 2",
      "Link": "http://www.example.com",
      "PublishDate": "4/02/2016",
      "XamImageSource": "NoImageAvailable.png",
      "Caption": "This blog post is greater"
    },
  ],
}

There is an API for Gorilla Player that allows you to import custom .dlls for views that inherit from them, and more.  Head on over to GorillaPlayer.com to check them out.  Happy coding.

Colorzilla Developer Add-On for Firefox

I found this amazing tool today:  The ColorZilla developer add-on tool for Firefox.  If you’re a web developer, and like browser F12 tools, you’ll love this.  It has an Eyedropper tool that lets you easily get the color of anything in the browser window, then automatically copies it to your clipboard.

EyeDropper

There are plenty of other features too, such as a color palette browser, and a webpage DOM color analyzer, which its pretty cool.  It extracts all the colors for the page in your current tab.

DomAnalyzer

My advice?  Definitely worth installing!

Using Json.NET Serialization Attributes with clean classes

Json.NET is a wonderful library for serializing and deserializing JSON in .NET.  It is immensely popular, and is included in the project template for ASP.NET applications.  Often when deserializing JSON, the JSON data does not map to your classes neatly.  You can use serialization attributes to decorate your class members, which will control how Json.NET serializes and deserializes your JSON.  If you use interfaces to define your objects, you can decorate the implemented class while keeping your core definitions clean.

[{"gastypes":["leaded","unleaded"],"pumpcount":"10","sandwichretailer":true,"sodaretailer":true}
,{"gastypes":["leaded","unleaded"],"pumpcount":"6","sandwichretailer":false,"sodaretailer":true}]
  
  public interface IGasStation
    {
        string[] typesOfGas { get; set; }
        string numberOfPumps { get; set; }
    }
  
  public interface IFoodMart
    {
        bool sellsSandiwches { get; set; }
        bool sellsSoda { get; set; }
    }

    public interface IMegaStation : IGasStation, IFoodMart
    {

    }

    public partial class MySuperStation : IMegaStation
    {
        [JsonProperty("gastypes")]
        public string[] typesOfGas { get; set; }
        [JsonProperty("pumpcount")]
        public string numberOfPumps { get; set; }
        [JsonProperty("sandwichretailer")]
        public bool sellsSandiwches { get; set; }
        [JsonProperty("sodaretailer")]
        public bool sellsSoda { get; set; }                 
    }

The decorated MySuperStation class above allows us to deserialize JSON containing different property names by mapping the JsonProperty attribute while keeping our interfaces free of decoration.

 

Abstract Classes vs Interfaces in C#

When should you use an abstract class, when should you use an interface?  Here’s the lowdown on some of the reasons to choose one over another.  First, take a look at a very simple example of an abstract class and two classes that inherit from it.

   public abstract class ToastBase
    {
        public ToastBase()
        {
            Console.WriteLine("Toast bread in toaster");
        }

        public abstract void AddSpread();
    }

    public class PeanutButterToast : ToastBase
    { 
        public override void AddSpread()
        {
            Console.WriteLine("Spread peanut butter on toast");
        }
    }

    public class JellyToast : ToastBase
    {
        public override void AddSpread()
        {
            Console.WriteLine("Spread jelly on toast");
        }
    }

Setting aside technical reasons, one of the strongest benefits to using an abstract class is the ability to provide an invariant implementation of some functionality across all sub classes, while leaving other implementations up to the subclass.  In our example above, all types of toast must first be toasted in a toaster.  Then, depending on the type of toast, the subclass can add whatever type of spread it wants.

On to the technical side.  An abstract class cannot be instantiated.  It is meant to be inherited.  If a method is not marked as abstract in an abstract class, the implementation belongs to the abstract class.  Abstract methods are implicitly virtual, and are meant to be overridden by the subclass.  They have no implementation in the base class, and therefore no method body, just a signature.  An class can inherit from multiple interfaces, but only one abstract class.  Here’s a more real world example.  Imagine a website back end where we want to collect and process credit cards for online purchases.  We might implement an abstract class such as the following:

  public abstract class PaymentBase
    {

        public void ProcessPayment(int paymentID)
        {
            PaymentProcessor.SendPaymentRequest(paymentID);
            PaymentProcessor.HandlePaymentResult(paymentID);             
        }

        public abstract void CollectCardInfo();
    }

The abstract PaymentBase class dictates that no matter what way we collect card information in the front end website, we must always process the payment the same way.

Interfaces are like contracts that dictate all the functionality a class must have that implements it.  When you implement an interface, you must define a method body for all the method signatures in the definition.  Interfaces are great for dependency injection, which states that we should always program to an interface, not an implementation.  This is beyond the scope of this article, but warrants further reading if you’re not familiar with it.

Interfaces enable you do decorate additional classes of the same concept, adding functionality.  Consider the example below.  We have a Customer and a LoyalCustomer class.  They both implement the ICustomer interface.  While we can place an order for each type of customer using the same interface, we can apply a discount to a loyal customer.  Meanwhile, all throughout our application, we can use the ICustomer interface anywhere we refer to a customer, and pass either Customer or LoyalCustomer to the method.  This also allows us to extend Customer to additional custom types down the road.

   public interface IOrder
    {
       int OrderID { get; set; }
       decimal orderAmount { get; set; }
    }

    public interface ICustomer
    {
        void PlaceOrder(IOrder order);
    }
   
    public class Customer : ICustomer
    {
        public void PlaceOrder(IOrder order)
        {
            //work with order properties, etc
            int i = order.OrderID;
        }
    }

    public class LoyalCustomer : ICustomer
    {
        public void PlaceOrder(IOrder order)
        {
            //apply discount
            order.orderAmount -= 5;
        }
    }

That’s all for now.  I hope you enjoyed this post!

 

 

 

 

 

 

 

 

Why is a manhole cover round?

If anyone ever asks you this in an interview, as I’ve had asked of me, they’re probably testing how you think.  I was a bit shocked at first, what does this have to do with code?  Much, as it turns out.  How do you answer this question?  Many of you know the answer, but if you were like me, sadly I did not.  I gave it my best guess.  Reason out loud.  That’s the most important strategy here.  Turns out manhole covers are round so they don’t fall in the hole, and possibly on someone working in the hole.

Edit in peek definition Window!

This is the coolest thing since Spreadable Bacon.  In Visual Studio 2017, you can view a method definition, and edit the code right in a pop up window with the Peek Definition command.  In the screenshot below, I’m actually editing the code right in the pop up window itself.  This will save you a bunch of time by not having to dig down into other folders where your classes or methods are defined, just to make a minor adjustment.

peekDefinition

 

 

 

Organize and visualize your using statements better in Visual Studio 2017

In Visual Studio 2017, you can clearly see what using statements you are not… using.    The IDE grays them out for you.  This is a nice touch, as it can get confusing as to what namespaces are actually in use.  Especially after you’ve added some code, refactored, taken some things out.  Those little orphaned using statements that are no longer needed become easy to see.

HighlightedUsings

Want to get rid of them?  No problem.  Just go to Edit > IntelliSense > Organize Usings.  From there you can choose to Remove Unnecessary Usings, Sort Usings, or Remove and Sort usings.

Here’s what it looks like after I’ve removed my unnecessary usings.

RemovedUsings

Pretty cool huh?  I thought so.  If you choose Sort Usings, it will sort them alphabetically for you.  Here’s the before and after of that

UsingBeforeOrganize

UsingAfterOrganize

Visual Studio Live Redmond 2015

Visual Studio Live  is a multi-city tech conference focused on primarily the Microsoft stack.  I had the privilege of  attending the conference in Redmond.  If you’re familiar with tech conferences, there can be great things and not so great things.   Fortunately, VS Live has been full of great things!

If like me, you’ve been to Microsoft Build and the now formerly Tech Ed, you’ll know some of the ups and downs that go with big conferences like these.  Here’s my take on how VS Live compares.

Location.  Location.  You Get the Idea  VS Live Redmond is at the Microsoft campus.  This is cool in and of itself.  Its the center of it all.  Its cool to be here and see where it all goes down.  They let us have lunch at the main Microsoft commissary they call the Mixer, using a pre-loaded credit card, and tour the Visitor Center.

Big Vs Small.  Build and the new Ignite are big.  There are benefits to this.  More swag, more networking opportunities.  Typically bigger recreational events to keep the geeks busy at night, and more session offerings.  More experts floating around to pick their brain. Comparatively, with a smaller conference like VS Live, you get more intimacy.  This means a lot of things, and most of them, in my opinion, are good.  Lets explore this.

Speaker Access.  Ever want to ask a speaker a question after a session?  At the bigger conferences its possible, but you’ll have to fight your way through a mosh pit of developers all clamoring around him or her immediately after they utter “so in conclusion”.  At VS Live, you simply walk up and ask them a question.  Sure there might be a few other developers asking questions, but you’re basically guaranteed to get some time.  At Build, the speakers hang out in the cordoned off speaker zone.  At VS Live, the speakers hang out among us mere mortals.  You can always see them walking around the hallways during meals or breaks, and they’re more than happy to answer your questions.  In fact, they actually seem to enjoy it!  There’s really no emphasizing this aspect enough.  Being able to talk to and hang out with experts that are approachable, not egocentric, and actually really cool and interesting people, makes all the difference.  I learned a lot just through side conversations.  They also provided round table sessions with folks from the Microsoft team and speakers.  Again, you get plenty of chances to talk to knowledgeable people and ask them questions.  Its expected and encouraged.  You’re not competing with a mob of people.

Bathrooms  If you’re female, this doesn’t mean anything to you and you can skip to the next section 🙂  There’s no better representation of the (unfortunate and unnecessary) gender imbalance in tech than the length of lines for the men’s vs women’s bathroom.  In smaller conferences like VS Live,  if you’re a guy, the lines aren’t 10 miles long.

Food  The food at VS Live is better than Build, hands down in my opinion.

Content The sessions at VS Live are relevant to what you can use TODAY.  The content is more rich, in my opinion.  Its a good mix of bleeding edge and practical.  In depth and informational.  The bigger conferences tend to be a bit infomercially.  That’s all well and good, they kind of have to be.  At VS Live, they seem to be striking a good balance between addressing the challenges we face in the trenches daily, as well as getting us up to speed with the things we need to keep current.

Fun Stuff to Do  VS live did a good job of providing fun stuff to do at night.

In short, I’d consider VS Live the next time you’re convincing your boss to pay for something and send you out of town.  I’ll post more on this topic later.  What are your thoughts?  Happy conferencing!