Bartek posted an article today as part of a series of his work modernizing/refactoring a legacy C++ project. His series of articles takes an old C++ application and brings it up-to-date.
In the article, Bartek covers the following techniques:
Having the latest Compiler and correct C++ Standard version
Bartlomiej Filipek (Bartek) is a software developer in Krakow Poland. He works at Xara as a C++ developer. Bartek is a Microsoft MVP and author of two C++ books:
C++17 in Detail: Learn the Exciting Features of The New C++ Standard! (paperback version available on Amazon)
C++ Lambda Story: Everything you need to know about Lambda Expressions in Modern C++! (Kindle version available on Amazon)
I have many favorite prebuilt components that are included with C++Builder10.4 Sydney. In this blog post I’ll show you how to create an RSS Feeds VCL (you can also use the same approach for a FireMonkey FMX) application using the XMLDocument, NetHTTPClient, NetHTTPRequest and WebBrowser components.
Start by creating a C++Builder VCL application. Set the form’s WindowState property to wsMaximized. Add a Panel, Button, ListBox (used to hold the list of RSS feed URLs to process) and a few labels and align them to the top of the form. Add Memo (to display the Feed XML), ListBox (to contain the title and URL for each article found in the feeds) and WebBrowser (to display the web page when you click on an item in the articles list box) components to the rest of the form.
To populate the Panel’s listbox, I use a text file, “FeedsList.txt”, which contains a number of RSS feed URLs. The panel listbox is populated in the Form’s OnShow event handler.
Clicking on the button will process all of the RSS feed URLs and add each article and URL item found into the list box of articles found.
The XMLDocument component has a DOMVendor property to select the DOM implementation to use for parsing and manipulating the XML document.
Clicking on an item in the articles list box uses the OnClick event handler to call the WebBrowser Navigate method for the selected article URL. In C++Builder 10.4 Sydney there is a new property added to the WebBrowser component that lets you choose which browser engine will be used on Windows. I’ve chosen the EdgeIfAvailable engine.
Finally here is the source code for the application:
//---------------------------------------------------------------------------
#include <vcl.h>
#include <fstream>
#pragma hdrstop
#include "MainFeedUnit.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm2 *Form2;
//---------------------------------------------------------------------------
__fastcall TForm2::TForm2(TComponent* Owner)
: TForm(Owner)
{
}
//---------------------------------------------------------------------------
void __fastcall TForm2::ArticlesFoundListBoxClick(TObject *Sender)
{
// for the ListBox item clicked - get the URL and Browse to the article
LabelStatus->Caption = ArticlesFoundListBox->Items->Names[ArticlesFoundListBox->ItemIndex];
ArticleWebBrowser->Navigate(ArticlesFoundListBox->Items->Values[ArticlesFoundListBox->Items->Names[ArticlesFoundListBox->ItemIndex]]);
}
//---------------------------------------------------------------------------
void __fastcall TForm2::Button1Click(TObject *Sender)
{
// Find and save Title and URL for items found
std::ofstream fs (AnsiString(FormatDateTime("yyyy-mm-dd-hhnnss",Now())+"_RSSFound.txt").c_str());
fs << AnsiString("RSS Feed for: "+ NetHTTPRequest1->URL).c_str() << std::endl;
fs << AnsiString(FormatDateTime("dddd mmmm dd, yyyy @ hh:nn:ss",Now())).c_str() << std::endl;
fs << std::endl;
// Clear the Articles Found List Box to prepare for the title and URL of articles
ArticlesFoundListBox->Clear();
FeedsItemsCountLabel->Caption = "Items Found = 0";
// get all articles and URLs in all feeds
for (int i = 0; i < FeedsListBox->Count; i++) {
// Get the RSS feed URL string from the ListBox
NetHTTPRequest1->URL = FeedsListBox->Items->Strings[i];
UrlLabel->Caption = "Feed URL: "+NetHTTPRequest1->URL;
UrlLabel->Update();
// Use NetHTTPRequest Execute method to get the RSS Feed XML
UnicodeString FeedString = NetHTTPRequest1->Execute()->ContentAsString();
// copy the XML string to the Memo
MemoFeedXML->Lines->Clear();
MemoFeedXML->Lines->Text = FeedString;
MemoFeedXML->Update();
// load the RSS Feed XML into the XMLDocument
XMLDocument1->LoadFromXML(FeedString);
XMLDocument1->Active = True;
LabelStatus->Caption = "Processing RSS for "+NetHTTPRequest1->URL;
LabelStatus->Update();
// find the RSS feed channel node
_di_IXMLNode ChannelNode = XMLDocument1->DocumentElement->ChildNodes->FindNode ("channel");
// test to make sure the ChannelNote is found
if (ChannelNode != NULL) {
for (int I=0;I<ChannelNode->ChildNodes->Count;I++) {
// iterate through child nodes
_di_IXMLNode ItemNode = ChannelNode->ChildNodes->Get(I);
// if child node is an item then get the title, pubDate and URL
if (ItemNode->NodeName == "item") {
LabelStatus->Caption = "Processing Node " + IntToStr(I);
LabelStatus->Update();
UnicodeString title = ItemNode->ChildValues ["title"];
UnicodeString pubDate = ItemNode->ChildValues ["pubDate"];
// author := ItemNode.ChildValues ['author']; // could be nil
UnicodeString url = ItemNode->ChildValues ["link"];
// populate the articles found ListBox with the pair of title and URL
ArticlesFoundListBox->Items->AddPair(title,url);
ArticlesFoundListBox->Update();
FeedsItemsCountLabel->Caption = "Items Found = "+IntToStr(ArticlesFoundListBox->Count);
FeedsItemsCountLabel->Update();
// write the Title, pubDate and URL to the text file
fs << AnsiString(title).c_str() << std::endl;
fs << AnsiString(pubDate).c_str() << std::endl;
fs << AnsiString(url).c_str() << std::endl;
fs << std::endl;
}
}
}
}
fs << std::endl;
fs << AnsiString("Items Found = "+IntToStr(ArticlesFoundListBox->Count)).c_str() << std::endl;
fs << "end of file" << std::endl;
fs.close(); // close the text file
LabelStatus->Caption = "RSS Processing Done!";
UrlLabel->Caption = "";
}
//---------------------------------------------------------------------------
void __fastcall TForm2::FormShow(TObject *Sender)
{
// load RSS Feeds ListBox with the "FeedsList.txt" text file
// I put the text file in the same folder as the app .EXE file
FeedsListBox->Items->Clear();
FeedsListBox->Items->LoadFromFile("FeedsList.txt");
LabelStatus->Caption = "RSS Feed Urls Loaded = "+IntToStr(FeedsListBox->Count);
LabelStatus->Update();
}
//---------------------------------------------------------------------------
C++Builder Product Page – Native Apps that Perform. Build Windows C++ Apps 10x Faster with Less Code C++Builder Product Editions – C++Builder is available in four editions – Professional, Enterprise, Architect and Community (free). C++Builder is also available as part of the RAD Studio development suite.
Here are a few technology news stories that I’ve read in the past week or so.
Code Partners Acquires SmartInspect from Idera/Gurock
SmartInspect is an advanced .NET logging, Java logging, and Delphi logging tool for debugging and monitoring software applications. It helps customers identify bugs, find solutions to user-reported issues, and gives a precise picture of how software performs in different environments. Read the article by Code Partners. Read the official announcement by Idera/Gurock.
Bill Gates says tech companies ‘deserve rude, unfair, tough questions’
Bill Gates believes tech firms “deserve” the kind of scrutiny they got during Congressional hearings last month. “If you’re as successful as I am or any of those people are, you deserve rude, unfair, tough questions,” the Microsoft founder told host Dax Shepard. “The government deserves to have shots at you,” Gates said. “That type of grilling comes with the super successful territory. It’s fine.” Read the Verge Article.
Scientists use artificial intelligence in new way to strengthen power grid resiliency
At the U.S. Department of Energy’s (DOE) Argonne National Laboratory a research team has developed a novel approach to help system operators understand how to better control power systems with the help of artificial intelligence. Their new approach could help operators control power systems in a more effective way, which could enhance the resilience of America’s power grid, according to a recent article in IEEE Transactions on Power Systems. Read the TechXplore Article.
FBI, CISA Echo Warnings on ‘Vishing’ Threat
“The COVID-19 pandemic has resulted in a mass shift to working from home, resulting in increased use of corporate virtual private networks (VPNs) and elimination of in-person verification,” the alert reads. “In mid-July 2020, cybercriminals started a vishing campaign—gaining access to employee tools at multiple companies with indiscriminate targeting — with the end goal of monetizing the access.” Read the Krebs on Security Article.
How Shopify Reduced Storefront Response Times with a Rewrite
In January 2019, Shopify set out to rewrite the critical software that powers all online storefronts on Shopify’s platform to offer the fastest online shopping experience possible, entirely from scratch and without downtime. Read the Shopify Engineering Blog Article.
Blockchain pet adoptions
Blockchain technology is not limited to cryptocurrencies. There are many other applications that might benefit from such as secure information system. Writing in the International Journal of Blockchains and Cryptocurrencies, a team from India explain how a blockchain might be used in pet adoption. Read the TechXplore Article.
Open source has a people problem
Open source sustainability is really a people problem. Or, as Langel highlights, “In open source, the maintainers working on the source code are the scarce resource that needs to be protected and nurtured.” Read the InfoWorld Article.
Fortnite battle escalates: Apple to terminate developer program membership, Epic files injunction
Epic attempted to lure users to use the new payment system by offering discounts of up to 20% on virtual purchases including the in-game currency V-Bucks on both iOS and Android. Both Google and Apple demand a 30% cut, and once the bypass was introduced, Fornite was removed from both Google Play and Apple’s App Store. Lawsuits have been launched against both tech giants. Epic deems the commission rate as “oppressive” and despite trying to use the massive Fortnite customer base as leverage — alongside some rather intense public mockery — the row now has the potential to severely impact iOS developers. Read the ZDNet Article.
How to disagree with your boss without losing your cool… or job
It doesn’t have to be this way though. You can totally express your opinion to your boss or manager without losing your cool. This post contains some of the scenarios where speaking up would be justified. Read the TNW Article.
Engineers set new world record internet speed
Working with two companies, Xtera and KDDI Research, the research team led by Dr. Lidia Galdino (UCL Electronic & Electrical Engineering), achieved a data transmission rate of 178 terabits a second (178,000,000 megabits a second) – a speed at which it would be possible to download the entire Netflix library in less than a second. Read the TechXplore Article.
Roberto V. Zicari interviewed Bjarne Stroustrup, the inventor of C++ programming language, back in 2007. Roberto again interviews Bjarne 13 years later.
In the interview, Bjarne talks about notable computer scientists that influenced his career and work. Bjarne also talks about why he designed the C++ language and why he started with the C language. Bjarne also talks about three guiding principles for the design of the C++ language: “Make the language simpler! Add these two essential features now!! Don’t break (any of) my code!!!”
ODBMS.ORG is designed to meet the fast-growing need for resources focusing on AI, Big Data, Data Science, Analytical Data Platforms, Scalable Cloud platforms, NewSQL databases, NoSQL datastores, In-Memory Databases, and new approaches to concurrency control.
About Roberto Zicari
Roberto is Full Professor of Database and Information Systems at Frankfurt University. He was for over 15 years the representative of the OMG in Europe. Previously, Roberto served as associate professor at Politecnico di Milano, Italy; Visiting scientist at IBM Almaden Research Center, USA, the University of California at Berkeley, USA; Visiting professor at EPFL in Lausanne, Switzerland, the National University of Mexico City, Mexico and the Copenhagen Business School, Danemark.
About Bjarne Stroustrup
Bjarne is a Technical Fellow and a Managing Director in the technology division of Morgan Stanley in New York City and a Visiting Professor in Computer Science at Columbia University. Bjarne designed and implemented the C++ programming language. To make C++ a stable and up-to-date base for real-world software development, Bjarne says “I have stuck with its ISO standards effort for almost 30 years (so far).”
One of my favorite RTL features for the VCL and FMX frameworks is the ability to customize the look and feel of your applications using Styles. The first step is to create a C++Builder VCL project and select a few of the VCL Styles in the Project | Options | Application | Appearance settings. The C++Builder 10.4 Sydney DocWiki explains that “the VCL Styles architecture has been significantly extended to support High-DPI graphics and 4K monitors. In 10.4 Sydney all graphical elements are automatically scaled for the proper resolution of the monitor the element is displayed on. This means that the scaling depends on the DPI resolution of the target computer or the current monitor, in case of multi-monitor systems.”
The C++ Application User Interface
For the application user interface I have a TButton (has code to populate the ComboBox with selected application styles) and a TComboBox (to display and allow selection of a style).
The C++ code
//---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
#include "Unit1.h"
#include <Vcl.Themes.hpp>
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
// populate the ComboBox with VCL styles that are selected
// in Project | Options | Application | Appearance
ComboBox1->Items->BeginUpdate();
try
{
ComboBox1->Items->Clear();
DynamicArray<String> styleNames = Vcl::Themes::TStyleManager::StyleNames;
for(int i = 0; i < styleNames.Length; ++i)
{
String styleName = styleNames[i];
ComboBox1->Items->Add(styleName);
}
}
__finally
{
ComboBox1->Items->EndUpdate();
}
}
//---------------------------------------------------------------------------
void __fastcall TForm1::ComboBox1Change(TObject *Sender)
{
// set the style for the selected combobox item
Vcl::Themes::TStyleManager::TrySetStyle(ComboBox1->Items->Strings[ComboBox1->ItemIndex],false);
}
//---------------------------------------------------------------------------
The Application in Action
TComboBox populated with VCL styles selectedApplication Style Changed by TComboBox selection
C++Builder Product Page – Native Apps that Perform. Build Windows C++ Apps 10x Faster with Less Code C++Builder Product Editions – C++Builder is available in four editions – Professional, Enterprise, Architect and Community (free). C++Builder is also available as part of the RAD Studio development suite.
The Parallel Programming Library (PPL) is one of my favorite features in C++Builder runtime library. PPL allows developers to create tasks that run in parallel to take advantage of multi-core processors.
Using the PPL, you can: 1) speed up loops with a Parallel For, 2) run multiple tasks in parallel using TTask, and 3) use Future Objects to allow a process run with your program focused on other work until the future value is set.
To showcase the TTask feature of the PPL, I’ve created a C++Builder VCL application (build and tested using the C++Builder 10.4 Sydney release) that runs three sort algorithms in separate tasks – Bubble Sort, Shell Sort and the ISO C++ standard Sort (which implements the Quicksort algorithm).
The User Interface
The VCL user interface for my application includes a TButton, two TMemos, and four TLabels. The TButton onClick event handler creates a vector of integers, creates three TTasks (for the sort algorithms) and waits for the sort tasks to complete using the TTask::WaitForAll method.
C++Builder Product Page – Native Apps that Perform. Build Windows C++ Apps 10x Faster with Less Code C++Builder Product Editions – C++Builder is available in four editions – Professional, Enterprise, Architect and Community (free). C++Builder is also available as part of the RAD Studio development suite.