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.

Friday, November 1, 2013

OpenBD, parsing BBCode, loops and a simple Regex solution

Lately I've been working on a bunch of AJAX applications, more or less chat-oriented, and they both needed variations of BBCode, so I started working on it.

My first iteration used a loop looking for the bbcode, counting the number of times and if it came up uneven with the ending bbcode it would add the closing code at the end of the text, all in all it was a very clunky way of doing things but it worked well.

The latest project however, I decided that there had to be a better way of doing it, so I started thinking about using regex, I came up with my own variant but it didn't work when you nest different bbcodes (I'm not very good with regex) but with some paid help on Fiverr I got the following regex and it works very nicely:


It's pretty simple, but works nicely, I haven't seen any other solution this straight forward out there so I figured I'd share this one.
The next problem was the url bbcode, now in this application we're only using [url][/url] because the link name will be same as the actual link, no way to hide a different link under a false name.
This is what we came up with:


The basic idea is that it works with or without the user writing out http:// and it supports variations such as https://, the original regex I came up with broke if the user only wrote www.link.com and the finished link was handled wrongly, making the browser look for a local page instead of the proper url.

So there you have it, nice and simple, feel free to use it.

Thursday, October 24, 2013

Adding a membership file-area with protected files

In this brief post I'll go over how to create a file-area for members-only, how to make files available for download while keeping them secure so that non-members can not download them, we're assuming that anyone who is logged in should have access to the files.

Assumptions: There are a few assumptions here, and that's just because this is not a thorough tutorial, but more aimed at helping out someone who's relatively new but has some experience.

The assumptions are that there is a datasource called 'fileDSN' which points to a database with a table called 'files' with the columns 'file_id' and 'name' in it, we assume the folder 'C:\SecureFiles' exists and contains the files you want to handle, and we assume that the folder is not under the webroot, and lastly we're assuming that there is a login function based on cflogin.

The code here is tested on OpenBD 2.0.2

Since this is a quick example rather than a full application tutorial I'll jump straight into the file-handling page.

We'll be using a database and two files, one for displaying files and links, and one for actually serving up the file.

We could have used cfdirectory to list what files are in the folder and then used a link with the filename, but that opens up a security hole, so instead we've put the filenames into a database table, all the information we need is the filename and the record ID, that way the only variable we take from the outside is the ID number for the record.

Create a file called filedisplay.cfm and paste the following code into it:



What we're doing is running a query to get a list of all the files we've added to the database.
We then create links for each file, using their ID and name, the that handles getting the file is described below.

Create a file called file.cfm and paste the following code into it:



This is a .CFM file, how can it handle downloads of other file types?
By using the cfheader and cfcontent tags to define the header and the content of the file presented to the browser.
Doing this, the file temporarily "becomes" the file we want to download instead of a usual .CFM file.

First we check if the user is logged in, because we decided earlier that you have to be logged in to get access to the files, and we check to make sure the url.id variable exists, if you're not logged in or the variable does not exist, the user is forwarded to index.cfm.

Then we run the query to get the file information, we use cfqueryparam to protect against some hack attempts, what this one does is make sure the url.id is a number, is at most 3 characters long (Which gives us up to 999 files to pull from the database), for a full description of how cfqueryparam works I point you to Adobes online documentation.

We then get into the actual file-handling, after running the query we check to see if it returns a single record which is what we want, if it doesn't we assume the file does not exist and output the text in the tag.

Next we set the folder to check in, which in this example is the C:\SecureFiles folder, we then run another cfif, this time to see if the file exists, and assuming it does we go on to set the fileInfo variable with information about the file which we'll use in a bit.

After that we set the mimeType variable and here we use the getPageContext tag which pulls information from an underlying JAVA function to get mime information about the file.

And then we set the header and content information by pulling it all together by outputting the various variables into the cfheader and cfcontent functions.

This is what transforms our .CFM file to whatever file it is we want to download, all these things are necessary for the browser to recognize what kind of file it's handling and what to do with it.

If it seems longwinded or complicated, it's not, just start playing with it and you'll get it.

So why are we doing this instead of creating a hidden folder somewhere and just link to the files?

Because security by obscurity is silly, it only takes one person to spread the link and anyone could download the file, doing it this way we can put in place various checks and balances, in this example we just make sure the user is logged in but it's easy to start adding other criteria or access levels.

I hope this short example is useful to someone, and remember I don't claim to present best coding practices or the best way to do anything, I'm just putting this out there as an example that might get someone going in the right direction :)