Tuesday, September 29, 2015

Scala for the C# Web Developer: Part 4 - Development Environment

I'm currently accepting new clients and projects! If you need an experienced Software Developer, please contact me.

Previously in this series, I introduced similarities and differences in language features between C# and Scala:

In this part, I'm going to show you how to set up your development environment so we can begin to write a web application.

Play Framework ~ ASP.NET MVC

There are several frameworks you could use to build a web application in Scala, but I chose Typesafe's Play Framework since it's very similar to ASP.NET MVC and it has good IDE support. The page syntax is similar to Razor and the conventions feel familiar.

Play Framework Installation

In the .NET world, you'd simply use the File->New Project menu item in Visual Studio to create a new project. Since the Java/Scala ecosystem isn't centrally controlled by a single authority (as Microsoft is to .NET), the process isn't quite as straightforward. Specifically for Play Framework, you'll use a command line tool to create the necessary assets for a new project.

  • Download the Java 8 JDK (and make sure the bin folder is appended to your PATH environment variable)
  • Download the latest version of Play Framework from the home page. For this post I'll be using 2.4.3.
  • Unzip the Play archive to somewhere convenient, such as your home directory (I put it in C:\Users\Name\activator).

Create a new project

  • Open a Command Prompt and navigate to your activator directory (note that this is not the .activator directory - the . indicates hidden file in *nix systems, and this directory is used for framework assets)
  • Create a new project:
  • After the dependencies download and you are prompted, indicate you want a basic Scala project:
  • Type a name for your project:

A new project should now be created for you at C:\Users\Name\activator\play-intro.

Using Typesafe Activator

You don't actually need an IDE to do any development with Play Framework. You could use any text editor alongside activator to accomplish all essential tasks. Of course, coming from Visual Studio, that probably doesn't sound enticing to you, but let's demonstrate how things work with activator by compiling the project.

  • Navigate to your project directory:
  • Start activator (this will probably take a long time for the first run; this is downloading installing everything you need to build and run your project):
  • Compile the project (this also may be slow the first time):
  • You should see a success message if everything went well.

If you've heard rumors about the speed of Scala's compiler in the past, you may be thinking that this process took far too much time. You're right in a sense – the first time you run through these steps, it will take a while since SBT (the underlying build system activator is based off of) has to grab every dependency for the build system and the project.

However, next time you run these steps, you'll see that each subsequent command is actually quite speedy. The slowness is not caused by the compiler, activator/sbt is just downloading and configuring all of the dependencies in the build chain on the first run.

Running Locally

Now you can run your project to access your website locally:

Open a browser and navigate to http://localhost:9000. You should see a webpage with the heading Your new application is ready. This is your website.

Configuring an IDE

We'll be using the Typesafe Scala IDE (based on Eclipse) for our development, simply because it's free. I'm actually not particularly familiar with this IDE, since I usually use IntelliJ IDEA, but the cost of IntelliJ could be a barrier to entry for some developers. If you have a copy of IntelliJ available, I would highly suggest using that instead, as it provides an experience much more similar to what you would expect with Visual Studio.

Installing the IDE

  • Download and extract the Typesafe Scala IDE to a location of your choosing. One nice thing about Eclipse is that it's fully self contained - you won't need to run an installer.
  • In order to get your new project working smoothly with Eclipse, you'll have to install a plugin for SBT. This can be done by navigating to the .sbt directory in your home folder C:\Users\Name\.sbt\0.13
  • Create a new folder at C:\Users\Name\.sbt\0.13\plugins
  • Create a new text file at C:\Users\Name\.sbt\0.13\plugins\plugins.sbt
  • Add addSbtPlugin("com.typesafe.sbteclipse" % "sbteclipse-plugin" % "4.0.0") as the first line in C:\Users\Name\.sbt\0.13\plugins\plugins.sbt
  • If you still have your activator console open (the last line in your console window starts with [play-intro] $), then reload the project:
  • If you closed your activator session, open a new console window and navigate to your project directory and open it again:
  • Create the Eclipse project files:
  • Open Eclipse. Go to File->Import->General->Existing Projects into Workspace. Browse to locate your project at C:\Users\Name\activator\play-intro and click Finish

You should now see a folder with your project name in the Package Explorer.

Setting up a Command Prompt in Eclipse

While you most certainly can set up Eclipse to run your project with a push of a button (like the Run button/F5 in Visual Studio), it's not as straightforward, and probably not worth it when working in Scala. IntelliJ has much better support for this, but because the compile times suffer, I tend to always just use an activator/sbt session in the command prompt when I'm working. It's slightly inconvenient, but since Scala supports hot code reloads and Eclipse continually checks for errors, you may not miss the push button convenience of Visual Studio anyway.

IntelliJ has Command Prompt/Terminal/Shell functionality baked in, but I was surprised to find that Eclipse does not. However, it's quite simple to add support, as found in this StackOverflow post.

  • On the top toolbar (just below File/Edit/Refactor/etc...), there should be an icon of a play button with a little red toolbox. Click on the drop down arrow and select External Tools Configurations
  • On the left side of the window, right click on Programs and select New
  • On the right side of the window, enter:
    • Name: Command Prompt
    • Location: ${env_var:ComSpec}
    • Working Directory: ${project_loc}
    • Arguments: -i
  • Click Run

You should now see a familiar command prompt in the console tab on the bottom window. If the command prompt does not show your project directory C:\Users\Name\activator\play-intro, then either:

  • change directories (using the cd command) cd C:\Users\Name\activator\play-intro, or
  • close the console tab. Click on your project folder in the Package Explorer, then click on the Run icon arrow again, and select 1 Terminal. This should start you in your project directory.

Type activator in the Console to get started.

Play Framework Project Structure

This should feel a bit familiar, although the structure is certainly a bit different than MVC. This is a rough, high level comparison of the Play Framework project structure compared to an ASP.NET MVC project.

Path ASP.NET MVC Play Framework
app/ MVC Project Code Primary Code Directory
app/controllers Controllers Controllers
app/views Views Views
conf/application.conf Web.config/Settings Application Configuration
conf/routes RouteConfig/RegisterRoutes Route Configuration
test/ Test Project Directory Test Directory
build.sbt .SLN/.CSProj/(NuGet) packages.config Project Configuration
project/project.sbt MSBuild Extensions/Visual Studio Extensions Project-specific Plugins

Write Some Code

Ok, so we have our IDE set up, we know how to run the project, and we are somewhat familiar with the project structure – let's finally write some code.

Create the Model

  • Create a new package (folder) at app/models
  • Create a new class at app/models/Student.scala
  • We're going to make this a simple case class with id, firstName and lastName fields:

Create the View

Now that you have a model, we can display it on a page. Create a new view students.scala.html in the views package. Right click on the package name, then select New->Play Template and enter students.scala.html as the filename.

Create the content for the view. This should look pretty familiar, as it shares a lot of similarities with Razor syntax.

Unfortunately, it looks like the Eclipse Scala IDE has a bug, so you aren't going to be able to verify if your view code is valid until runtime. This should be fixed soon.

Create the Controller Method

Open your Application controller (by default there's just this one, but you can create more at any time). Create a method called getStudents and pass a list of Students to your view.

Create the Route

Routes are quite a bit different in Play Framework, but fortunately are extremely simple. Instead of defining a rule by convention, you simply define each specific route in the routes file.

Place a new line underneath the default route, and point it to your getStudents method.

Run

Go to your console window and start activator if you haven't already. Then type run to start your development server. Navigate to http://localhost:9000/students, and you should see a table with the student data you passed into your controller method.

Update your code

Recall that I mentioned Play Framework supports hot code reloads. This means that you don't need to stop, compile and restart your server between changes.

Try adding another student to your controller method and save the file.

Refresh the page, and you should now see the new student without compiling. It's really handy to have the flexibility of a scripting language while still preserving the advantages of static compile time guarantees.

Until Next Time

That should be enough to get you started, but we'll talk about more advance IDE and project features next time in Part 5: Testing and Debugging.

I'm currently accepting new clients and projects! If you need an experienced Software Developer, please contact me.

3 comments:

  1. Hello!
    This MR Seok Hyun, Lee(futurewave) from Korea. I'v been working as a software developer in Korea.
    I was read your posting for Scala for the C#... from Reddit. And i was deeply impressed your posting.
    So may I translate and introduce your posting into my blog?
    Of course, I will indicate the reference(source).
    Thank you

    ReplyDelete
    Replies
    1. Yes that certainly would be fine, thanks for asking!

      Delete
    2. Thanks for replaying. I really appreciate it.

      Delete