Thursday 4 February 2016

Model View Control (MVC) pattern usage in C++

MVC (Model-View-Controller) pattern is often used in Web based applications, where "View" is your actual HTML content displayed on browser, where as "Controller" is the code that gather dynamic data and generates content within the HTML. Finally, "Model" talks about actual content, probably stored in DataBase or XML, and your business rules transform these contents based on user actions.
As I mentioned, MVC is most widely used in web based applications, but some how I liked this pattern and tried using it in my C++ application.
Scenario is, I have a module in C++ which generates set of System Information, and displays them to user. Since, they are system information, they keep change, and I have to update at view the same. Hope you understood.

Since I cannot get you what I wrote in my module, but I can surely show you a sample code, (the code is simple and self explanatory)

/* * * * * * * * * * * * * * *
* File       : mvc-class.cpp
* Author     : Kiran Puranik
* Copyrights : no copy rights :)
*
* * * * * * * * * * * * * * */

#include <iostream>

using namespace std;

/* Model class */
class SystemInfoModel {
   
private:
    string m_InfoName;
    string m_InfoValue;
   
public:
    string Get_InfoName (void) {
        return m_InfoName;
    }
   
    string Get_InfoValue (void) {
        return m_InfoValue;
    }
   
    void Set_InfoName (string info_name) {
        if (!info_name.empty()) {
            m_InfoName = info_name;
        }
    }
   
    void Set_InfoValue (string info_val) {
        if (!info_val.empty()) {
            m_InfoValue = info_val;
        }
    }
};

/* View class */
class SystemInfoView {

public:
    void Print_SystemInfo (string name, string val) {
        cout << "|---------------------------------|" << endl;
        cout << "|    System Info    |    Value    |" << endl;
        cout << "|---------------------------------|" << endl;
        cout << "|   " << name << "    |   " << val << "   |" << endl;
    }
};

/* Controller class*/
class SystemInfoController {

private:
    SystemInfoModel m_SysModel; //\ reference for Model and View
    SystemInfoView  m_SysView;  ///
   
public:
    /* CTR */
    SystemInfoController (SystemInfoModel si_model, SystemInfoView si_view) {
        m_SysModel = si_model;
        m_SysView  = si_view;
    }
   
    /* User control APIs */
    void Set_SystemInfo_Name (string si_name) {
        if (!si_name.empty()) {
            m_SysModel.Set_InfoName (si_name);
        }
    }
   
    void Set_SystemInfo_Value (string si_val) {
        if (!si_val.empty()) {
            m_SysModel.Set_InfoValue (si_val);
        }
    }
   
    string Get_SystemInfo_Name (void) {
        return m_SysModel.Get_InfoName();
    }
   
    string Get_SystemInfo_Value (void) {
        return m_SysModel.Get_InfoValue();
    }
   
    /* Now, bind the Model with View */
    void Update_System_Info (void) {
        m_SysView.Print_SystemInfo (m_SysModel.Get_InfoName(), m_SysModel.Get_InfoValue());
    }
};

/* Now, usage part of it ----------- */
int main ()
{
    // system info model instatiation
    SystemInfoModel siModel;
    siModel.Set_InfoName ("Memory Usage"); // looks dirty isn't it. But usually they are
    siModel.Set_InfoValue ("1024 KB");   //
fetched from system units/or other utilities
   
    // system info view instatiation
    SystemInfoView  siView;
   
    // now, the controller
    SystemInfoController siControl (siModel, siView);
   
    // let's display the content now
    siControl.Update_System_Info ();
   
    // now, the system info has changed, value is different
    siControl.Set_SystemInfo_Value ("2048 KB");
   
    // and display updated content
    siControl.Update_System_Info ();
   
    // isn't it a great pattern !!!!
   
    return 0;
}



Tuesday 2 February 2016

Create your own "offline" repository for apt-get

It's a nightmare, if you do not have connected to internet for your Debian/Ubuntu machine. I use to struggle to install dependent packages after first installation of my Debian. Untill I connect to internet I cannot install packages and untill I install relevant packages I am no way on internet.
I have found an alternative, where I get offline debian package collection in one of my directory and I will do #apt-get install from there. Let me list how to do that in 3 steps.

Step 1: Collect all available DEB files:
1. Your Debian/Ubuntu distribution DVD might have come with deb installer distribution. Check your cdrom, for .../pool/main/ directory, and if it has deb files, then 'hola', copy them into your local directory.
2. You will definitely get download deb packages from cyber cafe and get them in thumb-drive and copy them to your local machine.
3. Check "/var/cache/apt/archives" in a Debian/Ubuntu machine, (may be your friend's), which has all the packages pre-installed. If it is not cleared/deleted, you will get them all in one place.

So, by now I have deb files copied in my local machine and I kept them in /opt/deb-packages/ location.

Step 2: Create a list:
Goto /opt/deb-packages/ directory and run below command,

#dpkg-scanpackages .  /dev/null  |  gzip -9c > Packages.gz

This shall take some time, give yourself a break.

Step 3: Now, add sources list:
Open sources.list file from /etc/apt
#gedit  /etc/apt/sources.list

and, add below line at the bottom of file,
deb  file:/opt/deb-packages/  ./

That's it. You are ready to install your packages.

Run, #apt-get  update
and let it update all list.

Enjoy running #apt-get install <your-package-name>
and see your package getting installed offline.

Wednesday 23 October 2013

Qt with MAC OS-X - 4 simple points to know

I have been working on Qt for Mac OS-X and found it is quite different compare to Windows or Linux.
Mac is a very vast on its own and introduces many levels of security for user safety.
Let's have a look into 4 basic points about Qt in Mac OS-X.

I have used MacBook Pro, with OS X 10.8.4 and Qt version of 4.8

> Point 1 <
Qt installer comes as .DMG files, stands for Disk Image files. A DMG file is like a virtual DVD or hard drive. They can be “mounted” on your Mac in order to work with their contents, or even burned to an actual physical disc.
Right click on DMG file and chose "Open Wint > DiskImageMounter.app" or double click on DMG it should auto mount using DiskImageMounter, if it's your default image mounter application in Mac. Once the image is mounted, it is very easy to install Qt file from image.

> Point 2 <
Where all Qt gets installed in Mac?
This is little tough to explain. When I installed my Qt version 4.8.4, it got installed into many directories.
However, after installation, for qmake-query, I found this results,
QT_INSTALL_PREFIX:/
QT_INSTALL_DATA:/usr/local/Qt4.8
QT_INSTALL_DOCS:/Developer/Documentation/Qt
QT_INSTALL_HEADERS:/usr/include
QT_INSTALL_LIBS:/Library/Frameworks
QT_INSTALL_BINS:/Developer/Tools/Qt
QT_INSTALL_PLUGINS:/Developer/Applications/Qt/plugins
QT_INSTALL_IMPORTS:/Developer/Applications/Qt/imports
QT_INSTALL_TRANSLATIONS:/Developer/Applications/Qt/translations
QT_INSTALL_CONFIGURATION:/Library/Preferences/Qt
QT_INSTALL_EXAMPLES:/Developer/Examples/Qt/
QT_INSTALL_DEMOS:/Developer/Examples/Qt/Demos
QMAKE_MKSPECS:/usr/local/Qt4.8/mkspecs
QT_VERSION:4.8.4

Still it is difficult to say where all it got installed :)

> Point 3 <
How to deploy Qt application in Mac?
It is quite easy to deploy Qt applications in Mac, when it is dynamically built. Mac applications will have executable extension .APP. This .APP file is a special type of container [in other word folder] which will going to hold all Qt dependencies inside, for application to launch. Great thing is, the main executable will also be inside APP directory, here in this location,
MyDemo.app/Contents/MacOS/MyDemo
Let's build and deploy .app for MyDemo application.
Once you are able to successfully compile Qt application, Qt creates executable for your convenience.
If in case it is not created, just run below command,
sh-3.2# otool -L MyDemo.app/Contents/MacOS/MyDemo
After above step is done, we need to use a tool called install_name_tool.
Let's run these build scripts,
sh-3.2# mkdir -p MyDemo.app/Contents/Frameworks
sh-3.2# cp -R /Library/Frameworks/QtCore.framework  MyDemo.app/Contents/Frameworks
sh-3.2# cp -R /Library/Frameworks/QtGui.framework  MyDemo.app/Contents/Frameworks
Above two lines copy frameworks dynamic libraries into app Contents/Frameworks directory.
After copying Qt library into the bundle, we must update both the library and the executable so that they know where they can be found. This is where the install_name_tool command-line tool comes in handy. For the Qt library, run these two lines,
sh-3.2# install_name_tool  -id  @executable_path/../Frameworks/QtCore.framework/Version/4/QtCore  MyDemo.app/Contents/Frameworks/QtCore.framework/Version/4/QtCore
sh-3.2# install_name_tool  -id  @executable_path/../Frameworks/QtGui.framework/Version/4/QtGui  MyDemo.app/Contents/Frameworks/QtGui.framework/Version/4/QtGui
And for the executable,
sh-3.2# install_name_tool -change @executable_path/../Frameworks/QtCore.framework/Version/4/QtCore  MyDemo.app/Contents/MacOS/MyDemo
sh-3.2# install_name_tool -change @executable_path/../Frameworks/QtGui.framework/Version/4/QtGui  MyDemo.app/Contents/MacOS/MyDemo
Now that your application is ready to deploy. Just give MyDemo.app files as executable.

> Point 4 <
How to Un-Install Qt from Mac?
This is also a tough to explain. But I did below steps to un-install Qt from my MacBook.
For all below steps to execute, you must be super-user.
sh-3.2# cd  /Applications/
sh-3.2# rm  -r  QtCreater.app/*
sh-3.2# rm  -r  QtCreater.app
sh-3.2# cd  /Library/Frameworks/
sh-3.2# rm  -r  Qt*
sh-3.2# cd  ~/Library/Preferences/
sh-3.2# rm  com.qt*
sh-3.2# rm  org.qt*
sh-3.2# cd  /usr/local/
sh-3.2# rm  -r  Qt*
After all above steps, now run Qt un-installer located in /Developer/Tools/
sh-3.2# cd  /Developer/Tools/
sh-3.2# ./uninstall-qt.py
This, hopefully, will going to un-install Qt successfully from your Mac Book.

Friday 4 October 2013

Zip and Unzip with ZLib in Windows

Hi friends,
This is a quick post on 'How to use ZLIB for Zippinga and Unzipping archives in Windows'.
Nothing much to do, it's all ready available in ZLIB source. You just need to download and compile it. That's all.

I have used below configuration for my compilation:
[*] OS Type : Windows 7, 64-Bit
[*] Visual Studio 2010, Command line Compiler for 64-Bit


Before we begin, I will introduce you what's is there in ZLIB bundled.
ZLIB is a software library used for data compression. zlib was written by Jean-Loup Gailly and Mark Adler and is an abstraction of the DEFLATE compression algorithm used in their gzip file compression program. zlib is also a crucial component of many software platforms including Linux, Mac OS X, and iOS. It has also been used in gaming consoles such as the PlayStation 3, Wii, and Xbox 360.
The first public version of zlib, 0.9, was released on 1 May 1995 and was originally intended for use with the libpng image library. It is free software, distributed under the zlib license.

But ZLIB by itself doesn't support Zipping and Unzipping of archives, files and folders [refer FAQs]. It can handle only data compression. So, we need an external application to handle files and folders zipping and unzipping activity.

Fortunately, there is a package integrated inside ZLIB itself, called MiniZip, which handles all kind of archives. This comes part of ZLIB source now a days. [refer MiniZip].

So, basically, in this post, we will going to compile MiniZip source for Windows, coming with ZLIB source code.

Well let's start then.
At the time of writing this post, ZLIB latest version was zlib1.2.5.
Download ZLIB source code form >> here << or from >> here << [please inform me if link is broken]

For our compilation, we basically don't need ZLIB source code. So I will use pre-compiled ZLIB static library for my work. Download pre-compiled ZLIB libraries from >> here <<. This contains, Windows specific ZLIB DLLs and LIBs for both 64-bit and 32-bit compilation.

Unzip and keep both the directories in a common folder [for e.g, C:\TEST\zlib1.2.5 and C:\TEST\zlib125dll]

I have written a Makefile for windows 64-bit compilation. Please refer it. Download it and copy it into "C:\TEST\zlib1.2.5\contrib\minizip\" directory. The Makefile already present in minizip directory will support Linux only. So you can either keep a back-up of old Makefile or replace it with the one I have given you.

Inside minizip directory, you must find below source files,
ioapi.c, iowin32.c, zip.c, unzip.c, miniunz.c, minizip.c and corresponding header files.
minizip.c and miniunz.c are main source files for Zipping and Unzipping demo.
Open all the source files and header files, if you see below include at the top,
#include "zlib.h"
replace it with
#include "..\..\zlib.h"
as our main zlib source is two directory below the hierarchy.

Now, open "Visual Studio 2010 x64 Win64 Command Prompt" and navigate to "C:\TEST\zlib1.2.5\contrib\minizip\" directory and type command,

 nmake all
If everything goes fine, and if you have followed all the steps from above properly, it should compile perfectly and should yield 2 binaries "MyMiniZip.exe" and "MyMiniUnZip.exe"

Now it's time to test binaries,
[>] To zip any files, use MyMiniZip.exe
MyMiniZip.exe  <output_file_name.zip>  <input_file1>  <input_file2>...<input_fileN>


for e.g,(I hope no explanation is required)
MyMiniZip.exe  test_file.zip  file1.txt  file2.jpg  subDir\file3.png  C:\MyDir\file4.doc


[>] To UnZip any zipped files, use MyMiniUnzip.exe
MyMiniUnZip.exe  <input_file_name.zip>

for e.g,
MyMiniUnZip.exe  C:\MyDir\MyTestArchive.zip

[>] To list all the files inside a zipped files use MyMiniUnZip.exe with -l flag
MyMiniUnZip.exe -l <input_file_name.zip> 

I hope everything went good at your side. Enjoy. :)

Tuesday 23 April 2013

Why C++ compilation takes more time

C++ is one of the strong programming language, I believe. But people complain saying it takes long time to compile even a small piece of code compare to other competitors like C# or Java. The answer is Yes. 
Straight away we can think of one basic reason for this, the pre-processor directives, which gives instructions to compiler to pre-process the information before the actual compilation starts, and I should not miss, #include is also one among that pre-processor directives. But in reality, this is not only the reason. I was going through the whole compilation process and did surfing through Google and found below points,

One - Load and Compile Header: In C++ every single unit of compilation needs, may be hundreds of headers to be Loaded and Compiled each time. Everyone of them typically has to be re-compiled for every single compilation unit. This is because, compiler thinks the result of compiling header may vary for every other unit, such like, a macro defined in one of the compilation unit may cause change in contents of header included for another compilation unit. So, the process has to be re-carried out for each and every single unit. This, probably could be main reason for C++ compiler to consume more time on compilation.
On the other hand, languages like Java or C# if you compare, they don't have to include headers, they can depend on binaries from the compilation of the used classes. This means, if object X is used in abc.java file, to get it compiled, it is enough for compiler to check binaries of X.class, it doesn't require to go deeper check looking for dependencies of X.class.

Two - Templates: In C# like languages, List<T> is the only type that is compiled, irrespective of type 'T' and irrespective of how many instantiation of List you have in program. On the other hand, C++ compiler behaves differently. For C++, vector<int> and vector<float> are entirely different entities to handle and each one needs to be re-compiled on each time.
Add to this, templates makes a full Turing-Complete "sub-language" that the compiler has to interpret with, and this can become ridiculously complicated. Even relatively simple template meta programming code can define recursive templates that create dozens and dozens of templates of instantiations. However, it is likely that templates may result in extremely complex types, with ridiculously long names, adding a lot of extra work to the linker. (It has to compare a lot of symbol names, and if these names can grow into many thousand characters, that can become fairly expensive).

Three - Linking: Once all units are compiled, all the object files need to be linked together. This is the process of monolithic linking and cannot be parallelized. So compiler has to process whole project.

Four - Optimization: C++ really allows very peculiar way of optimization. This whole optimazation process is a compiler dependent and may vary with different techniques. If you compare other programming languages like C# or Java, they don't allow complete optimization to happen on program, they don't allow complete elimination of class to happen, because of their feature 'reflection' [Reflection is used to describe a code which is able to inspect another piece of code]. But, even a simple C++ template metaprogram can easily generate dozens or hundreds of classes, all of which are inlined and eliminated again in the optimization phase. And again, for C++, it doesn't get second chance and compiler has to do optimization on compilation time only, compared with C# program which can rely on the JIT compiler to perform additional optimizations at load-time.

Five - Parsing: The C++ syntax is extremely complicated to parse, as it depends heavily on context, and is very hard to disambiguate. This takes a lot of time in compilation.

However, most of the above factors are shared by C program also, which compiles fairly and efficiently. Only offender I can see is 'Templates' in C++. Templates are useful, and make C++ a far more powerful language, but they also take their toll in terms of compilation speed.