Programming in modern C++ with C++ 11

If you are following C++ lately you might have herd of C++ 11. C++ 11 is new revision to C++ standard approved in 2011. It offers significant improvements in both the language and the library. It include features such lambda functions/expression, range based for loop, uniform initialization, automatic type deduction, variadic templates and many more.
On the library side changes include regular expressions, atomic operations, threading (futures and promises), and tuples. Even though some of these feature exits for while in boost library now it is part of C++ standard hence it will be available from all compiler vendors (GCC,VC++ and CLANG).

With these improvements , programming in C++ 11 is as easy as in Java or C#.

In this blog post I will cover some of features I have explored in C++11.

1. Automatic Type deduction with ‘auto’

With C++ 11 , you can declare variable or object without specifying its specific type by using ‘auto’ keyword. This is especially useful if you are working with templates or lambda functions where actual type can be hard to write but compiler can infer from the expression. This feature is similar to c# var keyword

auto count  = 10; // compiler infer count type has int

vector wordCount = { 10,20,30,40 };

auto pos = wordCount.begin() ; //  compiler infer pos has vector::iteraror type.

// compiler infer the squareFunction is lambda function with integer input and integer return type.
auto squareFunction = [] (int x) -> int
                      { return x*x; };

// other example is iterating over any C++ containers using ranged based for loop
for(auto wordC : wordCount )
{
   cout<<wordC<<endl;

   cout<<squareFunction(wordC)<<endl;
}

2. Uniform initialization and Initializer list

This feature allows initialize any type (custom or built-in) using single common syntax. Following examples shows initializing built-in primitive types, containers and custom object using braces syntax

int count = { 10 };

double tempratureRange []  = {32.7,46.9,40.6,67.1,12.8 };

vector days = { "sunday","monday","tuesday",
                        "wednesday","thursday","friday","saturday"
                      };
map<string,vector> phoneList = { {"Joe",{"222-456-234","222-111-555"}},
                                         {"John",{"444-656-345","111-123-567"}}
                                        } ;
CustomType ct = {1,2,3,4,5,6};

for(auto day : days )
{
   cout<<day<<endl;
}

for(auto & phone : phoneList )
{
  cout<<phone.first<<endl;
  for(auto & num : phone.second )
       cout<<num<<" , ";
  cout<<endl;
}

3. Lambda functions/expression

This feature allows creating anonymous functions that can be passed/returned from another function. This feature used along with C++ generic function/algorithms allows writing short snippet of code inline to perform operation on C++ containers.

[] {
     cout<<"Hello from lambda"<<endl; }(); // square function auto squareFunction = [] (int x) -> int
                         { return x*x; };

vector values = {1,2,3,4,5};

for_each(values.begin(),values.end() , [&values] ( int n ) {
                                       cout<<n;
                                      if ( n % 2 == 0 )
                                         cout<<" is even number"<<endl;
                                      else
                                         cout<<" is odd numnber"<<endl;
        });

4. Range based for loops

This feature makes iterating over collection using simple syntax. It works with all standard containers

vector days = { "sunday","monday","tuesday",
                        "wednesday","thursday","friday",
                        "saturday"};
map<string,vector> phoneList = { {"Joe",{"222-456-234","222-111-555"}},
                                         {"John",{"444-656-345","111-123-567"}}
                                        } ;
// iterating over vector
for(auto day : days )
{
   cout<<day<<endl;
}

// iterating over map
for(auto & phone : phoneList )
{
    cout<<phone.first<<endl;
    for(auto & num : phone.second )
        cout<<num<<" , ";
    cout<<endl;
}

5. Variadic templates.

This feature allows users to write template class or function that can take variable number of types. For example writing type safe printf style function: See Wikipedia article . This feature will be more useful for library authors. Tuples are implemented using variadic templates as tuple can take multiple arguments of various types.

6. Tuples and Raw string literals

Tuples are ordered list of elements, many of the functional programming languages have this feature. Basically it allows to pass/return multiple values to/from function as single unit without creating separate custom type to do the same.

Example: to parse tcp host details to separate hostname and port.

tuple<string,string> ParseTcpHostDetails(const string & tcpHost)
{
   string host = tcpHost.substr(0,tcpHost.find_first_of(':'));
   string port = tcpHost.substr(tcpHost.find_first_of(':')+1);
   return make_tuple(host,port);
}
int main(int argc,char* argv[])
{
   auto parsedValue = ParseTcpHostDetails("127.0.0.1:9090");
   string host = std::get(parsedValue);
   string port = std::get(parsedValue);
}

Raw string literals allows to write character strings where escape character are not processed. A raw string literal starts with R”( and ends in )”

string uncPath = "\\\\servername\\sharepath";
string uncPathWithRawStringLiterals = R"(\\servername\sharepath)";

7.  Threading support ( async,futures and promises )

These features collectively help in writing concurrent application in a standard way on different OS platforms.

async allows launching task that can be executed on background thread, future allows waiting for the task to complete and wait for the result

int main(int argc ,char* arv[])
{
  std::future result1(std::async( [] () {
     cout<<"["<<std::this_thread::get_id()<<"] Inside long running task .. "<<endl;
  }));

  cout<<result1.get()<<endl;
}

All samples programs are compiled on Ubuntu 12.10 with GCC 4.7.2 compiler with -std=c++0x switch.

// sample c++ file for compilation with proper header include
// use 'g++ -g -std=c++0x -o Sample Sample.cxx' compiler options
#include
#include
#include
<map>
#include
#include
#include
using namespace std;
int main(int argc,char * argv[])
{

return 0;
}

In future blog posts I will write about remaining C++ 11 features such as

  • Decltypes
  • Move constructor & Delegating Constructors
  • Move semantics
  • New ways of making a Class non copy able and assignable using keyword
  • New smart pointer classes
  • More thread/async/future/promise examples

Resources

1. isocpp website provides all the news , articles ,videos and blogs related to C++.

2. C++ 11 FAQ by Bjarne Stroustrup.

3. podcast :Excellent C++ 11 podcast on software engineering radio with Scott Meyers.

4. Future of C++ : Build 2012 Talk by Herb Sutter.

Compile and Run .NET program with just .NET framework on your system.

Compile and Run .NET program with just .NET framework on your system.

Did you know that every .NET framework installation also installs VB & C# compiler.

Using these compilers you can compile and run C# or VB.NET program on machine with just .NET framework installed. This can be useful on system where installing full visual studio is not an option.

Here is how to do it

If .NET framework installed on you system, C:\Windows\Microsoft.NET\Framework directory  should list all the versions. Here is what is on my machine.

image

Once you find required .NET version, directory content should list csc.exe and vbs.exe compiler executable. As shown below.

image

Now use C# or VB compiler to compile the program as follows. For example use .NET 2.0 compiler to generate .exe c:\Windows\Microsoft.NET\Framework\v2.0.50727\csc.exe Program.cs

image

Push notification from server to client using SignalR

There are number of scenarios where we need send push notification from server to client, client gets update from the server when ever server has new data.

Some of the scenario which benefit from push notification(real-time web) are

  • Monitoring Server application over the web(Diagnostic reports or Error reports )
  • User signup notification.
  • Stock tickers.
  • Chat application.
  • Monitoring of hardware instruments.

Now we know the possible usecases ,so how can we implement server to send arbitrary data to client.

Currently there are four established technique to do push notification on web

    • Polling : In case of polling Web browser make connection to server, server responds immediately with data if present else empty response. After predefined time(polling time) Web browser makes same request to server.This process repeats. Even though this solution works, it is not scalable solution. It can put heavy load on the server depending on the polling interval and number of clients . Polling from JavaScript shown below
	function getInfo() {

	$.ajax("url", function ( newInfo){
		if ( newInfo != null) {
			// do something with the data
		}
	});
	// poll again after 20 seconds
	setTimeout(getInfo,20000);
}
// start the polling loop
getInfo();
    • Long polling: It is similar to polling , where Web browser makes request to server , but server does not respond to client immediately , it will leave the request hanging open till it has some data to deliver. Eventually server responds and client uses the data and starts new request, whole process repeats. This technique is improvement over polling as it does creates unnecessary connections.  Long polling from JavaScript shown below
function getNewInfo(){
  $.ajax("url", function (newinfo) {
      // do something with the data
	  // start the new request
      getNewINfo();
  });
}
// start the polling loop
getNewInfo();
  • EventSource: It is similar to long polling client make request ,server leaves the request hanging open till it has some data to deliver, difference is after sending data back server does not close the connection. Server will keep the connection open .  This solution provide good scalability in handling requests , also it is implemented in natively by Web Browser it can perform better compared to previous techniques.But EventSource is  not iimplemented IE.  Event source from JavaScript shown below
var eventSrc = new EventSource("url");
	// register event handler for the message
    eventSrc.addEventListener( "message",function (evt) {
        //process the data
    });
  • WebSocket:Is the new approach to Web browser/server communication. It is bidirectional communication channel compared to unidirectional Event Source.  At high-level client sends HTTP Connection with “Upgrade: websockets” header;server leaves connection open , client and server negotiate which version of web socket protocol to use. Client and Server exchange messages once connection is upgraded to web socket. This technique is natively implemented by the Web Browser/Server . Refer to caniuse website to check the latest websocket implementation in Web Browser. WebSocket usage from JavaScript shown below
var socket = new WebSocket("url");
socket.onmessage = function (msg) {
	var newInfo = msg.data;
	// do something with the data
}
// client can also send request to server
socket.send(.... )

As we seen ,each technique has some pros and cons and not all browser have implemented all the features.
What we need is some abstraction over the different implementation  so that developer need not worry about various implementations.

SignalR to rescue.

SignalR is an abstraction on top of a persistent HTTP connection. It provides on consistent API over different implementations(long polling,websocket).

SignalR can use websocket if it is implemented by the Web browser and server and fallback to long polling if it is not implemented.
SignalR uses C# dynamic feature on the server side ( asp.net ) and Javascript dynamic features on the client side to create server and client proxy.

It is similar to Nodejs+socket.io implementation based on JavaScript.

CPU usage monitor sample

To illustrate the SignalR usage I wrote sample web application which allows to monitor % cpu usage on the server in real-time. Sample  application uses SignalR on server/client and Google web chart  for visualization.

Tools used: Free Microsoft Visual Web Developer 2010 Express, SignalR on Nuget and Google Chart Tools.

Here is the step by step instruction.

1. Create “ASP.NET Empty Web Application” in VS Web Developer express.

2. Use Nuget Package manager console in VS to install SignalR and associated dependency from Nuget.

3.Create class to hold the cpu usage information.

public class CpuUsageInfo
    {
        public double CPUUsage { get; set; }
        public String DateString { get; set; }
    }

4. Create new class on the server side which derives from SignalR PersistentConnection class.

 public class Perfmon : PersistentConnection
    {
        protected override System.Threading.Tasks.Task OnConnectedAsync(SignalR.Hosting.IRequest request, IEnumerable groups, string connectionId)
        {
            return base.OnConnectedAsync(request, groups, connectionId);
        }
    }

5.Update the Global.asax file to map ASP.NET route

protected void Application_Start(object sender, EventArgs e)
        {

            // add routing
            RouteTable.Routes.MapConnection("perfmon", "perfmon/{*operations}");

            Task.Factory.StartNew(() =>
                {
                    // get connection to global client connections
                    IConnectionManager connectonManager = AspNetHost.DependencyResolver.Resolve();
                    var connection = connectonManager.GetConnection();

                    var counter = new PerformanceCounter();
                    counter.CategoryName = "Processor";
                    counter.CounterName = "% Processor Time";
                    counter.InstanceName = "_Total";

                    while (true)
                    {
                        var item = new CpuUsageInfo()
                        {
                            DateString = DateTime.Now.ToString("hh:mm:ss"),
                            CPUUsage = Math.Round(counter.NextValue(), 2),
                        };

                        connection.Broadcast(item);

                        Thread.Sleep(500);
                    }
            });

        }

6. Inside Application_Start method add code to get send CPU usage events to connected clients using SignalR library.

7. Create new html file with that plots line chart using Google charting tools. In the JavaScript make connection to server using SignalR js library. As the data arrives from the server update the chart data collection and redraw the chart.

    var output;
    $(document).ready(function () {

        output = $("#output");

    });

    var data;
    var chart;
    var options;
    // Load the Visualization API and the piechart package.
    google.load('visualization', '1.0', { 'packages': ['corechart'] });
    // Set a callback to run when the Google Visualization API is loaded.
    google.setOnLoadCallback(drawChart);
    // Callback that creates and populates a data table,
    // instantiates the pie chart, passes in the data and
    // draws it.
    function drawChart() {

        // Create the data table.
        data = new google.visualization.DataTable();
        data.addColumn('string', 'Time');
        data.addColumn('number', 'CPU Usage in %');

        // Set chart options
        options = { 'title': 'CPU usage history', 'width': 600, 'height': 400 };

        // Instantiate and draw our chart, passing in some options.
        chart = new google.visualization.LineChart(document.getElementById('chart_div'));
        chart.draw(data, options);
    }

    connection = $.connection('/perfmon');

    connection.received(function (dataItem) {
        var newItem = dataItem;

        output.text("Received text from the server .: " + newItem.DateString + "," + newItem.CPUUsage);

        // update chart with data received from the server
        data.addRow([newItem.DateString, newItem.CPUUsage]);
        if (data.getNumberOfRows() > 100) {
            data.removeRow(0);
        }
        chart.draw(data, options);
    });

    connection.start();

Here is the demo output in Browser

Complete sample code
Resources
1. SignalR Channel9 Video
2. SignalR on GitHub
3. Socket.IO

C# 5 Callerinfo Attribute

As application developer we log information related to execution (information or error) to log files. This information is helpful for tracing, debugging, and creating diagnostic tools. If the log message has file name, line number and function name it is easy to narrow down the issue file and function.

In C/C++ developer can use  __FILE__ , __LINE__ and __FUNCTION__ macros to print file name, function name and line information along with the log message.

Following code c++ code illustrate the usage

// logger function
void LogMessage(std::string caller ,std::string LogMessage)
{
	std::cout<<__FILE__<<":"<<__LINE__<<" - "<<caller<<" "<<LogMessage<<std::endl;
}
// main function
int main(int argc, char* argv[])
{
	LogMessage (__FUNCTION__,"Starting Application");
	return 0;
}

If you are .Net developer  prior to .Net 4.0  you would have used System.Diagnostics.StackFrameclass to get this information .

public class Program
{
	public static void LogMessage(String message)
	{
		// get access to caller stackframe
		StackFrame frame = new System.Diagnostics.StackTrace(true).GetFrame(1);
		String file = frame.GetFileName();
		int line = frame.GetFileLineNumber();
		String member = frame.GetMethod().Name;
		
		var s = String.Format("{0}:{1} - {2}: {3}", file, line, member, message);
		Console.WriteLine(s);
	}
	static void Main(string[] args)
	{
		LogMessage("Starting the application ...");
	}
}

In C# 5 and VB.Net 11 there is easier way of getting this information using CallerInfo attribute.By using Caller Info attributes, you can obtain information about the caller to a method.

You can obtain file path of the source code, the line number in the source code, and the member name of the caller.

Here is the sample which uses C#5 feature ( available in .Net 4.5 )

public class Program
{
	public static void LogMessage(    
	string message,
	[CallerFilePath] string file = "",
	[CallerLineNumber] int line = 0,
	[CallerMemberName] string member = "")
	{
		var s = string.Format("{0}:{1} - {2}: {3}", file, line, member, message);
		Console.WriteLine(s);
	}
	static void Main(string[] args)
	{
		LogMessage("Starting the application ...");
	}
}

More information about Callinfo attribute can be found here
1. MSDN

Microsoft All-In-One Code Framework

Often you will looking for code samples to solve certain programing tasks.
Code samples will help in  understanding available operating system API’s and it usage.

All-In-One Code Framework  is code samples library provided by Microsoft. More than 3500 quality code samples covering various technical topic ranging from System programming,Device Driver programming, Windows Azure,ASP.NET ,Office SharePoint etc. Samples will be available both for Native ( C++,MFC ) and .NET developers.

Microsoft All-In-One Code Framework  has “Sample browser” application , that helps you to find the code samples written by the Microsoft team.
These sample are based on request from developer communities, customers and typical  programming scenarios.

image[3]-20[1]

 

To find the code samples
Visit http://1code.codeplex.com/ and download the application. This application is based on click once technology.

Once it is downloaded , you can launch the application and search for samples by entering the query in the search box.
You can also apply search filter based on programming language ( C++,C#,VB.NET ) and technology.
Following picture shows the search results for “Mutex” with C++ filter.

 

allinone

 

More information can be found from

1. Codeplex website

2. Channel9 Resource

3. How to use video on developer channel

Embedding C++ library/exe inside .NET assembly

Often times in .NET you have to use your existing C++ library to get work done. Traditional way of doing is using Platform invoke API to access un-managed code and distribute both unmanaged library and managed code to end user. For simple applications shipping separate .NET executable and corresponding library can be cumbersome. You will lose simplicity of deployment.

Following example shows the techniques of single file deployment using binary data as resource.

.NET allows embedding any data (binary/text) as resource inside the assembly, using this technique you can create single file assembly which houses any number of binary data.

As an example, let say I have C++ library (TestLibrary.dll) which I need to use from my .NET application (MyApplication).

1. Create new .NET application MyApplication.

2. Add existing item “TestLibrary.dll” to the MyApplication. Select the properties windows by selecting “TestLibrary.DLL” in the solution explorer. Set “Embedded Resource” option for the “Build Action” property. This option enables to embed Test.dll as part of the MyApplication assembly.

3. From MyApplication main application extra DLL resource to a temporary file.

4. Load the temporary DLL to process using Win32 native Load Library function.

5. Use DLL functions from the .NET application using PInvoke.

Advantages.

1. Deployment is easier with single file executable.

2. If needed you can embed unmanaged executable inside .NET assembly and invoke from .NET using Process Start API.

3. You can invoke different executable based on the target OS. For example: By embedding both 32bit/64bit unmanaged executable , you pick executable to launch based on the target OS,

Disadvantages:

1. .NET Application size increases based on the number of resources.

2. If you want to change embedded resource you need to rebuild the host application.

Note: Similar technique can be used to embed other .NET assembly. See Jeffrey Richter Presentation

Following sample shows the how to extract unmanaged DLL from  the resource and invoke function present in unmanaged DLL.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace MyApplication
{
    static public class NativeMethods
    {
        [DllImport("kernel32.dll")]
        public static extern IntPtr LoadLibrary(string dllToLoad);


        [DllImport("TestLibrary.dll", 
        CallingConvention = CallingConvention.StdCall)]
        public static extern IntPtr GetString();
    }

    public static class CommonUtils
    {
        /// <summary>
        /// Loads given unmanaged library from the assembly.
        /// This allows to embed .dll file as resource inside assembly.
        /// Example: 
        /// string tempDllPath = LoadUnmanagedLibraryFromResource( Assembly.GetExecutingAssembly(),
        ///                                                         "PInvokeTest.TestLibrary.dll", 
        ///                                                         "TestLibrary.dll");
        /// </summary>
        /// <param name="assembly"></param>
        /// <param name="libraryResourceName"></param>
        /// <param name="libraryName"></param>
        /// <returns></returns>
        public static string LoadUnmanagedLibraryFromResource(Assembly assembly, 
            string libraryResourceName, 
            string libraryName)
        {
            string tempDllPath = string.Empty;
            using (Stream s = assembly.GetManifestResourceStream(libraryResourceName))
            {
                byte[] data = new BinaryReader(s).ReadBytes((int)s.Length);

                string assemblyPath = Path.GetDirectoryName(assembly.Location);
                tempDllPath = Path.Combine(assemblyPath, libraryName);
                File.WriteAllBytes(tempDllPath, data);

            }

            NativeMethods.LoadLibrary(libraryName);
            return tempDllPath;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            string resourceName = "MyApplication.TestLibrary.dll";
            string libraryName = "TestLibrary.dll";

            // create and load library from the resource
            string tempDllPath = CommonUtils.LoadUnmanagedLibraryFromResource(Assembly.GetExecutingAssembly(),
                resourceName, 
                libraryName);
            // invoke native library function
            string output = System.Runtime.InteropServices.Marshal.PtrToStringAnsi(NativeMethods.GetString());

            Console.WriteLine(output);
            
        }
    }
}

Weekly resource for developer

  • Reactive Extension Release and 6 part video series. : The Reactive Extensions (Rx) is a library for composing asynchronous and event-based programs using observable sequences and LINQ-style query operator.
  • Choosing right collection in .Net : This article explains the data structures ( collections ) available in .NET and how to choose right collection .
  • Articles on parallel programming with .NET framework 4. : .NET 4 introduces number of new API/collection to help developer take advantage of cpu hardware resource using parallel programming technique. This link gives whitepapers published by Microsoft on these technologies.
  • Silverlight spy : Silverlight Spy is a runtime inspector tool providing unprecedented access to all aspects of any Silverlight in-browser, out-of-browser and Windows Phone 7 application. Explore the UI element tree, monitor events, extract XAML, interactively execute DLR code, view statistics and more.
  • http://beej.us/guide/ : Unix IPC, Gnu Debugger, Networking
  • Functional Programming: A Pragmatic Introduction : This presentation talks about advantages of functional programming over OO . Good presentation with examples in java. It shows how functional decomposition will help in solving programming task elegantly.