Friday, November 14, 2014

Interview Questions on Socket Programming

Socket programming is used to make computers exchange data. It is an uncommon topic and not many programmers come across it in their professional career.
This blog post outlines several questions which might be asked from someone in an interview for a position that involves either writing code for network applications or managing a team of people writing network programming code.

The questions listed here are worth reading and knowing the answers to these questions in general means you have a sound top level understanding of computer networks work.

It is possible to learn network programming in only one hour, just take the Udemy course given below,

https://www.udemy.com/tcpip-socket-programming-for-coders-using-csharp-net/#/

1. A host is a machine that is hosting a software capable of communicating over the network. Yes/No?
2. A host is identified by an IP Address which is unique inside a network. Yes/No?
3. In enterprise scenarios, a host name is translated into an IP address by a server called:

  1. DHCP Server
  2. DNS
  3. LDAP Server
4. An IPV 4 IP address is a group of __???__ numbers, each 8 bit in size with a value between 0 to 255.


Demo TCP/IP Sockets Read and Write in C#, Free #Udemy Course, 100% discount from Naeem Akram on Vimeo.

5. We find the IP Address of our computer using a DOS command which is

  1. tracert
  2. ipconfig /all
  3. ipconfig /flushdns
Quick TCP/IP Socket programming for coders is a free course (limited time offer), take the course and learn about socket programming in only one hour.

https://www.udemy.com/tcpip-socket-programming-for-coders-using-csharp-net/#/

6. Every computer contains a finite number of ports which is

  1. 1024
  2. 65536
  3. 99999










7. The client process and the server process must be running on two different machines.
8. A pair of an IP address and a port number is used by the server process to listen for incoming connection requests, this pair is called an __???__

9. A client processes's attempt to connect with a server process can fail for various reasons including


  1. Windows firewall has blocked the client process or server process from using the network.
  2. Server IP address supplied to the client is wrong
  3. The server process is not started at all
  4. All of above


10. Telnet is a free utility, it is always enabled on every PC. Yes/No?
11. We will enable Telnet __???__ from the "Add Remove Programs" dialog "Turn Windows features on or off"

https://www.udemy.com/tcpip-socket-programming-for-coders-using-csharp-net/#/
Only one hour is all you need to know answers of the questions listed here and get loads of more interesting information about computer networks. The course link given above is free for a limited time, it won't cost you anything and you will learn loads of new stuff so just go ahead and sign-up.

Thursday, November 13, 2014

Learn TCP/IP Socket Programming in 1 hour


Demo TCP/IP Sockets Read and Write in C#, Free Udemy Course from Naeem Akram on Vimeo.

Network programming is a very important topic, it is also considered a bit complicated. Most of the tutorials and lessons already available on the internet tend to make this topic even difficult to learn.
This Udemy.com based online course is totally free for first month, and it makes socket programming using C# really easy.

By taking this free Udemy course, you will be ready to write network communication applications within only one hour!

You will learn a lot of other useful things during this course, for example how to find the IP address of your PC using command prompt and how to use telnet utility.
More techniques such as finding an IP address through a host address and selecting the active IPV4 address of your PC automatically will also be covered in this course soon.
I will also add videos about how to handle multiple client nodes and how to add/remove clients from the list of connected ones as well.

I've uploaded same demo video to Youtube as well.



Please join this course, watch it, and provide your highly valued feedback. It will be very helpful for me.

The author is a professional computer programmer with socket and network programming experience in C++ and C# languages on Windows platform, and same in Java language on Android platform as well.

The author loves to blog, which is evident by the posts in this blog which have been written over the course of six years(on time of this writing). On the side, this author has got a very nice kitchen garden on the roof top and loves to cook delicious Pakistani food as well. Most importantly, I'm a proud and loving father of two children as well :)

So please join this course about TCP/IP socket programming using C#.Net. I am sure it will be helpful and you will learn a lot of very useful programming techniques and some really cool theory.

Wednesday, October 15, 2014

Trick SQL Interview Question and team work

I was sitting with friends at our legendary Firdos Market flat 94/H just yesterday. Adeel my brother, told us about a query that an interviewer had asked him to solve. It was dinner time, so we handed the query to Zaheer Chaudhary, who'd eaten a couple of hours ago.

After the dinner, Aweas Dar, Adeel's class fellow (Zaheer is also a class fellow), opened SQL Server and created table structures needed for the operation. The trio I just mentioned graduated in computer science from the University of Gujrat(UoG) in 2012.
All of us sat down and started talking about the query. The problem statement is given below:
subjects-table-design"
Suppose we have two tables, students and subjects. The student's table contains two fields id and name. The subjects table contains three fields: id, std_id, and subject.
students-table-design
When executed, we need a query to produce the result set with columns describing how many courses each student is taking. In a better version of the result set, we will have a student id, student name, and several subjects.
"



Table structures are also given above for reference.
Everybody knew that we would need to do a count on the subject field of the subjects table. So we wrote a couple of queries, poked some jokes at each other, and ultimately achieved the desired result.
Unfortunately, I couldn't save various versions of the query as it evolved.







Aweas also keyed in dummy data rows. Below is a screenshot of student table data and subjects table data.

select-top-students

select-top-subjects

Next, it occurred to us that we will need to use SQL Group By in this situation. The possibility of using a join was ruled out quickly, and finally, the SQL where clause was also needed.
The final SQL query was made even more beautiful by adding an ORDER BY clause. The result of our quick teamwork is the SQL Query given below.

SELECT students.id AS StudentID, students.name AS Students, COUNT(subjects.subject) AS NoOfSubjects
FROM subjects, students WHERE subjects.std_id=students.id GROUP BY students.name, students.id
ORDER BY StudentID

There are small emotional holes that we leave unplugged due to laziness. We could have left the query unsolved and kept thinking about it for a long time. Some of us would even feel guilty that we could not sort it out. This event shows the importance of teamwork and how a cooperative thought process can help us to solve puzzling questions and crack jokes.

Sunday, October 5, 2014

Framework vs IDE

Microsoft Visual Studio 2012 is an IDE(Integrated Development Environment), whereas Microsoft .Net 4.5 is a Platform.
Android is a Framework/Operating System, and Eclipse is an IDE.
I started off with solid examples of framework and IDE since I believe these will facilitate further explanation.
Microsoft Visual Studio 2012

Putting the term IDE in perspective?

It is a group of various tools  which work together to compile a computer program, and create an executable package.
dotnetframework-4

For example, on Windows we have Microsoft Visual Studio in which you can create a project and write some code. You just need to click a button or two and an execute-able file with extension .exe will be generated which you could take to any suitable computer and run.

Another example Android platform, you can write some code in C++ or maybe Java and use an IDE of your choice which might be Eclipse, Android Studio, or any other and click a few buttons, an executable package or .apk will be created for you which you may copy to any suitable Android device, install and run right away.
android-os-logo

Explaining Integrated Development Environment

When we click a button inside an IDE and order it to create a nice package for us, a lot of things happen in the background. For example code of both .Net and Java languages need to be converted into a "byte code" which is then interpreted by the Java Machine/Common Language Runtime. There is a software tool which performs this task.
eclipse-juno-ide

But before going on with the conversion, someone needs to make sure that the code supplied as the brick and mortar of your awesome software is correct or not. Incorrect code cannot be used to generate correct software. You must have guessed it by now, there is a separate tool which performs the job of error checking and compiling.
Yet another tools is the notepad like editor in which you type code, it automatically makes the code look pretty and colorful. This part is called "pretty printer" and it too is a separate tool.
There are numerous other tools, but let's just stop here and imagine that we got only three tools

  1. One that makes the code look pretty as we type it
  2. One that's responsible for making sure that our code is correct
  3. One that makes a software package (.exe or .apk) out of our correct code
All three of these tools need to work together and cooperate, and do their job in an integrated fashion so that you can retain your development job.
When various tools work together in an integrated fashion, we get an integrated environment for development. Just to make things look uglier, an Integrated Development Environment.

visual-studio-code-pretty-printing


Framework Explained
A framework is a set of various software tools and standards which work together and make a computer programmer's job easy. A framework might contain things like
  1. Application Programming Interface (API)
  2. Just in time (JIT) compiler
  3. Virtual machine (JVM/CLR)
  4. Standards for making various language work together e.g. CTS or common type system(C#, F#, C++/CLI)
For a detailed description of framework, examples, and comparison with API please see following article:


I'm working as a full time freelance programmer through ODesk.com, I have a strong profile over there. Feel free to ping me if you need an Android app. Elance widget is given on top right of the page, for ODesk follow the link given below:


https://www.odesk.com/users/~012d73aa92fad47188

Saturday, October 4, 2014

c++ string to char array

C++ standard template library (STL) string A.K.A std::string was a novel concept back in the day when it was first introduced to the programming community with C++ programming language. Now we see every programming language be it Java or C# or Ruby contains an excellent implementation of string. Similarities between the modern string libraries can be traced back to yesteryear's string.h header file.

It is important to note that the std::string classes were actually a wrapper around C style null terminated character pointer string.

c-plus-plus-string-char-array-code

Even the apparently sophisticated(and complicated) BSTR of COM era are just a sequence of characters with some meta data(i.e. length of string).

c++ string to char* code

Since we know every std::string actually contains a char * (read character pointer) buffer in the background, there must be some way to convert C++ string to C style char array. The character arrays are also called zero terminated strings.







The good news is that there is a function in std::string class which lets us retrieve the const char * which is in the background of the string instance. The method is called

c_str

An exact example in code about how to use std::string.c_str() function is given below.

Code C++ string to char * or char array

using namespace std;

#include<string>
#include<iostream>

int main(int argc, char* argv[])
{
 std::string strILoveYou = "i<3U";// new object of std::string

 const char * szMe2 = strILoveYou.c_str();// new object of c style null terminated character pointer

 cout << strILoveYou << endl; 
 cout << szMe2  << endl;

 return 0;
}// code highligting with http://tohtml.com/cpp/


You must have noticed that the const char * retrieved this way is read only. If you want to extract a changeable string out of std::string we'll need to add a couple of lines to the code. We will use the strcpy C function, some might argue that this is not true C++ but I say everything from C is in the genesis of C++ so there's nothing untrue to spirit of C++ if we use functions from the C programming language which is the mother of all languages. The new code will look like

using namespace std;

#include<string>
#include<iostream>

int main(int argc, char* argv[])
{
 std::string strILoveYou = "i<3U";

 const char * szMe2 = strILoveYou.c_str();

 char * notConstantCharPtr = new char[strILoveYou.length()]; 
 strcpy(notConstantCharPtr, strILoveYou.c_str());

 cout << strILoveYou  << endl; 
 cout << szMe2   << endl;
 cout << notConstantCharPtr << endl;

 return 0;
}// highlight with tohtml.com/cpp

HAPPY CODING FELLAS!!!
I hope you found this small programming tutorial to be useful. Please do check my online courses which are listed on the top right of this page.

Thursday, October 2, 2014

C# Nested Switch Statement

Nested Switch C#Net code


private void button1_Click(object sender, EventArgs e)
        {
            switch(textBox1.Text){// outer switch statement c#
                case "1":
                    System.Diagnostics.Debug.Print("1");
                    switch (textBox2.Text)// inner switch statement c#
                    {
                        case "a":
                            System.Diagnostics.Debug.Print("1a");
                            break;
                        case "b":
                            System.Diagnostics.Debug.Print("1b");
                            break;
                        default:
                            System.Diagnostics.Debug.Print("1NA");
                            break;
                    }
                    break;
                case "2":
                    switch (textBox2.Text)// second nested switch statement c#.net
                    {
                        case "a":
                            System.Diagnostics.Debug.Print("2a");
                            break;
                        case "b":
                            System.Diagnostics.Debug.Print("2b");
                            break;
                        default:
                            System.Diagnostics.Debug.Print("2NA");
                            break;
                    }
                    break;
                case "3":
                    switch (textBox2.Text)// third nested switch statement in c#
                    {
                        case "a":
                            System.Diagnostics.Debug.Print("3a");
                            break;
                        case "b":
                            System.Diagnostics.Debug.Print("3b");
                            break;
                        default:
                            System.Diagnostics.Debug.Print("3NA");
                            break;
                    }
                    break;
                default:
                    switch (textBox2.Text)// default section of outer switch statement
                    {
                        case "a":
                            System.Diagnostics.Debug.Print("DEFAULTa");
                            break;
                        case "3b":
                            System.Diagnostics.Debug.Print("DEFAULTb");
                            break;
                        default:
                            System.Diagnostics.Debug.Print("DEFAULTNA");
                            break;
                    }
                    break;
            }
        }

Please note that the same nested switch logic can be reused in C++ and Java languages with a little language specific changes.

Switch statement is a very important programming language construct, appropriate usage can significantly speed up your code.
Keeping the importance of nested switch statement I've decided to put together a quick code example and make it available for the welfare of programmer community.

Example Background:
In case of this C# switch statement example, we have two text boxes and a button placed on a WinForm, when the user puts some text inside the first text box some text in second text box and then clicks the button our switch statement is fired in a button click handler.

The results are being printed using System.Diagnostics.Debug.Print function which cause them to show up in output console.

The user can enter 1, 2, or 3 in first text box and values a, b, or c in second text box. Anything else is handled in nested default sections.




C# .Net nested switch might not be used very commonly, but you never know when you'll run into a problem that's better handled by the gimmick like consumption of the construct. The exact code of a nested switch statement in C# .Net programming language is given at the beginning of this article.


Wednesday, October 1, 2014

C++ char array to string

The c style null terminated arrays might be considered a thing of past by many but as a matter fact these things are still there are used in many many large scale legacy software.\

Just recently I observed that a lot of people are trying to find an easy way to make a string out of a character array in C++ so I thought I should write a post and help the poor souls stuck in dark chambers of C++.

Without any further ado, the C++ code to achieve this extremely difficult task is given below.

char array to string c++

Wednesday, July 23, 2014

iPhone UDID using iTunes

How to find iPhone UDID (Unique Device Identifier using iTunes)

Plug your phone in to your PC/laptop and start iTunes software.

Click on phone icon highlighted in image below, don’t click the eject button
iphone-udid-itunes-graphic1

Another UI screen will be shown as a result of this click, the UI screen looks like following:


Only after a single click, the text label will start displaying the UDID of the phone which is needed for enabling testing on tester devices. 

iphone-udid-itunes-copy-udid


Right click the cryptic looking alpha-numeric string and select copy. Please note that I have distorted the UDID intentionally.
Now you can paste it anywhere and email me, or even get it tattooed on the biceps.

What is a UDID?

The iOS device UDID is added to a provisioning profile, it allows ad-hoc deployment of your apps during testing to the iOS devices of your testers. You would've already guessed that its a unique identifier and no other Apple mobile device will have this identifier on it.

Please note that only 100 iOS devices be it iPhone/iPod/iPad can be added to a single Apple Developer Account.

In case of Android, you can create a development build and send the apk file to any number of people who may deploy it on any number of devices.

Monday, June 2, 2014

How to create PhoneStateReceiver get CLI and call events

During first 5 years of my career I luckily worked at software houses that created computer telephony related software, I had used Microsoft TAPI and Dialogic APIs to create IVR and Operator Console and Call Recorder software. When I first started Android programming in 2010, I was very curious about phone states and CLI. 





I later figured it out and came to know that a BroadcastReceiver will be the right thing to use in
this case. BroadcastReceiver is a specially designed component offered by Android OS, and
it is used to handle various broadcasts sent by apps or OS components.
The broadcasts related to telephone call states are sent by TelephonyManager which is a
component of Android OS.
The phone state receiver given below can be used in scenarios like call blocking, call tracking,
and sending information to http or cloud based servers.
This salient features of my phone state receiver are given below
  1. Get the CLI from an incoming call
  2. Get the dialled number from an outgoing call
  3. When an inbound call is connected, get informed
  4. When a call is disconnected, get notified

Wednesday, May 21, 2014

Incoming SMS Receivers Stop Work Google Hangouts Is Villain

I'm working on an app which notifies a Windows desktop/laptop when a new SMS text message arrives on an Android phone, this app does not do anything else to the text of incoming SMS. It only reads and notifies the laptop using Bluetooth(or WiFi).

My app stopped working all of a sudden, and I didn't know what was wrong. There's a nice blog entry on making your app compatible with Android 4 KitKat, I read it thoroughly but in the end I discovered my will not be affected since it's too benign and only the apps that might cause trouble for other apps.

My sixth sense raised an alarm shortly afterwards, that perhaps this issue is being caused by Google Hangouts. I had allowed Google Hangouts to take care of my SMS messages a few hours ago, without knowing it will screw my poor app.
I got Android 4.3.3 running on Sony Xperia Z smart phone.
Given below are screen shots from Hangouts app settings.

google-hangouts-settingsgoogle-hangouts-settings-subgoogle-hangouts-sms-settings



So, if your SMS receiver stops working all of a sudden do make sure Google Hangouts is not the culprit.
Android KitKat has got its own style of handling SMS messages, but still I don't see a point in why Google Hangouts will break 3rd party apps that need to only read SMS messages.









On a side note, I did think once that maybe this error is caused an up version of Android because my app was working well on my older QMobile A50 which sports Android Jelly Bean 4.1.3.

In case you're wondering what permissions are needed to make a new SMS broadcast receiver work, well I got the following:

<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />

Monday, May 12, 2014

Disconnect Block Drop calls Android 4 and above

The internet is littered with forum posts and articles that tell you it is impossible to block, drop disconnect an incoming or outgoing call using code starting Android version 4 Jelly Bean because Google placed strict restrictions on MODIFY_PHONE_STATE permission. Only the manufacturer signing certificate can grant you MODIFY_PHONE_STATE permission.
block drop disconnect call android

Please check my Udemy course:

There are a lot of call blocker types scenarios in which we need to shield our user from a bad guy's or sour ex-girlfriend's telephone calls.
The good news is that you don't need MODIFY_PHONE_STATE permission to block, drop disconnect an incoming call on Google Android. The technique described here is available to drop block disconnect incoming calls without using the secretive infamous permission.

Time to disclose the secret sauce. A hint first:
Ever tried to dial a call using ADB(Android Debugger Bridge) shell?

If you've done that, it will be straightforward to disconnect or drop a call using a similar technique.
Time to spill the secret sauce on the internet.

Drop call on Android 4 Jelly Bean KitKat and above.


Friday, May 2, 2014

Android Package Name From APK Java Code Sample

apk-icon
public String getPackageNameByAPK(String _strAPKPath, Context _activityORservice)

Java Source Code
The Java language source code with android.content.pm.PackageManager to get the package name from a .apk file is shown in this post for online learning purposes.

Android apps are supplied in .apk files(even if you download from the Play store) which contain all information needed to install an app on an Android smartphone.
Once an app is installed on the phone it is identified by a unique package name; the package name format is:

  1. com.usrax.ca
  2. com.honestitconsultancy.patric
  3. mysymphony.pmi.com


This value is taken from the Manifest.xml file which is already present inside the .apk file of an Android application(app).

If we search "get package name from .apk" on Google we won't be able to find the source code to do this on the first page; almost everyone tries to tell us that this will be done through the command line.

This post will answer the following question:
Android, get the package name from apk file in your program

Package Archive files

There is a little twist behind these search results, is there another name for .apk files?
Yes sir, the full name of .apk files is "Package Archive". You can say that's the legal name .apk is only a nickname used by the Linux OS (Android is a Linux) and developer community.

Thursday, February 6, 2014

GROUP BY Date Time, Day, Month, Year, calculate SUM function in SQLite for app developers


SELECT strftime('%m', trxDateTime) as valMonth, 
SUM(trxAmount) as valTotalMonth 
FROM trx_log 
WHERE strftime('%Y', trxDateTime)='2014' GROUP BY valMonth

Given above is the query, which will be explained in the blog below; continue reading for further details.

SQLite GROUP BY Day, Month, Year and sum query example

I have a database table that contains a few fields like transaction date, which is a string representing date time, transaction amount, and transaction status in an SQLite database present on an Android device. The SQL Lite database contains a table named "trx_log" The table has fields _id int, trxDateTime text, trxTargetNumber text, trxAmount number, and trxStatus text. A graphical representation of the table structure is given below:

sqlite-android-search-by-year-group-by-month

SQLite Table used in the example of GROUP BY date, time, month, year, and SUM function.

SQLite Query Sum and Group By Year

How to calculate the sum of all transactions that took place in 2014? What is the SQLite query for the group by results by year and calculating a sum? We will combine SQLite aggregate function SUM with GROUP BY Clause.

SELECT strftime('%Y', trxDateTime) as valYear, SUM(trxAmount) 
FROM trx_log WHERE valYear = '2014' GROUP BY valYear