Prajwal Tuladhar’s Blog
 
programming, life and some random thoughts

Archive for the 'Programming' Category

Nov 11 2008

Parsing query string in ASP.NET safely

Published by Prajwal Tuladhar under ASP.NET, C#

Both of the code behind languages for ASP.NET (C# or Visual Basic.NET) are statically typed languages. So, the type checking operation is performed during the compiled time unlike during the run-time for dynamically typed languages like PHP, Perl, Python, Ruby and so on. This make a-bit difficult to validate and parse the query string for ASP.NET pages. All the ASP.NET query string are treated as a String by default. Parsing needs to be performed in order to get appropriate data types.

For instance lets take a URL: http://somedomain.com/Default.aspx?QueryStringInt=2

It has a single query string named QueryStingInt which is expected to have data type Int32. In a default scenario it would be enough to change the query string to an integer type by

Int32.Parse(Request.QueryString["QueryStringInt"]);

But what if someone just manipulated the URL like: http://somedomain.com/Default.aspx?QueryStringInt=a

There would be error.

This condition can be avoided by using a simple technique. Consider the code below:


    private int _queryStringInt;
    public int? QueryStringInt
    {
        get
        {
            return (int.TryParse(Request.QueryString["QueryStringInt"], out _queryStringInt))
                ? int.Parse(Request.QueryString["QueryStringInt"]) : 0;
        }
    }

    private string _queryStringDefault;
    public string QueryStringDefault
    {
        get
        {
            return (Request.QueryString["QueryStringDefault"] == null || Request.QueryString["QueryStringDefault"] == "")
                ? "" : Request.QueryString["QueryStringDefault"];
        }
    }

    private Guid _queryStringGuid;
    public Guid QueryStringGuid
    {
        get
        {
            try
            {
                _queryStringGuid = new Guid(Request.QueryString["QueryStringGuid"]);
            }
            catch (FormatException)
            {
                _queryStringGuid = new Guid("00000000000000000000000000000000");
            }
            catch (ArgumentNullException)
            {
                _queryStringGuid = new Guid("00000000000000000000000000000000");
            }
            catch (OverflowException)
            {
                _queryStringGuid = new Guid("00000000000000000000000000000000");
            }
            return _queryStringGuid;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        //_queryStringInt = (int.TryParse())
        Response.Write(QueryStringInt + "<br/>");
        Response.Write(QueryStringDefault + "<br/>");
        Response.Write(QueryStringGuid + "<br/>");
    }

If the query string is not of the expected data type then there would not be error rather a default value can be assigned in those situation.

Invalid Type Query Strings

Query String Values:

Valid Type Query Strings

Query String Values:

Technorati Tags: ,,,

No responses yet

Oct 15 2008

Introducing Model View Controller (MVC) Pattern

Published by Prajwal Tuladhar under MVC, Patterns, Programming

Model-view-controller (MVC) is both a design pattern and an architectural pattern used in software engineering. - Wikipedia

Historical Background

MVC was started by Ward Cunningham and Kent Beck who were working with SmallTalk and designing GUIs at Xerox PARC. The original implementation is described in depth in the influential paper Applications Programming in Smalltalk-80: How to use Model-View-Controller.

What is Pattern?

A pattern is a solution to a problem in a given context. Christopher Alexander says each pattern is a three-part rule which expresses a relation between a certain context, a problem, and a solution. Pattern in the software development was especially popularized from the publication of the book named Design Patterns: Elements of Reusable Object-Oriented Software by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides or often referred to as Gang of Four (GoF). Design patterns represents a solutions to problems that arise when developing software within a particular context.

What is MVC?

MVC Architecture

MVC can be defined as an architectural pattern that is used while developing interactive application on the web. As the name suggests there are three major components of MVC:

  • Model: Encapsulates core data and logic. Model is often related with the business logic of the application. It knows all the data that needs to be displayed. It is always isolated from the User Interface (UI) and the way data needs to be displayed.
  • View: It is the UI part of the application. It uses read-only methods of the model and queries data to display them to the end users. It may be a window GUI or a HTML page. View encapsulates the presentation of the data, there can be many views of the common data
  • Controller: It acts as a interacting glue between models and views. It accepts input from the user and makes request from the model for the data to produce a new view.

How it works?

How MVC Works

Advantages

  • Separation of Concern: Since MVC has three components whose operations are quite isolated from each other. For example; people working on view part can concentrate only on the UI and the part visible to the end users; people working on model part can concentrate on the business logic and the functional requirements of the system or ‘What’ part of the system and finally people working on the controller section may have knowledge of both view and model section so that interaction between other two components could be made easily. There is clear designation of roles for each stakeholder of a system.
  • Modularized Development: Modularization is the process of dividing any complex problem into smaller sub-modules and we human have been following this approach from the time unknown. In MVC, we divide our system into three parts in order to reduce complexity.
  • Pattern based development: As defined in the earlier section, pattern is the proven solution for any problem in a particular context. MVC itself is a pattern implemented in the presentation layer where it handles user’s interaction (controller) with a particular model through view. MVC is a proven solution for many contexts especially interactive web applications so following it in order to build a system may be comparatively more effective and trust worthy.
  • More Control over URLs: Almost all MVC based frameworks have the feature of URL routing that gives us more control over the URL we desire. For example; http://www.foo.com/prajwal/edit where ‘prajwal’ may be unique ID and ‘edit’ may be controller action.
  • Maintainability and Code Reuse: The Modular design of MVC supports the design goal of reusable software. As MVC requires a definite rule and style for coding, the result can be much more maintainable and reusable software.
  • Test Driven Development: By following MVC, one can easily tests each and every part of the system. Moreover, most of the MVC frameworks do have one or more built-in testing frameworks.
  • Platform and language independent: MVC is simply a pattern which can be implemented in any language or any platforms. Most of the popular languages and platforms like Java, .NET, PHP, Ruby, Python have one or more MVC based frameworks. So you once you know the MVC funda, you can implement in the platform of your choice.

Disadvantages

  • Adds additional level of complexity: MVC can increase the level of complexity of a system since. MVC requires in depth planning so, any wrong decision taken early could impact the whole application life cycle.
  • More files to manage means more headache: This may be context dependent. Some people might feel odd when dealing withe more files. A MVC based system has comparatively more number of files than a non-MVC based system.
  • Rigorous separation between the model and view can sometimes make debugging more difficult: In my experience, debugging a MVC application is still quite difficult as compared to a non-MVC application. I am talking about my experience while working with CodeIgniter, a PHP based MVC framework. But the same is not true when talking about ASP.NET MVC.

Implementations of MVC as web-based frameworks

.NET

PHP

Python

Ruby

Java

Conclusion

As the benefits of MVC out number the disadvantages, in my opinion one should follow this approach when creating interactive web applications with high degree of agility.

No responses yet

Oct 10 2008

Abstract Class versus Interface

Published by Prajwal Tuladhar under .NET, C#, Patterns, Programming

In software engineering, an abstract type is a type in a nominative type system which is declared by the programmer, and which has the property that it contains no members which are also not members of some declared subtype.
Interface generally refers to an abstraction that an entity provides of itself to the outside. This separates the methods of external communication from internal operation, and allows it to be internally modified without affecting the way outside entities interact with it, as well as provide multiple abstractions of itself. It may also provide a means of translation between entities which do not speak the same language, such as between a human and a computer. Because interfaces are a form of indirection, some additional overhead is incurred versus direct communication. -Wikipedia

In Java, .NET and PHP 5 there are three ways to create and object i.e. inheritance, composition and interface.

  • Inheritance defines “is-a” relationship. Example: Student and Programmer is a Person
  • Composition defines “has-a” relationship. Example: Class Student contains class Book
  • Interface only models the behavior of an object. Example: Student and Programmer are both Nameable and both may have actions.

In Java, .NET and PHP 5, multiple inheritance (child class with more than one parent class) is not allowed so, interface can be used as a powerful tool to separate implementation. Interface is not a strict “is a” relationship. Abstract class represents some sort of implementation and it is a strict “is a” relationship. For example: A dog is a mammal and a reptile is not a mammal showing strict relationship whereas both dog and reptile may be nameable and both may have some actions.

abstract interface example

As we know that interface and abstract class both provide abstract methods so, making the best use of them is crucial in the object oriented paradigm. Abstract class provides both concrete and abstract methods whereas interface provides only abstract methods. Lets go through an example:

Assume that we have an abstract class Person and its concrete implementation class Student and Programmer. We have an interface called IWork that may or may not be implemented by the concrete classes Student and Programmer. We also have a composite class Address, though it is not required while distinguishing between interface and abstract class, using composite class will help us to clarify the scenario.

Class Diagram

Abstract Interface Class Diagram

Abstract Interface Class Diagram

C# Code

Abstract Class - Person

Abstract Class - Person

Interface - IWork

Interface - IWork

Class Address

Class - Address

Class - Programmer

Class - Programmer

Class - Program

Class - Program

Conclusion

  • Classes in a strict inheritance relationship must be related.
  • Interfaces can be used for classes that are not related. In the above example, only Programmer class is implemented but it is not necessary that Student also implements the IWork interface.
  • An interface never provides any implementation, only behavior.

References

You can download the example from here.

No responses yet

Oct 10 2008

Some facts about stable systems and OO design

Published by Prajwal Tuladhar under Patterns, Programming

I am going through the book named “The Object-Oriented Thought Process (3rd Edition) (Developer’s Library) by Matt Weisfeld”. I got some interesting facts in the chapter 9 “Creating Objects” of this book which I want to share. Being a software developer, we know that we always want to create a stable system. The 1962 article titled “The Architecture of Complexity” by Nobel Prize winner Herbert Simon noted some quite interesting characteristics of the stable systems:

  • Stable systems have hierarchy. Each system is built from a sub-system and each sub-system is still built from another sub-system forming basis for functional decomposition. This approach has been used in structural approach also.
  • Stable system is nearly decomposable.
  • Stable system evolves from the the simple sub-system that have worked.
  • Stable systems are always composed of only few different kinds of sub-systems

Another fact I want to share is about the design decision that is required to be made. We know that a system needs to be loosely coupled and highly cohesive. But what should we do for achieving this? Three points have been proposed by the author:

  • Which objects collaborate with each other?
  • How many objects participate in each collaboration? (This represents cardinality)
  • Is the relationship mandatory or optional?

I really recommend this book to any developer who wants to enhance his/her knowledge about the object oriented development.

No responses yet

Sep 27 2008

Polymorphism in PHP

Published by Prajwal Tuladhar under PHP, Patterns

In simple terms, polymorphism is the ability of one type, A, to appear as and be used like another type, B. In strongly typed languages, this usually means that type A somehow derives from type B, or type A implements an interface that represents type B. In non-strongly typed languages (dynamically typed languages) types are implicitly polymorphic to the extent they have similar features (fields, methods, operators). In fact, this is one of the principal benefits of dynamic typing. - Wikipedia
Polymorphism is tightly coupled to the inheritance and is often considered to be one of the most powerful feature of the object oriented programming. It can be defined as a term according to which a name (variable declaration) may denote objects of many different classes that are related by some common suprclass; thus, any object denoted by this name is able to respond to some common set of operations in different ways. - Grady Booch

Lets consider an example:
There are two array of shapes called Rectangle and Circle. Even though we treat both these as a Shape but their implementation is quite different. In nutshell, each class is able to respond differently to the same method getArea(). This is called Polymorphism.

UML Diagram

PHP Code

No responses yet

Next »

RSS Feed

Related Posts


follow infynyxx at http://twitter.com