Our Blog.

Expert thoughts from our software developers and design leaders.

  • Daniel Oviedo

    Testing the Visuals of IE11 & Microsoft Edge on a MAC OS using VirtualBox

    As developers one of our duties is to ensure consistency in how content is displayed in a variety of browsers. If your web development project involves testing the visuals on IE11 or Microsoft Edge and don’t know how because you are using MacOS, then this post is for you! Note that you do not need a serial number or purchase anything in order to install Windows 10.

    I‘ll expose a fairly simple and popular way to operate Bill Gates’ giant having Steve Jobs as host using Oracle’s VirtualBox. The steps are as follows:

    1. Install Oracle’s VirtualBox.
    2. Install Microsoft 10 using a .iso file in VirtualBox.
    3. Testing your project with IE11 and Microsoft Edge.

    Let’s dive into the details of each step:

    1. Install Oracle’s VirtualBox

    Go to https://www.virtualbox.org/wiki/Downloads and under “VirtualBox 6.0.12 platform packages” label (as of today the current version is 6.0.12), click on “OS X hosts”

    image

    After the download finishes click the installer and follow the steps. You’ll be likely asked to grant accessibility features for VirtualBox in System Preferences. This may be relevant to avoid future problems when running the virtual machine, so make sure to allow it.

    2. Now we need to download Windows 10 .iso file and install it in VirtualBox. There are two main sub-steps:

    2.1 - Downloading Windows 10:

    Go to https://www.microsoft.com/en-us/software-download/windows10ISO. Under “Select edition” tab, select Windows 10 (Latest is 10 May 2019 as of today). Click on Confirm. Now select the language and click again on Confirm.

    image

    Download 32-bit or 64-bit version. I’m sticking with 64-bit version, but feel free to choose what best fits your setup. If your internet is not so speedy you might sit a while and wait until the download finishes.

    image

    2.2 - Installing Windows 10 in VirtualBox:

    Open VirtualBox and click on “New”, then enter a name for the virtual machine. I use “Windows 10 - 64bit”. Make sure “Type” is set to “Microsoft Windows” and in “Version” select “Windows 10 (64 bit)”. Click on continue.

    image

    In this step you need to allocate enough RAM. I assigned it 2GB since I have 8GB RAM in my iMac and I don’t want to run into performance issues in my host machine. Have in mind that x86 (32-bit) version requires a minimum of 1GB RAM and x64 version requires 2GB RAM at least. Click on “Continue”.

    image

    You need to create a Virtual Hard Disk. The default selected option is fine (Create a virtual hard disk now), click on “Create”. Select “VDI (VirtualBox Disk Image)” and choose “Fixed Size HDD”. Microsoft requires 16GB at least for 32-bit version and 20GB for 64-bit version. I’ll set mine to 50GB.

    image

    Make sure to allocate enough video resources to your guest OS. You can check those options in “Settings” then “Display” tab. If you’re not sure, leave default and adjust later.

    Go to “Settings”, click on the “Storage” tab, click on the blue “Empty” disk and click the blue disk to the right of “SATA Port 1”, click on “Choose Virtual Optical Disk Drive” and look for your Windows 10 .iso file.

    image

    Start your Windows 10 virtual machine and follow the installation instructions. As I mentioned earlier, don’t worry about the serial number, just select you don’t have one and it will anyway let you install.

    image

    After finishing installation you should have your Windows 10 up and running.

    3. Testing your project with IE11 and Microsoft Edge

    The default settings should be fine to let communication happen between host OS and guest OS. To know which IP address to point inside Windows 10, open the Command Prompt or the Powershell and run the following command:

    ipconfig

    The Default Gateway is the IP address we should use to connect with MacOS host, in my case is 10.0.2.2.

    image

    If you’re already serving a project in MacOS go ahead and test in IE11 or Microsoft Edge. For example I just created and deployed locally in my host machine a Vue.js app using Vue’s CLI and it listens on port 8080:

    image

    That’s it folks! Now you’re ready to see the looks of your project with IE11 and Microsoft Edge within MacOS. Also, feel free to experiment with Windows 10 as you need.

    Continue Reading
  • Larry Morales

    How Emergent Design Solved N+1 Problem In Buffalo Pop

    Disclaimer. Those who are not familiarized with N+1 problem, you can check “What is the N+1 selects problem in ORM(Object-Relational Mapping) with details explaining the concept.

    Since associations were introduced in Pop, the N+1 problem became part of it: many queries hit the database in order to load whole model’s associations. Good news is N+1 problem is not a disease without remedy. In this post I will give you some steps I took to solve it by incorporating emergent design.

    Step 1: Start Coding By Example

    Coding by example helps you to define what’s your input and what’s your output. Code By Example means you define a scenario where  your solution is tested and what is the expected result. The method I used to apply this technique was Test Driven Development (TDD).

    I started to code by example for the most simple scenario I could think of. To me, the most simple scenario was to solve N+1 problem for the has_many type association.

    =========== Scenario 1 =============================
    
     Given I have 3 Users with one Book each one related
     Then I would expect the query performed to be:
    
     select books.* from books where user_id in ($1, $2, $3)
    

    This, translated into code, would be:

      // pop_test.go
      type User struct {
         ...
         Books []Book `has_many: “books”` 
      }
    
      // pop_test.go
      type Book struct {
         ...
         UserID int `db:”user_id”` 
      }
    
    // preload_associations_test.go
    func TestHasManyNPlusOneSolution(t *testing.T) {
       ...
    
      for i:= 1; i <= 3; i++ {
          user := User{}
          tx.Create(&user)
          
          tx.Create(&Book{
              UserID: user.ID,
          })
       }
    
      Debug = true
    
      users := []User{}
      preload(tx, &users)
    
      a.Equal(3, len(users))
      a.Equal(1, len(users[0].Books)
      a.Equal(users[0].ID, users[0].Books[0].UserID)
    }
    
    // preload_association.go
    func preload(tx *Connection, model []User) error {
    	return nil
    }
    

    Step 2: Be Explicit With Your Input And Output.

    As soon as I wrote down the scenario, I noticed there are three things that I needed to do in order to produce the desire output:

    • First thing is to iterate over every user and store its ID value in a slice.

    • Second thing is that user_id column in the expected query result. I need to pull it out from db tag in Book model.

    • Third thing is to link all books with their respective users once the query is successful.

    Because I’m in a premature start point, and I don’t want to go into the code details about how to read that field tag, In order to make that test to pass as quickly as possible, I hard-coded the solution and be explicit to have that test with a green face.

    func preload(tx *Connection, model []User) error {
        // 1) fill in ids.
        ids := []interface{}
        for _, u := range model {
            ids = append(ids, u.ID)
        }
        
        // 2) load associations.
        books := []books{}
        tx.Where(“user_id in (?)”, ids).All(&books)
        
        // 3) fill in model with associations.
        for i := range model {
            for _, book := range books {
                if book.UserID == model[i].ID {
                    model[i].Books = append(model[i].Books, book)
                }
            }
        }
    }
    
    

    Step 3: Go From Specific To Generic.

    Once I have green light and test is passing, I noticed the solution was composed into a three steps process:

    1. fill in ids.
    2. load associations.
    3. fill in model with associations.

    At this stage I need to be less specialized and be more generic with the solution. The reason is this moment preload function only knows how to preload users and books, but models can be from different types.

    In order to achieve generalization, I take one step at the time and apply some refactorings techniques until I’ve satisfied the desired generic level.

    I started to refactor step one (fill in ids). In this step, the generic level I want to achieve is to get a list of all ids value from model, no matter what type that model is. This pushed me to incorporate some reflections code and go a little deep in details in order to get the expected result. For every tiny change I applied to my code, I ran my test making sure is still getting green.

    Once I got the level of abstraction I want for my step one, I move on to step two (load associations) and do same thing. I stablish first wich is the generic level I want to go, and then apply all code changes and refactorings necessary to achieve the correct result. Once I’m done with step two I then move on to step three, always trying to achieve generalization. Here is the result of applying this process to the has_many preload function.

    Step 4: Repeat, Repeat and Repeat.

    Once I feel I’m done with has_many type association, I start to cycle again following same process for has_one type association. I repeat same three steps: Code By Example, Be Explicit and Be Generic (from now on CBB) until I got all four type associations covered. https://github.com/gobuffalo/pop/blob/nplus1/preload_associations.go#L158

    Wrapping up

    As software developers we tend to find code solutions based on our experience in one project and try to reuse them in other projects where we think they’ll match up. Sometimes, there are cases where uncertainty is a variable, and applying CBB process helped me to overcome that. I’ve testified the good impact this process has. The way that solution design emerges, without a deliberated thoughtful specification in mind. It feels like an organic living growing from its seed. Give it a try and let me know how it works for you.

    Thank you for reading this post. I hope you have enjoyed how emergent design helped me  to find solutions to N+1 problem in Buffalo/Go, and hope you apply it into your projects.

    Continue Reading
  • Antonio Pagano

    Buffalo+Sendgrid is it possible?

    Sendgrid is one of the most well-known and used email delivering solutions. It has solutions for most (if not all) of the common email sending and delivering issues that we could face as developers. But this post is not about convincing you to use Sendgrid.

    One of the things I love about Buffalo is that it ships with all of the things a product needs for rapid application development and deployment. In this case that is email. Buffalo has a mail package that you can use to integrate sendgrid or any other provider with your app.

    import github.com/buffalo/mail

    Buffalo’s mail package key items are the Sender interface and the Message struct. It also ships with an SMTPSender implementation of the Sender interface which could be used if you have an SMTP server or want to use your gmail/hotmail email to send emails. I do not recommend you to use a single email account for SMTP on production environments but it could be useful when doing very quick iterations and hacks.

    Sender interface

    The Sender interface is a very simple interface which is defined as:

    ...
    type Sender interface {
    	Send(Message) error
    }
    

    What essentially says that anything that has a Send method that receives a mail.Message and returns an error can be considered as a Buffalo email Sender. Simple huh?

    Message struct

    The second part of the equation is the Message struct. This struct is the representation of the email message inside the mail package. It has fields like From, To and Cc which should sound for anyone who has sent or received an email before.

    I will not go into deep details of this one because I just want to give an overview of the email package, but you could go and check it out here.

    Plugin Sendgrid in

    As I mentioned before Buffalo allows developers to implement their own Sender. In order to plug in Sendgrid you will use a Sendgrid implementation for the Sendgrid API.

    github.com/paganotoni/sendgrid-sender
    

    To do so I’m assuming you:

    Assuming that’s all set, lets continue.

    Generating mailers package

    One common pattern/best practice in buffalo is to have your email-sending functions in a package called mailers.

    If you don’t have this folder in your app it means you have not generated it. It doesn’t get generated with the new app. You can generate it by running the following command:

    buffalo g mailer your_first_mailer_name
    

    This will generate:

    • mailers folder
    • mailers.go file
    • your_first_mailer_name.go file (with your first mailer there).

    Lets focus on the mailers/mailers.go file.

    Modifying mailers.go

    mailers.go file is the place where the mailers configuration resides. At the moment I’m writing this (buffalo v0.14.10) after running the command I mentioned before that file looks like this:

    ...
    var smtp mail.Sender
    var r *render.Engine
    
    func init() {
    
    	// Pulling config from the env.
    	port := envy.Get("SMTP_PORT", "1025")
    	host := envy.Get("SMTP_HOST", "localhost")
    	user := envy.Get("SMTP_USER", "")
    	password := envy.Get("SMTP_PASSWORD", "")
    
    	var err error
    	smtp, err = mail.NewSMTPSender(host, port, user, password)
    
    	if err != nil {
    		log.Fatal(err)
    	}
    
    	r = render.New(render.Options{
            HTMLLayout: "layout.html",
    		TemplatesBox: packr.New("app:mailers:templates", "../templates/mail"),
            Helpers: render.Helpers{},
    	})
    }
    

    This is cool if you were going to use the SMTP sender. It has everything you need to use it. However, since we’re going to use the Sendgrid sender we will need to change it to be:

    
    import (
        ... 
        ssender "github.com/paganotoni/sendgrid-sender"
    )
    
    var sender mail.Sender
    var r *render.Engine
    
    func init() {
    	APIKey := envy.Get("SENDGRID_API_KEY", "")
    	sender = ssender.NewSendgridSender(APIKey)
    
        r = render.New(render.Options{
            HTMLLayout: "layout.html",
    		TemplatesBox: packr.New("app:mailers:templates", "../templates/mail"),
            Helpers: render.Helpers{},
    	})
    }
    

    This will require now that you add your Sendgrid API key to your development and production servers as an environment variable SENDGRID_API_KEY. This is so the Sendgrid Mailer is able to communicate with the Sendgrid API in order to send your emails.

    And as long as the same sender.Send method is called from within your mailer functions all will work as with the default SMTPSender. p.e:

    func NotifyForgotPassword(user models.User) error {
    	m := mail.NewMessage()
    	m.Subject = "Your password change request"
    	m.From = "do-not-reply@wawand.co"
    	m.To = []string{}
    
    	err := m.AddBody(r.HTML("password-forgot.html"), render.Data{
            "FullName":     user.FullName(),
            ...
    		"Link":         user.ForgotPasswordLink(),
    		"ReportLink":   user.ReportForgotPasswordLink(),
    	})
    	
    	if err != nil {
    		return err
    	}
    
    	return smtp.Send(m)
    }
    
    

    And that’s all. You can now use sendgrid to send emails for your Buffalo app.

    Wrapping up

    Thank you for reading this article. I hope you have enjoyed this brief description on how to use Sendgrid with your Buffalo app. If you are using Postmark I wrote a Sender for it, you can check it out here.

    If you have questions or comments about this post, you can find me on twitter at @paganotoni. You can also find my company at @wawandco. I would love to hear your opinions on this and other posts.

    Continue Reading
  • Antonio Pagano

    Deploying Buffalo to Google Cloud Run

    Google Cloud Run is a service that allows you to run containerized applications in a serverless environment. This means that you don’t have to care about servers. Billing is done for what you use in terms of memory and processor for time (Google provides a free tier you can check here).

    In this post, I will describe how you deploy your Buffalo application to Cloud Run.

    Setup

    In order for us to be able to send the app to Google Cloud Run, you need:

    • Docker installed
    • Gcloud CLI tool installed with the beta components
    • Gcloud logged into your google account
    • Docker setup with your GCR account

    I'll continue with this post assuming you have all that, if you need instructions for these you can go here and take a look at how to install or setup these tools.

    Building container image

    After ensuring you have all the permissions and given Buffalo ships with a valid (and very nice) multistage Dockerfile. You can now build your image with the following command:

    docker build . -t gcr.io/buffalo/buffalo-app:v1.0.0
    

    Notice that you added -t gcr.io/buffalo/buffalo-app, which is:

    • gcr.io (base for GCR)
    • buffalo is the project name
    • buffalo-app is the name of the image you’re sending to GCR
    • v1.0.0 is the tag you’re using for that image

    This will build your image and tag it locally.

    Pushing container image

    Given you’ve already set permissions on the GCR docker repo you can now just push the container image there with the following command:

    docker push gcr.io/buffalo/buffalo-app:v1.0.0
    

    That will take the container image from your local docker repo and push it to GCR. By the time I’m writing this, Cloud Run doesn’t support images from other repositories apart from GCR.

    Creating and running service

    Once you have your image pushed to GCR you can tell Cloud Run to run your app with the following command. It will take care of service creation and deployment.

    gcloud beta run deploy buffalo-app --region us-central1 --platform managed --allow-unauthenticated --image gcr.io/buffalo/buffalo-app:v1.0.0 
    

    With this you’re telling gcloud tool:

    • To deploy a service called buffalo-app
    • To deploy it in the us-central1 region
    • To deploy it in a managed (full serverless) way
    • To allow unauthenticated access to it
    • With the image tag (gcr.io/buffalo/buffalo-app:v1.0.0) that will be pushed to GCR

    After this command has completed you will get a message saying:

    Service [buffalo-app] revision [buffalo-app-00001] has been deployed and is serving traffic at https://blog-5zw4ak7zjq-uc.a.run.app.
    

    Which is our signal that the deployment has been completed. That’s all, Your app is running in Google Cloud Run.

    Wrapping up

    I have to admit that as you may have noticed this post is more about Google Cloud Run than Buffalo, but I’m mostly doing Buffalo lately. I named this post “Deploying Buffalo to Google Cloud Run” with the hope that in the future I could continue sharing those lessons. My team and I are learning about Buffalo on Google Cloud Run for now; all I can tell is we’re loving that mix.

    Thanks for reading until here! If you have questions or comments about this post, you can find me on twitter at @paganotoni, or find my company there at @wawandco, I would love to hear your opinions on this and other posts.

    Continue Reading
  • Antonio Pagano

    Deploying a Buffalo app to Heroku

    A lot of things have changed in the Buffalo ecosystem since my last post on how to deploy to Heroku from Gitlab.

    Indeed, everything has changed since I posted how to deploy from gitlab repo into Heroku with the birth of the buffalo-heroku plugin. In this post I will try and describe how to use it to deploy your buffalo app to Heroku.

    Setup

    First thing you need to install (or ensure you have) is buffalo-plugins plugin. If you’re on buffalo v0.14.6 or higher you’re all set. If you’re on an older version you should:

    1. Move to your project root folder
    2. Download and install buffalo-plugins plugin
    $ GO111MODULE=off go get -u github.com/gobuffalo/buffalo-plugins
    
    1. Init your application plugins (just in case):
    $ buffalo plugins init
    

    You may notice that a config folder has been added to your codebase, this will hold plugin information for your app.

    Installing buffalo-heroku plugin

    Then you will need to install buffalo-heroku plugin which (assuming you’re still in your application root folder) you can do by:

    $ buffalo plugins add github.com/gobuffalo/buffalo-heroku
    

    Once that passes successfully we’re all set to start deploying your app. You can check if your installation is ok by running:

    $ buffalo heroku -h
    

    Deploying

    Buffalo-heroku plugin provides very cool commands that I invite you to take a look at, for now I will concentrate in the details for you to deploy that app.

    Deployment Configuration

    Buffalo-Heroku uses some files in your repo to deploy your app, to create those files you should run:

    $ buffalo heroku config
    

    This will update your project with configuration files for deployment:

    1. Will create a heroku.yml file.
    2. Will ensure you have a Dockerfile (Will create it for you if you don’t have it)
    Creating the Heroku app

    One of the coolest commands in the buffalo-heroku plugin is the new command, it allows you to create new apps with a bunch of configuration options.

    We will create your app by running:

    $ buffalo heroku new -a name-of-your-app
    

    Once the app is created this will do your first deployment.

    Deploying Again

    Now that your app is all set with Heroku, you should be able to deploy your app at any time you need by just running:

    $ buffalo heroku deploy
    

    Very simple right? Now that you’ve set up your app and deployed you can get back to what we all love. Building actual apps with Go and Buffalo :).

    Recommended Reading
    • More on heroku.yml file
    • Buffalo plugins and plugin system (in the Buffalo repo)
    • Buffalo documentation

    Thanks for reading until here. If you’re interested in application development, my company Wawandco can help you building quality web and mobile applications. You can check what we have been up to in our dribbble posts, our Twitter or LinkedIn profiles. Stay tuned.

    Continue Reading
  • Antonio Pagano

    Page indicator with Buffalo

    Buffalo already ships with very cool pagination support, more than that it even uses the pagination when we generate resources, which is awesome.

    I’ve been working lately in a project that uses that pagination (again thanks to the buffalo team), but this app also has a page indicator on the left side, as the following image shows:

    Yes, i’m talking about the section that says “Displaying 1 - 25 of 120 Policies” (design typo there).

    So my first thought was computing those variables on the action and then passing these to the view, where i would use them to build my “page indicator” section.

    My action was turning very ugly, until i realized most (not to say all) that i needed was already contained in the pagination context variable set in my action:

    q := tx.PaginateFromParams(c.Params())
    …
    c.Set("pagination", q.Paginator)
    

    Which is an instance of pops paginator! wow! i already had:

    • Page
    • PerPage
    • Offset
    • TotalEntriesSize
    • CurrentEntriesSize

    With that in hand building my page indicator was not very hard, but wanted to share my _page-indicator.html partial just so if anyone needs to do something similar this could be a good starting point.

    <div class="pagination-label">
        <span class="opacity">Displaying <%= pagination.Offset + 1 %> - <%= pagination.Offset + pagination.CurrentEntriesSize %> of <%= pagination.TotalEntriesSize %> <%= plural %></span> 
        <i class="per-page-separator">|</i>
        <span class="per-page-<%= perPage(per_page) %>">
            <a href="<%= basePath %>?per_page=25"><i class="opacity per-page-25-number per-page-option">25</i></a> 
            <a href="<%= basePath %>?per_page=50"><i class="opacity per-page-50-number per-page-option">50</i></a> 
            <a href="<%= basePath %>?per_page=100"><i class="opacity per-page-100-number per-page-option"> 100</i></a>
            <i class="opacity"><%= plural %> per page.</i>
        </span>
    </div>
    

    The way i use this partial from my table templates is:

    <%= partial("partials/page-indicator.html", {plural: "Cats", basePath: catsPath({humanSlug: currentHuman.Slug})}) %>
    

    As i’ve said it was very easy with the help of the Paginator that the Buffalo team created for us, hope this helps you if you’re needing to create a page indicator in your app.

    Continue Reading