Category Archives: Windows Presentation Foundation

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.

Using C# for cross-platform development

Introduction and Background

I wrote a bunch of articles about C# programming, but all of them were Windows or .NET oriented. I want to write an article about C# programming on multiple platforms. C# is a very powerful and strong programming language with a very solid foundation over programming concepts. The language is indeed designed to work on high-level applications and initially it was designed to run for .NET applications only, but as time passed it got introduced to other platforms and applications too.

In this article, I will share a few things that you can do on Windows and Linux. I don’t own a Macintosh so I won’t be able to share that concept but I guarantee the procedure to program a Mac application in C# is also similar to this one! Cross-platform itself means to be able to do everything that you can do one platform, on another one too. C# is able to do the same, on every platform. The concept only requires to modify your compilers to be able to accept new environments, same thing applies to C++ and Java and other similar high-level programming languages. C# also works in a similar manner. The concept of C# compilation is that the code doesn’t compile down to machine code. Instead C# code is compiled down to a bytecode, which is later assembled and translated to machine code by the virtual machine; .NET’s virtual machine! That is what makes C# programming language very powerful and at the same time flexible and portable programming language.

If you are a “diagram” lover, please view the following image:

IC15013
Image from MSDN article: Introduction to the C# Language and the .NET Framework

The assemblies are sent to virtual machine, who then translates the code using their metadata and other stuff all the way down to the metal. That is exactly, why it is possible to execute the same C# code on every machine, every platform and every architecture (x86 and x64). Although the instructions are different, but bytecode helps C# to be executed on any machine! In this article, I am going to use the same concept (and a tool) to help you write native applications on other platforms, too.

References:

If you want to learn more about C# or cross-platform, you may read the following contents,

  1. Cross-platform programming: An open-source overview
  2. Introduction to the C# Language and the .NET Framework

Cross-platform tools for C#: Mono Project

If you started programming on Windows, you might have used Visual Studio as your first IDE and specifically, chances are that you started programming using C# programming language. C# is widely used, that it managed to get attention of developers from other platforms and systems too. Mono Project is one of such products which came up not in a near future, but had been known since a while. Mono Project was started to provide C# developers a cross-platform experience. Mono Project can be installed on the following platforms:

  1. Windows
  2. Linux
    This counts any of the distro of Linux kernel, Ubuntu, Red Hat and so on.
  3. OS X

Mono Project can then be used to compile the C# projects as a native application on that platform. In my opinion, that is pretty much self-explanatory, each platform has the resources and architecture information and the related binaries used to target the platform, Mono Project uses those resources and compiles the project down to bare metal components.

In this post I am going to use Mono IDE, not Visual Studio, because Mono is a cross-platform C# development environment, whereas Visual Studio is a Windows-only tool. But C# can be used on other platforms, all thank you to Mono Project! Using Mono Project you can build,

  1. Console applications in C#
  2. Graphical applications using C#
  3. ASP.NET web applications

Mono Project also allows you to use VB.NET, but I won’t be talking about that, instead I am going to cover C# only.

Getting starting…

First of all, you may want to install the Mono on your environment. If you are using Windows, then (in my opinion), you should consider using Visual Studio. You can get Visual Studio Community for free if you are a student, learner, open-source developer or a small team. That’s the beauty of Visual Studio. But, if you are going to develop applications using C# where Visual Studio is not supported, you should consider downloading and installing Mono Project, which includes everything starting from the Mono documentation, Mono IDE and the compilers for the languages.

I did say, that you should try Visual Studio on Windows but if you want to learn other environment on Windows, you can for sure install Mono on your Windows environment too. It would give you a much better experience to program C# applications on non-Windows environment and all by just using terminal or command-line commands to compile and use the application. I have learnt a lot of things by using the terminal in Linux environment, so I would also recommend you guys to give it a try!

Installing Mono

Installing the Mono is different on different environments, on Windows and Mac it is pretty much same. All you have to do is to download the installer and run it. It installs everything for you. But on the environments, like Linux you have to create repositories and then start installing the packages. That takes a bit of time. I will show you how to do that on all of the environments!

1. Installing on Windows/OS X (Mac)

The procedure to install on Windows and Mac is similar. Just download the package and then go install it, by executing the installer. It would install the Mono project including all of the dependencies, files and executables. You can then use your Mono project to build C# applications on platforms, other than .NET themselves.

Install Mono on Windows
Install Mono on Mac OS X

2. Installing on Linux (or Linux distros)

Now the things here get complicated. In Linux, you are going to use the terminal and then execute the commands to build the repository systems and then install the packages, for every Linux distro, it is different process so that may also cause a trouble and that is why I won’t be sharing a single script “to rule it all”, instead I will be providing you with a link that contains all of the scripts that you should execute to get your job done! In the Linux environments, you can execute commands differently to have your job done! Head over to this page to find out which command set would work on your environment. That page would give you the commands that you can execute to set up the environment. Rest assured, now you can execute the following command in your own environment to install the Mono assemblies.

sudo apt-get install mono-complete

This command may also differ based on the environment, some may use yum, some may use rpm or others. Please refer to your own installer commands.

Wait, I cannot find the IDE. Where is it?

Correct, until now, you have only installed the binaries and assemblies required to make Mono workable. You have not yet installed the IDE. Until now you just installed the compilers and binaries. To install the IDE, execute the following command:

sudo apt-get install monodevelop

Now, head over to your IDE that was recently installed and start it! You are going to love it, and well, the folks have seriously put some great efforts in it.

Screenshot (1547)
Ubuntu Studio showing the list of IDEs.

Screenshot (1549)
Hello world project opened in Mono Project.

In the next step, I will share a few example of using C# to build cross-platform applications. Head over to the next step!

References:

I am attaching a few good links in this section too,

  1. Visual Studio Community
  2. Mono Project — Official Website
  3. Install Mono

Building the applications

In this section, I will show you three sample codes for C#, which you already do know in .NET environment. The samples are not to give a new task in C#, but rather just a simple code, to help you understand how C# can be used to execute commands on different environments, different platforms and so on.

Hello world from Linux

First of all, I want to make my application greet me, from a Linux environment, using the same code that you would use on .NET environment. You all are already aware of the following code,

using System;
using System.Net.Http;

namespace HelloWorld
{
   class MainClass
   {
        public static void Main (string[] args)
        {
            Console.WriteLine ("Hello, who's there?");
            string name = "";
            name = Console.ReadLine ();
            Console.WriteLine (string.Format("Hello {0} from Linux using C#.", name));
        }
    }
}

Aren’t you? Yes, it’s the same “elementary” C# code to greet someone! This time, running on a non-.NET environment. This would just prompt me for some input and then continue to do what it was intended to do.

Screenshot (1550)

Pretty simple, right? But notice that this code now runs on native Linux environment. There is no underground .NET frameworks supporting it. In real, it is the Mono Runtime that actually does the processing underground. Please read the reference to Mono Runtime in the references below.

C# programming using collections

Collections are a great resource in any application, you can accept a long record of user data in a single object, that is of type: Collection. C# has been providing generic programming objects, for collections. Collections are much better than arrays, because collections are mutable, unlike arrays. In this section, I will show you how to write an application that consumes the collections.

I created a class object, to hold the values of the people. Then I created a list to hold “some” people and then printed their values. It is also a similar code.

using System;
using System.Net.Http;
using System.Collections.Generic;

namespace HelloWorld
{
    class MainClass
    {
        public static void Main (string[] args)
        {
            // Create the list of the people.
            var people = new List<Person> ();
            people.Add (new Person { Name = "Afzaal Ahmad Zeeshan", Age = 20 });
            people.Add (new Person { Name = "Sofiya Zeeshan", Age = 19 });
            people.Add (new Person { Name = "Daniyal Ahmad Rizwan", Age = 15 });
            people.Add (new Person { Name = "Eminem", Age = 43 });

            // Printing the details for people.
            foreach (var person in people) {
                Console.WriteLine (person);
            }
        }
    }

    class Person {
        // Provide the attributes.
        public string Name { get; set; }
        public int Age { get; set; }

        // Override the default ToString
        public override string ToString ()
        {
            return string.Format ("[Person: Name={0}, Age={1}]", Name, Age);
        }
    }
}

How this code actually ran, please see below.

Screenshot (1551)

It just prints everything and then terminates. These were a few things that were basic. Let’s try out if C# still has the same power or not, why not try out Internet access in C#?

Using C# to access online resources

Now in this section, I will be referring an online API of my own to access the data. This may make things a bit tough, if you have never worked with System.Net namespaces in .NET framework. I will be using an object from these namespace and then I will call the functions to actually download the data from an online API and then I will print it.

Linux also provides the similar manner to use the TCP/IP protocol that is why C# code written for Windows would work in a similar manner with Linux and other Mac’s OS X system.

In the following code, I have also used another concept in C#, asynchronous programming. Mono supports async models of C#, and you can avail the services right in the IDE, just like Visual Studio. The code I have used is like the one below,

using System;
using System.Net.Http;
using System.Collections.Generic;

namespace HelloWorld
{
    class MainClass
    {
        public static void Main (string[] args)
        {
            downloadAndPrint ();
        }

        private static void downloadAndPrint() {
            System.Threading.Tasks.Task.Run (async () => {
                using (var client = new HttpClient()) {
                     Console.WriteLine ("Downloading the data...");
                     var message = await client.GetStringAsync("http://afzaalahmadzeeshan.gear.host/api/sample");
                     Console.WriteLine();
                     Console.WriteLine(message);
                }
            }).Wait();
            Console.WriteLine ("Exiting the function..");
        }
    }
}

The above code simply downloads the response as string and prints it. This shows, that C# not only just works in the console, but it also works perfectly with the protocols on different systems. All of this is managed by the Mono Runtime.

Screenshot (1552)

So, I guess this is enough to demonstrate how C# can be used.

References:

A few topics that you should consider reading:

  1. The Mono Runtime
  2. HttpClient Class
  3. List<T> Class
  4. Asynchronous Programming with Async and Await

Points of Interest

In this article, I have demonstrated how you can use C# to develop cross-platform applications. There is no need to learn multiple languages to target multiple frameworks and application systems. You can use one single programming language, even C#, and write native applications on multiple platforms.

Although C# doesn’t execute natively, even on those platforms. Mono Runtime is responsible for executing the applications on those platforms. Just like .NET’s virtual machine or Windows Runtime executes C# code on Windows environments. On other platforms (and including Windows if compiling and using Mono), you can use Mono Runtime to target the platforms and make use of .NET libraries and lightweight programming model of C# programming language.

I hope you like this article, wait up for the next articles, or write back to me to get more. 🙂

[Review] Spire.Doc .NET library for cross-file format document creation

Most of the time developers waste their 90% of time thinking how to generate Office format documents. Perhaps, that is what is being used by most of the companies and developers right now. Microsoft Word, PDF, Rich Text Format and other similar formats are in high demand now a days.

Creating custom interoperability service is a very time-consuming, and a less efficient function when enterprise is the solution type for your application. Third-party applications provide us with a very good solution to such tasks, which can enable us to kick-start our applications in a matter of few minutes.

Spire.Doc (by E-Iceblue) is one of them. I have personally tried the software library for .NET framework and it is kind of a helpful tool for .NET developers (no matter whether you are a Windows Form, Windows Presentation Foundation or ASP.NET developer) for generating cross-file format files.

Note: By cross-file format I mean you can generate the output in a number of formats, file based (under files, this library supports PDF, Microsoft Word, HTML web pages, Rich Text Format and more), it also supports that you can generate images for your documents and to get the streams for your document resources.

Spire.Doc API

I have used Spire.Doc (and other connected APIs and namespaces) to give it a quick look and start. If someone has a great understanding of how these documents are, what a paragraph is and what can be added to different components.

The very much basic document in Microsoft Word would require only

  1. Single document object
  2. Single section to contain the data. This is also the page of your application’s document.
  3. A number of paragraphs, depending on whether and what you want to add to the document.
    The paragraph would allow you to add images or other stuff, such as text and characters; symbols in Unicode format you just need to pass the integer value for the Unicode character.
  4. Tables are also added to the section object, if required.

Spire.Doc namespace also allows you to save the document, in any number of format, ranging from PDFs to a wide variety of Microsoft Word formats.

Note for E-Iceblue developers

I have had a few intuition problems using the product, for a .NET developer, adding a new element to the current child hierarchy is something like this,

var element = new Element();
// Any properties or similar editions
parentElement.Children.Add(element);

Whereas, Spire.Doc supports adding the the objects to the document as,

var element = parentElement.AddChild();
// Child type is determined by the function called, AddParagraph, AddTable etc.
// Then element is edited out.

Perhaps, this is just my opinion and intuition problem. I would believe that most of the readers would not agree to me on this point. Also, the API guide is a good one, I loved it. But it lacks the description of the class that is open at the moment.

Few code samples for readers

Since review-only posts are not my style, so I would provide a few code samples to the readers also, as if to show how easy it is to use Spire.Doc library for their personal use. As, already mentioned this is a library to .NET framework, the library is consumable by every framework (although, E-Iceblue also ships the library in different versions, one for every framework on .NET).

The same code sample would work on Windows Forms, Windows Presentation Foundation, SilverLightASP.NET and (as I have tested it enormous times on) Console application.

Documentation of the Spire.Doc is available along with the package when you download it (and IMO it is a very much great and intuitive documentation, with a pretty much style as that of MSDN). You can always use the documentation application, to read the API and continue where you get stuck while developing the application.

Loading a new document

Loading the new document is similar whether you are trying to create a new document, or load it from an existing file. Spire.Doc provides you with constructors that can be used to initialize the Document object.

// First method, new document
var document = new Document(); // works

// Second method, existing document
var document = new Document("path", FileFormat.Docx);

In the above examples, there are two documents being generated (please ignore the document already exists in current context for a moment). First one is constructor used to generate a new document (perhaps for creating a new file), where as the second one is used to load existing file as a document object in your application. You can load files of any type discussed above.

Once loaded, you can then work with document to add new section, paragraph or other similar objects or to edit the existing objects in the document.

Editing the document

Editing the document is another key feature of this library, because it not only let you create new documents but also allows you to edit already existing documents and files; no matter what data type they hold. The key points are that you can edit the document (of any type) and save it (in any format).

You can add new paragraphs, or sections to your document which in turn allow you to add images and text to the document. (As already mentioned above) I do have a little problem with this process in Spire.Doc namespace, but still it is a great way of handle-oriented programmers, which have a great intuition for creating the object then saving the handle for further processes.

// Creating a document, adding a section and a new Paragraph
var document = new Document();

var section = document.AddSection();
// update the section, if required

var paragraph = section.AddParagraph();
// Update the paragraph, for example
paragraph.AppendText("Love for all, hatred for none!");
paragraph.AppendPicture(imageObject); // accepts System.Drawing.Image object

Now the above code is enough to generate a very much simple document, that has 1 section (page in document), and a very basic paragraph followed by an image; please look into Windows Forms image controls for more on the System.Drawing.Image object.

Saving the document

Final stage is saving the document on the file system, or processing it for further processes. Mostly, web developers would want to send dynamically generated Word or PDF files to their clients on run-time. Spire.Doc is a great way to complete this task.

Spire.Doc exposes functions to store the generated document in a couple of formats, you can use just one function, pass the type and you’re done! See below, (Continuing the previous example of document)

// Continuing from the previous example
document.SaveToFile("MyNewFile.pdf", FileFormat.PDF); // extension required

Above code would get the details from the document object, and would generate a PDF file with name MyNewFile. Um, you need to know that in this function you need to write the file extension also, otherwise it would generate a plain FILE in your file system.

Plus: Library also allows you to get results in Stream and Image formats. You should try them also!

Tested sample

The following code is a sample example of what I have discussed above (using the library for applications to generate PDFs and to send them to the clients on run-time using an SMTP server; for emails.

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

using Spire.Doc;
using Spire.Doc.Documents;
using Spire.CompoundFile;

using System.Net;
using System.Net.Mail;

namespace SpireConsoleApplication
{
   class Program
   {
       static void Main(string[] args)
       {
          // Create the document
          var document = new Document();

          // Add a section to document
          var section = document.AddSection();
            
          // Add paragraph to the section
          var paragraph = section.AddParagraph();

          paragraph.AppendText("Love for all, hatred for none!");
          paragraph.AppendPicture(
              System.Drawing.Image.FromFile("E:\\j'[oj.jpg")
          );

          document.SaveToFile(".pdf", FileFormat.PDF);
          new Program().SendEmail(".pdf");
      }

      private void SendEmail(string fileName)
      {
         using (SmtpClient sc = new SmtpClient("smtp.gmail.com", 25))
         {
             sc.Credentials = new NetworkCredential("", "");
             sc.EnableSsl = true;

             var message = new MailMessage(
                "justin17862@gmail.com", "justin17862@gmail.com",
                "Spire.Doc PDF file", "Email contains the attachment."
             );

             message.Attachments.Add(new Attachment(fileName));
             sc.Send(message);
         }
      }
   }
}

The above program would generate the PDF, and then send the PDF to the client; which is hard-coded in this example, you can use variables for giving out emails to the clients required.

The email was received,

The email with attachment generated on run-time in PDF format using Spire.Doc library.

The email with attachment generated on run-time in PDF format using Spire.Doc library.

Perhaps, this now shows how simple it was to use the library to generate run-time PDF documents and send them to client; yes, I love Cut the Rope game and the Om Nom character so I used his (or its perhaps, or maybe hers… Whatever) picture to be sent. The library can be used in WPF, Windows Forms, ASP.NET or other .NET framework applications, to generate the files on run-time, then they can be sent to the clients, opened as files on the desktop or shown to the users. I have personally enjoyed using it, ignore the intuition problems that I mentioned. 🙂

Pro tip: You can convert the Microsoft Word document to HTML format to show it in your web application also. So it solves the “How to show Microsoft word document in website” problem also.

Note: I did not use the license, you should use the license in order to remove the red watermark on the documents.

Review Excerpt

I would quote what I was saying to myself (while I was using the library to test the quality):

Spire.Doc is a very fast and efficient solution to enterprise applications for generating office documents in desktop and web applications on .NET framework. It removes the pain of interoperability from minds of .NET developers and provides a very agile solution to developers. A very much easy, recommended and efficient solution for cross-file format document generation.

References

The library is available on E-Iceblue’s website, you can also install the packages by executing the NuGet command in NuGet package manager console.

PM> Install-Package Spire.Doc

The packages (and other others by E-Iceblue for PDF and Excel based solutions) are available on the E-Iceblue’s account on NuGet.

You can also download the product from their website to use them in your own applications. I would leave the rest of application and resource up to you. Happy coding! 🙂

Handling events in WPF in an easy and short hand way

I would talk about the WPF events and how to handle them easily, perhaps you might already know how to handle them; XAML gives you a lot of good handy functions, but there are a lot of other good ways of doing the same.

Events in WPF

Events in WPF are similar to what we had in Console and Windows Forms. They provide us with notifications and procedures to handle the business logic based on what state of application is. They allow us to manage what to happen when the application is starting, what to do when the application is closing and when the user interacts with the application.

Interaction includes the button clicks, input value change, window resize and many other similar processes that can be handled to ensure that our business logic is always applied. Validation and other checks can be easily applied to check the values.

Handling the events

Although handling the events is another function, thus we require a function to perform (or get triggered) when a certain event is triggered.

Note: Please note that I would be using Visual C# for this article’s purpose, it would be different as to what VB.NET would provide you as intuition and library resource, so try to follow Visual C# and not VB.NET at the moment.

In C#, you can handle the event, by attaching a function to it. It is similar to say, “When this happens, do that“. You tell your application to perform an action when something happens. The similar action is perform when a new email is received in your email clients, or when download is complete; if notification gets raised for that download complete. The attachment of the event to another function is pretty much simple, the only thing to worry is the required dependencies (the parameters or values or objects required to handle the event).

Look at the following code,

<Button Click="handleEvent">Click me</Button>

The above code is a XAML code (remember we are in WPF), the function to handle the event would be like this,

void handleEvent(object sender, RoutedEventArgs e) {
   // 1. sender is the Button object, cast it
   // 2. e contains the related properties for the Click
   // Code here... Any code!
}

Now, the function handleEvent is attached to the Click event of the Button object. Remember that event needs to be raised in order to trigger that function.

Pretty much easy it is to handle the events in WPF, just embed the code in the XAML markup, and Visual Studio would generate the back-end code. Write what you want to be done and you’re good to go!

Using back-end code

As, you know you can do anything with back-end code. You can also attach the event handler to the control’s event using the back-end code. In this section, I would explain how can you do that using back-end code.

Since we used Button for previous example, I would use the same for this one. Attaching the event is as easy as 1, 2, 3…

button.Click += handleEvent; // 1

void handleEvent(object sender, RoutedEventArgs e) { // 2
   // Handle the event
}

Step 3 is the click event that is performed by the user. 😉

Easy isn’t it? (IMO, it is not! Look in the next section to make it even better!)

Simple way…

This section is the actual section, which I wanted to talk about. The simple way to handle the events in WPF. It uses the lambda expression, to generate the delegate functions which in turn are executed when the event gets raised. If you are unclear as to what lambda expression or delegate functions are, I would suggest that before continuing, you learn them from the links I have provided. 🙂

A very simple way (IMO) to handle the event in WPF is like this,

myButton.Click += (sender, e) => 
{
   // Handle the event
}

Notice the above expressions. It is a simple lambda expression, being resolved as a delegate function with two paramters (sender and e). The parameters are required by the event handler itself, so that is why we need to pass them.

Points of Interest

The above is the simplest way anyone can handle the event in WPF and is a very much short hand, because you leave everything to the context of the object itself. You skip one more step for casting the object, you also don’t have to create different functions with different appended names such as, “myButton_Click”, “myButton_MouseEnter”. All you need to do is just create a lambda expression and use it as the event handler. Pretty much simple isn’t it?

That’s all for now. 🙂 I hope, I might have helped you out in making programming WPF applications easier. I would post more of such helpful tips for WPF developers soon. 🙂 Stay tuned.