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.

A few points to consider while working with literal string in ASP.NET

This post is for ASP.NET developers, working around with string literals in their applications for displaying run-time or dynamic data to their users. In the past few days, there have been quite a lot of new discussions about efficient way of creating a personalized string to represent the data on the websites.

A few tips that I had in my minds would be possible to share here with other developers of ASP.NET web applications. Note that, I have always been saying ASP.NET is built right on top of .NET framework, so anything that can be developed and run over .NET framework, can be used with ASP.NET too in the back-end. .NET exposes a few functions of the class System.String that are good for use with strings and modification and personalization of the strings.

Response messages

Usually, developers build a few messages to be shown to the clients as a result to their request. You can somehow, write a message (or return a message; possible way of usage in the ajax applications) in the Reponse.Write() function. You can write the string to return the data in the format of,

Response.Write("Thank you for your message " + name + " we will get back to you relating to your " + problem + " and we will have our " + client_name + " working on it right away to give you response in " + max_days);

Above code would work well, show the correct result, and at the very same time would be a good way to show your laziness too. No one uses string concatenation now-a-days. There is a very useful extension in .NET for String class. That is the .Format function. It is overloaded. Now let us consider writing the above code in a String.Format way,

Response.Write(
     String.Format("Thank you for your message {0} we will get back to you relating to your {1} and we will have our {2} working on it right away to give you response in {3}"), name, problem, client_name, max_days);

The second way of doing the same is more efficient. You,

  1. Write the message to print in a very literal (constant) way, with just embedding the parameters in the form a {index}.
  2. You pass the parameters to add to the string as a second, third, fourth and so on number of parameter to the function.

Now once you’re about to write the message in a new way; such as updating the message. You won’t have to worry about the concatenation problems, parser errors; that get raised a lot in ASP.NET applications. You can simply write the message in a string form. Embed the parameters. Pass the values via variables and .NET would take care of the rest.

HTML attributes

Another common usage of building strings is to create the HTML markup of the web applications, on the run-time and then returning the response to the client to be rendered.

Such scenarios, require your to build the HTML markup, in a well formatted way and then sent down to client. For example, this question on CodeProject provides a similar scenario for us to investigate a possible solution to such problems. That is a problem, which gets raised due to a similar problem of string concatenation in HTML elements and attributes.

You should always write the HTML attributes in a very similar way, to avoid concatenation, and making a use of variables and the String.Format() function. An example code can be the following one (the code from the question).

Response.Write("<script language=javascript> 
                    alert('"gk_szEnter_Value_Error_Message"'); 
              </script>");

The above code has a problem of attribute, well can be handled, but another major problem is the concatenation of the string by a variable. Which required him to add this value using a + operator but didn’t so caused a problem.

This could be possibly minimized by using the format function, in the following way,

Response.Write(String.Format("<script>alert('{0}');</script>"),    
                              gk_szEnter_Value_Error_Message);

Now the above string would be created as it is, but the parameter would be filled by the value passed. This now avoids any error of concatenation-type and so. Secondly, for HTML elements like image element, you can create that element in a way,

// Notice the single quote in the strings; whichw ould be converted to double.
String.Format("<img src='{0}' alt='{1}' />", image_source, alternate_text);
// which would yield
"<img src="~/value/of_image_source.png" alt="value of alternate_text" />"

These methods allow us to efficiently create strings. This code lets .NET framework handle the rest of the problems.

A tip for ajax developers in ASP.NET MVC framework

Download the sample project from Dropbox.

This is another quick blog post for the ASP.NET developers, who’re using ajax (or are going to use the ajax in their applications for async calls for the data to the server), and might be getting confused in the View-part of the MVC pattern. This blog post, would try to tip them up with a simple method of creating ajax functionality in their applications, and how to get the confusion about View-part clear. The background to this post is a question, that arose, of how to use the ajax to get the data in ASP.NET MVC framework. Although that was a simple task, but I know new developers get into trouble in making the logic, that is why I am writing this blog post, to explain the core-concept of the behaviour.

I will also be providing a sample code, that you can download and test in your application. This application would be a simple “Hello world, using Ajax in ASP.NET MVC” application. You can after that, make this application complex as per your own requirements.

Getting hands dirty in some ASP.NET code

First stage would be to write the back-end code for our application, which is the ASP.NET MVC application. Wait, the first thing I want to elaborate here is that ajax requests don’t usually require you to send entire HTML markup, to be rendered. Usually, ajax requests are used to download just a few details about the user, such as their name, their company name, or a little message such as success message for the process user has started. That is why, sending entire HTML markup would take a lot of time, and network size, by sending entire XML tree as HTML markup.

That is why, I am going to not-create any View in this project. But I am going to work with just a single Controller. That controller would be used to perform all of the actions, and after the controller has been made, I am going to use the Route mechanism to allow custom URLs in our application; which do not map to our actual HTML files on the application set up. Don’t worry, as the application would build up, the concept of this paragraph would start to get some gravity and you will understand it how did I do and what you would do in order to create your own Ajax running ASP.NET MVC application.

Note: If you’re unaware of the ASP.NET MVC framework itself, I force you to please go and read my other article that focuses on the ASP.NET MVC framework itself. In this blog post, I am not going to explain any concept about the framework itself, instead I am just going to simply swap things up and explain the ajax and ASP.NET MVC part. So, it would be better if you move on to that article and first understand the underlying concepts about Controller, View and Model (that makes up the MVC part of the ASP.NET MVC framework).

First of all, let us create a Controller. To create a controller, you can get some help from Visual Studio, click on the Controllers folder and Add Controller to it. Name it, what so ever you want to. I named it as AjaxController; to specify that it would control all of the ajax requests over HTTP protocol. Once that has been done, you can create your own action methods that would response to your own personal functions. I didn’t bother creating any complex task, instead I just simply created a function, named it as “CustomAction”. It would be used as the URL to our ajax handling web page.

Inside that page, you would write the following code, to handle it and provide the result to it. Like simple C# application, the functions can have any return data type and thus, in ASP.NET MVC application we can, instead of a View, return a string (or any other data type object) that would be sent down to the client as the response to his ajax request. It would be much simpler, and much shorter in structure.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace AjaxRequests_in_ASPNET_MVC.Controllers
{
   public class AjaxController : Controller
   {
      // GET: Ajax
      public string Index()
      {
         return "Not allowed";
      }

      // Our custom action, URL would be /ajax/customaction
      public string CustomAction()
      {
         // We're going to return a string, not a view.
         return "Hello world, using Ajax in ASP.NET MVC application.";
      }
   }
}

The above code would return a string, that can be then used as a response and rendered into the HTML or done what-so-ever with it.

Now let us change the routes to actually let the application run without having to use a web page that is a View inside the Ajax folder in our Views folder. Open the App_Start folder, and inside there open the RouteConfig file, and inside it. Write this new route.MapPath() function.

// Create a new route, set the controller to "Ajax" and the remaining would be the Action
// Note that there are no Views in the Views folder to map to this location.
routes.MapRoute(
   name: "AjaxController",
   url: "Ajax/{action}",
   defaults: new {controller = "Ajax"}
);

Now this code would create a routing scheme in your application, and is able to let your application run without actually having to have a specific file at that location to run and handle the ajax request. In the above code, I am using the URLs of the type “/ajax/customajax“, in this URL ajax is a constant string value, used as a path, and then the customajax would be the action of the controller. When this URL would be called, ASP.NET would execute the CustomAjax action of the controller, and would return the string result inside the function.

Performing the ajax code

The ajax code for this project is simple jQuery code to create an async request to the server, to download some more data. But before I share the code for the ajax request, I would like you to make a few changes in the _Layout.cshtml file of your project. The change is to include the jQuery library in the project, so that in the web page you can use the jQuery (because we will be using that layout). Add this line of code to your HTML markup’s <head> element.

<script src="~/Scripts/jquery-1.10.2.js"></script>

Now that the jQuery has been added to your HTML DOM, you can use this library in other pages which has this page set as their layouts, to make use of the jQuery syntax and other objects. I will be using the ajax.

The following code depicts the code used for an example ajax request,

$(document).ready(function () {
   $.ajax({
      // The URL
      url: "ajax/customaction",
      // If the request was successfull; which will be, if it is not successfull check for errors
      success: function (data) {
         // Alert the data; it would be "Hello world, using Ajax in ASP.NET MVC application."
        alert(data);
      }
   });
});

Now once this code would run, it would try to make a call to the URL specified, in the above section we discussed how ASP.NET would handle that request using the routings and action methods, and then would return a single string value. It would finally alert the user with the string that would be returned. That would be a single ajax running application, which would return simple plain message to the user without any complex and large sized View.

Points of Interest

ASP.NET MVC framework can support the ajax requests, just like any simple website would.

You can use the routings to define your own custom URLs. You can define the paths that you want to use, and the controller or action patterns. You are not required to always have a view being returned to the user. Sometimes (if you want) you can also send any kind of data (which in turn would be serialized to string for transmitting).