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.

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. :)