Friday, March 25, 2016

New update to the CFDoc Sublime plugin (CFMLDocPlugin)

Wow, I am really bad at keeping up with this blogging thing.. Will try to do better!

For now, just a small update, I released a new version of the CFDoc sublime plugin.

If you don't know what it is; It's a sublime plugin which automatically generates inline CFDoc comment blocks for CFML components and functions.

You can find it in the Sublime Package Manager under CFMLDocPlugin, or at https://github.com/MFernstrom/cfmldocplugin

Install it and set a key combination such as [{ "keys": ["ctrl+shift+2"], "command": "docifycfml" }]

An example:

public array function myAwesomeFunction( required string awesome, maybeAwesome = "totally" ) hint="My text here" {
    return arguments.awesome;
}
 
Turns into


    /**
      * My text here
      *
      * @method myAwesomeFunction
      * @public
      * @param {string} awesome (required)
      * @param {any} [maybeAwesome = "totally" ] 
      * @return {array}
      */
    public array function myAwesomeFunction( required string awesome, maybeAwesome = "totally" ) hint="My text here" {
        return arguments.awesome;
    }

You can then use YuiDoc or other compatible tools to generate documentation for your cfml code.

Monday, November 16, 2015

How to set up OpenBD on a VPS

After hearing about others wanting to know how to set up OpenBD on a server, and fighting with it myself, I wanted to write a simple How-To on how to set up a simple VPS for OpenBD.

Tiago Lopo from AW2.0 helped me set up with NGINX, and it's that setup that's described here.

The basic premise for the setup I needed was; A DigitalOcean VPS running a single OpenBD instance to host multiple sites.

You can easily adjust these instructions to run multiple instance of Jetty with OpenBD if you prefer that.

Disclaimer: I'm not responsible for anything you do on your own server, I take no blame if something were to happen to your server by following this advice. There's plenty to do after setting up the basic server software, not the least of which is securing things, which is not covered in this post.

Here's what we'll be doing:
Set up a VPS
Install Java 8
Install unzip
Install OpenBD Ready2Run
Install NGINX
Set things up
Grab a beer

For this project I'm using Digital Oceans smallest Droplet, but I'm using Linode for another server, whatever you prefer should be fine.

The instructions will be as detailed as I can make them, so that anyone can follow, at least if you've spent an hour or two on a linux box before.


Assumptions
I assume that you have a domain and can point it to the VPS you're setting up.


Get started
Set up the Droplet with Ubuntu 14.04 LTS (64 bit) and wait for your login information

When the server is up, set up your domain to point to the IP, it may take a while before it takes effect so you can test it.

Log in to your VPS


Installing Java 8
Enter these commands in order, one by one:
add-apt-repository ppa:webupd8team/java
apt-get update
apt-get install oracle-java8-installer

Follow the instructions in the installer.


Install unzip
Since the OpenBD file is zipped, we need an unzip utility, enter this:
apt-get install unzip


Get Openbd nightly
First we create a folder to hold the OpenBD file:
mkdir /home/marcus

Then we cd there, and get the OpenBD file:
cd /home/marcus

wget http://openbd.org/download/nightly/jetty-openbd.zip

This can take a few minutes.

When it's done, unzip to where you want to run it from
unzip jetty-openbd.zip -d /opt/openbd

When that's run, OpenBD is technically installed!

If all you want is a single website, you could change the Jetty port from 8080 to 80 by modifying the /opt/openbd/start.ini file, uncomment and modify the line that reads # jetty.http.port=8080

cd /opt/openbd

Edit the file by using this command:
vi start.ini

Scroll down until you find that line, press the letter i on the keyboard, delete the first character, change the port to 80, press escape, then write :wq and hit enter.

To start the server, you type (from /opt/openbd/):
java -jar start.jar

If everything worked, you should be able to enter the ip of your server, or the domain name you pointed at it, and see the freshinstall page.

If you're like me, and want to run multiple sites from one OpenBD instance, read on.

I assume that you didn't change the port if you're following on.


Installing NGINX
apt-get install nginx

Easy, eh?

Now comes the hardest part (It's not actually hard), configuring NGINX to route the domain requests to the proper place, and securing Jetty to only accept connections from NGINX.


Setting everything up
This is how Tiago Lopo helped set up my server, to make it easy to extend and add sites as I go.

Rather than having a large single file containing all sites, he split it up into multiple files that are easy to copy and adjust as needed.

Create these files and add the contents, adjust URL's as needed.

To create the file you can either create locally and upload, or create on the server through SSH.

If you're on SSH, you could create the file below like so:
Copy the contents below.
Write vi /etc/nginx/conf.d/cors.conf in the console
Press i
Paste the contents, then press escape, and then :wq and press enter.

wq means write and quit.

/opt/openbd/www/mysite/index.cfm
<cfoutput>#Now()#</cfoutput>

/etc/nginx/conf.d/cors.conf
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE';
add_header 'Access-Control-Allow-Headers' 'X-Requested-With,Accept,Content-Type, Origin';

/etc/ngingx/conf.d/openbd-proxy.conf
proxy_pass  http://127.0.0.1:8080;
proxy_read_timeout 1200;
proxy_connect_timeout 75;
proxy_redirect default ;
proxy_set_header Host $host;
proxy_set_header X-RealIP $remote_addr;
add_header ServerId 0001;
proxy_intercept_errors on;

/etc/nginx/conf.d/mysite.conf
server {
        server_name mysite.marcusfernstrom.com;
        listen 80;

        location / {
                include /etc/nginx/conf.d/cors.conf;

                if ( $host = 'mysite.marcusfernstrom.com' ){
                        rewrite ^(.*)$ /mysite/$1 break;
                        proxy_pass http://127.0.0.1:8080;
                }
                include /etc/nginx/conf.d/openbd-proxy.conf;
        }
}

/etc/nginx/nginx.conf
worker_processes 1;
events {
        worker_connections 1024;
}

http{
        include                 mime.types;
        default_type            application/octet-stream;
        sendfile                on;
        keepalive_timeout       65;
        client_max_body_size    10m;
        gzip                    on;

        include /etc/nginx/conf.d/mysite.conf;


Don't forget to restart nginx at this point, to make sure the settings are live.



service nginx restart

To make sure that Jetty only accepts connections from NGINX, you need to modify the /opt/openbd/start.ini file again, fine the line that reads: # jetty.http.host=0.0.0.0 and change it to jetty.http.host=127.0.0.1

The only thing left is to make sure OpenBD starts automatically when the server starts.

There are difference methods for doing this, here's what I did on this server:
 vi /etc/rc.local
 
Add these lines before exit0:
cd /opt/openbd/
java -jar start.jar

 

Save with :wq

And that's it, if things went like they should, you now have your own VPS running OpenBD, set up to handle multiple sites as virtual hosts under a single Jetty/OpenBD instance.

 If you need help or something doesn't work right, stop by the Google group at https://groups.google.com/forum/#!forum/openbd, I'm happy to try helping you, but know that I'm not expert when it comes to Jetty or NGINX. 

Thursday, August 6, 2015

Learning Java, and OpenBD plugins

I've wanted to work with the OpenBD engine itself for a long time, the idea of being able to extend it sounded both fun and useful but there were two things working against me.

1. I didn't know Java
2. I didn't know how to make plugins or modify the engine

I can't say that I know Java now, but I'm learning and at a pretty decent rate I think.

I just can't do "Hello World" over and over, so I wanted to do something real, and then I saw someone on the google group ask if we could have a function added to the engine, isUserLoggedIn()

Now, knowing what the function does, I figured that's about as easy as it gets, so I started digging and figured out (With some help) how to register functions and whatnot, and created the isUserLoggedIn() function, made a pull request on GitHub and it was accepted, my code is now in the engine    :)

The next step was to figure out how to make plugins, as some of my ideas aren't a good fit for getting added to the engine itself.

Andy Wu with AW2.0 suggested that I look at an existing plugin to get an idea of how they work, and with his help I managed to get up and running, and created a plugin that uses a Mashape API for converting strings of text into Yoda-speak.

Not a very useful plugin, but not only was it a real plugin, it talked to an external API, so kind of cool.

Today I released my first "real" plugin, one that's a bit more useful.

Something I've always wanted was the ability to create barcodes, and now I finally created a plugin for that purpose.

Tadaa:  https://github.com/MFernstrom/barcode-plugin

It uses the barcode4j for regular barcodes, and ZXing library for generating QR codes.

The images are saved to disk, and the function returns a boolean true if all went well.

I'm learning Java the same way I taught myself CFML, by doing things for real, and I'm having a blast.

I'm open to ideas about things the community would like to have, if it's doable and sounds like fun I'll likely take a stab at creating it, be it functions, improvements or plugins.

For anyone else thinking about getting into making plugins, all I can say is: DO EEET!

It's fun, and is a natural progression for a CFML dev wanting to continue on the path, since the engines are all written in Java.



Saturday, July 19, 2014

CFScript vs CFTag

I started out by only coding CFML in tags, being self-taught I had to go by what people were using to show how to do basic things, as I progressed I learned how to expand on that knowledge, but kept working in tags because, well, that's what I was used to.

I've looked into CFScript in the past, but didn't really start practicing until more recently (A few months ago), writing new CFCs in script and taking the opportunity to practice my cfscript-fu while updating old code.

I saw Adam Camerons post about him helping someone convert old tag-based code into cfscript, and it made me think (And ask) "Why is cfscript better?"

After many messages between me and Adam Cameron, and between me an Sean Corfield (Both are programmers I highly recommend following on blogs and twitter), I'm *still* not sure what's so great about cfscript compared to cftags.

Ps. I hate twitter for discussions.

Neither Adam nor Sean can, in my not-always-so-humble-opinion tell me in simple terms what's so great about cfscript.

It seems to boil down to personal choice (Unless you ask Sean, who will tell you what an evil man you are for using tags. Not a direct quote.)

Check out Adams blogpost about script vs tags, it's an interesting read and he has a different take on it than I do.

I'm always looking to improve my skillset, because programming is awesomely fun   :)

I'm now coding in both tags and script, mostly writing new CFCs in cfscript, because it means I'm learning new stuff, while adding useful skills to my skillset, learning cfscript was natural to do because it's used all over the place, and a lot of shops and companies use it to a varying extent.

Overall, I don't know of any inherent benefits to using cfscript, while it sometimes *feels* like it's executing faster than tagbased code, that's not exactly empirical proof, I've yet to find any *real and proven* benefits to cfscript in terms of performance.

It's been debated that it's better to use cfscript because it's closer to other languages, since CFML is the only tag-based language around.

Personally I don't find it very beneficial to know a language similar to a new one, and I still think of cftags and cfscript as just two different syntax-sets to the same language.

Sean thinks it's harder for someone to learn any other real language, coming from CFML tags, and noted it as a reason for not hiring someone.

I agree, but only if the person *only* knows CFML tags and nothing else..

But I don't know any web developer who don't also speak at least JS, so right there that argument fall, unless he's ever looked to hire someone who *only* speaks CFML, and literally nothing else.

From what I know there is nothing available in CFScript that isn't available in CFTags, and vice versa, there isn't any performance gain to either.

It seems that many people feel that tags are too close to html, being inside of <>, and should thus not be anywhere near business logic

I do find it amusing that CFML = ColdFusion Markup Language, which is only sortof true after the introduction of CFScript.

I'm not "defending" the use of tags, again I code in both, I just wanted to see if anyone could give me actual, specific reasons why cfscript is better than tags, and so far... I haven't seen it.

I'm filing this under "Personal preference", maybe some day I'll have that Aha-moment when working with script and write a post about it.

Friday, June 13, 2014

AJAX currency converter, for funzies

Everyone loves AJAX, right?

Here's a simple, but functional, AJAX based currency converter based on the this api: https://www.mashape.com/warting/currency-converter.

You'll need to get an API key before you can use it (It's free). Here's the CFM file:

<!DOCTYPE html>
<html>
    <head>
        <title>AJAX powered currency converter</title>
        <cfajaxproxy cfc="currency" jsclassname="jscfc">
        <script>
            function convertCurrency(){
                document.getElementById("final").innerHTML = "Please wait, doing magic...";
                var e = document.getElementById("currency");
                var selCurrency = e.options[e.selectedIndex].value;
                var jscfcInst = new jscfc();
                jscfcInst.setCallbackHandler( updateSpan );
                jscfcInst.convert(target=selCurrency,amount=document.getElementById('amount').value);
            };
           
            function updateSpan(result) {
                document.getElementById("final").innerHTML = result;
            };
        </script>
        <style>
            #leftie{
                width:80px;
                padding-right:40px;
                display:inline-block;
                text-align:right;
            }
        </style>
    </head>
    <body>
        <h3>Currency converter</h3>
        <div>
            <span id="leftie">From:</span> USD<br />
            <span id="leftie">Amount:</span> <input id="amount"><br />
            <span id="leftie">To currency:</span> <select id="currency"><option value="EUR">Euro</option><option value="SEK">SEK</option></select><br />
            <br />
            <span id="leftie">Result:</span> <span id="final"></span><br />
            <span id="leftie"><button onClick="convertCurrency();">Convert</button></span>
        </div>
    </body>
</html>

There's not a whole lot here!

We'll also need the cfc file, here it is (And don't forget to replace the YOURAPIKEY with your api key..), save it as currency.cfc in the same folder as your cfm file.

<cfcomponent>
    <cffunction name="convert" access="remote" returntype="string">
        <cfargument name="target" required="yes">
        <cfargument name="amount" required="yes">
        <cfhttp url="https://currencyconverter.p.mashape.com/?from_amount=#arguments.amount#&from=USD&to=#arguments.target#">
            <cfhttpparam type="header" name="X-Mashape-Authorization" value="YOURAPIKEY">
        </cfhttp>
        <cfset var theResult = DeserializeJSON(cfhttp.filecontent)>
        <cfreturn NumberFormat(theResult["to_amount"],"0.000")>
    </cffunction>
</cfcomponent>

And that's it!

So what are we doing?

We're using IDs to grab the values for the amount and which currency to convert from USD into, then we send that to the convert function in the cfc, which sends the values to the api, converts the response to a struct and then returns the to_amount formatted to display up to 3 decimals.

When that's returned, we replace the text in the span ID with the new value.

Tested on OpenBD, but there's nothing fancy here at all, just some basic AJAX for those who are curious, should work on all engines (Should.. but not tested)

Friday, March 7, 2014

Respons till @Kryptoblogg

Jag vill svara på @Kryptobloggs tweet men twitter är inget bra ställe att föra dialog på (Blir en jäkla massa tweets väldigt snabbt), så jag valde att svara via min blogg istället.

Här nedan har jag klistrat in Kryptobloggs tweet för de som är intresserade av att se hela argumentet och inte bara mitt svar.

Jag håller inte med om att offensiva cybervapen skulle göra vårt samhälle svagare på något sätt.

Om jag läser dina tweets rätt verkar du anse att vi inte kan utveckla/köpa exploits därför att det skapar en kapprustning, samt att användandet av cybervapen ger motståndare vapen som kan användas mot oss, vilket inte gynnar vårt samhälle

Problemet med det argumentet är att en handfull länder redan har cyberavdelningar med offensiva förmågor som man får anta att dom skulle använda vid krigsföring, dessa länder köper/utvecklar redan offensiva förmågor, oavsett vad vi gör.

Kapprustningen har redan börjat från deras sida.

Hur lång tid brukar det ta innan en motståndare lyckats identifiera och kopiera en exploit som använts mot dom?

Det finns väl inget som säger att man inte kan använda en offensiv exploit för att sedan släppa redan gjorda patchar för sitt eget samhälle, vilket då i stor mån negerar problemet med att en motståndare skulle kunna använda samma exploit mot oss.

Det är precis som att utveckla nya bomber, man skyddar sina egna från densamma, även om man inte ställer i ordning skyddet innan det behövs, tack var risken att Den Lede Fi då lättare kan luska fram vad man pysslar med och skydda sig själv.

Men redan i fredstid kan man börja skydda sig själv, bygga kompetens, samt bygga upp en egen exploit databas genom att hitta och patcha säkerhetshål i både militära och samhällsviktiga system.

Att ha en avdelning programmerare som sitter och gör det här skulle ge en otroligt stark offensiv förmåga tack vare att de då redan HAR kompetensen, erfarenheten och verktygen som behövs för att använda samma information offensivt, som de tidigare arbetat med defensivt, samt inte minst vore det intressant att se patchar släppas i fredstid utvecklat av SVFM, vilket då skulle göra en potentiell motståndares arbete svårare och dyrare.

Vi behöver utan tvekan ett starkare arbete för att säkra vår infrastruktur mot cybervapen, det är helt otroligt att man kan ta sig in via nätet för att påverka samhällsviktiga system som visats i de senaste årens relativt små attacker.
 



Thoughts on LiveCode from RunRev

I'm a programmer, I build things, and I like to pick tools that gives me lots of power, speed of development and is fun to work with.

For the web I work with CFML using the OpenBD engine, it's fast, reliable and powerful, I use MySQL for database work for the same reasons.

For desktop I picked LiveCode.

If you have no clue what LiveCode is;  It's a Crossplatform Rapid Application Development tool.
It's a graphical environment with a built-in IDE, it's the next-gen of what Delphi was and could have been.

The RAD part is seriously true, you can make things really fast with LiveCode.

But the more I work with it the more its quirks are starting to get to me though, and it's mostly small things that should not be issues!

Here's my list of petpeeves in LiveCode:

Over the day as I use it, it slows to an absolute crawl, and I have to restart it a couple of times a day to be able to continue working in it.

 No hightlighting in the IDE. Seriously, none, just blocks of text, this brings me to my next point.

No way (That I know of) to use an external editor. I use Notepad++ for my web stuff, I LOVE that editor, it's as flexible as needed, does highlighting and I can make my own patterns if I want to, just being able to use that as my external editor would make my development that much fast.

The compiler can't handle \
Seriously guys, LiveCode is at version 6.x something, and your compiler still clonks out on the \ character?
I have a project that relies almost entirely on regex, which LiveCode "supports". I put support in citationmarks because.. it doesn't. The compiler has random breakdowns if you try to escape characters, which, you know, happens every once in a blue moon (All the time) in regex.

No simple "Stop" button. Loops happen, sometimes I would like to get out of that endless loop in a simple way, without having to hard-close the whole LiveCode editor, or by "inserting a break" (Which sometimes isn't possible because the *whole thing* has locked up due to a loop)

 The Dictionary. The dictionary itself is an absolutely great feature, but for some reason that thing is so incredibly resource heavy or malcoded that it randomly locks up, forcing the whole editor to a grinding halt.

No built-in json handling, nope there's no built-in way to handle json. There is an excellent 3rd party library though, but even so, json is arguable pretty common (Industry standard...) and would be nice to have available by default.

The mouse scroll stops working when flipping between the various parts, but starts working if you press the Escape button once.

All of this is mostly minor, but they all add up to frustration.

That's a nice list of bad stuff, are there no good sides to this thing?

Oh yes there are.

The speed, the syntax (It's like broken English, lol), the community (I've only had a couple of bad experiences on their forums, other coders seem very willing to help most of the time)

It's an almost-mature product, I love coding in it and I'll continue to do so, but I can't rely solely on it because of the above issues, I have to use other solutions simply because LiveCode can't handle the simple stuff, like escaping characters.

I currently do not have a commercial license with LiveCode (And I haven't released any commercial software with it) but I plan to get it, simply because LiveCode IS that good, fast and fun to work with, and I think (hope) that these issues will be rectified in the future.

If it was me,  I'd focus on fixing issues like these rather than put new functions on there, because I need Regex to work a whole lot more than I need a built-in json library (Especially since LiveCode claims to be fully regex compliant using the PCRE Perl regex engine)

There you have it, a 5-minute rant about LiveCode.