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

What is debugging, How to debug… A beginners guide

We get exceptions mostly, it is best to always test your applications before submitting it to markets or other platforms for users. Debugging is one of those options to test your applications. As the name suggests, Debugging means “to debug” (What?) the application. It is a process in which framework problems and other logical errors are removed from the errors.

As a software developer you might know that there are usually three type of errors.

  1. Syntax error
  2. Run-time error
  3. Logical error

Syntax error and run-time error are two types of errors that can be shown to the developer by the framework or compiler (first one). So developer just have to check what went wrong and how to do to fix it. However the third type of error cannot be checked by a compiler. Logic is something you make up. You have to write correct algorithm to make it work. If there is some kind of problem, you have to check your algorithm once again to make sure that it is correct algorithm. Logical errors, do not generate any error while compiling the source code. They also don’t notify the user about wrong results. A common example would be,

int Remainder(int a, int b) {
    // provided b is not zero
    return a / b;
}

Indeed developer wanted to get the remainder, but used division operator. Source code would compile and would give results… Wrong results.

Debugging helps us in finding such errors and solving them to get the correct answer and solution. This option is provided in every IDE (Visual Studio, Android Studio, Eclipse… Others that you have tried) for developers to debug their applications.

How to debug

Now you might also want to know how to debug your applications. Well, that is pretty simple. I have also mentioned above that (almost) all of the  IDEs provide tools to debug your application. I have used Eclipse, Visual Studio, Android Studio… They have all provided me with (similar) tools to debug the applications and see how things are done.

The thing, “How things are done” is helpful when solving the logical error. Point to note here is that debugging is not only helpful in solving the logical errors. It is also sometimes helpful while removing the run-time errors such as the most famous “NullReferenceException” (For more on NullReferenceException you can read this another post of mine to understand What it is?… Why it is generated!… And how to solve it?). Syntax errors need to be resolved before the object-code can even be generated. So that leaves the debugging method applicable to run-time and logical errors only.

The steps to debugging processes generally depend on the type of error you are trying to debug. So let me clarify the two types of debugging process. However, the actual process is similar. You start and end up in the same way it is just your internal process that is different for both, 1. Run-time error, 2. Logical error.

Process

In every IDE, option to set up some Breakpoints is included. Breakpoints are a few steps in your code where IDE notifies you when the code execution reaches that place (or point). You are then allowed to check the application’s memory consumption, variables (including their “at that time” values). At this stage you can see what is the state of application and how it should behave. You can also check what type of variables (with value) are sent to this block and how are they being used or manipulated. This would further guide you in fixing the problem.

Run-time error debugging

For example, if you stumbled upon DivideByZeroException. Then you can add a Breakpoint to your function and execute step by step, one by one each statement and look into how does your code get a variable with zero (or is the user passing the value to be zero) and so on. This type is the Run-time error debugging. DivideByZeroExceptions are generated at run-time when the code executes. That is why you usually would face this error while running the application only.

This type of debugging is somewhat easy, because it doesn’t require a lot of searching for error. The framework that you are using would throw an exception and you (if having more than beginner level experience) would easily know that the program is telling you to fix this problem at this location. And then you can easily add the patch to fix the problem.

Logical error debugging

Debugging a logical error is somewhat tough task because they cannot be found easily. You have to run through each and every statement and check for Where actually do things mess up? Sometimes it can take 5 – 10 minutes, sometimes it can take an hour. Depending on the complexity of the logic or algorithm being designed.

Let us take an example of an “Age calculating” algorithm. Take a look at the following C# code.

// Assume dateOfBirth is coming from user having valid dateTime expression
var age = (DateTime.Now - dateOfBirth).Days / 365;

age variable would hold the correct data only if the logic is applied correctly. We know that our logic is correct. Which is not! We know 365 are the number of days in a year… But we don’t know is that we round up the overhead number of hours in the Leap year after 4 years. So if above code is run, it is not guaranteed to give the correct answer to every input. It might have at least >10% of errors chances. If processed under debugging tools, we would find that using 365.25 as divisor is the correct way to find the age of a user using DateTime object. So now the following code would run correct and would not have as much error ratio as above code had (Still might have error chances!)

var age = (DateTime.Now - dateOfBirth).Days / 365.25;

Now when you would use it, it would display correct for the provided input.

Note: The above example has a physical significance, I wrote the age calculation algorithm which gave me my age to be 20 years (while I was 19.5 or something years old).

Points of interest

Now let us wind things up. A few of things mentioned in this post are,

  1. Debugging is a process in which bugs (mainly logical or run-time) are removed from the application.
  2. (Almost) every IDE supports debugging tools.
    1. Breakpoints.
    2. Debugger (in which application runs… vshost.exe can be an example for Visual Studio geeks).
    3. Profiling tools, memory management, variable information and other tools required to alter the state of application and to check what is going on under the hood.
  3. Run-time errors are easily understandable and solvable because the underlying framework tells the developer what went wrong. So (if developer has some understanding of the framework then) he can remove the chances of problem occurring again.
  4. Logical errors take more time. Because they depend on the complexity of the logic being solved. They can be removed only if the algorithm is fully understood and how should it be written in the language.
    See the examples above for more.

That’s all for now folk! :-) I hope it helped some of you…

Novice to MVC? Read this…

This post is meant for beginners in MVC pattern (do not confuse yourself with ASP.NET MVC; if you want to learn ASP.NET MVC then please read this post of mine). If you’re novice to this framework then read this post of mine. I will cover most of the parts of MVC framework itself and how can you implement this framework in your applications.

Understanding the Model-View-Controller

MVC stands for Model-View-Controller. If you have developed a few applications in OOP model then you will understand this easily. Otherwise, you might have some tough time understand this MVC pattern. But you will synchronize as we continue.

First of all, you should get rid of any other programming model that or framework that is inside your head. Also, (as mentioned earlier) do not confuse MVC with ASP.NET MVC. This pattern is very common among other patterns of software architecture. MVC is just the term used to develop the software in a pattern such that it is divided into three sub-categories.

  1. Model — The data source for your application.
  2. View — Your application’s views, putting it simply graphical user interface.
  3. Controller — Controller the is actual background logic for your application.

Above are the three categories in which code is distributed efficiently. How application programming is made simpler, I will explain in further sections. Let us first talk about the concepts of MVC, then I will walk through implementation of MVC in different programming languages and frameworks.

Diving into MVC

Let us first consider MVC as our subject of talk. How can we use it and what it actually is. MVC is just the framework, architecture or a pattern, what so ever you want to call it. It is just the model for your software development process. Which is targeted to maintain your source code and data sources. Also, this framework is targeted to reduce ambiguity and complexity found in enterprise software. Usually when an application reaches enterprise level of complexity it is a lot harder to debug it.

MVC-Process.svg

Now let us dissect the MVC into three sections and study it thoroughly.

1. Model

Model part of this architecture puts the focus on the data of the application. You data might come through different methods,

  1. Database
  2. Reports
  3. Data sources such as files; JSON is a major example
  4. User input

These compose the model section for your application. Model is responsible for updating the user interfaces and indicating a trigger to an event (if any) in the application to demonstrate that the data has now changed. Usually these are just fancy names given to a simple model of the data. In most of the programming languages it can be a simple class, with a few members (trailing the properties or the attributes in database table for the object) and a few functions to store the data in the data source and extract it. This must be kept secure and away from user interactions. Keeping it separate would help in minimizing unauthorized access attempts.

Note: The function part can also be implemented inside the controller to save the data or extract the data. 

2. View

View is the user-interface part of the software application. All of the interface design such as buttons, input fields etc. are to be added to this category. In most of the applications (such as web applications) HTML pages are the View where as in other applications and frameworks other methods are used to create an interface such as XAML files in WPF applications.

The main purpose of having a view is to get the data from model and represent it to the user. All of the styles and other UI and UX techniques must be applied here. Views are usually called by the the controllers and returned to the users as a response after being filled up by the data from a model.

3. Controller

Coming to the most important part of this framework. It is the actual software logic running underground. It is mostly composed of, functions that your application runs, other underlying logical code for the users and such other code that has to run throughout the initial stage to the very last line when the application ends.

In web applications, a controller is responsible for handling the requests coming from a user and then returns the response to the user after merging the data from the model in to the required view. Although the process is similar to getting request and returning the response. But under the hood process is something like,

  1. Request is made.
  2. Controller handles the request.
    Url is read and then appropriate functions are triggered.
  3. Inside those functions, model is asked for data and data is filled in to the view.
  4. View is then returned as a response.

The overall framework is something like this following image.

The user must be allowed to interact with Model himself, instead a Controller must be used to connect to the Model to get the data for the user's View that would be shown to him.

The user must be allowed to interact with Model himself, instead a Controller must be used to connect to the Model to get the data for the user’s View that would be shown to him.

As I have mentioned earlier, the user must not be allowed to interact with the model. User must be provided all of the required tools and buttons on the view. View can interact with the controller to download data (if required). This is the MVC pattern of software development. Now in the next section I will give you other helpful resources that you might find helpful.

Other material…

As I had already mentioned that I would provide other tools and materials for developers in a particular framework or language.

Any framework or type

This section is meant for everyone. If you’re developing an application and want to implement MVC pattern then read this section and you will understand how to develop this pattern in your own application development process.

Default language used is C#, you can use your own particular language also. C, C++ and Java are quite similar to the language.

Creating a Model

Creating the model is a very easy task. It is just the wrapper for your data sources. Which can be converted to an object and then interacted with in the application. Think of it as a simple object.

class Model {
   public string Name { get; set; }
   public int Age { get; set; }
   public string Email { get; set; }
   public string Message { get; set; }

   // Functions
   public static List<Model> GetData() { /* code */ }
   public static void SaveData(List<Model> data) { /* code */ }
}

The above code is the model for your own application. It has a few attributes (from the database) and 2 functions. One to retrieve the data and other to store the data.

You can now connect this with database, file or other resource in the functions and fill up your data using the data sources that you have right now.

Creating a View

This is simple (another) task. It contains building up the user-interface. If you’re using web application, then you would create the HTML web pages and add the required elements in the web page. Same process has to be applied to the software applications, where you can design the user-interface for your application and show it using (back-end) code.

Creating a Controller

Now coming to the necessary part. Controller is the entire code that runs the logic for your application, its interaction with events and underlying operating system. What happens when your application is to be started, what should be done when your application has to terminate and what happens in between them. All of this code is Controller.

You can create classes which handle the start up events, and also the classes which handle other interaction event with your View. Controller also has the code to trigger the model; such as the code to trigger either one of the method in our model (See above the “Creating a Model” part).

MVC in web applications

If you are going to develop a new web application, you can develop your application in a very similar manner discussed above. Write your code in a manner that it categorizes itself into three categories.

  1. Model
  2. View
  3. Controller

It is helpful once your application reaches an enterprise level of complexity. So that at that time you won’t have to scratch your head twice to think like, “What was I thinking?”

If (however) you are going to use ASP.NET, then there is already an MVC framework built for you with all of the underlying code done and an IDE ready to serve your needs. For more on that for learning purposes, please read this another thread of mine. That article of mine has all of the required information that a beginner requires to kick start his ASP.NET MVC web application development.

Offline applications

If you are using Java… Then I have another major thread for the same purpose. You can read it to learn how to implement the same pattern in your Java application development. You can also download and try the samples included in it.

Other software languages and framework can also implement the MVC pattern, you just have to categorize the code of your software application.

Points of interest

That said, now I might give you other helpful points for secure applications and frameworks. Following might be helpful for you,

  1. MVC pattern helps you in sorting your code and categorizing same types of code under a single lable M-V-or-C.
  2. You should never allow your user to interact with model. Model contains the data or the definition for your data. If potential user is able to interact with your application’s model he might also get through the security checks. That is why, always use controller to validate the requests and then access the data from model.
  3. I have used databases, JSON files and all kind of other data sources available. So your model is capable of interacting with any kind of data source present (provided you have enough code to make it work).
  4. You can also use Ajax to run Controller partially on the views. If you are interested in learning how to use Ajax in MVC pattern then please read this another article of mine.
  5. MVC pattern is a software designing and developing architecture. It does not require you to be in web or offline context.

I hope this post must have helped you out. :)

Downsides of learning {programming-language} in {x} days!

This might be my first post about such topics… Which might contradict other (self-claiming) authors who say that they can teach you a programming language in a number of days. For example, “Learn ASP.NET in 7 days”, “Learn HTML5 in a matter of 3 days”. Let me point out a few of the downsides of this type of teaching and learning for new developers, who might fall for this approach.

Who are the victims?

The most victims to this type of approach are the young developers… Inexperienced, rushing to learn new things, express-to-impress type of teens and those with a deadline of them self fall to this type of approach very often. Sometimes those who cram the rules, types, structures of the language do so.

Remembering never helps you out! You have to understand how things work.

Remembering never helps you out! You have to understand how things work.

Most usually, the teens who are eager to learn something in a very short number of time are victims to this approach. 7 days? 14 days? Seriously? What is it like… A pond’s challenge! Programming is something that cannot be fed into minds of other people; you cannot move a clock in simple harmonic motion and expect the human to become a programmer once you’re done hypnotizing and brain washing him. It cannot be taught the way we learnt it. It must be taught by lowering our standards to the standard that our student can understand us. Our students come to us to learn… We should educate them, not force them to remember what we said.

Who claims such thing?

I have no personal hatred towards those who claim such. In fact people who are extraordinary in learning and experimenting claim such things. They learn things in a very fast manner. Authors who write a title to their publication in a way, “Learn {subject} in {x} days!” are them self very quick learners. That is why they expect others to learn the same subject in a very fast manner.

It won’t be false to claim that they actually are very genius of their era. They have a very resilient grip of their subject and field. But not all fingers are of same size. Are they?

Discussing the downsides of this approach

Now let us discuss, why new programmers should not learn programming or any architecture or a framework using this approach. I would state a few points of mine, you can have your own feelings and opinions and might contradict to mine. But… Be logical and learn stuff slowly and by understanding what they are to you!

Not at all a true statement

First downside that I feel about such content is that they are not at all true. How can someone claim to teach you something in a matter of deadline. I teach programming to a few, some of them learn the concept very quickly. Some take time… Some take a lot of time. For those who take a lot of time, I try to make sure that they at least learn and understand the basic concept and tend to do something with it. I do not expect them to cram to reach the “x” days limit.

More appropriately such topics for publications are a term for publicity stunt. Because they are more straight-forward, targeted by those who want to make more in less time, author is challenging himself to be able to teach you more in less days.

Different psyche levels

Humans do not have similar psyche level… And you just cannot expect everyone to be similar when it comes to ability to learn and understand something. It would be responsibility of the instructor to teach his/her student in a way that they can surely learn something and not just waste their own time. I have taught people of almost every psyche level… From geniuses to average students. Those who were genius asked such questions which led me to go deep inside my mind to extract a scrap of information which I had locked in my limbo for a decade (not really!). Those who were average students had to pay some more time to learn it, they also tried not to understand the concept as to apply it. But just to learn it… To learn it!

I had never been a great instructor. So I have tried giving them a lesson in a way a friend would. Publications claiming to 5, 7 or 30 days time period don’t claim that they would teach programming to those with average mind set. They are of the same period and good use to someone who has the 100% same mental ability as the author had when he was learning the same framework or language.

A book, in any way cannot claim that the readers are expected to benefit from the content. But, claiming something that is not expected or guaranteed should not be used. When an author claims something, he must be able to prove it.

Only good side of this…

The only good side of this approach is that the subject is catchy! ;)

Personal views

There are many other points… But, I would not want to criticize such content any more. Instead I would share my views to beginners how can they benefit from less in more time.

Practice makes you better!

First of all, I should say that you need to practice what you learn. Practice is something that doesn’t make the applicable task easier, it just makes you better!

You should never think things are getting easier. It is you who have evolved.

You should never think things are getting easier. It is you who have evolved.

What Google might respond to your search as?

Deliberate_Practice

I learnt programming in a matter of 2 months. I just learnt C# at that time… Not software programming! There was nothing that I knew about creating an efficient software, writing a good API, creating a web application and so on. The more your practice the better you get. More errors you get, more you will understand. Sometimes when I go back in time 3 years ago and have a look at my questions, problems that I faced. I laugh. That doesn’t mean things are easy. That means practice has just given me enough understanding of these frameworks that now I can slice and dice them in any way that I want to. It also now has an impact on my social life.

Now, after learning and practicing. I speak less but qualitative. The quality of my speech is great now. I do not speak gibberish (or that I feel like).

Now, after learning and practicing. I speak less but qualitative. The quality of my speech is great now. I do not speak gibberish (or that I feel like).

There is no limit to study

I can build good applications in a matter of day or two. But that doesn’t mean I should give up learning more and more about such particular platform or subject. I have good grip over .NET framework, but I believe I should learn more and more.

Every new developer must only focus on learning part. I remember a lot of good threads where I have participated, ended up in a same conclusion. That you cannot learn anything in a matter of week, fortnight, month or even a year. You need at least to consume 5-10 years to learn something. Yes, if you’re going to cram through the concept for a term test then good, do it. It might even take 3 days for that.

Focus on something… Put smaller time periods in your learning

But to learn something fully, you need to focus on it in a very better way. Give more and more time to it. Let it settle down. Give your education a short time of more like 30 minutes, 45 minutes regularly. Try something, learn something. You would stumble upon more like a million errors before you can think yourself as a pro beginner! Before you can even enter intermediate level, you will fall into the errors like a million, or billion times.

Do not rush!

There is no need to rush. You can learn something in a very easy, smooth and friendly way. For new developers, it is a very good approach to read articles of other developers, read their code. Reading good content, good articles, good code helps you out to understand how they did. Remember they might be better than you (I don’t mean to tease anyone here, sorry if you take my words seriously), so if they did something in one day and you took 3 days. Do not hesitate! It is OK!

Finally. It is you, who knows where you lag. Best learning environment is when there is an instructor available for you. Books, articles, blogs do not teach you in a way they can. If you are a beginner never rely on them. If books were everything there would have been no requirement for a school, institution or university. There would have been great great libraries every where. You should ask your instructor what to do and how to do. Your instructor should help you out… He should be able to know where you lag behind others. He should polish you in a way that you can really get into something.

How to calculate birthday from year, month and date

You might have usually created applications for evaluating and calculating the age of people using their date of birth. In this post I will teach how you can perform the math to find the birthday of a person.

Required input

For this program to run and find the birthday we require three inputs.

  1. Years — That have passed
  2. Months — That have passed
  3. Days — That have passed (negative value if the date has still to come in this month).

Then we can pass those values to the AddDays, AddMonths, AddYears functions of DateTime to find the birthday.

Code

I used the following code to perform this function.

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

namespace FindingBirthday
{
    class Program
    {
        static void Main(string[] args)
        {
           // Create variables
           int year = 0, month = 0, date = 0;

           // Get the values
           Console.WriteLine("How many years have passed?");
           year = Convert.ToInt32(Console.ReadLine());

           Console.WriteLine("How many months have passed?");
           month = Convert.ToInt32(Console.ReadLine());

           Console.WriteLine("How many days have passed?");
           date = Convert.ToInt32(Console.ReadLine());

           // Do the math and write it!
           Console.WriteLine(
               String.Format("Your birthday was on {0}",
               DateTime.Now // Get current instance of time
               .AddYears(-year) // Add years
               .AddMonths(-month) // Add months
               .AddDays(-date) // Add days
               .ToString("MMMM dd, yyyy on dddd") // Format it
               )
           );

           // Just for sake of pausing the Console
           Console.Read();
       }
    }
}

The above code performs the action required and finds the date of birth.

Result

For my input, the result was August 29, 1995 on Tuesday. Which is my date of birth calculated from my input of years, months and days that have passed since my birth.

What is code reuse and why use it?

In computer programming, there are many techniques used by programmers to make their programming life easier and better, different terms are used to denote the simple and compactness of a framework, such as, Object-oriented programming language. For example there are quite possible methods to let you re-use the same functions and properties in your code, by inheriting the actual class and using those members; functions or properties, inside your derived class. But OOP has been criticized a lot for its less reusability. But that is not the topic of discussion

Re usability

In programming, code re usability is using the similar code in different functions… No, not by copying and then pasting the same code from one block to another and from there to another and so on. Instead, code re usability defines the methodology that you can use to use the similar code, without having to re-write it everywhere; like I already said not in a way to copy and paste it. There are a lot different techniques that you can use in order to make use of code reusability in your applications. This technique follows the general programming DRY (Don’t repeat yourself) rule, which states, “Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.” and helps the developers to maintain the structure of their applications from being messed up and frustrating while debugging the applications. There are quite different scenarios and methods to use,

  1. Inheritance
  2. Functions
  3. Libraries
  4. Forking

And it continues with many other frameworks being formulated every day and new paradigms being designed every decade and being used. But I would like to explain a few of these and why they’re better and so on. Finally, it would be clear, why DRY rule is better and how does it support the developmental process and makes it easy to debug our applications efficiently. You should also know that I am not going to demonstrate entire paradigm, I will just describe the use of paradigm in code-reuse.

Inheritance

Inheritance has been into programming world since quite a long time and is overly used in Object-oriented programming paradigms. This paradigm lets you use the base-class’s functions and members in other classes, most of the times an Animal class is used to describe this behavior, Animal is used to inherit from for a Lion and Human and many other types of the Animals. Who have their own different functions, like Lion can roar, human can speak, but they have something similar… Such as walk. So  it is not necessary to write walk function for all of these objects separately instead you can create this function for an Animal and use it in your derived classes; Lion, Human etc. Let us go through a code example of this scenario…

class Animal {
   // properties
   int legs;
   
   // functions
   void run () { /* code to run here.. */ }
}

Now you can then use the above class as the basic structure to define two other classes, with same properties and functions, like this.

class Animal {
   public int Legs = 4;
   public void Run() { 
       Console.WriteLine("Running..."); 
   }
}

class Human : Animal { }

class Lion : Animal { }

I know that this code hides inherited members and I should have used virtual or abstract keyword inside the Animal class. But, you get the idea don’t you?

Now this is just a complex way, to ensure that the members of Animal class are available under Human and Lion classes also. If you can the function Run over Lion or Human object, you will see that it will Run. Although making the functions work for different objects differently is a totally different aspect of this, you need to implement virtual or abstract keywords to avail such functionality to allow the developer to override the functions (or members more specifically) and add the body of their own; to write “Human running…” instead of just “Running…”.

Function calls

Function calls are another way of reusing the code from different parts of your application. You create small code blocks of an algorithm or logic-based source code, and give it a name, identifier. Which identifies your code; can describe the process too. Functions have,

  1. A return type, which denotes what type of data would be returned or a void.
  2. An identifier, which is used to make a call to this function.
  3. Function body, which is the code block containing the code to be executed when this function is called.
  4. Zero or more parameters to provide values to the code block variables.

Function are used to make sure that every logic is written once, and so that if there has to be made a change in the logic, we make it once and it is updated everywhere in the application. For example, if you have to greet a user many times inside your application, instead of writing a greeting message everywhere, you can create a greeting function

void greet() {
   // Greet user
}

This can be then used in enormous places to greet the user. Good thing is that it can be edited at one location, and changes will be reflected through where-ever you call this function. This was a very basic example, if you allow users to post something (such as status, photo etc.) then instead of writing post_update code everywhere, you can create a function in the business-logic-layer and call that function from where-ever you want to call it. Good thing, once again, is that you get to update the function at one place only and the changes will be reflected everywhere.

Libraries

You might have heard of using Dynamic-link library? Yes, the most used .dll files. These libraries are a set of compiled programs, majorly used by larger and enterprise level software, to support the execution as they can be executed upon call.

If you have ever used NuGet packages, tried using .dll files, or added any assembly to your bin folder in .NET application or ASP.NET application, then chances are that you’ve already used libraries before and are well-known with these libraries. Most of the packages that are distributed to be used by other clients, are libraries that can be linked to your executable for purposes that they are defined for.

Most of the framework allow support of creating third-party libraries and to distribute them through different methods. You can also note, that System (namespace of the .NET framework) is also present in the System.dll library.

Forking

Forking, well if you’re a git geek, then you should know it better than me because I use Github’s GUI version and I don’t have much knowledge about underlying git. But, forking is a process of using someone else’s source code and making changes to it to fit your own needs, to distribute, use, share etc.

You can also fork someone else’s source code and write some more details to it. Make some bug fixes, add some patches and share it. This terminology and method has been widely used by different companies, to fork open source projects, make a few changes to the “Under the hood” and then distribute it with their own label and tag.

In my opinion, Forking is not one of the code reuse methods. You do not just reuse the code, you use it from ground up, building another framework of it and so on. But everyone has their own opinion, I have mine and so I cannot say anything about your opinions. Although, these methods have proved a lot helpful in programming, as to create robust and strong enterprise applications and have helped programmers maintain their hairs on their head and not in their hands as the application reaches the enterprise level of complexity.