Using Twitter Authentication in an Application

I will begin with a little back story. So I manage an internal User Group inside the company I work for (ImageTrend, INC). I proposed a challenge to the attendees to come up with a cool implementation of an app using the Twitter API.

Myself being the proposer I feel I am not eligible for the prize but wanted to take on the challenge just for fun. I found a good blog post by Mr. Ray Camden Adding support for automated tweets with OAuth that was very helpful getting started. I won't go into detail on setting up the Twitter Application on Twitter it's in his blog post. But it's kind of an older post and Twitter4j was released newer versions that do not work with his implementation in the blog. Scanning through the comments on the post, Sean Ryan had posted a blog entry with the updated details using the latest version of Twitter4j. Here is the post

Now to some code examples. Setting up the application cfc I added this code snippet to my onApplicationStart method:

view plain print about
1var paths = [this.siteroot & "twitter4j/twitter4j-core-2.2.6-SNAPSHOT.jar"];
2        application.javaloader = createObject("component", "javaloader.JavaLoader").init(paths);
3        
4        application.RequestAccessToken = "Consumer Key From Twitter";
5        application.RequestAccessSecret = "Consumer Secret From Twitter";
6        
7        application.Twitter = application.javaloader.create("twitter4j.TwitterFactory").init().getInstance();
8        application.Twitter.setOAuthConsumer(application.RequestAccessToken,application.RequestAccessSecret);

My callback URL on Twitter is setup to call http://www.ryanvikander.com/twitter/twitterlogin.cfm?mode=1 I created a CFM page to handle the twitter login. This file looks like this:

view plain print about
1<cfset userInfo = application.userController.getTwitterCredentials(session.userid) />
2
3<cfif userInfo.recordCount EQ 0 AND NOT structKeyExists(url,'mode')>
4    <cfif NOT structKeyExists(session, "RequestToken")>
5        <cfset Session.RequestToken = application.Twitter.getOAuthRequestToken(application.twitterlogin)>
6    </cfif>
7    
8 <cfset Session.oAuthRequestToken = Session.RequestToken.getToken()>
9 <cfset Session.oAuthRequestTokenSecret = Session.RequestToken.getTokenSecret()>
10     
11 <cflocation url="#Session.RequestToken.getAuthorizationURL()#" addtoken="No">
12<cfelseif userInfo.recordCount GT 0>
13 <cfset session.StoredAccessToken = userinfo.token>
14 <cfset session.StoredAccessSecret = userinfo.secret>
15     
16 <cflocation url="index.cfm" addtoken="false" />
17<cfelse>
18 <cfset AccessToken = application.Twitter.getOAuthAccessToken(Session.RequestToken,url.oauth_verifier)>
19 <cfset session.StoredAccessToken = AccessToken.getToken()>
20 <cfset session.StoredAccessSecret = AccessToken.getTokenSecret()>
21
22    <cfset application.userController.saveTwitterCredentials(session.userID,AccessToken.getTokenSecret(), AccessToken.getToken()) />
23
24 <cflocation url="index.cfm" addtoken="false"/>
25</cfif>

Very similar to Ray's code for the one time authentication but I wanted to database the tokens that Twitter returned so in the else if I check to see if the user exists and I have stored their token if they do not exist I database the token and secret so they don't have to authorize the app every time.

Once this is complete you can do pretty much whatever is available from the Twitter4J class library.

I apoligize if this is a scattered post wanted to do a quick write up. If you have any questions/concerns I am more than willing to try and answer.

Using Local SQL Server Express 2008 Server with Coldfusion

So I know there are a few articles out there on this subject but I seem to have to reinstall sql server on my laptops often and I always have to hunt down how to do it so I thought I would post a blog so it would be a bit more recent.

I won't go over installing SQL Server Express, it takes a while seems like a good 30 minutes. Anyways, once you install it you can connect to your local database by connecting to the server (depending on what you named your server) [PC_Name]\SQLEXPRESS and depending on if you are using windows authentication you would enter your user name and password.

Ok so once you've gotten that installed there are some more tricky stuff you need to do within SQL Server. First you will need to turn on TCP/IP which is located under Start > Microsoft SQL Server 2008 > Configuration Tools > SQL Server Configuration Manager. Once you open up the manager go under: SQL Server Network Configuration and click on Protocols for SQLExpress (I assume this the name of the server). By default TCP/IP is disabled. So enable it by right clicking and enabling it. You will be prompted to restart your server service but I would wait until finished to do so. Now double-click TCP/IP or right click and go to Properties. Go into the IP Addresses tab and for each IPs enter in under TCP Port 1433. This allows for Coldfusion to connect to your database. Now you can apply and restart your server service.

A tip if you skip that last step you will get this annoying error message and this is why I needed to post this:

Connection verification failed for data source: rvikander java.sql.SQLNonTransientConnectionException: [Macromedia][SQLServer JDBC Driver]Error establishing socket to host and port: localhost:1433. Reason: Connection refused: connect The root cause was that: java.sql.SQLNonTransientConnectionException: [Macromedia][SQLServer JDBC Driver]Error establishing socket to host and port: localhost:1433. Reason: Connection refused: connect

If anyone has any thoughts or questions I would love the comments. Otherwise I hope this helps someone.

Modal Helper for ColdMVC

So during my spare time I have been working on a wedding site for myself and its written in a coworker's Coldfusion framework ColdMVC. Within learning the language I decided I was going to create my own custom helper for a modal window. I went with the jQuery modal library jQModal. The way I created the helper you can use whatever modal window library you want this is just one that I like. But anyways enough with that let's look at some code.

So a typical ColdMVC directory will look like this. Inside I have a Helpers folder. This folder is where you will put your CFCs that contain your helper functions. I do believe you can override the built in functions if they are the same name and function name? I am not positive but I can find out.

My modal CFC contains one function called display and this is where you would put your HTML to render your modal window. Since I went with jQModal I have had to add some certain classes that only pertain to that library. Your function might be different.

view plain print about
1<cffunction name="Display" returntype="any">
2        <cfargument name="ID" required="true" />
3        <cfargument name="URL" required="false" default="" />
4        <cfargument name="Content" required="false" default="" />
5        <cfargument name="Label" required="false" default="" />
6        <cfargument name="Title" required="false" default="Modal Window" />
7        <cfargument name="Loading" required="false" default="" />
8        
9        <cfset var html = "" />
10        
11        <cfsavecontent variable="html">
12            <cfoutput>
13            <script type="text/javascript">
14                $(document).ready(function() {
15                    $('###arguments.ID#').jqm({
16                            modal: true,
17                            trigger: 'a.modal_link#arguments.ID#'
18                            <cfif arguments.URL NEQ "">
19                                ,ajax: '#arguments.URL#'
20                                ,ajaxText: "#arguments.Loading#"
21                            </cfif>
22                    });
23                });
24            </script>
25            
26            <div id="#arguments.ID#" class="jqmWindow">
27                <div class="modal_title">#arguments.title# <div class="floatright text_right"><a href="##" class="jqmClose">Close</a></div></div>
28                <div class="text_left">
29                    <div class="modal_content content">
30                        #arguments.Content#
31                    </div>
32                </div>
33            </div>
34            <a href="##" class="modal_link#arguments.ID#">#arguments.label#</a>
35            </cfoutput>
36        </cfsavecontent>
37        
38        <cfreturn html>
39    </cffunction>

The function itself accepts an ID which is required and must be unique. This is for the fact that if you want to have multiple modal windows on your page we need them to be unique. The URL argument is used if you are doing an AJAX call. This will do a refresh every time you make a call to the modal window. The content argument is used if you want to send in content to the window by using cfsavecontent and passing the variable to the function. The label argument is used for the link. This can be modified if you want to do something different to display for the user to trigger the modal window. Title is the title of the argument. By default the window will just say "Modal Window" this is incase I forgot to include a title of course you don't HAVE to have a title, but I like it. Loading is just some HTML that I display for the AJAX calls so the user just doesn't see a blank window.

So that's the function now how do we use it? Well there are two ways I use the modal window. Well there is two different ways you can use it. First is if you want to take some content and pass it to the modal window. Here is how I do that:

view plain print about
1<cfsavecontent variable="text">
2Hello World!
3</cfsavecontent>
4
5<cfoutput>
6#$.modal.display(label="Click Me", Content=text, id="displaycontent", title="How We Met")#
7</cfoutput>

Now if you are not familiar with ColdMVC I suggest visiting: Tony Nelson's blog and read up on some of his posts explaining the ins and outs on the framework. But just for this blog I will explain that $ replaces the helper scope inside ColdMVC so you don't have to type out helpers every time. That's one way I call the modal helper. The next way is by making an AJAX request.

This way is a bit more trickier:

view plain print about
1#$.modal.display(ID="loginWindow", URL="#linkTo({controller='wedding',action='loginform'},'currentView=#cgi.path_info#')#",label="Login", loading="<div class='text_left'>Loading<marquee style='width: 1.5em;'>.....</marquee>")#

The first thing I do is use the built in ColdMVC linkTo() function to link to my controller and pass the action of loginform. Again, ColdMVC is going to know how to use that and render the correct view. The only other thing different is I pass in some HTML for loading so I can display loading to the user while the page loads. *note my best use of the marquee tag ;)* And that's pretty much it. I have some custom css for displaying the modal window and it comes out looking like this:

Example of non AJAX modal:

Example of AJAX modal:

Note I am in no way the best designer. I am sure someone could design a better window. I am up for suggestions.

Also here is a link to the jQuery plugin I used jQModal

Reverse Loop An Array of Structs

So I was trying to figure out how to loop an array of structs backwards. I found ways to loop arrays backwards but it only worked with using the reverse() function and that only works on a list of strings. Something that I was aware of until recently cfloop has a step attribute. So really it just came down like this, pretty simple:

view plain print about
1<cfloop from="#ArrayLen(ArrayofStructs)#" to="1" index="i" step="-1">
2 <cfdump var="#ArrayofStructs[i]#" abort="true" />
3</cfloop>

This is probably well known, but I wanted a reference so I can use it again later. Hope this helps someone.

Weird Coldfusion Error

So a coworker found this out if you run this test page Coldfusion will return that the cfcatch is not a struct even though when you dump the variable it says that it is a struct. Also on the argument in the function if you put a type="struct" Coldfusion will error out saying that it is not a struct. I have filed a bug here: Bug Also it turns out that it is not just a CF9 issue I have seen it as well in my local CF8 instance.

view plain print about
1<cffunction name="testFunction" output="true">
2    <cfargument name="exception" required="true"/>
3    <cfdump var="#arguments.exception#">
4    <cfdump var="#isStruct(arguments.exception)#">
5</cffunction>
6
7<cftry>
8    <cfthrow message="Help!!!!" />
9    
10    <cfcatch type="any">
11        <cfset testFunction(exception=cfcatch) />
12    </cfcatch>
13</cftry>

Switching Back To CFEclipse From CFBuilder

So I have been on the private beta of CFBuilder since it was Bolt when it first went to private testing and have loved most of it. I love the Extensions, the RDS is pretty cool, and being able to manage my servers inside the IDE is pretty slick. Although I have dealt with all the performance issues between each release I do have to say that I am in love with CFBuilder. Unfortunately what has killed most of my love for Builder is the price tag. $300 is a bit much for an IDE. Especially since there are a few really good ones that are free. Now you don't get as much of the cool stuff Builder offers, but it is pretty darn close. Also, $300 is fine when you are purchasing one license and that is it. As some people know I work at a pretty big Coldfusion shop. There are probably about 50 CF developers maybe. And at $300 bucks its a bit much. Event if they could do half off that is that is still $7,500 total. I don't know, it hurts me to switch off but I think I will live.

Quick Coldfusion Shoutout: ColdMVC

So one of my co-workers has released their new framework for people to test out. ColdMVC is a pretty cool framework I have seen him present on it and seen some of the code. You can check it out at ColdMVC Available On Github

cf.Objective() Attendee...

Just a quick blog but I am excited to say that I am greatful to be able to attend cfObjective this year. I attended last year's event and had a great time learning new stuff whether it's about a framework that I have not seen before or just new coding techniques. I feel like last years event had motivated me in ways that I think has helped me as a developer. Not only did I learn new developing techniques but also fell in love with the art of user group meetings I guess you could say. I know that there is a local twin cities CFUG group but I hate driving to Minneapolis if I don't have to. I started up an internal Imagetrend user group meetings that seems to interest a lot of my co-workers. Usually I see turn outs of 15 people consistently which I think is pretty good. Anyways I digress, I cannot wait for this years conference and I will probably blog my thoughts and opinions on each of the sessions I tend. Hopefully to those that do read my blog and are attending the event I will get to meet you. I will be the big guy with the Halo tattoos hah.

Random Coldfusion Error

So just a quick post of an error I was receiving on an environment with an older version of Coldfusion 8 (prior to 8.01). The error was "Branch target offset too large for short". I googled this error an not a lot of clear help but what it came down to is the main function was just too large ( 1,000 lines of code). And it really only came up when I added like 15-20 more lines to the function. In order to fix it however I just broke my new changes off into their own function and it seemed to work. Further refactoring of this function is almost a must and will probably happen when I have time to do so. Just wanted to point this out, maybe for my own reminder but maybe it might help someone else.

VarScoper Gotcha Example

So I grabbed a function from a cfc that we use (replaced sensitive data of course) and as you can see there are some non-scoped variables. When I run through the varscoper that I have (version 1.3 latest from RIAforge I believe) it doesn't catch some variables. First it says that Template and TemplatePath need to be var scoped but they are actually in the arguments scope not the local scope. Second of all it doesn't catch the returnVariable from the invoke on line 40 and then it also doesn't catch PeopleID on line 38. I figured the PeopleID is fine since it is in the argument scope, but if varscoper is supposed to catch unscoped arguments than this would be a problem anyways. I attached the example hopefully the line numbers are the same as in CFBuilder.

view plain print about
1<cfcomponent>
2    <cffunction name="PersonLayout">
3        <cfargument name="PersonID" required="yes">
4        <cfargument name="Page" required="no" default="">
5        <cfargument name="Template" required="no" default="">
6        <cfargument name="TemplatePath" required="no" default="">
7        <cfargument name="FullScreen" required="no" default="true">
8        <cfargument name="ColoredBackground" required="no" default="false">
9        <cfargument name="Breadcrumbs" required="no" default="#arrayNew(1)#">
10        
11        <cfset var FullPath = "" />
12        <cfset var Outerwidth = "" />
13        <cfset var InnerWidth = "" />
14        <cfset var personCrumb = "" />
15        
16        <cfif Template eq "">
17            <cfset Template = ListLast(CGI.PATH_INFO,"/")>
18            <cfset Template = Replace(Template,"dsp_","cnt_","All")>
19        </cfif>
20
21        <cfif TemplatePath eq "">
22            <cfset FullPath = request.URLHost & CGI.PATH_INFO>
23            <cfset TemplatePath = ReplaceNoCase(FullPath,request.URLRoot,request.TemplatePath,"")>
24            <cfset TemplatePath = ReplaceNoCase(TemplatePath,ListLast(CGI.PATH_INFO,"/"),"","")>
25        </cfif>
26        
27        <cfif FullScreen eq "true">
28            <cfset outerWidth="100%">
29            <cfset innerWidth="90%">
30        <cfelse>
31            <cfset outerWidth="700">
32            <cfset innerWidth="650">
33        </cfif>
34        
35        <cfinvoke
36            component="cfc_DA_Q_PeopleData"
37            method="getPeopleHeader"
38            PeopleID="#PeopleID#"
39            FieldList="FirstName"
40            returnVariable="getPersonInfo">

41        </cfinvoke>
42        
43        <cfscript>
44            personCrumb = structnew();
45            personCrumb.display = "person (#getPersonInfo.FirstName#)";
46            personCrumb.url = "People/Overview/dsp_viewPerson.cfm?PeopleID=#PeopleID#";
47            arrayprepend(Breadcrumbs,personCrumb);
48        
</cfscript>
49        
50        <cfoutput>
51        <table width="100%" style="height: 100%" cellpadding="0" cellspacing="0" border="0">
52            <tr>
53                <td nowrap valign="top" id="SideMenu" width="200" rowspan="2">
54                    #PeopleMenu(arguments.PeopleID,arguments.Page,breadcrumbs)#
55                </td>
56                <td style="padding:0px;" valign="top"><cf_tag_Breadcrumbs2 Breadcrumbs="#Breadcrumbs#"></td>
57            </tr>
58            <tr>
59                <td width="100%" valign="top" colspan="2">
60                    <table width="#outerWidth#" cellpadding="8" cellspacing="0" border="0" align="center">
61
62                        <tr>
63                            <td>
64                                <cfif ColoredBackground>
65                                    <cf_tag_RoundedCornersTop bgcolor="##E9E9E9">
66                                </cfif>
67                                <table width="100%" cellspacing="0" cellpadding="0" border="0" <cfif ColoredBackground>class="roundtable" style="background-color:##E9E9E9;"</cfif>>
68                                    <tr>
69                                        <td>
70                                            <div id="outerContent">
71                                            <table width="#innerWidth#" cellpadding="8" cellspacing="0" border="0" align="center">
72                                                <tr>
73                                                    <td>
74                                                        <cf_tag_personHeader
75                                                            PeopleID="#PeopleID#"
76                                                            getQueries="true"
77                                                            showHealth="#request.config.personShowHealthIndicator#">

78                                                    </td>
79                                                </tr>
80                                                <tr>
81                                                    <td>
82                                                        <div id="innerContent">
83                                                            <cfinclude template="#TemplatePath##Template#">
84                                                        </div>
85                                                    </td>
86                                                </tr>
87                                            </table>
88                                            </div>
89                                        </td>
90                                    </tr>
91                                </table>
92                                <cfif ColoredBackground>
93                                    <cf_tag_RoundedCornersBottom bgcolor="##E9E9E9">
94                                </cfif>
95                            </td>
96                        </tr>
97                    </table>
98                    <cf_tag_personFooter>
99                </td>
100            </tr>
101        </table>
102        </cfoutput>
103
104    </cffunction>
105</cfcomponent>

More Entries

BlogCFC was created by Raymond Camden. This blog is running version 5.9.6.004. Contact Blog Owner