|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.
There is an ever-growing explosion of new devices that are connected to the Internet using “cloud” solutions. This rapid growth is creating a massive new demand for efficient access to data. And it’s not just about connecting to that data anymore. This new demand is bringing new issues and challenges and it is important for companies to scale for the coming growth. And with that scaling comes the need for greater security, gathering and data analysis, storage, connectivity and, of course, the...
May. 3, 2016 07:15 PM EDT Reads: 1,075
Manufacturers are embracing the Industrial Internet the same way consumers are leveraging Fitbits – to improve overall health and wellness. Both can provide consistent measurement, visibility, and suggest performance improvements customized to help reach goals. Fitbit users can view real-time data and make adjustments to increase their activity. In his session at @ThingsExpo, Mark Bernardo Professional Services Leader, Americas, at GE Digital, will discuss how leveraging the Industrial Interne...
May. 3, 2016 06:45 PM EDT Reads: 1,187
SYS-CON Events announced today that Ericsson has been named “Gold Sponsor” of SYS-CON's @ThingsExpo, which will take place on June 7-9, 2016, at the Javits Center in New York, New York. Ericsson is a world leader in the rapidly changing environment of communications technology – providing equipment, software and services to enable transformation through mobility. Some 40 percent of global mobile traffic runs through networks we have supplied. More than 1 billion subscribers around the world re...
May. 3, 2016 06:30 PM EDT Reads: 1,253
The IoTs will challenge the status quo of how IT and development organizations operate. Or will it? Certainly the fog layer of IoT requires special insights about data ontology, security and transactional integrity. But the developmental challenges are the same: People, Process and Platform. In his session at @ThingsExpo, Craig Sproule, CEO of Metavine, will demonstrate how to move beyond today's coding paradigm and share the must-have mindsets for removing complexity from the development proc...
May. 3, 2016 06:30 PM EDT Reads: 696
The IETF draft standard for M2M certificates is a security solution specifically designed for the demanding needs of IoT/M2M applications. In his session at @ThingsExpo, Brian Romansky, VP of Strategic Technology at TrustPoint Innovation, will explain how M2M certificates can efficiently enable confidentiality, integrity, and authenticity on highly constrained devices.
May. 3, 2016 06:30 PM EDT Reads: 1,122
The increasing popularity of the Internet of Things necessitates that our physical and cognitive relationship with wearable technology will change rapidly in the near future. This advent means logging has become a thing of the past. Before, it was on us to track our own data, but now that data is automatically available. What does this mean for mHealth and the "connected" body? In her session at @ThingsExpo, Lisa Calkins, CEO and co-founder of Amadeus Consulting, will discuss the impact of wea...
May. 3, 2016 06:30 PM EDT Reads: 1,005
We're entering the post-smartphone era, where wearable gadgets from watches and fitness bands to glasses and health aids will power the next technological revolution. With mass adoption of wearable devices comes a new data ecosystem that must be protected. Wearables open new pathways that facilitate the tracking, sharing and storing of consumers’ personal health, location and daily activity data. Consumers have some idea of the data these devices capture, but most don’t realize how revealing and...
May. 3, 2016 05:45 PM EDT Reads: 253
trust and privacy in their ecosystem. Assurance and protection of device identity, secure data encryption and authentication are the key security challenges organizations are trying to address when integrating IoT devices. This holds true for IoT applications in a wide range of industries, for example, healthcare, consumer devices, and manufacturing. In his session at @ThingsExpo, Lancen LaChance, vice president of product management, IoT solutions at GlobalSign, will teach IoT developers how t...
May. 3, 2016 05:00 PM EDT Reads: 250
A critical component of any IoT project is the back-end systems that capture data from remote IoT devices and structure it in a way to answer useful questions. Traditional data warehouse and analytical systems are mature technologies that can be used to handle large data sets, but they are not well suited to many IoT-scale products and the need for real-time insights. At Fuze, we have developed a backend platform as part of our mobility-oriented cloud service that uses Big Data-based approache...
May. 3, 2016 04:15 PM EDT Reads: 261
Increasing IoT connectivity is forcing enterprises to find elegant solutions to organize and visualize all incoming data from these connected devices with re-configurable dashboard widgets to effectively allow rapid decision-making for everything from immediate actions in tactical situations to strategic analysis and reporting. In his session at 18th Cloud Expo, Shikhir Singh, Senior Developer Relations Manager at Sencha, will discuss how to create HTML5 dashboards that interact with IoT devic...
May. 3, 2016 04:00 PM EDT Reads: 1,290
We’ve worked with dozens of early adopters across numerous industries and will debunk common misperceptions, which starts with understanding that many of the connected products we’ll use over the next 5 years are already products, they’re just not yet connected. With an IoT product, time-in-market provides much more essential feedback than ever before. Innovation comes from what you do with the data that the connected product provides in order to enhance the customer experience and optimize busi...
May. 3, 2016 03:30 PM EDT Reads: 1,174
In his session at @ThingsExpo, Chris Klein, CEO and Co-founder of Rachio, will discuss next generation communities that are using IoT to create more sustainable, intelligent communities. One example is Sterling Ranch, a 10,000 home development that – with the help of Siemens – will integrate IoT technology into the community to provide residents with energy and water savings as well as intelligent security. Everything from stop lights to sprinkler systems to building infrastructures will run ef...
May. 3, 2016 03:15 PM EDT Reads: 1,156
Artificial Intelligence has the potential to massively disrupt IoT. In his session at 18th Cloud Expo, AJ Abdallat, CEO of Beyond AI, will discuss what the five main drivers are in Artificial Intelligence that could shape the future of the Internet of Things. AJ Abdallat is CEO of Beyond AI. He has over 20 years of management experience in the fields of artificial intelligence, sensors, instruments, devices and software for telecommunications, life sciences, environmental monitoring, process...
May. 3, 2016 03:15 PM EDT Reads: 1,170
Digital payments using wearable devices such as smart watches, fitness trackers, and payment wristbands are an increasing area of focus for industry participants, and consumer acceptance from early trials and deployments has encouraged some of the biggest names in technology and banking to continue their push to drive growth in this nascent market. Wearable payment systems may utilize near field communication (NFC), radio frequency identification (RFID), or quick response (QR) codes and barcodes...
May. 3, 2016 02:30 PM EDT Reads: 939
Whether your IoT service is connecting cars, homes, appliances, wearable, cameras or other devices, one question hangs in the balance – how do you actually make money from this service? The ability to turn your IoT service into profit requires the ability to create a monetization strategy that is flexible, scalable and working for you in real-time. It must be a transparent, smoothly implemented strategy that all stakeholders – from customers to the board – will be able to understand and comprehe...
May. 3, 2016 12:30 PM EDT Reads: 1,162
You deployed your app with the Bluemix PaaS and it's gaining some serious traction, so it's time to make some tweaks. Did you design your application in a way that it can scale in the cloud? Were you even thinking about the cloud when you built the app? If not, chances are your app is going to break. Check out this webcast to learn various techniques for designing applications that will scale successfully in Bluemix, for the confidence you need to take your apps to the next level and beyond.
May. 3, 2016 12:15 PM EDT Reads: 1,585
SYS-CON Events announced today that Peak 10, Inc., a national IT infrastructure and cloud services provider, will exhibit at SYS-CON's 18th International Cloud Expo®, which will take place on June 7-9, 2016, at the Javits Center in New York City, NY. Peak 10 provides reliable, tailored data center and network services, cloud and managed services. Its solutions are designed to scale and adapt to customers’ changing business needs, enabling them to lower costs, improve performance and focus inter...
May. 3, 2016 12:00 PM EDT Reads: 1,358
So, you bought into the current machine learning craze and went on to collect millions/billions of records from this promising new data source. Now, what do you do with them? Too often, the abundance of data quickly turns into an abundance of problems. How do you extract that "magic essence" from your data without falling into the common pitfalls? In her session at @ThingsExpo, Natalia Ponomareva, Software Engineer at Google, will provide tips on how to be successful in large scale machine lear...
May. 3, 2016 09:45 AM EDT Reads: 1,436
You think you know what’s in your data. But do you? Most organizations are now aware of the business intelligence represented by their data. Data science stands to take this to a level you never thought of – literally. The techniques of data science, when used with the capabilities of Big Data technologies, can make connections you had not yet imagined, helping you discover new insights and ask new questions of your data. In his session at @ThingsExpo, Sarbjit Sarkaria, data science team lead ...
May. 3, 2016 07:00 AM EDT Reads: 1,090
SYS-CON Events announced today that Fusion, a leading provider of cloud services, will exhibit at SYS-CON's 18th International Cloud Expo®, which will take place on June 7-9, 2016, at the Javits Center in New York City, NY. Fusion, a leading provider of integrated cloud solutions to small, medium and large businesses, is the industry's single source for the cloud. Fusion's advanced, proprietary cloud service platform enables the integration of leading edge solutions in the cloud, including cloud...
May. 2, 2016 10:00 AM EDT Reads: 2,686