Why to use C# and when to prefer other languages?!

Introduction and Background

Either it is Quora, or is it C# Corner or is it CodeProject, beginners and novice users are always asking questions like, “Which one to use, C++ or C#?”, and many more similar questions. It is harder to provide an answer to such questions on multiple platforms and to multiple questions. That is why, I thought, why not post a blog post to cover most of the aspects of the question. In this post I am going to cover a few of the concepts that you may want to understand to chose either language from the most widely used languages:

  1. C or C++
  2. Java
  3. C# (or .NET framework itself)

Basically, my own preference in many cases is C#, but that depends on what I am going to build. I have been using C, C++, Java and C# in many applications depending on their needs, depending on how they allow me to write the programs and depending on whether it is the suitable programming language for this type of project and application architecture.

The way, I do that, is just a trick. Which, I am going to share with you, in this blog post. Among these a few of the very basic things to consider are:

  1. How simple and easy it would be to use this language in the program?
  2. What is the productivity of that language in your scenario!
  3. Difficulty level and how many people know the language!

I will be talking about these things points in this post, so to make it clear where to use which programming language. But my major concern in this post would be to cover the aspects of C# programming language.

Productivity of language

First thing to always consider about the language is the productivity that a programming language can provide your team with. Productivity of the language depends on many factors, such as:

  1. How programs are built in that language?
  2. How fast and reliable is it to build the project regularly?
  3. Is the program’s source code readable for other members on the team?
  4. Is the language itself suitable for the case that we are going to use it in.

Productivity of the language, in my opinion, is the first thing to consider as the valid candidate to always discuss in the team and not just talk about in a black room. You should manage to get your teams up in a conference room, and then talk about a language. There may be many aspects where one language may fall short and other may get well. There would be many factors that most of the programmers don’t¬†know but talking about them one of the geek would stand up and raise another important point that may guide your team to walk on the correct paths to build greater applications.

Let’s talk a bit graph.

chart
Figure 1: Productivity graph of most widely used programming languages.

In this chart we can see that C is the most productive programming language, of which we are interested in; C, C++, Java and C#. C++ and C# are competing with each other, whereas Java is a bit behind than C# and so on.

In the above graph, it is clear that C# is an average programming language. The average doesn’t mean it is below the requirement. But it means that it can be used in any case, and its performance won’t fall as the data increases. The successful run graph shows that C# programs are much successful in many cases. That is why, in many cases, C# proves to be the valid candidate in many cases, since it is a general purpose programming language.

Then the question arises, “Productive in which sense?

That is the most important part here. Now, this topic may take a bit more of the time to explain how productive a language is. For that, I have dedicated the topic, “Choosing the right language for the right task“. The right programming language for the right task would always help you to elevate the speed of the programming of your team! But among other aspects, the most important ones are:

  1. What sort of project this is?
    • Of course you don’t want to use knife to unscrew a screw.
  2. What are the IDE and compilation tools present?
    • Even a program written in C can go wrong if compile is buggy or inefficient.
  3. How your team would like to manage the projects?
    • Does the language support good software engineering concepts?
    • Can it be used to generate good diagrams: Use-case, activity, class and other diagrams.

Thus, you should always consider thinking about the productivity of your development team while guessing which language to be used.

Choosing the right language for the right task

It is always stated to use the best tool for the best jobs! Then, why not use the best programming language for your projects, to get the best possible results? Before I continue any further, there is one thing I want to mentioned… “There is no best programming language ever built.” Every time a programming language is built for a purpose, another group of programmers jump in to create a new programming language, for the sake of fixing the errors in the previous language. What do you think motivated Bjarne to create C++ when there was C language and Scala already in the market?

In this section, there are many things to consider, from the performance and benefits to the clients, to the perk packages for the employees to the efficiencies of the project repositories and the tools provided for that programming languages.

C# was created by Microsoft and therefore, in my opinion, has, by far, the most efficient tools for programming. I mean, Visual Studio, alone is the beast in this game.

visual-studio-2013-logo
Figure 2: Visual Studio logo.

I am a huge fan of Visual Studio, and i would doubt someone who isn’t a fan of Visual Studio. C# has a better support and benefit of using the best IDE out there. Java has also a number of IDE, so does C++ and many of the C programs are written in minimal environments, like a small program to manage and compile the C programs; no offence geeks!

2013-12-27-csharp-for-systems-programming
Figure 3: Graph of performance to safety ratio.

Now, if you look at this graph, it’s pretty much clear as to what it is trying to guide you with. Of course, as I had mentioned in the starting paragraph here, that there is no best programming language.

In many cases, C# and Java rule over C++ (and C) and in many cases, they rule over C# and Java. There are many factors, like the programming paradigms, performance of the code that is generated; Just-in-time compilation, memory-management delay and so on. While C# and Java may provide the best environment to build “managed” programs in, there are many cases where C# and java don’t work well, like writing a low-level program. Java developers wanted to build a Java OS, but they had to give up because something’s aren’t meant to be done in Java.:-)

Always consider to search before making the final call. There are many companies working in the similar field that you are going to work in. There would be many packages and languages built for your own field that may help you to get started in no time!

top201020programming20languages-100422646-orig
Figure 4: Top 10 programming languages.

But, I think these are a bit backwards. I think, C is on the top because it causes a lot of trouble to beginners, so everyone is searching for “How to do {this} in C” on Google, raising the rankings.ūüėČ

Selecting the best framework

I don’t totally agree with people when it comes to talk about frameworks like, Java, Qt (which I do like in many cases; like Ubuntu programming), and other programming frameworks available for programming applications to be run despite the architecture of the machine. In this case, my recommendation and personal views for .NET framework are very positive. As, already mentioned, I have programmed on Qt framework for Android, Ubuntu and Linux itself. It was a really very powerful framework to build applications on. But the downside was it was tough to learn, their compilers were modified, their C++ was tinkered.

While selecting the best framework for application development by choices are below:

  1. How much flexible a framework is?
  2. What language does it support?
    • Some frameworks support multiple languages, like .NET framework, it supports C#, VB.NET, Visual C++, JavaScript applications.
  3. Is it cross-platform?
  4. If not cross-platform, then does it support multiple architectures, at least?

Java framework is cross-platform, and entirely framework oriented. You simply have to target the framework despite the operating system or architecture being used. .NET framework on the other hand is a very beautiful framework to write applications on. It uses C#, VB.NET and C++ (no Java!) to write the applications, and then the compiled binaries can be executed on many machines that can support .NET framework. This provides an excellent cross-architecture support.

C# however, does not support Mac OS X, at the moment. Microsoft has started to roll out cross-platform binaries for C# programs. .NET Core has been a great success and once it gets released to a public version, I am sure most of the companies would start to target it. That is not going to happen, in a near future. In which case, Java and C++ are better than C#.

If you are interested in C# programming on multiple platforms, consider using Mono Project instead. You can read about that, on my blog here: Using C# for cross-platform development.

spectrum
Figure 5: Top languages and their platforms of usage.

Java may be supported 100% in the rankings, but C# is also supporting multiple platforms and is rapidly growing making the language better than the rest. With the release of C# 6, Microsoft has proved that the language is much better than the rest in the race. There are many features that I like C# 6:

  1. String interpolation
  2. Getter-only auto-properties as lambdas
  3. Improvements to lambdas

There are a few things Java still doesn’t have. For example, one statement code to write the data to the files and to extract the data. You have to get messy in the streams, or you have to write an entirely non-intuitive code with Files object and then to get the data from there… Yuk!

Performance of the compiled code

Writing the source code may be different in many ways:

  1. Syntax of the programming language.
  2. The way their objects and procedures are imported in the source code.
  3. How clean the source code looks. Many programming languages are just nightmares.

But the major concern comes to mind when we are going to execute the programs. In many cases, or should I say in all the cases, the language which are bytecoded languages, lag behind than the languages that are compiled to native codes or Assembly codes. For example, C or C++ codes are faster, because they are not compiled to a bytecode instead they are generated as machine codes for a platform or architecture. C# or Java programs are compiled down to a bytecode which causes a JIT to occur when the programs are executed. This takes time.

However, you can see the following charts from https://attractivechaos.github.io/plb/ and see for yourself, the way bytecoded languages are similar and how much compiled languages are different, see for yourself.

plb-lang
Figure 6: Mathematical calculations.
plb-lib
Figure 7: Pattern matching and machine learning.

Which makes it pretty much clear, how much compiled language are faster than bytecoded, and then come the ones that are interpreted, like Ruby.

In many cases, there are other factors too, which cause bad performance:

  1. Bad compiler.
  2. A lot of resources being allocated.
  3. Slow hardware resources; bad combination of CPU, RAM and other peripherals.
  4. Bad programmer and bad code being used.
  5. Bad practices of programming.
  6. Keeping CPU halted for most of the times.

Much more are a valid candidates for the halting processes.

Finally… Final words

As I have already mentioned that there is no best programming language out there. One language is best in one case, other is best in another case and so on and so forth. In such cases, it is always better to communicate with your development team and then ask them questions and ask for their feedbacks. Choosing the good tools for your projects is always a good approach and good step in the process of programming.

If your software engineer or software architect are trying to find a good solution, ask them to work on the following questions:

  1. What are the teams and developers qualified for?
    • Asking a team of C++ programmers to leave C++ and join Java or C# programming teams is not a good idea!
    • Always consider the best approach.
    • Time is money¬†‚ÄĒ Manage it with care.
    • Recruit more programmers with skills.
  2. Is the programming language long lived, or a minor one?
  3. Is programming language capable of making your application work?
    • I have used many programming languages, and thus I can decide which language to use. This is the job of your software architect to decide which languages to select.

If you follow these rules, you will save yourself from many of the future questions that cause a lot of problems. Many times developers ask questions like, “I have an application in Java, how to migrate it to C#?” Many web developers ask questions like, “I have a PHP application, how to convert PHP code to ASP.NET?” These questions have only answer. “Re-write the applications”.

There are many things that you should consider before designing the applications. Facebook is stuck with PHP, because it was written in PHP. Even if they wanted to migrate to ASP.NET, they won’t. Instead, they have found a work around the PHP bugs and downsides.

This is why, you should always consider using a conference or meeting to decide how to start the project, which programming language to use, what frameworks to target, who would lead the team and much more. These few days of discussion and designing would save you a lot of money and time in future.

Understanding the Visual Studio IDE for R language

Introduction and Background

Previously we had talked much about installing and setting up the environment for R language. In this post, I will walk you through different stuff that Visual Studio provides you with. Typically, every R IDE supports the following tools and features for data processing.

  1. A scripting toolkit; where you can write R language code.
  2. An R interactive shell for executing the commands.
  3. Plot builder for plotting the graphics.
  4. Markdown editors and much more.

I will walk you through these windows in Visual Studio IDE itself and would give examples of using Visual Studio as your default IDE for R programming. In my personal (and humble) opinion, I think Visual Studio is the best IDE out there, provided its simplicity, ease of use and now that the price has also dropped down to zero for personal use! What more can someone ask for?:-)

Exploring Visual Studio for R

I have talked about the things that we are going to explore in this post. Those are listed above, and in this section I am going to expand them and I am going to demonstrate what benefit they have for R developers in the industry of data science.

visual-studio-2013-logo
Figure 1: Visual Studio logo.

Besides R, Visual Studio is also going to have the tools for Java programming. At least, I am very much excited about Visual Studio’s future, in which it is going to be used as a universal IDE. But in this post we should just focus on the R tools provided. If you have not yet set up the R tools for Visual Studio, I recommend that you read the post of mine for that,¬†Installing and setting up R environment on Windows. This would help you to set up the environment for data analysis using R language.

1. R code editor

First thing to know about in any IDE for any programming language, is the code editor that it has. Code editors are simply the text editors, but there are a few other additional features that it has apart from the ordinary text editing and caching services. Visual Studio code editor provides the following powerful features:

  1. R syntax highlighting.
    • Every IDE should support syntax highlighting and highlight the different data types, different keywords and the scope resolutions like matching brackets.
  2. Autocomplete suggestions.
    • Visual Studio calls them IntelliSense, which provides the easy way of writing the programs. It provides the clean way of providing suggestions for function calls and the parameter lists.
  3. Squiggly lines for errors
    • It is better to show off the errors in the language syntax or commands, before programmers build their project and finally stumble upon the errors. Visual Studio shows the errors if there are any, in the commands using the interpreters!

Screenshot (3147)
Figure 1: Visual Studio code editor.

This is the most basic usage of the code editor at now.  Visual Studio renders the codes in their own format, R syntax has been implemented in Visual Studio to support for string literals, keywords, comments and matching brackets.

You should consider using the R code editor instead of using a plain-text file to write the R scripts.

2. R interactive shell

Every interpreted programming language has an interactive shell. Python has it, so does R because R is an interpreted language. Interactive shells allow you to execute minimal programs, commands, and test the environment itself. They are also used to compile (interpret!) and execute the statements in the source file that you may have somewhere.

Visual Studio supports the Interactive Shell. If you do not find it, it is right there under R Tools → Windows → R Interactive. The WIndow allows you to enter the commands to:

  1. Create new variables in the environment.
  2. Explore the environment.
  3. Print the variables.
  4. Perform calculations on the data.

Screenshot (3232)
Figure 2: R interactive shell.

You can see that the R project starts, and then it allows the users to enter the commands that are to be tested or executed in the R environment. If you pay a bit more attention, you will see that i am currently running Microsoft’s R Open,

Screenshot (3232) - Copy
Figure 3: Microsoft R Open being used in the shell.

This allows you to add the commands which require execution. You can perform many functions in this shell as already mentioned above.

Screenshot (3235)
Figure 4: Executing commands in R Interactive Shell.

You can also run other versions of the R. But, Microsoft R Open is the Microsoft’s implementation and distribution of R language. To change the currently active engine to be used for R, you need to have other versions of R installed on your machine. If they are available, then you can update the current active R engine from the settings themselves. Just select R Tools¬†‚Üí Options. Inside those options, select the path for the R engine’s installation folder.

Screenshot (3233)
Figure 5: Options in R Tools.

Select this field and update the directory which it targets to target another directory for a different R engine. Once done, you can restart the Visual Studio to take the actions.

3. Plotting graphs

Another great feature of R programming is that it provides you with native support for graphical presentations. If you want to build charts, pie charts and bar charts or graphs. You can get the functions that can do the trick for you! In no time, you will be up and running your own projects, presentations and anything.

Benefit is that R generates quality and enterprise ready graphics, not just careless graphics! You can show the R plot window by either executing the command for plotting the graph or by manually opening it. To select the R plot, you can go to R Tools → Windows → R Plot. You can then direct R to build and generate the graphics on the plotter, a few of the commands used are:

  1. Pie
  2. Plot
  3. Barplot

You can use these commands to build the graphics, based on the data sets or vectors that you have. You can consult any of the statistical book or guide to learn more about charts and how they are used to render the data on the graphical level.

Just to demonstrate, I am going to use the following data, assuming they are marks:

> a <- c(55, 73, 44, 85, 65, 76)

Execute this, and R would create a variable in the environment.

Using plot()

First function to use is the plot() function. It plots the dotted graph of the points. Execute the following function,

> plot(a)

Following is the result of this command in the shell:

Screenshot (3236)
Figure 6: Plotting the dotted graph.

You can change how text is rendered and how the indices are selected, too!

Using barplot()

Next I would like to talk about the barplot() function that generates the graphics in the bar graph form. You pass the elements, and then it would generate the output in the bars form. The benefit is that you can compare how long a bar is, as compared to another one.

To get a bar graph, execute the following command:

> barplot(a)

The following output would be captured by you:

Screenshot (3237)
Figure 7: Bar graph for the data set.

This shows the data in a bar graph form. This is more readable and is easily understood. You can see how our graph is built and how the indices are selected for our data sets. You can then perform other actions, which I will talk about later before ending this section.

Using pie()

Pie is another kind of graphical notation in which we can render the data, to learn about it, read any basic statistical guide or course book. The pie uses the shape of a pie to render the graph. But, it uses the ratio of each data item to slice the pie into different sections to demonstrate their part in the pie.

To build a pie chart, use the following command:

> pie(a)

This would result in the following:

Screenshot (3238)
Figure 8: Pie chart graph.

Although this uses 1, 2, 3…6 to label. You can change them later in the function call. But I just want to tell you how Visual Studio can help you to have multiple windows working simultaneously for your project.

Features of R Plot

I mentioned that I will talk about the features of the R Plot. One of the best feature is that they are native. You do not need to import any extra package or library. But you can import other libraries, if you like any other implementation of the graphs.

Secondly, R Plot allows you to import the graphics in the form of:

  1. PNG images
  2. PDF documents

Which makes it even more easier to share the graphics that you render using the data set of your own environment.

Generating documents¬†‚ÄĒ R Markdown

Finally, I would like to talk about the R Markdown a bit. I think, this is one of the best things that R has right now. If you have ever been to Stack Overflow, GitHub or other similar websites, you would know that they already support a markdown that can be used to generate and render the HTML in a much simpler way. For example,

Hello _everyone_! I am using the following code

```
var obj = new Object();
```

// Would result in
<p>Hello <i>everyone</i>! I am using the following code</p>

<pre>
var obj = new Object();
</pre>

Which makes it much easier to render the documents in a much simpler way. Instead of writing a complex, standard or platform based language. You write a third-party standard, which is then converted to another standard. R Markdown does the same thing. You use it to generate the documents. The benefit is that you can use a single R markdown document to build multiple documents of multiple types and kinds:

  1. PDF documents
  2. HTML documents
  3. Word documents
  4. Other documents, supported!

Thus, it seriously elevates the document generation for the research that you have just conducted. Plus, it allows embedding the document code which can be executed when needed, such as generating the charts, calculating the means and so on and so forth.

In Visual Studio, you can create a new R Markdown document just the way you would create any other file in Visual Studio. Right click → Add → New Item → R Markdown.

This document can contain the plain-markdown content, which would be then rendered and compiled based on the medium that you want to render the data in.

References

To learn more about R Markdown, please refer to the following links:

  1. R Markdown
  2. Knitr with R Markdown

Points of Interest

In this post I have talked about and walked you around many aspects of using R programming in Visual Studio IDE. Visual Studio is, no doubt, the best programming IDE available and providing the services for R programming is a great step by Microsoft.

RTVS
Figure 9: Visual Studio IDE having 4 windows of R tools open.

I assume, using Visual Studio for R programming is pretty much explained in this post, and in the later posts I will walk you through using R language for real projects and real time data processing and analysis.

In the later posts, I will talk about using R programming in real world projects. Hold tight, it’s going to be an excellent data science journey.:-)

Guide for building C# apps on Ubuntu: Graphical applications using Windows Forms

Introduction and Background

I took more than necessary break in posting the content and articles for Ubuntu programming in C#. Anyways, I am continuing from the same place where I left and, as already taught that we were at the final stages of sharing the guide for programming C# on Ubuntu; which can be thought of as a Linux environment. The previous posts can be found easily on my blog and on some of the networks that I support.

Previously, we had already talked about NuGet gallery packages, cryptographic helpers and much more. Whereas, in this post I am going to walk you people through using Windows Forms framework on Mono framework.

Windows Forms framework

Now, who doesn’t know Windows Forms framework in today’s world? If you have ever wanted to or have developed the C# programs or .NET applications. Then you are already familiar with Windows Forms application. Windows Forms is an old framework with graphical capabilities, and has been in the game for a more than a decade by now! It has started to get replaced by Windows Presentation Foundation, but nonetheless, it is still very popular and is being used widely by many software developers and many software development companies are still relying on it.

There are many benefits of using Windows Forms in your regular development teams,

  1. It supports graphics, not just the CPU and RAM processing.
  2. It can be used with resources for localization support is excellent.
  3. Provides a better way for drawing graphics on canvas.
  4. Event handling, delegate generation.
  5. Asynchronous programming patterns.
  6. Good data binding support provided.

I am going to provide you with some good references that you can use to learn more about Windows Forms, if sadly, you have no idea about the Windows Forms framework. However, one thing is for granted. Using Windows Forms is one of the easiest ways of building the graphical applications in ,NET environment.

References

Follow the following links and learn more about Windows Forms:

  1. Windows Forms
  2. Getting Started with Windows Forms
  3. Windows Forms Overview

Graphical applications in Mono Project

We have until now, discussed and learnt how to build small programs and some very common applications that use special kind of algorithms, such as cryptographic helpers which can be used to encrypt and decrypt the data in Ubuntu using C#. Now, until this we haven’t covered graphical applications development in Mono, because that is where this framework lags behind. ¬†So, in this post we would like to learn how to build applications with graphical capabilities too. But, first, let’s talk about the frameworks provided in Mono Project itself.

  1. GTK#
    • Which is a similar one to the GTK+ that C++ programmers have. This is a graphical toolkit that compiles down to the native code generation. It supports the native look and feel and can be used. But, it is somewhat difficult to learn!
      Banshee1
      Figure 1: GTK# control application example.
  2. Windows Forms
    • This is the topic that we are going to cover in this post.
  3. Other tools?
    • Not yet, Mono Project is not ready to implement other frameworks yet.

The thing is, Mono Project¬†doesn’t have an excellent UI designer as we have in Visual Studio.

Screenshot (3062)
Figure 2: Visual Studio UI Designer.

In Mono Project and Xamarin Studio, you are not provided with the similar tools until now. However, the designer is just the wrapper around the back-end code available. Xamarin Studio does have a good designer, but that works with GTK# tools and controls only. Not in the case of Windows Forms.

Applying a quick hack!

If you have ever programmed for Windows Forms, then you would know that Windows Forms is actually a bunch of objects with many fields and properties, which run and work to render the graphics on the screen. The same is applicable here. We would be using the codes to render the stuff on the screen. Basically, everything that you have on the screen is a field in the backend class, such as “Button”, “TextBox”, “Label” etc. These are all going to be used, but, we are going to write the codes for this, instead of having a designer build them up for us.

Building the UI with Windows Forms

So, I hope using the hack is clear to you, after all, it is not a hack it is the actual way in which Windows Forms applications are constructed, built and executed. Only difference is that on Windows we also get to use the UI designer. In case of Mono Project, we would have to craft the UI with our own codes and then re-implement it if there is a changing to be performed on the screen later. Thus, putting it simply, we are going to implement it the hard way since there is no, “Drag-and-drop” method here.

To get started, you need to understand that a Windows Forms application is a C# application too. So, only thing to understand is C# language itself and the .NET framework. We are going to use the same concepts of .NET framework and then implement the same concepts to Mono to get our graphical applications ready.

Create project — Any type

I had chosen to build this application on the top of Console application. You can select other types too. But, my recommendation is using the Console application.

Screenshot (3064)
Figure 3: Selecting the console project as the type.

Enter the names and details and create the project.

Screenshot (3065)Figure 4: Entering the details for the project.

At this moment, you will be at the same stage where you were in the beginning of this module, and the previous ones. You will have an empty project, that only renders, “Hello world”. That is the start, from here we will continue to build the larger and complex stuff.

Screenshot (3066)
Figure 5: Hello world!

This program is the default program that every time we were shown. Now, we need to add the graphics to the console. That’s simple. All we need to do is… Read the next section.ūüėČ

Adding graphics to the console

Adding the graphics to the console is pretty much simple, you just need to do the trick as:

  1. Include the System.Windows.Forms namespace to the project.
  2. Include the System.Drawing namespace to the project.
  3. Import the packages to your source code.
  4. Write the code yourself; since we do not have the designer.
  5. Run the program, and you will see the program start up.

But, I am going to show you how to do that in a minute or two. But first, let us understand why Windows Forms can be build using the code itself. The thing is, the Windows Forms applications are started on a thread, the thread gets the graphics objects and bitmaps which are rendered on the screen later. The objects are simply instances of the classes, for instance of Button class. These are all passed to the Application object, and they are executed, upon execution they render the graphics on the screen.

Another thing to understand and note is that Windows Forms uses System.Drawing to draw the native code in Mono. Mono targets the objects using the assemblies provided in System.Drawing namespace, and then renders the objects on the screen. At the moment, Mono supports on Win32 theme for the objects. In the end of this post, you will see how your objects are going to look. Remember, the objects are instances…:-)

Open the references and add the references to System.Windows.Forms and System.Drawing namespaces,

Screenshot (3067)
Figure 6: Initially references are like this.

Screenshot (3068)
Figure 7: Adding the references to the namespaces. 

Now that we have everything set up, we can now continue to create a new Windows Form. This method is not similar to what we had in the previous IDEs, like Visual Studio. Instead, we are going to just mimic having a Windows Form.

Adding the Windows Form to your project

First thing to note is that there is no way of creating the form by itself in Mono Project. So, we are going to create a new object, and then we are going to turn it into the form and then render it using the main function. That’s just similar to what happens in Visual Studio too. You create the form, whose graphics are rendered separately in a designer, and the codefile is generated separately. Visual Studio maintains everything for you, which is why you do not feel anything different.

Step 1:

Create a new class, name it what you like, I chose MyForm and then write the following code to it.

using System;
using System.Windows.Forms;

namespace GraphicalApp
{
    public class MyForm : Form
    {
        // No properties.

        public MyForm ()
        {
            // Default constructor
        }

        // No functions.
    }
}

This is it. This is out, Windows Form now.

Step 2:

Before running the program, you also need to make sure that the main function now calls this form to be executed in the application too.

// In the references
using System.Windows.Forms;

// In the main function
Application.Run(new MyForm());

Now, run the project and you will (should!) see the following window with no controls, but with a graphical notation and rendering.

Screenshot (3069)
Figure 8: Sample empty Windows Form application.

This shows that our project is ready to accept the objects for graphical components. We can now write the code for the objects that we need to render. For example and for the sake of simplicity I would like to create a sample form that renders the form, which would ask me about my name and then would greet me once I click on the button.

All of these are core C# programming concepts and this has nothing to do with the Windows Forms or any other fundamental concept. Instead, these are very simple and yet easy features of C# programming language itself.

Step 3:

Anyways, to update, we can just update the MyForm class and write the code that we would need to have in order to render the form.

using System;
using System.Windows.Forms;
using System.Drawing;

namespace GraphicalApp
{
    public class MyForm : Form
    {
        // Properties.
        private Label label;
        private TextBox myName;
        private Button btn;

        public MyForm ()
        {
            // Call the function to render the objects.
            Text = "Windows Forms app";

            this.Size = new Size(300, 350);
            render();
        }

        private void render() {
            label = new Label { Text = "Your name: ", Location = new Point(10, 35) };
            myName = new TextBox { Location = new Point(10, 60), Width = 150 };
            btn = new Button { Text = "Submit", Location = new Point(10, 100) };
            btn.Click += Btn_Click; // Handle the event.

            // Attach these objects to the graphics window.
            this.Controls.Add(label);
            this.Controls.Add(myName);
            this.Controls.Add(btn);
        }

        // Handler
        void Btn_Click (object sender, EventArgs e)
        {
            MessageBox.Show ("Hello, " + myName.Text + "!");
        }
    }
}

Now again run the program, and you will see the following graphical application being rendered on the screen for you!

Screenshot (3070)
Figure 9: This is the Windows Forms application on Ubuntu. 

Screenshot (3071)
Figure 10: Entering the data and seeing that it works. 

Now, if you have been an old geek for Microsoft and Windows, then you would know that this style existed for decades in Windows environment. This style was typically adopted for Windows programming with C++, especially Win32 and then later C# was introduced and they had a different style; create a WPF app and look for yourself!

This is how Mono does the trick for Windows Forms. It does support Windows Forms and can use the same power of .NET framework to provide the similar ways to build the graphical applications for Linux environment. The benefit is that, you can now execute, build and run these graphical applications on Windows, Linux (every distro that supports Mono runtime) and Mac OS X. What more could you ask for?:-)

Points of Interest

In this post, i have walked you through different stages of building the graphical applications on Ubuntu using C# in Mono Project. The benefit of using graphical applications is that you can do more in less area, because “A picture worth a thousand words!”. Windows Forms is a framework that has been widely used by programmers of C# language and is still being used. If you can port your applications of Windows Forms to other platforms, it would be much better.

In this post, I have shown you how to do that. You can port your Windows Forms application, by porting the code for that application project, and then building it under Mono compilers.

The Mono runtime however, only supports Win32 theme for controls and however, provides a versatile amount of features, incredibly, they support all the new features of Windows Forms too. Which means, you can work around with:

  1. Graphics
  2. Multimedia
  3. Content management
  4. Data binding
  5. Event handling
  6. Asynchronous programming

And much more. There are more posts about Mono framework to come, but we are getting closer to having the guide completed and to be ready as a complete guide for “Programming C# on Linux”; or Ubuntu, what-ever you prefer.:-)

Installing and setting up R environment on Windows

Introduction and Background

One day in the previous week, I heard my professor say something about “R language” and I said to myself, “What is this R language?”. Of course I had no idea about what that language was but I was a bit curious to know about it and to learn about it. Luckily, I was provided with a few concepts about R language on C# Corner’s R language category and later I Googled stuff around to learn more about it. In this post, I am going to walk you through different things that I have learnt during my learning time.

In this post, I will walk you through many steps to set up the environment for R programming. I will be covering the basic R environment set up and later I will talk about using Visual Studio as the default IDE for R programming, after all, “Who doesn’t like Visual Studio?!”.

What is R, anyways?

A good introduction to the R language and R environment is given by Mahesh on C# Corner, I would recommend that you read that one, What Is R Language.

R is a programming language, as well as an environment for computation. What sort of computation? Statistical computation is the major field for R. However, many fields are using R language for their purposes, for example, Data Scientists are using R language for many analysis that they have to perform on data sets. Data mining etc. come later in the picture.

I will point out a few of the major fields that R can be used in, later, but first a bit of the intro to R language would be useful.

R-Programming-Language-Logo-785x595
Figure 1: R logo.

R language was developed in the early 1990s for statistical computation purposes. It started all with small modules, then it gathered and gained much reputation from online communities and it became a very popular environment to use in many fields of computer-related sciences. It was developed using C and FORTRAN as the basic language for interpretation.

R is distributed under GNU license and allows modifications to be made and shared online. R was developed in C and FORTRAN. That is why, you can modify the source code and recompile the binaries to make it suitable for your own needs. You can do that, too!

Why learn R?

As already mentioned that R is a programming language and environment for statistical programming and computation. That is why, R is a very prominent language to be used in data science projects. Specifically, the R language is used instead of C, Java or even C++ in these cases because the packages in R are already ready to be used and in no time, you get to use the best of the data science in this environment.

Untitled-1
Figure 2: A chart for benefits of learning R language. 

Even if you are not an open source developer, you would still find R language very much helpful. The usage of R ranges from field to field. As already depicted in the diagram above, this project can be used in many ways, in many fields and for many purposes. A few of the basics where, this can be used can be categorized as following:

  1. Working with data science projects.
  2. Building reports for data analysis.
  3. Creating presentations with graphical representations of results.
  4. Adding your own extensions to the projects.
  5. Educational use.

I will write some articles about using R in many ways, for many projects and tasks in computer science, but I would like to leave that all to a later time. Until now, just know that if you are going to analyze large amount of data sets, process data mining and similar projects. Then your best bid would be R language instead of C++ or Java.

Another beauty of R language is that it can be coupled with many other famous programming languages and environments and frameworks. For example, R functions can be called from C, C++, Java, Python and from the .NET environment, easily. You would be using the R language to:

  1. Process the data from CSV or TXT files.
  2. Generate summary reports in the form of graphics or tables.
  3. Use a special type of Markdown format to build the results.
  4. Use multiple formats to extract the data results.

There is much more to learn R for. Many giants such as Google and Facebook are already using R for their computation purposes, because it is open source and can be updated as per needs. It allows educational institutes to teach their students in a much simpler and easy way.

Setting up R environment

First step to perform would be to install the R environment packages on your machine. You can get the binaries for installation packages free of cost, from R website itself. Go to the CRAN network and select your own operating system and download the binaries to be used for installation purposes on your own machine.

I am using Windows operating system, so I used Windows instead. You can download the binaries for your own system. Start the setup and continue to follow the steps that are provided on the UI itself.

Screenshot (2752)
Figure 3: R installation setup for Windows.

Later you would be asked to select the location where you want to install the packages. Chose a location, but recommendation is to leave it as it is.

Screenshot (2753)
Figure 4: Location selection process.

Then the environment would be installed. You can run the environment programs by selecting either of the following icons.

Screenshot (2754)

Select the one that suits your architecture, mine was 64 bit so I executed the one for my architecture.

Screenshot (2755)
Figure 5: Running the R console.

Just to test that everything is running and set up fine, execute the following test on it.

> 3 + 3
[1] 6

Screenshot (2756)
FIgure 6: Running a test in R console.

This shows the R is set up and we can continue to use it in our projects for our own purposes. Now, you don’t want to work on your projects using this console only. For that, you would require a full-featured Integrated development environment; IDE. In the next steps, I will walk you through many steps to install the IDE for R.

Setting up R using Visual Studio

Visual Studio is, no doubt, the best IDE available for everything. It already supports C, C++, C#, VB.NET, Python and many more languages and frameworks such as web development languages of HTML, CSS and JavaScript.

R language support has also just arrived with the “R Tools for Visual Studio” extension that you can install to get started with using R language in Visual Studio. But for this to run, you need to have Visual Studio 2015 with Update 1, any edition would work from Community to Enterprise.

To set up, you can go to the URL provided above. Download the tools, you can also install the Microsoft R Open manually. Microsoft R Open is what we are going to use from now on. Go to this website for Revolution Analytics, and start setting up MRAN (Microsoft’s distribution of CRAN)

  1. Download Microsoft R Open and install it.
  2. Download MKL Math Library, which is going to enhance the performance of MRAN.

Screenshot (2811)
Figure 7: Microsoft R Open installer.

After that, install the MKL and you’re done!

Screenshot (2812)
Figure 8: MKL installer.

After that, just run the Visual Studio IDE to get started with your first R program. That, I am going to cover in an upcoming post.

Points of Interest

In this post, I have talked about a few of the stages that you can undergo to set up your R environment. Before that, I talked about why and how to use R. Apart from that, I also shared a few of the things required to set up R environment on Windows and to use Visual Studio as the default IDE for programming with R language.

In the later posts, I will write about using R language for your computation that require a lot of data processing. See you in the next posts.:-)

What Windows Runtime can teach .NET developers?

Introduction and Background

C# programming language has evolved too much in these years and many frameworks and platforms have been created and developed that support C# language as their primary programming language. Indeed, C# was release with .NET framework but has grown out to support Windows Runtime applications, ASP.NET applications, many .NET framework platforms such as WPF, WinForms etc. I have programmed for all of these frameworks, taught beginners in these frameworks and also wrote a lot of articles for these frameworks. However, the framework that appealed my interests the most was Windows Runtime. Windows Runtime is the new kid on the block with an object-oriented design and performance factor much similar to that of C++ applications.

At a higher-level it seems very simple, easy and straight-forward application development framework. At its core, it has great amount of validations and check points and most of the times, it is pain in somewhere censored. I remember the days when I was developing applications for .NET framework. WPF, WinForms, ASP.NET and other similar ones. I did have a few problems learning and starting, but there was one thing: Underlying framework was a very patient one. They never showed hatred for beginners or newbies. But when I started to write applications for Windows Runtime, I found out that it had no patience in it, at all. It was like, do this or it’s not gonna work.

3jLdy
Figure 1: Windows kernel services and how it branches into different frameworks. 

In this post, I am going to collectively talk about a few things that Windows Runtime may teach C# programmers, for a better overview of the applications that they are going to develop.

1. As a framework

Windows Runtime came into existence way after .NET framework itself and the child frameworks of .NET framework. But one thing that I find in Windows Runtime is that it is very much based on asynchronous patterns for programming. Microsoft never wanted to provide a good UI and UX but to leave out the performance factors.

One of the things that I find in Windows Runtime is that it still uses the same philosophy of C# programming language. But, adds the asynchronous pattern, too much. Not too much in a bad way, but in a positive way. The benefit is that you get to perform many things at the same time and let the framework handle stuff. So a few of the things that it teaches are, that you should always consider having tasks when there is a chance of latency.

  1. Network
  2. File I/O
  3. Long running tasks

These are the bottlenecks in the performance. Windows Runtime allows you to overcome these. .NET framework also uses the same mechanism, but developers typically leave out that part and go for the non-async functions. Bad practice!

References

For more on asynchronous programming, please refer to:

  1. Diving deep with WinRT and await
  2. Asynchronous Programming with Async and Await

2. Modularity

C++ programmers have been using modular programming, developing small snippets of codes and then using them here and there. Basically, modularity provides you with an efficient way of reusing the code in many areas of the application. Windows Runtime has a great modularity philosophy.

The foundation has been laid down on categories, and under those categories there are namespaces that contain the objects that communicate and bring an outstanding experience for the developers.

C# is an object-oriented programming, which means that even if you’re forcing yourself to have a single source file. You are still going to have multiple objects, working collectively for each of the purpose of that application.

Yet, it is recommended that you keep things where they belong.

IC269648
Figure 2: Modules can contain the functionality in them, through which user can communicate with the underlying objects and data sources.

References

  1. Windows API reference for Windows Runtime apps
  2. Modularity

3. Simplicity of the development

I don’t want to lie here, Windows Runtime is simple, it takes times to understand its simplicity.ūüėČ

When I started to write applications for Windows Runtime framework, I did not understand the framework or how to develop the application. That is because, I was fond of straight-forward small programs. Windows Runtime is a beast, a humungousaur, with its handles hanging down to the developers through the interfaces of C# language.

Windows Runtime has everything already set up in different areas. Like, the views, source code, capabilities, properties, resources and much more.

Visual Studio brings a way more simpler mean of development. I mean, Visual Studio handled everything,

  1. Managing the source code.
  2. Managing the output directories and how binaries are generated.
  3. Managing the visual items; the image assets may be difficult to add, Visual Studio makes it really very easy to add the assets of different sizes.
  4. The properties and manifest of the application is also written in XML. But Visual Studio makes really very simple to edit and update the manifest of the application.

While building applications for other platforms and frameworks, like WPF, we can use the same philosophy of Windows Runtime to build a great project and package directory. The settings and configuration files can be kep separate to make it simpler to build the development process.

4. Keep all architectures in mind

.NET framework developers don’t have to worry about the architecture that they are going to target. That made them forget the way that application would be targeted on multiple devices and environments. Windows Runtime is not like that. Windows Runtime generates multiple binaries for multiple environments, multiple architectures and devices.

  1. x86
  2. x64
  3. ARM

These are a few of the configurations for which binaries are generated and since the code that gets generated in a native one. The code must match the architecture, otherwise, the results are undefined.

However implementing the multiple architecture pattern would also require more manpower, more time for testing and implementing the patterns. Windows Runtime in Visual Studio has all of that already supported, but thing is, you need your men ready for any new framework to be included and tested on.

5. You may want to test it again!

Before, Windows Runtime, I thought, if everything works correctly. It is going to work anyways. But, ever since I had started to write applications for Windows Runtime and Windows Store I forgot that mind set and wanted to ensure that it passed all of the tests that it must undergo. That all started when I was about to upload my application, “Note It! App” to Windows Store. Application was passing all of the tests in Debug mode. Yet, when it was tested in the Release mode, it failed many of the tests.

Note: I am not talking about the Windows App Certification Tests.

The thing is, the code in the Debug mode has a debugger attached, which knows when something is going wrong and tells the developers about it and we can fix it. In Release mode, it is not the same. The error checks, the memory segmentation and other stuff in Windows Runtime is not same as it is in .NET framework. .NET framework uses Just-in-time compilation and performs many checks. However, in Windows Runtime, that is not the case. Everything is pre-compiled to overcome the JIT latency; delay.

That is exactly why, you should build the application in debug mode. However, always test the applications in Release mode. If you test the application in debug mode, you will skip a few of the key points in your application where it needs to be checked against.

Also, at the end, the App Cert Kit would be found useful to test if other tests, like resources, binaries and signature packaging is all well.

acx0E
Figure 3: App Certification Kit.

References

For more about it, read these:

  1. Release IS NOT Debug: 64bit Optimizations and C# Method Inlining in Release Build Call Stacks
  2. Debugging Release Mode Problems

Points of Interest

No developer wants to publish their buggy and faulty application on the Internet. I try, not to publish the application until it has passed every possible condition of test. However, no software is 100% bug-free and perfect solution.

In this post, I didn’t mean to target Windows Runtime as an ideal case for solution building, instead I wanted to just share a few of the great cards it has up its sleeves. .NET framework is simple, easy and agile to build on. But agility may drive you insane someday sooner.

Always keep these things on mind, and write applications by keeping these things in mind.

Building custom email client in WPF using C#

Download from Dropbox

Introduction and Background

Yesterday, I was talking to myself about writing another post for C# programming; I agree I am addicted to programming now. So, I wanted to write a blog post and I found that I had a topic on my “write list”. Just not that I wrote about that topic, I added a bit more of programming to it to support another feature. So basically what I had on my writing list was an email client in C# programming language. In this blog post, I will share the basics for developing an email client in C# using Windows Presentation Foundation framework. The source code is very much shorter and compact that building your own basic client takes no time at all. However, adding a few more features would take some time. I will point out those features later in the post itself, and you may add them later.

You are required to have the basic understanding of Windows Presentation Foundation framework and how C# language can be used. Typically, C# can be used to create an application of any kind. However, WPF is a framework that can be extended to any limit and can be used to create a graphical application of high-performance and maximum extensibility. WPF power would be used to build this one SMTP + IMAP application to develop a simple email client.

Understanding the protocols

Before I dig deeper and start to write the source code and explain the methods to build the application. I would try to explain the protocols that would be used in this application. The two of them are:

  1. IMAP: Internet message access protocol.
  2. SMTP: Simple mail transfer protocol.

These protocols are typically used to send and receive email messages. Other than IMAP, POP and POP3 are two protocols used to receive the emails, or to keep the emails on your devices. But, I won’t talk about them.

.NET framework provides native support for SMTP protocol for sending emails through your .NET applications like Console, WinForms or WPF etc. However, .NET framework doesn’t provide any implementation for IMAP protocol. Instead, they provide you with TCP clients and listeners. Since, IMAP and SMTP etc. are all protocols running on TCP protocol; or any other transmission layer protocol like UDP, implementing the native protocols like IMAP is very simple and easy in .NET framework.

For more of such packages and namespace to manage the networking capabilities of an application, read System.Net namespaces on MSDN.

Instead, I will use a library to get myself started in no time. Very long time ago, I came up to a library, “ImapX”, which is a wonderful tool for implementing the IMAP protocol in C# applications. You can get ImapX from NuGet galleries by executing the following NuGet package manager command:

Install-Package Imapx

This would add the package. Remember, Imapx works in only selected environments and not all. You should read more about it, on the CodePlex website.

The IMAP protocol is used to fetch the emails, to read, rather than downloading the entire mailbox and storing it on your own device. It is very flexible protocol because the email is still present on the server, and is accessible on every device that you have. Network latency is not a bad factor here, because you don’t have to download the email entirely. You just download the content that you need right now.

3dUC5U4Ly
Figure 1: IMAP protocol usage on the network.

Building the application

Now that I have pointed out a few of the things that will be used in this application, I guess the time is to continue the programming part and develop the application itself. First of all, create a new application of WPF framework. It is always a good approach to write the concerns and different sections of your applications.

Our application would have the following modules:

  1. Authentication module.
    • Initially we will ask the users for authentication.
    • Due to complexity level, I have only supported Google Mail at the moment.
      • That is why, application only asks for username and password combination.
    • You definitely should leave the maximum fields at the user’s will to be filled so that they can connect to their own IMAP service; other than Google Mail.
  2. Folder view
    • Viewing the folders and their messages.
  3. Message view
    • Viewing the messages and its details.
  4. Create a new message.

Separating these concerns would help us build the application in a much agile way so that when we have to update or create a new feature in the application, doing so won’t take any longer. However, if you hard-code everything in the same page. Then things get really very difficult. In this post, I will also give you a few tips to ensure that things are not made difficult than they can be.

Managing the “MainWindow”

Each WPF application would contain a MainWindow window, which is the default window that gets rendered on the screen. But, my recommendation is that you only create a Frame object in that window. Nothing else. That frame object would be used to navigate to multiple pages and different views of the applications depending on the user and application interactions.

<Grid>
   <Frame Name="mainFrame" NavigationUIVisibility="Hidden" />
</Grid>

One thing to note here is that Frame has a (IMO) really annoying navigation UI. You should keep that hidden. Apply the same setting to frames, or use this in the application resources and apply is application-wide.

This is helpful, in changing the views instead of changing the visibilities of the grids and stack panel objects. However, on the runtime exchange, this won’t be available. To be able to use it, you would have to store the frame instance at a location which can be accessed from external objects too. I created the following property in the class, to hold the reference to this frame.

public static Frame MainFrame { get; set; }

Static fields would be accessible from the out objects, without having to require an instance. It would be helpful and you will find it being helpful in the later source samples below. The class itself is like this:

public partial class MainWindow : Window
{
    public static Frame MainFrame { get; set; }
    public static bool LoggedIn { get; set; }

    public MainWindow()
    {
        InitializeComponent();
        MainFrame = mainFrame;

        // Chance are, its not logged in.
        MainFrame.Content = new LoginPage();

        // Initialize the Imap
        ImapService.Initialize();
    }
}

Pretty much simple, developing the building block of the application. This would allow us to have separate UIs for our separate concerns and features. The main things would be done, rendered and handled by the separate pages that we will have for our application.

Before I get started with rendering the later sections of pages, I would need to explain the IMAP base controller that I had developed to provide and serve me with the basic functionality and features of the IMAP protocol.

ImapService object

It is better to keep things allocated at the same place so that when we need to make a chance we can make change right from there, instead of having to search, “Where I wrote that part of API?” That is why, this service object would contain all of the functions that are going to be used in the application.

We need 4 functions and an event handler (for IDLE support; discussed later)

  1. Initialization function; which is a requirement by design.
  2. Login and logout functions.
  3. Function to get all folders
  4. Function to fetch the email messages of a function.

The event is used to notify when a new message comes.

The object is defined as below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using ImapX;
using ImapX.Collections;
using System.Windows;

namespace ImapPackage
{
    class ImapService
    {
         private static ImapClient client { get; set; }
  
         public static void Initialize()
         {
              client = new ImapClient("imap.gmail.com", true); 
 
              if(!client.Connect())
              {
                   throw new Exception("Error connecting to the client.");
              }
         }


         public static bool Login(string u, string p)
         {
              return client.Login(u, p);
         }

         public static void Logout()
         {
              // Remove the login value from the client.
              if(client.IsAuthenticated) { client.Logout(); }
       
              // Clear the logged in value.
              MainWindow.LoggedIn = false;
         } 

         public static List<EmailFolder> GetFolders()
         {
              var folders = new List<EmailFolder>();

              foreach (var folder in client.Folders)
              {
                  folders.Add(new EmailFolder { Title = folder.Name });
              }

              // Before returning start the idling
              client.Folders.Inbox.StartIdling(); // And continue to listen for more.

              client.Folders.Inbox.OnNewMessagesArrived += Inbox_OnNewMessagesArrived;
              return folders;
         }

         private static void Inbox_OnNewMessagesArrived(object sender, IdleEventArgs e)
         {
              // Show a dialog
              MessageBox.Show($"A new message was downloaded in {e.Folder.Name} folder.");
         }

         public static MessageCollection GetMessagesForFolder(string name)
         {
              client.Folders[name].Messages.Download(); // Start the download process;
              return client.Folders[name].Messages;
         }
    }
}

This basic class would be used throughout the application to load the resources and messages. I won’t go in the depth of this library because I will just explain a few points and how to use the basic functions and features. However, the library is very strong and powerful and provides you with every tool and service required to build a full featured email client.

Login page

The first step would be to authenticate the users by asking them for their username and passwords. Typically, your application would cache the user authentication details; in most cases username, and in some cases if user allows, then the password too.

In a real application you are going to have a full authentication page, which would provide the fields such as input for username, port, IMAP hosts and passwords etc. But however in my application I have not used any of such fields because I wanted to keep things really simple. I just asked user to username and password, and used other settings hard coded in the application’s source code.

The XAML of the page looks like this:

<StackPanel Width="500" Height="300">
    <TextBlock Text="Login to continue" FontSize="25" />
    <TextBlock Text="We support Google Mail at the moment, only." />
    <Grid Height="150" Margin="0, 30, 0, 0">
       <Grid.ColumnDefinitions>
           <ColumnDefinition />
           <ColumnDefinition Width="3*" />
       </Grid.ColumnDefinitions>
       <StackPanel Grid.Column="0">
           <TextBlock Text="Username" Margin="0, 5, 0, 15" />
           <TextBlock Text="Password" />
       </StackPanel>
       <StackPanel Grid.Column="1">
           <TextBox Name="username" Margin="0, 0, 0, 5" Padding="4" />
           <PasswordBox Name="password" Padding="4" />
       </StackPanel>
    </Grid>
    <Button Width="150" Name="loginBtn" Click="loginBtn_Click">Login</Button>
    <TextBlock Name="error" Margin="10" Foreground="Red" />
</StackPanel>

This content would be loaded and since in the constructor for the MainWindow we had loaded this page, we will see this page initially.

Screenshot (2082)
Figure 2: Authentication page for the application.

Definitely, you are going to provide extra sections and fields for the users to configure the way your application is going to connect to their IMAP service provider. However, this would also work. Mozilla’s Thunderbird does the same, they just ask for the username and password and find the correct settings and configurations themselves. But, however you want, you can write the application in your own way.

We just need to handle the event of the button,

private void loginBtn_Click(object sender, RoutedEventArgs e)
{
    MainWindow.LoggedIn = ImapService.Login(username.Text, password.Password);

    // Also navigate the user
    if(MainWindow.LoggedIn)
    {
        // Logged in
        MainWindow.MainFrame.Content = new HomePage();
    }
    else
    {
        // Problem
        error.Text = "There was a problem logging you in to Google Mail.";
    }
}

Clearly, this would just make the calls to the service that we created previously. The benefit is that we just need to add the validation and verification code here. We ¬†don’t need to write anything new here because we have done all of that in the previously set up service named, “ImapService”. At the end, if everything went correct, it would navigate the user to the home page.

Note: There is no asynchrony in the application and that is why, it may “freeze” sometimes. To overcome this problem you may want to rewrite the entire service provided to develop it with async/await.

Home page

In this application the major component is the home page, the home page is where the folders and messages would be loaded. There is no difficulty in loading those, because we have already created the function to execute to get the folders and messages in those folders (read the ImapService class once again).

The basic XAML controls that are being used here, are the following ones:

<ListView Name="foldersList" SelectionChanged="foldersList_SelectionChanged">
    <ListView.ItemTemplate>
        <DataTemplate>
            <TextBlock Margin="10" Cursor="Hand" Text="{Binding Title}" Name="folderTitle" />
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>
<Frame Grid.Column="1" Name="contentFrame" NavigationUIVisibility="Hidden" />
A list view that would render the folders and another frame that would be used to load multiple pages. I used the same method to hold a reference to this frame, in my class object and I loaded it using the contructor itself.
public HomePage()
{
    InitializeComponent();
    ContentFrame = contentFrame;

    foldersList.ItemsSource = ImapService.GetFolders();

    ClearRoom();
}

Just using the same small steps, I created the page. Which would then have its own functionality and would allow the features to handle their interaction with the users.

Screenshot (2052)Figure 3: Folders listed in the application.

We can load the folder messages by selecting a folder. That would show the messages in the right side and we can then read a message. The code for which is provided in the application itself.

private void foldersList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    var item = foldersList.SelectedItem as EmailFolder;

    if(item != null)
    {
        // Load the folder for its messages.
        loadFolder(item.Title);
    }
}

private void loadFolder(string name)
{
    ContentFrame.Content = new FolderMessagesPage(name);
}

This way, we load the folder in the content frame that we are having in the application’s home page.

Sending the emails

We have talked a lot about the IMAP protocol and I guess I should also share a few points about the SMTP protocol support in this application. SMTP protocol support is provided natively in .NET framework.

I have written an article for SMTP protocol support in .NET framework, which you may be interested in,¬† Sending emails over .NET framework, and general problems ‚Äď using C# code. That article discusses a lot about doing so, and guess what, I used the same code from that article and wrote the entire feature for sending the emails on it.

I created the “send email” form as follows:

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition />
        <ColumnDefinition Width="3*" />
    </Grid.ColumnDefinitions>
    <StackPanel Grid.Column="0">
        <TextBlock Text="To" Margin="0, 5" />
        <TextBlock Text="Subject" Margin="0, 5" />
        <TextBlock Text="Body" Margin="0, 5" />
    </StackPanel>
    <StackPanel Grid.Column="1">
        <TextBox Margin="0, 3" Padding="1" Name="to" />
        <TextBox Margin="0, 3" Padding="1" Name="subject" />
        <TextBox Margin="0, 3" Padding="1" Height="130" Name="body" 
                 AcceptsReturn="True"
                 ScrollViewer.CanContentScroll="True" 
                 ScrollViewer.VerticalScrollBarVisibility="Auto" />
        <Button Width="50" Name="sendBtn" Click="sendBtn_Click">Send</Button>
        <Button Width="50" Name="cancelBtn" 
               Click="cancelBtn_Click" Margin="130, -20, 0, 0">Cancel</Button>
    </StackPanel>
</Grid>

Although, I understand that is not the best of what I could have made, but, for the sake of this post, that would (should!) suffice. This would allow the user to enter the details for a very basic email.

Screenshot (2056)
Figure 4: SMTP protocol test, email form. 

Upon clicking the send button, the email would be sent. The code to do so is really straight-forward and (as mentioned ago) available on that article I wrote about sending the emails in C#.

Bonus: IDLE support for folders

Before I wind things up, I wanted to enlighten the topic of IDLE support. In IMAP, IDLE support means that your application don’t need to send the request to the server in order to fetch new messages. Instead, the server would itself send the data to the client, whenever a new email is received.

What I did was, that I wrote that code to support IDLE feature in the ImapService because that was a service of IMAP and not the application itself. I updated the folder fetching code and added the following statements, (or since I haven’t shared the code at all, the code is like the following),

public static List<EmailFolder> GetFolders()
{
     var folders = new List<EmailFolder>();
 
     foreach (var folder in client.Folders)
     {
          folders.Add(new EmailFolder { Title = folder.Name });
     }

     // Before returning start the idling
     client.Folders.Inbox.StartIdling(); // And continue to listen for more.

     client.Folders.Inbox.OnNewMessagesArrived += Inbox_OnNewMessagesArrived;

     return folders;
}

private static void Inbox_OnNewMessagesArrived(object sender, IdleEventArgs e)
{
     // Show a dialog
     MessageBox.Show($"A new message was downloaded in {e.Folder.Name} folder.");
}

The handler and the event would then work as a counter-part and would provide us with a very beautiful service in which our application would be able to fetch the messages when a message is received!

We can use a folder, to start IDLE for. In my case, I used Inbox folder. Inbox folder would let us know for any new email message that we may receive and we can then use the properties of the event arguments to find out which folder received which message.

Points of Interest

In .NET framework, SMTP protocol is supported natively, implementing the IMAP protocol is a bit of a task. For that, developers may use ImapX, which is a free and open source package and library for C# applications that may want to support email messages.

In this blog, I have explained the methods used to build the applications that can receive and send email messages on the internet to the clients. IMAP protocol is much preferred and loved protocol because it doesn’t need you to download the emails, you can just download the stuff that you need.

If I write something extra, I will update the post or create a new one. Do leave me a message if you find something missing.

Building a custom documentation tool

Introduction and Background

A team of software developers would all be willing to write a great amount of documentation because after all it is the document that provides their users a resource from where they can get some help. But if your team believes in Agile development methodologies, then you are better off left with programming and “no-documentation” face! That is not at all a problem to most of the programmers, but that is also not a good practice after all. Most of the libraries and tools out there require a good documentation of their APIs. This can be understood by the fact that many programmers are building applications for Microsoft platforms and not for other platforms. I consider myself one of them. The fact is easy, to get any kind of help in Microsoft platforms, I just need to go to MSDN (Microsoft Developer Network) and I can get any document, help with any framework, with any object, with any task and much more. Microsoft has really invested a lot of their times in building a great amount of resources on internet. Their investment pays off in a way that others cannot expect to get paid. The result is, they get a lot of attention from developers, and novice programmers also feel great while programming. Compare this to that of a Linux, compare this to that of any Java library and so on. I don’t want to be biased, but Java APIs, even of Oracle, are very badly written. There is a list of functions, but no remarks, no explanation, no nothing. Which makes it much more complex for beginners to learn and get a grasp of.

Currently I am seeking my Master’s degree in Computer Science and I am going to have a project to build later this year. While that has some months to come, I am thinking of something to build that would help me in many ways. One of them is to build a custom program that helps me to document the API so that I can submit that to the professors when they ask me for my project.

This blog post is about the “things” I have thought about, while building the tool. I haven’t built the tool yet, but I am hoping to have it built soon. But, I can show you the blueprint and the scratch code for that.

Why document the code?

If you are an indie developer, and you don’t like to share the code with anyone, don’t worry about this. Chances are, that 2 or 4 years later, you may “still” have the idea, why you wrote down that code. But if you also have to share the same code with your partner, team or external world. Then, you should either comment the code well. But… In the cases, where you don’t want to share the internal code, then you should provide a well written API for that code.

That would save you from many messages, emails and feedbacks, like, “How to do that?”. That question annoys many people because, developer of that API is already aware of the “simplicity” of the API, but others don’t know it. They are not aware of the objects introduced and so on. In such cases, you should always consider documenting the code well, so that others, when face a trouble, can simply read that documentation and say, “Oh, that’s how I do that!”

In many cases, it also helps you when after 2 years, you lose the focus that you had back in those days when you started the project. Happens to me too.:-)

keep-calm-and-document-your-code
Figure 1: Keep calm programmers! 

How to build a custom documentation tool?

I am sorry to disappoint you guys, but I am going to talk about C# only. There was a lot of time when I was learning other frameworks, writing applications for Linux, compiling articles and books for other operating systems. This is, when I feel I need to get back to where I belong. I belong to C#. I am going to use C# to show you how you can build the application that documents the code that you have written. Now that is somewhat a complex idea and process. But, for the sake of this post, I am going to keep things really very short here and I will demonstrate the use of the very basic concepts to build such a great and vital tool for you team so that they can focus more on the programming part, and leave the documentation part to this tool itself.

I am going to use the following three basic features:

  1. C# language itself.
    • You can use any framework, Console, WPF, WinForms etc.
  2. HTML document for previewing the results.
    • You may use ASP.NET applications or web sites for previewing. I used static HTML pages.
  3. Some reflection.

In the above parts, I think most of you would get yourselves confused when it comes to “Reflection” in C#. Well, it is not that tough part to understand. Reflection in C# (or .NET itself) is a very simple and easy concept to understand. Using reflection, we can simply, get to know the assemblies, objects, classes and their members, on the run-time. In the IDE, we know what is the class name, what are functions defined. But how to know on run-time, is a part of reflection.

Introduction to Reflection

Before, I finally end up the post I want to give you an overview of the reflection in C#. If you have ever programmed in C#, you are aware of, typeof() operator or GetType() function. Both of them are the first steps toward the reflection. Basically, reflection is performed on types of the objects. Types expose the assembly information, members information, properties, functions (methods) and events information… Much more! So, we use the signature to determine many values, like the names, assembly, namespace, versioning etc.

I am going to use the same tool, and I am going to extract the properties from these types and I am going to build an HTML documentation for the classes. This is same mechanism which is used on MSDN or any other “good” documentation. You should never write the documentation yourself, one object after the other. Create an interface which does the underlying task and then do the modifications and reviews.

I would end this section with this one code sample:

class Student {
   public int ID { get; set; }
   public string Name { get; set; }
}

// In the main function
public static void Main(string[] args) {
    var type = typeof(Student);

    // Above line is similar to, 
    var type = new Student().GetType();

    // But prefer the previous one. 

    // We can use the variable to extract the name of the type.
    Console.WriteLine(type.Name);
}

// Output: Student

We get many other similar functions that we may use to actually get the information on the class that we are using.

You should try them out, for further reading please refer MSDN, System.Reflection Namespace.

Building the HTML document

As I have already mentioned that you can use ASP.NET web site, web application too, to represent the documentation for online users. But I used static HTML pages, which are much simpler to build and don’t have to manage the rest of the underlying stuff for the application.

What I did was that I used a C# program to render the HTML content for me. Based on the type that I pass. I created a new class, “DocumentHelper”, and created a function which takes an object and renders the HTML document for its name. Here is what I made:

<!doctype html>
<html>
<head>
   <title></title>
   <style>
      html {
         margin: 0 auto;
         font-family: 'Segoe UI';
         font-size: 13px;
      }
 
      body {
         /* Nothing special here. */
      }

      table {
         min-width: 500px;
         border: 1px dashed #cecece;
         padding: 5px 10px;
         text-align: center;
      }

      table tr:first-child {
         width: 150px;
         font-size: 15px;
         font-weight: 600px;
      }
   </style>
</head>
<body>
   <h4></h4>
   <p></p>
   <table id="properties">
 
   </table>
   <table id="methods">
 
   </table>
</body>
</html>

This is the very basic HTML document, that will be used to render the details for the item. We can then use the C# program to loop over the properties and render them in our HTML document.

If you would consider using C# 6, you would be provided with useful features such as, string interpolation etc.

// Create the instance
StringBuilder builder = new StringBuilder();

// Append html head
builder.AppendLine("<!doctype html><html><head>");

// Append title and the style here
// Append the lines, based on an iterative loop

// Append the final lines
builder.AppendLine("</body></html>");

// Get the document
var htmlDoc = builder.ToString();

You can then store the file, and at the same time, execute the call to show the file too.

System.Diagnostics.Process.Start(linkToFile);

It would open the default application to render the HTML file (if you saved the file with .html or .html extension). In my case, it was Google Chrome. I did not write the table content or anything, but just the simple title and the full name of the object. Whose web page screenshot is:

Screenshot (943)
Figure 2: Rendering the dynamic HTML content.

This way, we can use other classes and their types to render the documentation web pages too.

Points of Interest

In this post, I have talked about the simplest method required to build a tool that automatically documents the code in your project. You can share the HTML documents with your clients who can easily read those documentations based on the content that you have provided based on the UI you use in the HTML document.

Of course this is not complete, this was just the idea that I was having and I am hoping to complete this project as soon as possible and if I do develop, I will share the source code publicly on GitHub.

There are many more things to do:

  1. Learn Reflection
  2. Find a good way to store the HTML documents.
    • In database
    • In static files
    • Other data source
  3. Build a crawler for your API

Crawler would simply crawl from one object to another using the relations and would continue to build the documentation.:-)