C# for the Impatient, Lesson 1 – The Basics

To be able to follow this tutorial, I assume that you have a working Visual Studio environment (I’m using VS2013). I’m pretty sure there are other ways to create C# programs (mono for example) but for beginners VS does a lot of magic that saves time. Maybe later as I understand the basics, I’ll investigate other options for creating and building C# programs. I also assume that you already know how to program and are just searching for a fast way to get started on C# (just like what I am doing/did), so I’ll be skipping many details here. All code examples in this tutorial are located at github, so you don’t have to copy and paste all the time from the browser.

We’ll start by creating a simple console application in which we will learn the basics of the language. This is done by selecting “File–>New–>Project”. Select “Console Application” under The “Templates–>Visual C#–>Windows” tree on the left. You have three things to decide: the name of the project, the name of the solution, and where they are located. A few words on solutions and projects: A solution is a logical grouping of projects. A project MUST be contained inside a solution. A solution may contain more than one project, and also elements that are not part of a specific project, like build files, or configuration files. A project is usually a single application component (.exe, .dll, service role, etc.). I created a solution called “learning-csharp”, and my first project is called “lesson1″. VS works it’s magic and opens a new file “Program.cs” that I can start editing. So let’s do the typical example and print “hello world” to the console:

using System;

namespace lesson1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World");
        }
    }
}

Now hit F5 to run the program. You will see a console that opens and closes. What’s wrong here? nothing – VS opened a console, executed the app and when the app finished, closed the console. But we want to see that the program really worked! so let’s add something that leaves the console open. This is easy – ask the user for input:

using System;

namespace lesson1
{
  class Program
  {
    static void Main(string[] args)
    {
      Console.WriteLine("Hello World");
      Console.ReadLine();
    }
  }
}

Now if you hit F5, the console will print “Hello World” and will stay on top, waiting for the user to enter something and hit enter. So go ahead and hit enter. This will let the program finish and close the console window.

Great, we have our first program running. Now let’s do a quick run on the language basics, starting with variables. Variables are declared giving them a type and a name, and optionally an initial value. For example:

int i = 1;
bool b = true;
string s = "hello";

When you type this in VS, you probably saw something interesting: auto-complete proposes both string and String, or int and IntXX where XX can be 16, 32, and 64. From the “simple programmer” POV, they are the same (Int16 is short, Int32 is int, etc.). Under the hood, we have both primitive types (int, bool, string) and classes (Int32, String). Bear with me here, we’ll get to classes later), with a direct matching between a primitive type and an a class. The primitive type is probably stored in a smaller memory space and when used as an object it is Boxed, and when an object is set into a primitive type it is Unboxed. So use the ones you like, just know that using only class types may reduce your performance because of Boxing/unboxing.

So let’s extend our function to write some variables and their values (changes only in the main function). I also added a new trick that shows how to print multiple variables to the console:

static void Main(string[] args)
{
  Console.WriteLine("Hello World");
  int a = 1;
  bool b = true;
  String c = "Something";
  var d = 34.5;
  Console.WriteLine("a = {0} is an integer, b = {1} is a boolean, c = {2} is a string, d = {3} is a var", a, b, c, d);
  Console.ReadLine();
}

Oh, I missed another cool (IMHO) feature of C# – the var declaration. I won’t get into details here (mainly because I don’t know them), but the idea is that if the compiler can understand what is the type of the value of a variable, then you can declare it as var. This comes really handy when you have long type names – which are a good practice. To finish this basic section, let’s define a couple of arrays. The array definition is similar to C/C++/Java. As a Java programmer, I tried using int array[] but it doesn’t work. So don’t try it.

int[] arr1 = {1,3};
int[] arr2 = new int[5]; 

Now for some control structures. We have the usual suspects here: for, while, and do-while.

for (int i = 0; i < 5; i++)
{
    Console.WriteLine("i is {0}.", i);
}

int j = 5;
while (j >= 0)
{
    Console.WriteLine("j is {0}.", j);
    j--;
}

int k = 5;
do
{
    Console.WriteLine("k is {0}.", k);
    k--;
} while (k >= 0);

And the unusual one: foreach.

int[] l = { 1, 2, 3, 4, 5 };
foreach (var item in l)
{
    Console.WriteLine("item is {0}.", item);
}

So putting everything together, here’s the program we have:

using System;

namespace lesson1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World");

            // simple variables;
            int a = 1;
            bool b = true;
            String c = "Something";
            var d = 34.5;
            Console.WriteLine("a = {0} is an integer, b = {1} is a boolean, c = {2} is a string, d = {3} is a var", a, b, c, d);
            Console.ReadLine();

            // Arrays
            int[] arr1 = {1,3};
            int[] arr2 = new int[5];

            for (int i = 0; i < 5; i++)
            {
                Console.WriteLine("i is {0}.", i);
            }
            Console.ReadLine();

            int j = 5;
            while (j >= 0)
            {
                Console.WriteLine("j is {0}.", j);
                j--;
            }
            Console.ReadLine();

            int k = 5;
            do
            {
                Console.WriteLine("k is {0}.", k);
                k--;
            } while (k >= 0);
            Console.ReadLine();

            int[] l = { 1, 2, 3, 4, 5 };
            foreach (var item in l)
            {
                Console.WriteLine("item is {0}.", item);
            }
            Console.ReadLine();

        }
    }
}

I think this is enough for a first lesson. Before we finish, let’s talk a bit about conventions. As an experienced (and pedantic) programmer, I really like to follow language conventions, both in the formatting and in the naming of elements. This is because conventions makes it easier to read code by reducing how much the brain has to process, because it recognizes the convention as a pattern in the code (I just made up that explanation, but I’m sure I can prove it anecdotally). So these are the basics (based on this and this articles):

  • Names use camelCase. Variables with initial lowercase, classes with initial uppercase.
  • Every statement is in one line, including opening and closing braces (this REALLY bothers me).
  • 4 spaces indentation
  • Namespaces should follow the [Company].([Product]|[Technology]).[Feature].[Subnamespace] format.

Hope you enjoyed the tutorial. More will be coming (hopefully) soon.

Creating an OPM GEF Editor – Part 23: Drag & Drop from the Palette

Previous tutorial: Creating an OPM GEF Editor – Part 22: Enabling Select-All Action in a GEF Editor

Doing D&D from the palette never seemed to me an important feature, but after seeing this question on SO, I thought to myself that this shouldn’t be so complicated. So I took the challenge, and after 1 hour of shoveling through the GEF examples, I found how this is done. Someday, someone must write good documentation for GEF… but in the meantime, this is how it is done.

First, you need to add two lines to the graphical editor’s configuration (lines between D&D comments):

protected void configureGraphicalViewer() {
  super.configureGraphicalViewer();
  getGraphicalViewer().setEditPartFactory(new OPMEditPartFactory());
  getActionRegistry().registerAction(new ToggleGridAction(getGraphicalViewer()));
  getActionRegistry().registerAction(new ToggleSnapToGeometryAction(getGraphicalViewer()));
  getGraphicalViewer().setContextMenu(
    new OPMGraphicalEditorContextMenuProvider(getGraphicalViewer(), getActionRegistry()));
  configureKeyboardShortcuts();

  // D&D
  getGraphicalViewer().addDropTargetListener(new TemplateTransferDropTargetListener(getGraphicalViewer()));
  getEditDomain().getPaletteViewer().addDragSourceListener(
    new TemplateTransferDragSourceListener(getEditDomain().getPaletteViewer()));
  // end D&D
}

I executed the new editor, and D&D still didn’t work… I was missing something. So I went and checked the Shapes
example and found that the palette entries created there are of type CombinedTemplateCreationEntry and
not the regular CreationToolEntry which I am using. This seemed in the right direction, so I changed one
of my palette entries:

private void addNodeTools() {
  CreationToolEntry entry =
    new CreationToolEntry("Label", "Create new Label", new LabelFactory(), ImageDescriptor.createFromFile(
      this.getClass(), "icons/label.ico"), ImageDescriptor.createFromFile(this.getClass(), "icons/label.ico"));
  group.add(entry);

  entry =
    new CombinedTemplateCreationEntry("OPMObject", "Create a new Object", new OPMObjectFactory(),
      ImageDescriptor.createFromFile(this.getClass(), "icons/object.ico"), ImageDescriptor.createFromFile(
        this.getClass(), "icons/object.ico"));
  entry.setToolClass(CreationAndDirectEditTool.class);
  group.add(entry);

I also had to alter the OPMObjectFactory so that the OPMObject so that it comes
with default constraints. Now fire up the editor… And there it goes! it works! it works!!!

Enjoy your D&D. As usual, you can browse the source code at github.

Next Turorial: Creating an OPM GEF Editor – Part 24: “Smart” Multi-line Text Figure

Enhanced by Zemanta

JJTV Presentation – Creating Graphical Editors with GEF

Last week I gave a short presentation in JJTV meetup on how to create graphical editors with Eclipse and GEF. This is a very short and fast tutorial that shows the basic concepts and how they are developed. The code that implements the examples is far from being complete, but for those who are just getting started with GEF, you may find this interesting.

The code and the presentation can be found here.

 

Enhanced by Zemanta