|By Steve Parks||
|November 19, 2002 12:00 AM EST||
In computer terms, objects are abstracts of real-world entities that are all around us in everyday life. Examples of such objects could be people, organizations, cars, animals, or even less tangible entities such as math or time.
Of these examples, only the first four can be considered collections. One or more persons is a collection of people; one or more organizations is a collection of organizations, and so on. However, math is not a collection of math and time is not a collection of time. They are just simple objects with methods and properties. Simply defined, a collection is a set of related objects.
Collections come with many advantages. First, they are objects, so any and all advantages of objects, such as encapsulation and reusability, are inherent to the collection. Second, you can access a group of objects easily by looping through the collection and executing the same code against each object in the collection. Finally, you can simplify a lot of the external data manipulation by using collections. For instance, instead of returning a query containing users (which might change in six months) you could use a Users collection. The User object that is stored in the Users collection would encapsulate all the code that goes into retrieving the user data. That way, when the database changes, you can change your User object while your collection and the code accessing the collection remain the same.
What Makes a Collection?
There are three hard and fast rules that an object (or in ColdFusion, a component) has to adhere to in order to be a collection:
1. Every object in the collection can be accessed individually. Each object in the collection is unique in instance, if not data. If there are five objects in the collection, you should be able to call properties and methods from each object.
2. Every object in the collection is the same type of object and has the same properties and methods. This means that you wouldn't have a collection called People with two types of objects: People and Computers. You would, in fact, have two collections, the People collection and the Computers collection.
3. A collection usually has at least four methods: Add, Remove, Count, and Item.
Most collections can be completely accessed through the use of just four methods:
Creating the Collection Files
In order to create a collection we need to create two files, both of which are CFCs. The first CFC we'll create will be named ActiveUsers.cfc; the second will be named ActiveUser.cfc. The ActiveUser.cfc file will be the actual object that is contained in our collection. The collection filename is usually the plural term for the name of our object, hence, ActiveUser object and ActiveUsers collection. The ActiveUser.cfc file is shown in Listing 1.
The ActiveUsers collection will have four methods: Add(strFirstName, strLastName), Remove(index), Item(index), and Count(). Our ActiveUser object will contain five methods: GetName(), SetName(strFirstName, strLastName), SetLoginTime(), GetLoginTime(), and GetMinutesActive().
Our ActiveUsers collection will be used to display only users who are currently active on our Web site, similar to a "who's on" interface. Anytime you access a variable in a shared scope, such as the Application scope, you should lock it using CFLOCK.
The first step is to set up a data structure to store our data in the ActiveUsers collection. We need only one private (or member) variable called arItems, which is an array. You can add that code just inside of your CFCOMPONENT tag as shown below.
<CFSET arItems = ArrayNew(1)>
Next we're going to add four methods to the component. The first method is the Add method. The Add method will take two arguments, FirstName and LastName, both string literals. The Add function simply adds an element to the private variable arItems using the intrinsic function, ArrayAppend(). The tricky part is that our Add method needs to add a value that represents an instance of an object. Since we can't use the CFOBJECT tag inside the ArrayAppend() function, we will use the CreateObject() function, shown below. After we add that element to the array, we also need to get the length of the array so we know the index of our recently added user. Again, locking is important here, because we want to add an element to the array and then get the length of the array before anyone else adds another element to it. This is sometimes called a race or race to commit, in database terminology. If we don't lock the actions, we will be racing against other requests to add elements to the array, potentially returning the wrong values to the calling page.
<CFSET ArrayAppend(arItems, CreateObject("component","ActiveUser")>
<CFSET idx = ArrayLen(arItems)>
The next two lines of code in our function will be calling methods from the prebuilt ActiveUser object. These methods set three internal variables in the ActiveUser object: the user's first name, the user's last name, and the date the user logged in.
The last thing we do is return the current element of the array for the programmer to use in the calling page, if necessary. That was the hard part. The next three functions are short and sweet, so I'm going to spend more time describing why you need to do this, rather than stepping through the code line by line. Listing 2 shows the code for the entire collection object.
With the Remove method, we require one argument that is an integer representing the index of the internal array, arItems. We need to check to make sure the value passed is less than or equal to the length of the array so there aren't any errors produced, and then we simply remove that element using the ArrayDeleteAt() function. Remember, you'll need to lock this action to prevent the wrong index of the array from being deleted. In a situation where the method is called twice, there will be a race to commit the deletion. In the event the deletion was not locked, the array would be resized after the first deletion and then the wrong index could potentially be deleted during the second deletion.
The Item method also requires an index value, but the result is different. Instead of removing an item (or doing any type of action), we're just going to return the instance of the ActiveUser object that was stored at that index. This allows us to access each individual object from external ColdFusion templates easily, as you'll see later.
The Count method accepts no arguments and returns an integer describing the number of objects in our collection. We use the ArrayLen() function to determine the return value.
That's it for our collection. All of the internal code is written for our ActiveUsers collection to work properly. It's relatively easy to generate code for collections once you understand the concepts. Now we're going to look at how to use collections in ColdFusion templates.
Making the Collection Persist
In order for our "who's on" application to persist, we need to set up the ActiveUsers collection in the Application scope. Open the Application.cfm file in Listing 3 and add the following code:
<CFIF NOT IsDefined("Application.objActiveUsers")>
<CFOBJECT NAME="Application.objActiveUsers" COMPONENT="ActiveUsers">
This code basically says to check whether the Application.objActiveUsers collection is defined at the beginning of every request. If it isn't defined, it will create the collection using the CFOBJECT tag.
Accessing the Collection
In the index.cfm file (see Listing 4) we're going to output the current number of users online and then loop through the ActiveUsers collection and output data pertaining to the users that are online. You can do all this using the code below:
<CFSET iCount = Application.objActiveUsers.Count()>
As you'll see, we've set the iCount variable to the value of the ActiveUsers collection's Count method. This lets us know how many active users are online right now. Now we can loop through the collection using a simple FROM/TO (or FOR) loop where the TO attribute is equal to the number of users online, or iCount.
We can access the individual objects in the collection using the Item(index) property such as Application.objActiveUsers.Item(i). In the code below, we use that notation to call different methods of the object, such as GetName(), GetLoginTime(), and GetMinutesActive().
<CFLOOP FROM="1" TO="#iCount#" INDEX="i">
<CFSET stName = Application.objActive
#i# - #stName["FirstName"]#
#TimeFormat(Application.objActiveUsers.Item(i).GetLoginTime(), 'h:mm tt')# -
Running index.cfm at this point in time would result in the printing of "Number of Users: 0", since we haven't added any users to the collection. In order to add users to the collection we have to call the Add() method of the ActiveUsers collection. In this example, we'll make a ColdFusion page called AddUser.cfm (see Listing 5) that requires two URL variables called FirstName and LastName. The following code is all we'll use for our AddUser.cfm file:
<CFSET objActiveUser = Application.objActive
If we access the AddUser.cfm page passing "Steve" and "Parks" through the query string such as
our page will then add the user to the collection and refresh us to the index.cfm page. You should now see that there is one user named Steve Parks in the collection. If your browser caches the index.cfm page, you may have to manually refresh the page. In the index.cfm file we called the GetName(), GetLoginTime(), and GetMinutesActive() methods from the ActiveUser object in the collection. You'll now see that data outputted through the collection. Try it again, adding another user using your name. You should now see that you are in the collection as well.
The last file that needs to be created is the RemoveUser.cfm file, which will remove users from the collection. Instead of passing the FirstName or LastName of the user, you'll need to pass a valid index. In this example, we'll just remove the first index, but in theory you would remove users based on an algorithm possibly determined by a method called GetMinutesIdle(). To remove the first user from the application, call the file RemoveUser.cfm, shown in Listing 6, passing a value of 1 in the attribute index, as shown below:
We've now created our ActiveUsers collection in a simplified form. You can add properties and methods to the ActiveUser object to make the system more robust. I recommend adding locking and validation to the Application scope and methods, respectively.
Connected devices and the industrial internet are growing exponentially every year with Cisco expecting 50 billion devices to be in operation by 2020. In this period of growth, location-based insights are becoming invaluable to many businesses as they adopt new connected technologies. Knowing when and where these devices connect from is critical for a number of scenarios in supply chain management, disaster management, emergency response, M2M, location marketing and more. In his session at @Th...
Dec. 3, 2016 09:30 AM EST Reads: 3,918
"Dice has been around for the last 20 years. We have been helping tech professionals find new jobs and career opportunities," explained Manish Dixit, VP of Product and Engineering at Dice, in this SYS-CON.tv interview at 19th Cloud Expo, held November 1-3, 2016, at the Santa Clara Convention Center in Santa Clara, CA.
Dec. 3, 2016 09:30 AM EST Reads: 821
What happens when the different parts of a vehicle become smarter than the vehicle itself? As we move toward the era of smart everything, hundreds of entities in a vehicle that communicate with each other, the vehicle and external systems create a need for identity orchestration so that all entities work as a conglomerate. Much like an orchestra without a conductor, without the ability to secure, control, and connect the link between a vehicle’s head unit, devices, and systems and to manage the ...
Dec. 3, 2016 09:00 AM EST Reads: 443
"We're a cybersecurity firm that specializes in engineering security solutions both at the software and hardware level. Security cannot be an after-the-fact afterthought, which is what it's become," stated Richard Blech, Chief Executive Officer at Secure Channels, in this SYS-CON.tv interview at @ThingsExpo, held November 1-3, 2016, at the Santa Clara Convention Center in Santa Clara, CA.
Dec. 3, 2016 08:30 AM EST Reads: 483
In addition to all the benefits, IoT is also bringing new kind of customer experience challenges - cars that unlock themselves, thermostats turning houses into saunas and baby video monitors broadcasting over the internet. This list can only increase because while IoT services should be intuitive and simple to use, the delivery ecosystem is a myriad of potential problems as IoT explodes complexity. So finding a performance issue is like finding the proverbial needle in the haystack.
Dec. 3, 2016 06:30 AM EST Reads: 6,003
In his keynote at 18th Cloud Expo, Andrew Keys, Co-Founder of ConsenSys Enterprise, provided an overview of the evolution of the Internet and the Database and the future of their combination – the Blockchain. Andrew Keys is Co-Founder of ConsenSys Enterprise. He comes to ConsenSys Enterprise with capital markets, technology and entrepreneurial experience. Previously, he worked for UBS investment bank in equities analysis. Later, he was responsible for the creation and distribution of life sett...
Dec. 3, 2016 05:45 AM EST Reads: 6,920
The WebRTC Summit New York, to be held June 6-8, 2017, at the Javits Center in New York City, NY, announces that its Call for Papers is now open. Topics include all aspects of improving IT delivery by eliminating waste through automated business models leveraging cloud technologies. WebRTC Summit is co-located with 20th International Cloud Expo and @ThingsExpo. WebRTC is the future of browser-to-browser communications, and continues to make inroads into the traditional, difficult, plug-in web ...
Dec. 3, 2016 05:30 AM EST Reads: 1,200
20th Cloud Expo, taking place June 6-8, 2017, at the Javits Center in New York City, NY, will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Cloud computing is now being embraced by a majority of enterprises of all sizes. Yesterday's debate about public vs. private has transformed into the reality of hybrid cloud: a recent survey shows that 74% of enterprises have a hybrid cloud strategy.
Dec. 3, 2016 04:15 AM EST Reads: 1,718
Internet-of-Things discussions can end up either going down the consumer gadget rabbit hole or focused on the sort of data logging that industrial manufacturers have been doing forever. However, in fact, companies today are already using IoT data both to optimize their operational technology and to improve the experience of customer interactions in novel ways. In his session at @ThingsExpo, Gordon Haff, Red Hat Technology Evangelist, will share examples from a wide range of industries – includin...
Dec. 3, 2016 02:30 AM EST Reads: 1,523
WebRTC is the future of browser-to-browser communications, and continues to make inroads into the traditional, difficult, plug-in web communications world. The 6th WebRTC Summit continues our tradition of delivering the latest and greatest presentations within the world of WebRTC. Topics include voice calling, video chat, P2P file sharing, and use cases that have already leveraged the power and convenience of WebRTC.
Dec. 3, 2016 02:15 AM EST Reads: 1,501
"We build IoT infrastructure products - when you have to integrate different devices, different systems and cloud you have to build an application to do that but we eliminate the need to build an application. Our products can integrate any device, any system, any cloud regardless of protocol," explained Peter Jung, Chief Product Officer at Pulzze Systems, in this SYS-CON.tv interview at @ThingsExpo, held November 1-3, 2016, at the Santa Clara Convention Center in Santa Clara, CA.
Dec. 3, 2016 01:45 AM EST Reads: 788
Data is the fuel that drives the machine learning algorithmic engines and ultimately provides the business value. In his session at 20th Cloud Expo, Ed Featherston, director/senior enterprise architect at Collaborative Consulting, will discuss the key considerations around quality, volume, timeliness, and pedigree that must be dealt with in order to properly fuel that engine.
Dec. 3, 2016 12:30 AM EST Reads: 1,524
"Once customers get a year into their IoT deployments, they start to realize that they may have been shortsighted in the ways they built out their deployment and the key thing I see a lot of people looking at is - how can I take equipment data, pull it back in an IoT solution and show it in a dashboard," stated Dave McCarthy, Director of Products at Bsquare Corporation, in this SYS-CON.tv interview at @ThingsExpo, held November 1-3, 2016, at the Santa Clara Convention Center in Santa Clara, CA.
Dec. 2, 2016 11:15 PM EST Reads: 916
IoT is rapidly changing the way enterprises are using data to improve business decision-making. In order to derive business value, organizations must unlock insights from the data gathered and then act on these. In their session at @ThingsExpo, Eric Hoffman, Vice President at EastBanc Technologies, and Peter Shashkin, Head of Development Department at EastBanc Technologies, discussed how one organization leveraged IoT, cloud technology and data analysis to improve customer experiences and effici...
Dec. 2, 2016 08:30 PM EST Reads: 4,984
Fact is, enterprises have significant legacy voice infrastructure that’s costly to replace with pure IP solutions. How can we bring this analog infrastructure into our shiny new cloud applications? There are proven methods to bind both legacy voice applications and traditional PSTN audio into cloud-based applications and services at a carrier scale. Some of the most successful implementations leverage WebRTC, WebSockets, SIP and other open source technologies. In his session at @ThingsExpo, Da...
Dec. 2, 2016 08:15 PM EST Reads: 1,574
"IoT is going to be a huge industry with a lot of value for end users, for industries, for consumers, for manufacturers. How can we use cloud to effectively manage IoT applications," stated Ian Khan, Innovation & Marketing Manager at Solgeniakhela, in this SYS-CON.tv interview at @ThingsExpo, held November 3-5, 2015, at the Santa Clara Convention Center in Santa Clara, CA.
Dec. 2, 2016 06:45 PM EST Reads: 4,001
As data explodes in quantity, importance and from new sources, the need for managing and protecting data residing across physical, virtual, and cloud environments grow with it. Managing data includes protecting it, indexing and classifying it for true, long-term management, compliance and E-Discovery. Commvault can ensure this with a single pane of glass solution – whether in a private cloud, a Service Provider delivered public cloud or a hybrid cloud environment – across the heterogeneous enter...
Dec. 2, 2016 06:30 PM EST Reads: 1,489
The cloud promises new levels of agility and cost-savings for Big Data, data warehousing and analytics. But it’s challenging to understand all the options – from IaaS and PaaS to newer services like HaaS (Hadoop as a Service) and BDaaS (Big Data as a Service). In her session at @BigDataExpo at @ThingsExpo, Hannah Smalltree, a director at Cazena, provided an educational overview of emerging “as-a-service” options for Big Data in the cloud. This is critical background for IT and data professionals...
Dec. 2, 2016 05:00 PM EST Reads: 4,089
Today we can collect lots and lots of performance data. We build beautiful dashboards and even have fancy query languages to access and transform the data. Still performance data is a secret language only a couple of people understand. The more business becomes digital the more stakeholders are interested in this data including how it relates to business. Some of these people have never used a monitoring tool before. They have a question on their mind like “How is my application doing” but no id...
Dec. 2, 2016 04:45 PM EST Reads: 2,119
@GonzalezCarmen has been ranked the Number One Influencer and @ThingsExpo has been named the Number One Brand in the “M2M 2016: Top 100 Influencers and Brands” by Onalytica. Onalytica analyzed tweets over the last 6 months mentioning the keywords M2M OR “Machine to Machine.” They then identified the top 100 most influential brands and individuals leading the discussion on Twitter.
Dec. 2, 2016 04:45 PM EST Reads: 1,985