Still don’t get the difference of “overloading and overriding”?

Mostly questions arise about the difference of overriding and overloading, these are two common terminologies being used widely in Object-oriented programming frameworks and languages. Because most new programmers come from Java or .NET framework, they have to stumble upon many of these Object-oriented programming concepts, among which these two are most confusing ones. In my opinion, the confusion is because of their names. Beginners often confuse themselves with another and cause a confusion that if understood fairly should never come again. In this post, my concern is to explain these concepts in details so that tomorrow when you stumble upon these two things you know which-is-which!

The answer to this question is regularly provided, but since most of the beginners hate to Google for a solution and want to re-start the thread, most of us write the answers in a blog format and then publish the content. The content published is then provided to the OP, which had no interest in searching for a solution. So, that said, this post also has been written by me on separate threads and forums. But re-writing the same thing is pretty much idiotic act and “saving it once use many” will be a good rule to follow. That is why, I am going to write all of the key notes, differences, personal experience in understanding and learning them and other resources. So that someday later when someone asks the same question, I can give him the link to this one single post so that he can learn and I also don’t have to write the same thing again.

What are these—concepts?

Now a days, in application programming, Object-oriented programming model is taken very seriously. Thus giving rise to many concepts, approaches and requirements. In such cases, these new concepts are usually named very tightly as they may require some additional English knowledge base for developers to understand them. I also had these troubles while learning what they actually are, until I tried to Google “define overriding” or like to Google “define overloading”. Google is a great resource for learning, (if you use Bing; you can prefer it) for beginners, I have found many resources and article already published there in a very much simple way which you can read and learn the framework or concepts. Technical documentations by the developers are not easily understood by beginners, that is why third-party or indie developers share their expertise with beginners in a blog-format or an article sharing media. Where they explain:

  1. What the framework is?
  2. Why was it needed at all?
  3. Who built it (optional)?
  4. Who uses it? (Required and is shared; no one wants to invest their time in learning something that no one uses)
  5. Am I to use it at any cost?
  6. How to learn it then?
  7. Source code compiles, am I there?

These questions are there in every beginner’s mind. They are zealous to learn, thus there comes the fun part where the author has to provide answers to all of these questions that arise in a reader’s mind. If he is not able to explain them, the reader simply consider the framework to be difficult enough. :-)

Same thing here, these are simply concepts, nothing more than that! Each OOP language implements these concepts and provides interfaces and other resources to using these concepts in their application programming models. Nothing else, :-)

Overloading and overriding are just two names of different concepts, they are indeed different and sometimes confused with each other due to their such strange names.

What is overloading?

Overloading, before I conceptualize the use in programming, you should understand the meaning of it first. Native English would get the idea of this term so easily since they use the word in their regular chat, where as for those who are not native, understanding the use requires understanding the word itself.

Definition for "overload" by Google.

Definition for “overload” by Google.

Thus, the definition provided by Google gives us a very broad and general idea of what this term is. Why would programmers then need it anyway and such other questions arise in our minds. In this section I will be covering those questions also! We are interested in the second definition, “give excessive work, responsibility, or information to.

First of all, recall the rules for identifiers, I don’t remember all of them! But there is a rule that an identifier can be used to identify one and only one variable, function or other tokens. So, if you have to write the functions that execute based on values provided or additional cases, you would have to write them with separate names.

CreateAccount(); // No arguments
CreateAccountName(string Name); // Full name argument
CreateAccountFnameSname(string Firstname, string Surname); // Both parts provided
CreateAccountFnameSnameAge(string Firstname, string Surname, int age); // Other details

But in OOP, you don’t need to do this. The concept of overloading is that you can define the functions with different signatures. A function will be identified based on the signature that it is being called with. The signature includes,

  1. Identifier name.
  2. Argument list.

Return-type cannot be used for overloading. 

Thus, it allows you to write the above code in a much more neater way, like this:

CreateAccount();
CreateAccount(string Name);
CreateAccount(string Firstname, string Surname);
CreateAccount(string Firstname, string Surname, int age);

Now the rest of the job is assigned to the compiler, it will determine which of these to use and which should be ignored.

/*
 * This function would trigger the second function, because I am passing only one string argument to it: CreateAccount(string);
 */
CreateAccount("Afzaal Ahmad Zeeshan");

/*
 * This would then trigger the third function, as I have provided it with 2 string arguments: CreateAccount(string, string);
 */
CreateAccount("Afzaal Ahmad", "Zeeshan");

/* 
 * No overload found for CreateAccount(type);
 */
CreateAccount(customType); // Assume customType is an instance of CustomType class

Thus it shortens the code for our need, and we can then use the functions to manage what is to be done in each of these cases. When one argument is provided that is the name, when two are provided they are first and surnames and so on. Plus it allows us to maintain the code-readability, because reading “CreateAccount(string, string, int)” is simpler than reading “CreateAccountWithGivenFirstNameSurNameAndAge(string, string, int)”.

Also, I mentioned that you cannot overload a function based on the return type, yes, you cannot.

class Person {
   int x() { return 0; }
   void x() { }
}// here comes ; in case of C++ program

The above program won’t work. I used a class to ensure they are in same scope, otherwise you will be scratching your head calculating the global and local scopes. Now, the above program complains that there is already a definition for x. I have tried them in both, C++ and C# and both say the same thing in different words.

C++ complains that a function cannot be overloaded based on the return-type. C# complains that there is already a function x defined with same parameter types. Which ensures that overloading doesn’t care about the return-types, it works with identifier for the function and the parameter types.

Operator overloading

Thinking of overloading, I came to the operator overloading also. The concept of overloading doesn’t just make up the functions overloading, operators can also be overloaded. Operator overloading is somewhat a different concept, you cannot create multiple functions for operators because operators are only applied to 2 items at a time, at max.

  1. Unary operators
  2. Binary operators

Unary operators are applied to a single object whereas Binary operators are applied to two objects at a time, in case where there is an expression taking part, the operators work in precedence and resolve the expression by working on 2 objects at a time.

int result = a + b * c / d;

/*
 * In the above expression:
 *   1. First of all c is divided by d; DivideByZero to be taken care of. 
 *   2. Then the result of (c / d) is multiplied with b.
 *   3. Finally the result of (b * (c / d)) is added to a.
 *   4. Their sum is then resolved as a value for variable "result".
 *
 * So the final expression that is resolved is as:
 */ 
int result = (a + (b * (c / d)));

You should also consider giving DMAS rule a quick look, it explains how to resolve the equation to get correct answer!

Operator overloading on the other hand is (but not restrained to be) performed for custom classes and objects. A very common example of such cases and learning techniques is the complex numbers class. Complex numbers have a real and an imaginary part, operator overloading is required to work around with addition, multiplication and other operations. So, for example, you can use a complex number object to work around with your operator overloading skills.

An example here would be to show how to add two Program classes in C#:

class Program {
   public static string operator + (Program a, Program b) { return "Added"; }
}

The above program has an overloaded operator, which returns a string message (see the function signature) “Added” each time you add two Program objects. That is just to show you, that operators also, when overloaded, allow you to perform the functions that you want to! You can return multiple results, such as array of results or you can pass another message, or like talked about complex numbers, you can return another complex number after the operation. In C# overloaded operators are static, so that is why I provided that keyword in the signature. Rest is the body for the function, where I am only returning a string-literal.

Still got questions?

Well if you still have some questions, I have some answers for them. My apologies if I can still not satisfy your needs. This is not a TL;DR.

1. Is it really required?
No, it is not required, but is provided as per your need. Whenever you need to overload your functions to allow multiple arguments or different arguments under the same process. You can use (function) overloading. Also, if your objects require arithmetic operations, addition or subtraction, you can overload the operators provided in the language also. Almost every OOP or widely used programming language supports operator overloading.

Note: Java and C do not support operator overloading. Java is an example of OOP language not supporting operator overloading, and C is a widely used programming language that doesn’t support operator overloading.

2. How does it work? (Applies to function overloading)
Overloading is worked out by compiler itself, it makes a choice based on the formal parameters passed to the function. There can be implicit casting that can take place to find a suitable function to handle the call.

Let us compile a few examples and see what happens:

void func(int i) { }
void func(char c) { }
void func(string s) { }
void func(double d) { }

// Call them
func('c'); 
func(5.0);
func("Hello");
func(0);

In the above cases, all of the functions are mapped to their representative function calls based on their parameters. First one gets called for the one that accepts a character, then a double (float can be casted to double and so on) and then comes a string later is the integer value. All of these choices were made by the compiler to detect which one to execute; based on the formal parameters being passed.

Off-record: I am waiting for more questions to be added to the list, if you have one, let me know.

What is overriding?

Just as we noticed a few things about overloading, we should consider learning the same things about overriding also. Let us break the concept into pieces and see what does it have for us and why should we use it anyway. Override, ever heard the same English term in a movie? If you are an Avengers fan of a same military-like movie fan or same, such as Interstellar ( I loved that movie), you must have heard them saying, “override” to some command that machine was talking about. We are talking about the same “override” function here. Google says,

Definition of "override" by Google.

Definition of “override” by Google.

In the above definition-list, we will find our interest in the second definition. “interrupt the action of (an automatic device), typically in order to take manual control.” Once again, Google has explained the term override and we can understand it in our general-programming concepts. Indeed overriding is used to overcome the default behavior of a function in our objects and APIs. So that we can enforce our own implementations for the process. In the coming sections, I will show you how to override the default behaviors and functions in languages; C# and C++ are to be taken into concern, Java and others can also be implemented but with a little modification as was in the case of operator overloading.

Object-oriented programming languages provide us with a function to inherit from base classes. In this post, I won’t share the inheritance concepts, but you should consider giving it a thorough look before moving forward. The inherited functions and other stuff is passed down to the child object, thus allowing it to perform the same functions as the previous one did.

class Father {
   public void Walk () { /* Walk some meters */ }
}

class Son : Father { }

// new Son().Walk(); would be OK!

Now, we know that we can define functions which can be passed down to the next, as they are generally. The Son object can also walk and so on. Where is the overloading then? The overloading comes, when Son performs a different action, or overrides the default behavior that was performed for a long time by the base classes; was intended to be performed.

So, for example in a carpenter’s family if father’s job was as a carpenter and somehow son doesn’t like that job and wants to be a football player, he can easily override that and perform his own actions. Like this,:

class Father {
   public virtual string Job () { return "Carpenter"; }
}

class Son : Father {
   // Override
   public override string Job () { return "Footballer"; }
}

In the above code, there were two tag marks added. One of them to the father and other to the son. The tag mark of “virtual” meant, that this can be overriden. So Father object does allow the derived objects to perform a different action, and child if interested in, can perform a different action or can maintain the family occupation and serve as a carpenter. The keyword “virtual” (or “abstract”; explained later) is required in order to override the default behavior in derived objects. It is just to change the implementation of a procedure.

Question and answer session:

1. What are virtual and abstract keywords?
These keywords are used to identify the functions that can be overridden. Abstract is somewhat a different story and it takes you back to the inheritance and the concept about concrete and abstract classes and etc. I am not interested in confusing you for those topics here.

Long story short, virtual is applied to the functions, that can be overridden.

2. Any real world implementation?
Yes, if you are a C# programmer you would have noticed (and known) that object is the base class for every managed type. In a C# program, when you call the .ToString function (where does that come from? See the first code sample in this overriding section) the program itself returns the full type name for it. For example,

using System;

namespace Example {
   class Program {
      static void Main(string[] args) {
         // Our very basic Console app.
         Console.WriteLine(
           new Program()
         );
      }
   }
}

// Output:
// Example.Program

Which is the type name for the class object. Now, for example if you have a class that holds the data for the users. You don’t have to create a separate function to display the details for a user, you can override the function and change its implementation for your class.

class User {
   public string Name { get; set; }
   public int Age { get; set; }

   public override string ToString() {
      return string.Format("Name: {0}, Age: {1}", this.Name, this.Age);
   }
}

The above code, when called as

var user = new User 
{ 
    Name = "Afzaal Ahmad Zeeshan", 
    Age = 20 
};

Console.WriteLine(user);

Would provide you with the following output:

Name: Afzaal Ahmad Zeeshan, Age: 20

Pretty easy isn’t it? We have no overridden the default behavior of object’s ToString function. You can in a similar manner, override other functions and procedures as required.

Points of Interest

This post would be much beneficial to those who don’t understand the concept of overloading and overriding and their common difference. This post aims at them, to teach them the difference. I hope by now you must have understand the common difference of them.

If you still get confused over something, or you have another question for them, do let me know and I will update the post for future readers. Finally, a graphical difference of overloading and overriding is:

Illustration of the difference.

Illustration of the difference.

ASP.NET 5 mixed with Windows 10!

Recently I was amazed by the new things ASP.NET 5 has in the Web API of its and also on the other hand I was looking forward to write an article for Windows 10. I thought why not write an article for them both! It was a great opportunity for me to do so, as I learnt many things while on the way to write the article and while compiling the resources for my article.

The article that I recently published on CodeProject and C# Corner introduces how users can create a Windows 10 application which actually serves as the client for an ASP.NET 5 Web API! ASP.NET 5 introduces many updates to old Web API and this one is as simple as a single controller that you can use to create and set your API, yes a single controller!

I would recommend that you definitely go and read the article on any of the following networks, which ever you prefer.

  1. on CodeProject
  2. on C# Corner

Do not forget to vote and share your valuable comments or feedback so that I can make the post even better!

You may also get the source code from MSDN galleries. Be sure to download the package and vote for it.

See you next time with something else, helpful for you! :-)

A few tips for security in .NET framework

Hello everybody, I am back with another good article for covering security in .NET framework for passwords of users. Although I was very much disappointed by the articles and resources published previously by many editors and authors. So I thought I must publish an article that covers all of the parts, that a good article needs.

I wrote an article for C# Corner community specifically, titled as: Efficiently Storing Passwords in .NET Framework. In that article I have discussed a lot of points and topics that a reader is trying to get in an article about Cryptography. A few major points are:

  1. What is cryptography? Why protect the passwords?
  2. How password should be protected?
  3. What algorithms are there to protect my password.
  4. Which of those algorithms are out-dated and which are expensive for my company?
  5. Where would the algorithms in .NET framework work.

And many more similar things are discussed there. Another major thing to understand is the usage of Salt. A salt is a random string generated to prevent password cracking attacks, such as Rainbow Table attack, Dictionary attack and many more. Salt just prevents any of them from happening.

Hashing, is an algorithm function that generates a random alphanumeric string for a password that is impossible to convert back to plain-text password, easily. Note the term, “easily”. Although a hash algorithm is designed to never run backward, still computer can run such algorithms that can get the password string back or at least try as much combinations to get the same hash value!

You should read the article from C# Corner, and learn how to protect passwords and other sensitive data in .NET framework.

Efficiently Storing Passwords in .NET Framework

Formatting and working with Date objects in JavaScript

Recently I have posted a new article on C# Corner about date objects in JavaScript. I have always found more questions from beginners about Date objects in JavaScript, as compared to questions for Date objects in a server-side language.

Date object in JavaScript has many things that cause it to lag behind Date objects in server-side languages. Or maybe, it is true to say that JavaScript doesn’t need to be provided with enough tools as a server-side programming language must have. Date object in, for example, C# has many members and functions that allow us to work around with the date in a very compact and easy way. For example, finding the age of a user by his age is as simple as,

var age = (DateTime.Now - dateOfBirth).TotalDays / 365.25; // Might require a cast

This, would give you the answer for age. For example if dateOfBirth holds my date of birth it would provide me with 19 as an answer. However, doing the same doesn’t work in JavaScript. Similarly, there is a function getMonth in JavaScript’s Date object. Which provides you with (zero based) Number for the month; starting with January at zero. So, to write the dates in a formatted way you would again need to use some other function to get the month’s name in string.

I have written an article on C# Corner, that covers these two topics. You can read the article at, Calculating and Formatting Date in JavaScript (I think, the title would have been, “Formatting the Date and Calculating age in JavaScript“, well authors don’t follow my words).

  1. Formatting date in JavaScript.
  2. Calculating the age of user in JavaScript.

Read the article, provide with feedback and share it. :-)

Five steps rule!

I was just working around a simple algorithm to create good forms that can be used for Desktop, mobile or web applications. Although this is not a very general one but a specific one for developers only — Developers are requested to contact UI and UX designers while working around. You will find this Five steps rule helpful in most scenarios. :)

11720775_905107572889452_864596541_o

 

The above image demonstrates the rule for you. I would try to explain them in a form they are meant to be explained.

  1. First of all you need to make a list of questions or items you need feedback in form of. This is the most important part of a form. If your feedback form doesn’t even provide you with enough details and answers, or if you have to create more than one form for one subject. Then it is not very much good enough.
  2. Mostly, feedback or reports are generated by software itself; logging. Software would generate everything itself. But in some scenarios you have to ask user to provide some input. In such cases you have to generate UI for him. In such scenarios, you are required to create a UI in a very compact, yet efficient manner. I have also explained this stage in a box above. Read it.
  3. You must not refrain from your UX rules. The controls and theme that you chose for your feedback pages must conform to UX and UI guidelines for your application. You should always consider testing your application for good UI and UX standards.
  4. Next stage is somewhat optional that is why it is being added as a catalyst only. Mostly targeted audience is same throughout application cycle. But, you should always consider this stage if your application has to worry about globalization and language or other requirements. But if your application doesn’t consider such changes then you don’t have to work on this stage.
  5. Final stage is the output.

To get good reports forms, you should always consider focusing on Step 1, 2 and 3 only. Making a change in Step 2 only would ensure that your application has a great form of reports page. You should always try to work around with UI and UX team to get suggestions for layout of controls and how should they be in order to get good UX and UI standards for your application.

[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.