A .NET Developer Introduction to Salesforce

Many people have heard of Salesforce.  Right now, you’re probably thinking of a web portal used by sales people to find new customers, maintain accounts, and track opportunities, and you’d be right to think that.   Salesforce is a great platform for CRM, but it’s so much more than that.

There are plenty of articles out there on the web tracking the meteoric growth of Salesforce as a company.  One reason for this, is that Salesforce is becoming a full-blown platform, allowing developers (or even savvy business users) to create workflows, business processes, and more using an entire ecosystem of tooling.

Salesforce is a multi-tenant application, meaning multiple organizations will share the same instance. Think of this as renting office space in a downtown sky rise instead of building your own office in the suburbs. When you rent the space, the landlord (Salesforce) is taking care of everything for you in terms of water, electricity, security, mail delivery, and likely offers several on-site services such as a dry cleaning. In a similar fashion, Salesforce is providing you with hosting, application monitoring, security, API extensibility, and much more by building your application inside their environment. It’s less for you to worry about as a developer.

Let’s use a contrived example that I want to manage my video game collection on Salesforce, which is about as far from “sales” as one could get.   Inside the web portal, I create my objects (Games, Publishers, Platforms) specifying the field types, validation rules, any parent-child relationships.  Once my data types are setup, I can enter records right away using the Salesforce UI.  Additionally, my data is available via a REST or SOAP API automatically.  It’s also available for me in the Salesforce mobile app.  I didn’t need to do any programming to setup the basic CRUD behaviors for these new objects, everything exists there for me.   Sure, I can extend the application (more on that later), but a lot of the tedious boilerplate work is already taken care of for me.

If I want to write applications that work with this data I created, I can do so using a programming language known as Apex, which is syntactically very similar to C#.  I can write database queries inside this programming language to query my data using SOQL (Salesforce Object Query Language) which is very similar in syntax to SQL.  If I want to insert/update/delete data in Salesforce I can use DML (Data Manipulation Language).  I can also search this data using SOSL (Salesforce Object Search Language) which has a similar syntax to Lucene for anyone who is familiar with the popular search framework that powers Elasticsearch/Solr.  Development is either done inside the ‘Developer Console‘ in Salesforce or can be done with an extension for VS Code.

As if the full development environment were not enough to convince you, there is also a full-featured learning portal, Trailhead, which gamifies the learning process, allowing you to earn badges and points for completing tutorials and even allows you to complete hands-on exercise and checks those exercises for you.  There are exercises for every type of user (business user, admin, or developer) with varying degrees of difficulty that allow to get a quick start on the basics, but also continue to learn and grow to become an advanced user.  Once you’re comfortable developing on the platform, Salesforce even offers several certifications to show to prospective clients that you are indeed qualified and capable.

There are a large number of courses available to developers on both Pluralsight and Udemy (and others I’m sure) for anyone who is looking to learn more about Salesforce development.  Salesforce has a large community following of very passionate customers as well.  If you were to look at any job board, you would see Salesforce skills are in high-demand, and growing rapidly along with the company itself.  They also host a number of conferences they host each year, including Dreamforce in San Francisco.

I really hope this post gave you a good high-level overview of what Salesforce offers.   In the future, I plan to dive into more specifics of the Salesforce platform as I continue to learn all it has to offer.   Two key areas I’m really interested in learning more about are Einstein Analytics, Salesforce’s AI/BI intelligence platform, and Integration Cloud (formerly Mulesoft), an integration platform that connects multiple systems with an intelligent API.   I should also probably include Commerce Cloud (formerly Demandware) as well given my history as an Ecommerce developer.

 

Create Your Own .NET Core Templates in 4 Easy Steps

Do you ever develop prototypes, or starter projects/accelerators, that you’d like to use again in the future? A good way to do that is by creating custom templates for dotnet. Once completed, anytime you want to create a new project of that type in the future, you can use key in “dotnet new ” and you’re off, complete with correct namespaces. You can even do conditional checks, or variable replacements.

1. To start, clone or download the MyGameStartup project which will make following along easy. There is nothing special about this, it’s just for the purposes of showing how you can bundle multiple projects, and do some variable replacements. Note: You’ll need .NET Core 2.1 SDK for this at a minimum. Once open, you’ll see a solution file, and a few simple projects with some basic Entity Framework Core behavior.

2. Note that in the downloaded project, there is a folder labeled “.template.config” with a file inside it labeled “template.json”. Let’s review the contents of that file. Feel free to update this file with values you plan to use for your own project type, but you can leave these if you want to just continue with the demo.

I’ve added comments to the file so it is easy to understand, along with a link to the official documentation. There are more features than I am covering here if you wish to add them. A few noteworthy settings in the file are the “shortName” property. This is the trigger for your project, i.e. ‘dotnet new mygamestartup’. Also, if you see the section labeled “symbols”, and then cross-reference this with the projects ‘appsettings.json’ file, you’ll see the connection string’s database will be replaced with the “–db” parameter once we run it.

3. Ready to add this new project type to your available list? I’ll also show you how to remove it if you no longer plan to use this one. Run the following command, from the same folder as the downloaded .sln file and .template.config folder: “dotnet new -i .”. The dot here refers simply to the current directory. You could have also specified the path, but this is easier. If successful, you should see a list of project types, along with your project type added.

New project added screenshot from ConEmu terminal

Woohoo! You now have your own custom accelerator template you can use for other projects. Side note: This screenshot is from the ConEmu terminal which I use. You can download it here.

An important note also on this step. Running the “dotnet new -i .” command will bundle the current folder. I may not have discovered the setting yet, but keep in mind this skips empty folders. So if your wwwroot folder was empty, you will see this is not created after installing. I added a site.css to my version to avoid this.

4. We’re moving along quickly now. Next step… fire up a new project with our new template! Navigate the directory you’d like your project to be a folder within, such as “C:\Users\myusername\source\repos” and then issue the command, “dotnet new mygamestartup –db MyCustomStartupDB -n MyCustomName“. The database name will be set in the connection string in appsettings.json and a folder will be created named MyCustomName. Your projects namespace will also be MyCustomName. Note: If you get an error about a lock, be sure your Visual Studio instance with “MyGameStartup” project you downloaded in step 1 is closed. You may need to remove the MyCustomName folder and try again.

Follow the steps in the README to create the database with the name you specified, and also steps on how to run the Entity Framework Core Update-Database command properly. After that, you’re done! You just created a new project from a template you previously created.

Optional: To Uninstall the project, you can use the “dotnet new -u” command to list the currently installed projects. You should see your “MyGameStartup” project listed here. You can simply remove it with the command “dotnet new -u “Path-To-Folder” such as shown below.

Next Steps: A few steps I haven’t taken yet, but may in the future, is to add the following features to my template:

  • Create a nuget package to easily distribute your new package.
  • Add a new ‘symbol’ to the template.json which has datatype ‘choice’. A choice symbol will allow the user to pick from several options when creating your template.
  • Modifiers can be used to conditionally output certain code or not. You may wish to optionally include authentication as an example. More details here.
 

Exploring Video Games With the New IHttpClientFactory In .NET Core 2.1

REST services are everywhere. It’s tough to find an application that doesn’t leverage an externally hosted REST service in some way. Prior to .NET Core 2.1, a common library that was used to perform REST requests was RestSharp. I love RestSharp, but let’s explore the new alternative IHttpClientFactory that became available as part of .NET Core 2.1.

In this demo, we’re going to cover a bunch of awesome features:

  • Simple dependency injection
  • Named instances
  • Typed clients
  • Message handlers

In addition, for this service, we’re going to leverage the Internet Game Database API to pull in some data about Nintendo Switch games. As an aside, if you don’t already own a Nintendo Switch, it’s a fantastic device for the family, for travel, or just for fun. If you want to follow along with the code, you’ll need to create a free account here. Once you have your API key, you’ll want to be sure to include that in the code. There is a host of functionality available with this API, and you could use it to start building your video game collection, embed information about games in your apps, and much more.

You may also wish to download the source code for this. It is available on Github here.

Basic Usage

To start, let’s open Visual Studio 2017 and create an ‘Empty’ project denoting ASP.NET Core 2.1 as the framework.

Once we’re up and running, let’s add a few lines to our Startup.cs class. It should look like this when we’re done. Specifically, note the new services.AddHttpClient(); extension method on IServiceCollection which is exposed in 2.1.

Next, let’s create a GameController and a Game class for the purposes of deserialization. Notice how we inject the IHttpClientFactory into the controller constructor? We then use the CreateClient() method of the factory inside the controller action to create a basic instance. A noteworthy feature for IHttpClientFactory is that it maintains a pool of reusable clients, each with a lifetime of 2 minutes by default. This keeps the overhead involved with connectivity and instantiation at a more manageable level by default which is great for our overall performance and scalability.

Named Instances

In the above code, we are defining the HttpClient inside the controller class, but it’s also possible to have a “named” instance of the HttpClient. We could re-write our line from our Startup.cs class above to use this code instead:

Then, inside our controller, we would inject the IHttpClientFactory the same way, but we would change the CreateClient() method to use our named instance.

Typed Clients

Cool stuff so far, right? Let’s take it one more step further: typed clients. Let’s add the interface and class below to our application. Note how we have a private HttpClient as part of our IgdbClient object which exposes developer friendly names for each of the Igdb.com API endpoints we can consume in our application. Note: There are plenty more fields available in this API, including artwork, screenshots, and more but we are just keeping it simple for the demo.

Finally, let’s modify our Startup class to inject our configured client for our application, and also modify our GameController class so that it exposes these two new methods for testing purposes. We’re configuring the Startup class to inject our application specific configuration (so we can distribute this class to other applications which each have their own API key, and we’re also injecting IgdbClient this into the controller.

Message Handlers

The last feature we’re going to discuss is message handlers. Handlers can be attached to clients to monitor messages as they go in, or messages as they go out. You could perform logging for messages or duration, request validation, and more. Handlers can be chained as middleware as well. We’re going to keep it simple for our demo, and simply verify that the user-key which is required for the Igdb.com API is specified for the request before it goes out for our application. Let’s add the following class to our app:

Let’s also modify our Startup class, specifically the ConfigureServices method so that the following appears after we registered our IgdbClient.

Now, if we try to call the /game/id or /game/popular endpoints without having specified our user-key, this will result in a 400 Bad Request error before it is even attempted to be sent to the Igdb API. This potentially saves us API usage limits and cost as well as improves our performance by failing before the attempt is made.

 

Adding AppSettings.json Configuration to a .NET Core Console Application

This post will walk you through the steps necessary to add a strongly typed appsettings.json configuration file to your console application. I’ll dispense with the formalities of writing a detailed introduction on why you would be interested in doing this and jump right into the steps involved.

Note: This post assumes .NET Core 2.1, but I believe any 2.x version will work.

1. Add the following NuGet packages to your console application:

2. Right-click your console application, and select “Unload project“. Once the project has been unloaded, right click the project and select “Edit <your_console_project_name>.csproj“.

3. Add the following just below the <TargetFramework> element:
<UserSecretsId>93d033dc-12eb-446a-91a6-efec88dfb437</UserSecretsId>
(note: you should replace this guid with your own)

4. Add the following to a <ItemGroup> with other CliToolReference elements, or add your own:

5. Right-click your console application and select the “Reload project” option.

6. Open the developer command prompt and navigate to the directory with your console application, then run:

Note: This will create a secrets.json file located at: %APPDATA%\Microsoft\UserSecrets\<SecretId_From_Step_3>\secrets.json
Edit the newly created file and change the contents to:

7. Create a new JSON configuration file for your console application and name it appsettings.json. Set the following to the contents of the file to the JSON below. Important: Be sure to right-click this file and select properties. Change the “Copy to Output Directory” option to “Copy if newer”.

8. Create a class named MySettingsConfig:

9. Add the following code to your Main routine inside Program.cs

If your console shows your settings correctly, congratulations! If you’re missing the AccountName and ConnectionString settings, be sure you followed the step to “Copy to Output Directory” listed in step 7.

 

NDC Minnesota 2018 Recap

NDC Minnesota is the inaugural NDC Conference event for the United States. I’ve long followed the event online as they post most of their conference sessions on Vimeo. The event was held in the very well appointed St. Paul RiverCentre in downtown St. Paul, MN. Absolutely no complaints about the venue, the event itself, or any of the speaker presentations. I honestly was expecting a number of hang-ups since the first year for a conference is usually a learning experience but it feels as though the NDC team is really on top of everything given their past events at other locations.

Sessions & Speakers

I attended a number of really great sessions. Some of my favorites were Steve Sanderson talking about Blazor, the new experimental WebAssembly transpiler, Scott Allen discussing his opinionated approach to .NET Core development, and Nik Molnar talking about progressive web apps (PWAs).

On top of my favorites there were other really wonderful sessions on AWS Lambda, Azure Functions, React + TypeScript, Docker, Azure Data Lake, and Webpack. All of the speakers were well prepared, well rehearsed, and there were no technical issues in any of the talks I attended. It was a great way to process a lot of information in a very short period of time.

Final Thoughts

I always leave a developer conference feeling inspired. NDC Minnesota was no different. During the sessions I’m usually furiously pounding notes away on OneNote and I have a laundry list of topics I’d like to spend more time learning in the near future. Most of my current weaknesses are on the client, centered around TypeScript, Unit Testing, and React. I’d really like to spend more time on those technologies in the near future and NDC Minnesota provided a lot of really great material to help point me in the right direction to improve those before the year is out.

 

Setting Up A React & Web API Development Environment in Visual Studio 2017

Front-end frameworks like React, Angular, and Vue are making big waves in software development. Microsoft makes great tooling for working with JS frameworks like those in the form of Visual Studio Code. There is also a large trove of information and tutorials getting setup inside the VS Code environment. One specific resource I really appreciated was Cory House’s Pluralsight course on setting up a JS development environment.

Unfortunately, at least in my experience, there isn’t much available out there on how to setup a React dev environment using Visual Studio 2017, for those of us who wish to use only a single editor to maintain our .NET applications. My hope is, that the rest of this guide will serve as a useful resource for anyone else who is facing this same impediment to getting started and will end up saving them time.

Some pre-requisites before we get started:

Disabling Package Restore in Visual Studio

Visual Studio tries to take care of a number of things for you when dealing with npm pacakges. Some people prefer this, other’s don’t. I fall into the latter camp. It took me a bit of headache to figure this out, but by default, when you save a packages.config file, Visual Studio attempts to run ‘npm update’ for you automatically when you save the file or open the solution. So, if you are trying to run the command yourself after updating packages.config, then you are going to run into file locks with the /node_modules/ folder.

Thankfully Visual Studio offers you a way to disable the automatic updates when saving packages.config. Navigate to Tools > Options, then to Projects and Solutions > Web Package Management > Package Restore and set the following settings for NPM (below). What this does is prevents npm from being executed every time you open a project, or run a command line ‘npm update’/’npm install’. You can leave these on if you wish, but for me I found the experience better by being able to execute the npm command line syntax myself.

Setting Up The Application

Instead of walking you through line by line of each step you need to follow, please download the sample application from Github. There are a few important areas that I think are worth mentioning.

  • If you changed the package restore settings above, you’ll want to run “npm install” inside each project after cloning.
  • The ‘Empty’ solution assumes the webpack-dev-server for hosting, so when you run ‘npm start’, webpack will host a simple webserver at the port listed in webpack.config.js.
  • The ‘MVC’ solution assumes it will be hosted by IIS Express or the built in webserver. The ‘npm start’ command on this application will actively watch for JS file changes and rebundle them for you. No need to recompile to see your changes unless you something managed by .net.
  • This approach does leverage Babel as the transpiler. If you would like to use TypeScript, you could do that as well.
  • The webpack configuration assumes that the application start/root is /ClientApp/index.js.
  • The webpack configuration also assumes that everything is written to the /wwwroot/ folder as is convention with ASP.net Core projects in Visual Studio 2017.

I hope you find this post useful. It took me a bit of searching to figure some of this out since most tutorials focus on Visual Studio Code. Feel free to reach me on twitter if you have questions about any of this. Happy programming.

 

Generate Test Data With Faker.js

Here is a common scenario for you. You’re building an application… any application. It could be your side project, a sales tool, an ecommerce site, a REST api, a video game, a reporting dashboard. Anything. You’re building your app, and you reach a point that you’d like to try it out, to see how it would look to a user. How do you simulate a production scenario with no data to test with? If you’re lucky, you have data from an existing customer you can use, or there is a sample dataset available online. If you’re unlucky, you’re left generating dummy data using garbage inputs (random strings, random numbers, etc) – data that passes the regex, but doesn’t provide a good simulation.

Do you wish there was a library that allowed you to programatically generate test data? Enter Faker.js. Faker.js allows you to generate a variety of data types in an intelligent and structured way. You can generate: Addresses, Products (Ecommerce), Companies, Dates, Images, URLs, and random objects as well (numbers, strings, words, uuid, etc). Click here to see a demo.

If you’d like to consume data from faker in another programming language, such as c#, you could use their hosted microservice at http://faker.hook.io (i.e. http://faker.hook.io?property=name.findName&locale=de). A second option would be Bogus, a port of Faker for .net. There are ports available for other languages as well and the API surface is roughly the same in each instance.

I setup a very simple Github repo that demonstrates how to use Faker in a variety of scenarios to help you accomplish your goals. Hopefully you find this utility as useful as I do for prototyping new functionality before it goes into production.

 

Switching from Mac to PC for .NET Development

Just like hammers, drills, and screwdrivers are the tools of the modern tradesman, so to is the computer the trade tool of the modern software engineer. How it is constructed and how well it performs determines how well you can accomplish the tasks you set out to complete.

With this notion in mind, it was time for me to sell my 2014 MacBook Pro 15. It was a great machine from a performance standpoint. It had a wonderful display, fantastic keyboard to type on for long sessions, and a trackpad that could beat any others in the year I bought it.

So why sell the laptop? Well, frankly, because it’s hard to be a .NET developer on MacOS. Sure, there are great IDEs like Visual Studio Code, but that pales in comparison to the feature offering of a full fledged Visual Studio IDE when working with a large solution compromised of multiple projects. What about Visual Studio for Mac you ask? Also wonderful if you’re primarily working on Xamarin apps. They’ve made fantastic strides with it, but support is behind for several features not directly benefiting Xamarin, such as TypeScript. Honestly, I don’t mind the idea using a cloud Mac provider like Macincloud.com to handle my Xamarin builds remotely as there is nice support for this now. The final nail in the coffin is Parallels. Yes, it works, but it’s expensive (including recurring fees), it’s clunky, and it’s not nearly as performant as a native OS. Throw in applications like Docker and you have strange Inception level virtualization issues to wrestle with.

So, where does that leave us? In the past, this may have been difficult to swallow, because one reason so many developers love their Macbook is because it runs a variation of unix, and subsequently has great capabilities beyond the wonderful UI it offers. A .NET developer looking to verify their apps run cross-platform could have considered this, but thankfully, today we have Linux subsystem for Windows. I just installed Ubuntu… from the Microsoft Store… crazy!

Ultimately, after a lot of research, I settled on the Lenovo X1 Carbon (5th Gen). It is a fantastic laptop, and “everything works” despite my belief that was only possible on a Mac. I went with the 16GB model, 512GB of storage, and the WQHD display. It’s got great battery life (I spent about 5 or 6 hours on it with pretty heavy load tweaking settings, installing all my applications, and it lasted on battery only no problem).

Some additional features of the laptop I plan to leverage but haven’t yet, are the fact this unit has 4 PCIe lanes, so an external GPU such as the Gigabyte Aorus GTX 1070 will allow me in the future to have the dream setup: one single machine for both work and play. I looked at other models like the Dell XPS 15 but this had some shortcomings like the webcam position (I do video calls for work sometimes) and also I didn’t want the 4K display to avoid some high dpi compatibility issues and battery drain. Another positive, on modern laptops in general, is the fact that USB-C charging is nearly ubiquitous and getting my laptop charged is now less of a concern than before with the proprietary Macbook charging adapter.

Also, if I ever decide to convert this into a Linux laptop, it’s good to know that this model has good support already for it and all of the hardware should be compatible for me. It will allow the laptop to last quite a long time if necessary.

All in all, I’m really, really happy with this laptop. And the best part about it: Windows has come a long way and is actually pretty nice to use. More applications run on it, it has the Linux subsystem support, and it’s improving constantly with the “Creator” updates they are releasing.

 

My Favorite Visual Studio Shortcuts and Tips

Hey everyone – I’ve been maintaining a list of little shortcuts to save me time and ease my development efforts and figured they would be worth sharing here. If you have any you would like to share here, please email me and I’ll include them as well.

Visual Studio Keyboard Shortcuts

  • Ctrl+. opens up the ‘Smart Tag’. Use it when you see the red squiggle line to add a missing reference, or implement an interface.
  • Ctrl+K,C will comment either the current line, or any block of code you have highlighted.
  • Ctrl+K,U will uncomment either the current line, or any block of code you have highlighted.
  • Ctrl+, opens smart search to quickly find and jump to a class or method name.
  • Ctrl+I allows you to do an inline search (basically search quickly without dialog box)
  • Shift+Alt+Enter for enter and leave full screen mode.
  • Ctrl+- moves cursor to last known position (helpful to navigate back, Ctrl+Shift+- is forward)

Visual Studio Features

  • Snippets, like ‘prop‘ will inject a property into your code, or ‘foreach‘
  • Custom snippets, click here for a starter list and how-to.
  • Right-click file in Solution Explorer, select Source Control > Annotate. This shows all history of the file and who checked in what line of code.
  • Use ‘Package Manager Console’ to install Nuget packages (Alt+T,N,O). (ex: PM> Install-Package Newtonsoft.Json)
  • Tell debugger to ‘break’ when an exception is thrown even if no breakpoint exists (Ctrl+Alt+E, then check Thrown on CLR).
  • From Visual Studio Command prompt, use this command to get a list of all checked out files (and to who): tf status /collection:http://my-tfs-server:8080/tfs/MyCollection $/pathto/mytfsproject /user:* /recursive
 

Techniques For Improving Website Performance

Annotated below is a presentation from Nik Molnar, co-founder of the open source debugging and diagnostics tool Glimpse, who demonstrates several different strategies for improving the performance of your web application. This is easily one of the most useful conference presentations I have ever seen and I wanted to share it with everyone. If were curious about how to do any of the following tasks, this presentation will cover those for you. Next to each point is a bookmark for you to jump to that portion of the presentation.

  • Using browser tools to analyze usable content and latency for each request [13:00]
  • How to use HAR files for analyzing performance metrics [14:30]
  • Using the ‘Audits’ tab in Chrome to make recommendations [15:40]
  • Adding Google PageSpeed to the browser tools and how to use it [16:45]
  • Specifying in the web.config how to use compression for static and dynamic files. [17:50]
  • How to enable client side caching with the expires header [19:00]
  • How to use bundling in ASP.NET to bundle and minify CSS and JS files. [19:35]
  • How to use Web Essentials Visual Studio plugin to easily do image sprites [20:40]
  • Using TinyPNG.com to optimize PNG images with lossy compression [22:00]
  • Using Web Essentials to embed small images as base64 encoded text in CSS [24:22]
  • Using async script attribute and img lazyload attribute to lazy load resources [26:19]
  • Pre-caching client data using dns-prefetch, prefetch, and prerender HTML tags [28:30]
  • Using the RedGate CPU profiler to identify bottleneck code (note: Visual Studio has a simpler built in feature) [35:00]
  • High level thoughts on how to improve server side performance [35:55]
  • Using browser tools like Octane to profile Javascript CPU performance [38:30]
  • High level thoughts on how to improve javascript performance [42:25]
  • Understanding frame rates and the concept of jank [44:05]

Resources:
Link to the video in it’s entirety
Link to baseball demo site used in presentation