Singleton and Static Classes
Singleton
- A single constructor, which is private and parameter less. This prevents other classes from instantiating it.
- The class is sealed, though this is option or unnecessary, but may help the JIT to optimize things more.
- A static variable which holds a reference to the single created instance.
- A public static means of getting the reference to the single created instance, creating one if necessary.
Static Class
Difference between the two
- There is no functional difference between the following
//calling the singleton class method
- Singleton means “single object across the application life cycle”. The scope of singleton is at application level.
- Static means “We cannot have any object pointer”. The scope of static is at App Domain level.
- The benefit of Singleton class is it is much more flexible than static classes. Your code will be more flexible if you use a singleton. The code that uses the singleton doesn’t need to know if it is a singleton or a transient object. On the other hand if we are using a static class means we have to call static methods explicitly.
- Dependency Injection is one of the primary requirements while designing decoupled applications. Static classes once defined could not accommodate any future design changes as by design static classes are rigid and cannot be extended. Singleton on the other hand provides flexibility and also provides sort of a mechanism to control object creation based on various requirements. They can be extended as well if need arises. In other words you are not always tied to a particular implementation. With Singleton you have the flexibility to make changes as when situation demands.
- Singleton Class can have value when Class object instantiated between server and client, such a way if three client want to have a shared data between them Singleton can be used. Static are always just shared and have no instance but multiple references.
- Singleton, as a non-static class, can still implement an interface, supports inheritance, etc. For example, you can’t inherit a static class and override a virtual method in it.
- Consider that today the application has a global shared object and tomorrow we decide that there has to be more than one instance of it. If you use a singleton, all you need to do is make your constructor public. But if you decide to use a static class, the change would have to be much more intrusive.
- If we ever decide to add unit tests to your code, replacing a singleton instance with a fake one is much easier (change in one place) compared to having to deal with a whole bunch of static functions that all share global data.
- If it is a Web application, Static Classes can create some major problems in a concurrent environment (because of shared data), specially when you are also using static variables and static methods.
- Singleton class does maintains state while Static doesn’t.
- We can pass Singleton object as parameter.
- If design calls for inheritance and variation then we must use a Singleton and not a Static class as we cannot use inheritance with static classes, by definition. In most usages, we would want our Singleton to implement an interface, something you cannot do with a static class.
- When we want to increase your performance we will encounter situations where we will have to use threading, so when making our application thread-safe we avoid some race situation.
- Static and Singleton classes will share there values for the entire instance of your application. When we access that object from multiple threads we can reuse or overwrite variables that’s also being used by another object. This will result in some very strange output and it’s hard sometimes to find what is going on since it ain’t easy to simulate this in test cases. We can implement a lock in your methods to introduce thread safety in these classes.
Injection Flaws/ Attack
Introduction
There are different types of Injection flaws. SQL injection is the most common, HTML / JavaScript Injection, LDAP injection, XML Injection, XPath Injection, OS command injection
Recommendation
- Input validation is a key for secure applications. In all topics you should consider INPUT VALIDATION. Use an “accept known good” validation strategy.
- Use strongly typed parametrized query APIs with placeholder substitution markers, even when calling stored procedures.
- Enforce least privilege when connecting to databases and other back-end systems.
- Avoid detailed error messages that are useful to an attacker. Don’t forget that attacker accumulate clues from your error messages.
SQL Injection Attack
- Weak input validation.
- Dynamic construction of SQL statements without the use of type-safe parameters.
- Use of over-privileged database logins.
Products
|
|
Column Name
|
Data Type
|
product_ID
|
Int
|
product_Name
|
varchar(100)
|
supplier_ID
|
int
|
category_ID
|
int
|
unitPrice
|
money
|
stockQuantity
|
int
|
The web application is using following query to display data in a page.
Suppose the catID required by the SQL query is passed using a query string as follows:
SELECT * FROM Products WHERE CategoryID = 1 or 1=1
Obviously 1=1 always evaluates to true so the filter by category is entirely invalidated. Rather than displaying only beverages we’re now displaying products from all categories.
This is just a small example of SQL injection the same above query can be used to get more information about other tables and its data. The only thing the hacker will require is some common sense and combination of data which will either pass or fail.
Suppose now it modifies the query string as follows:
http://localhost:8000/MyProductList.aspx?CategoryID=1;update products set productname=ProductHacked
SELECT * FROM Products WHERE CategoryID = 1;update products set productname= ProductHacked
You are really hacked now. There is no limit to this and hacker can go beyond our imaginations.
- Constrain input. All input must be validated against a white-list of acceptable value ranges.
- Use parameters with stored procedures.
- Use parameters with dynamic SQL. Use Named SQL parameters.
- Use ORM like Entity Framework, N Hibernate, LINQ to SQL etc
- Applying the principle of least privilege
HTML / JavaScript Injection Attack
- JavaScript injection attack can be used to perform a Cross-Site Scripting (XSS) attack. In a Cross-Site Scripting attack, you steal confidential user information and send the information to another website.
- JavaScript injection attack can be used to steal the values of browser cookies from other users.
- If sensitive information such as passwords, credit card numbers, or social security numbers is stored in the browser cookies, then a hacker can use a JavaScript injection attack to steal this information.
XML Injection and XPath Injection
- This can be prevented in a similar way to SQL Injection. The best way is to carefully sanitize user input. Any data received from a user should be considered unsafe. Removing all single and double quotes should remove most types of this kind of attack.
- Beware that removing quotes can have side effects, such as when usernames might contain valid quotes. Imagine common names such as O’Malley, which contains a legitimate quote and may be input on a name request form. In these cases, the input should be escaped, often by adding a \ in front of quotes. Check with your specific library and XML software for the proper syntax.
Cross Site Scripting (XSS) Attack
Introduction
This post is part of a multi-post series on web application security threats and their solutions. Please visit my introduction article here to know about more security threats and their solutions.
This type of attack enables attackers to inject client-side script into web pages viewed by other users. XSS flaws occur whenever an application takes untrusted data and sends it to a web browser without proper validation and escaping. XSS allows attackers to execute scripts in the victim’s browser which can hijack user sessions, deface web sites, or redirect the user to malicious sites. According to WhiteHat security Statistics report, approximately 65% has XSS security issues.
Example of XSS Attack
Suppose we are developing a page as follows.
Let’s consider this common scenario where user can enter name and email Id. And on click of Signup button click a personalized response welcoming user, is displayed. The problem is, oftentimes that string in the thank you message is just the input data directly rewritten to the screen.
var name = txtName.Text;
var message = “Thank you ” + name;
lblSignupComplete.Text = message;
If there is no data validation and a user enters following value in the name field. Suppose the user types
alert(“You are hacked”)
in the email id field.
Then the output of the above code will execute the script and will result in displaying an alert pop-up box on the web page which was not the desired behavior. This is a small example what a hacker can do with XSS attack. The hacker can also use such holes to redirect a user to unwanted sites too.
This happened because of two reasons:
- There was no expectation set as to what an acceptable parameter value was.
- The application took the parameter value and rendered it into the HTML source code precisely. It trusted that whatever the value contained was suitable for rendering on the page.
- There was no sanitation of data output while displaying on the web page.
Recommendations
To eliminate such instances and other types of XSS attacks, we need to follow some coding rules. These rules are:
- All input must be validated against a white-list of acceptable value ranges
- Always use request validation:
Request validation is the .NET framework’s native defense against XSS. By default, it is turned ON. Unless explicitly turned off, all ASP.NET web apps will look for potentially malicious input and throw the error above along with an HTTP 500 if detected. So without writing a single line of code, most of the XSS exploits would never occur. It’s an effective but primitive control which operates by looking for some pretty simple character patterns. But what if one of those character patterns is actually intended user input? What if a user is inputting data in rich HTML editor control? In such cases, we can turn off the validation within the page directive of the ASPX.
Alternatively, request validation can be turned off across the entire site within the web.config. But this is not a smart idea unless there is a really good reason why we’d want to remove this safety net from every single page on the site.
- User inputs should be encoded using HTMLEncode and URLEncode functions
Another essential defense against XSS is a proper use of output encoding. The idea of output encoding is to ensure each character in a string is rendered so that it appears correctly in the output media. For example, in order to render the text in the browser we need to encode it into <i> otherwise it will take on a functional meaning and not render to the screen.
- Non-HTML output encoding
In real world web applications we cannot encode all output to HTML. JavaScript is an excellent example of this. Let’s imagine that we wanted to return the response in a JavaScript alert box:
var name = Server.HtmlEncode(txtName.Text);
var message = “Welcome Mr. ” + name;
var alertScript = “alert(‘” + message + “‘);”; ClientScript.RegisterClientScriptBlock(GetType(), “ThankYou”, alertScript);
Let’s try this with above example: If user types Welcome Mr. ABCD
Obviously, this isn’t what we want to see as encoded HTML simply doesn’t play nice with JavaScript – they both have totally different encoding syntaxes. This brings us to the Anti-XSS library.
Anti-XSS
JavaScript output encoding is one of the reasons for Microsoft Anti-Cross Site Scripting Library also known as Anti-XSS to exist. This is a CodePlex project with encoding algorithms for HTML, XML, CSS and of course, JavaScript.
A fundamental difference between the encoding performed by Anti-XSS and that done by the native HtmlEncode method is that the former is working against a whitelist whilst the latter to a blacklist. The whitelist approach is most of the time a more secure route. Consequently, the Anti-XSS library is a preferable choice even for HTML encoding.
Moving onto JavaScript, let’s use the library to apply proper JavaScript encoding to the previous example:
var name = AntiXss.JavaScriptEncode(txtName.Text, false);
var message = “Welcome Mr. ” + name;
var alertScript = “alert(‘” + message + “‘);”; ClientScript.RegisterClientScriptBlock(GetType(), “Welcome”, alertScript);
We’ll now find a very different piece of syntax to when we were encoding for HTML:
alert(‘Welcome Mr. ABCD \x3ci\x3eHunt\x3c\x2fi\x3e’);
And we’ll actually get a JavaScript alert containing the precise string entered into the textbox:
Using an encoding library like Anti-XSS is absolutely essential. The last thing you want to be doing is manually working through all the possible characters and escape combinations to try and write your own output encoder. It’s hard work, it quite likely won’t be comprehensive enough and it’s totally unnecessary.
One last comment on Anti-XSS functionality; as well as output encoding, the library also has the functionality to render “safe” HTML by removing malicious scripts. If, for example, you have an application which legitimately stores markup in the data layer, and it is to be redisplayed to the page, the GetSafeHtml and GetSafeHtmlFragment methods will sanitize the data and remove scripts. Using this method rather than HtmlEncode means hyperlinks, text formatting, and another safe markup will functionally render (the behaviors will work) whilst the nasty stuff is stripped.
SRE
The Anti-XSS product has another good component called the Security Runtime Engine (SRE). This is essentially an HTTP module that hooks into the pre-render event in the page lifecycle and encodes server controls before they appear on the page. You have quite granular control over which controls and attributes are encoded and it’s a very easy retrofit to an existing app.
Set the Correct Character Encoding
To successfully restrict valid data for your Web pages, you should limit the ways in which the input data can be represented. This prevents malicious users from using canonicalization and multi-byte escape sequences to trick your input validation routines. A multi-byte escape sequence attack is a subtle manipulation that uses the fact that character encodings, such as uniform translation format-8 (UTF-8), use multi-byte sequences to represent non-ASCII characters. Some byte sequences are not legitimate UTF-8, but they may be accepted by some UTF-8 decoders, thus providing an exploitable security hole.
ASP.NET allows you to specify the character set at the page level or at the application level by using the <globalization> element in the Web.config file. The following code examples show both approaches and use the ISO-8859-1 character encoding, which is the default in early versions of HTML and HTTP.
To set the character encoding at the page level, use the <meta> element or the ResponseEncodingpage-level attribute as follows:
OR
To set the character encoding in the Web.config file, use the following configuration.
HTML Escape before Inserting Untrusted Data into HTML Element Content
Attribute Escape before Inserting Untrusted Data into HTML Common Attributes
JavaScript Escape before Inserting Untrusted Data into HTML JavaScript Data Values
CSS Escape before Inserting Untrusted Data into HTML Style Property Values
URL Escape before Inserting Untrusted Data into HTML URL Parameter Values
Use an HTML Policy engine to validate or clean user-driven HTML in an outbound way
Prevent DOM-based XSS
References
https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet
http://www.opensecuritylab.org/xss-prevention-rules
Hope you will find it helpful. Please stay tuned for more articles in this series in introduction article here.
Introduction
Example of XSS Attack
- There was no expectation set as to what an acceptable parameter value was.
- The application took the parameter value and rendered it into the HTML source code precisely. It trusted that whatever the value contained was suitable for rendering on the page.
- There was no sanitation of data output while displaying on the web page.
Recommendations
- All input must be validated against a white-list of acceptable value ranges
- Always use request validation
- User inputs should be encoded using HTMLEncode and URLEncode functions
- Non-HTML output encoding
- Set the Correct Character Encoding
- HTML Escape before Inserting Untrusted Data into HTML Element Content
- Attribute Escape before Inserting Untrusted Data into HTML Common Attributes
- JavaScript Escape before Inserting Untrusted Data into HTML JavaScript Data Values
- CSS Escape before Inserting Untrusted Data into HTML Style Property Values
- URL Escape before Inserting Untrusted Data into HTML URL Parameter Values
- Use an HTML Policy engine to validate or clean user-driven HTML in an outbound way
- Prevent DOM-based XSS
Security implementation in Web applications
Introduction
After working for many years in application development both Windows and Web-based, one is clear to mind is software development is not just writing logical code but also writing business logic in a secure way. As the technology is growing so is the threat to the information. Organizations are always in fear of data being stolen by unauthorized people and misusing it.
This fear is more daunting in case of web applications. So developing secure web applications is becoming more and more challenging day by day. In coming days I will post a series of we post which will focus on developing secure web applications. We will try to understand what are different types of security threats and how to handle those. We will cover following topics in coming days. I will keep them updating whenever I feel that the information is outdated and needs to be updated. Please click on any item in below list to visit the page which provides details about a particular attack and its solution.
- Click-jacking
- Cross Site Scripting Flaws
- Injection Flaws
- Brute-force password guessing
- Password Grinding
- Json Hijacking
- Buffer Overflow
- Network eavesdropping
- Data Tampering
- Dictionary Attack
- Elevation of privilege
- Disclosure of confidential data
- Luring Attacks
- Configuration management
- Session Management
- Canonicalization attacks
- Cookie replay attacks
- Exception Management
- Parameter Manipulations
- Cryptography
- Auditing & Logging
- Autocomplete in Login Page
- Cookie without HttpOnly flag set
- Sensitive Information in URL
- SSL Cookie Without Secure Flag Set
- HTTP Banner
- Cacheable HTTPS Response
- Authentication
Click Jacking OR UI redress Attack
Introduction
This post is part of a multi-post series on application security threats and their solutions. Please visit my introduction article here to know about more security threats and their solutions.
In click-jacking attacker hijack user’s click. Click-jacking (also known as a “UI redress attack”) is when an attacker uses multiple transparent/opaque layers to trick a user into apparently clicking, dragging or typing into a visible webpage, when in actual fact the user actions interact with a different page. Thus, the attacker effectively “hijacks” clicks meant for the visible page by routing them to another page, most often belonging to another application, domain, or both.
Recommendation
To avoid this kind of attack we need to implement something called a frame killer. A frame killer / frame buster / frame breaker is a piece of JavaScript code that prevents a web Page from being displayed within a frame. A frame is a subdivision of a Web browser window and can act like a smaller window. This kind of script is often used to prevent a frame from an external Web site being loaded from within a frameset without permission, often as part of click-jacking attack.
FrameKiller Code Implementation
We need to implement following code in each and every web page. But if your web site is based on Master page concept and each page is displayed inside it then this code can be implemented in Master page itself. No need to implement in all the pages, as each page inherits from a Master page and so the frame killer code will be.
The logic of this script is to disable presentation of the page by default and enable it only in top location.
body { display : none;}
if (self == top)
{
var theBody = document.getElementsByTagName(‘body’)[0];
theBody.style.display = “block”
}
else
{
top.location = self.location;
}
This code should be implemented in conjunction with the secure response header. So in Global.asax file we need to implement following code.
void Application_BeginRequest(object sender, EventArgs e)
{
this.Response.Headers[“X-FRAME-OPTIONS”] = “DENY”;
}
Use the Security Attribute
Internet Explorer 6 and later support a new security attribute for the <frame> and <iframe> elements. You can use the security attribute to apply the user’s Restricted Sites Internet Explorer security zone settings to an individual frame or iframe. By default, the Restricted Sites zone does not support script execution. If you use the security attribute, it must be set to “restricted” as below:
Hope this will help. Stay tuned for more posts on the security implementation in web applications.
Model View Controller (MVC) Design Pattern
Introduction
- Model-View-Controller (MVC)is a classic design pattern often used by applications that need the ability to maintain multiple views of the same data. That is when we want to use the same data but rendered on different types of devices like PC, mobile, pad etc. Each of these devices will be required to render the same content in a different format.
- The MVC pattern hinges on a clean separation of objects into one of three categories
- models for maintaining data,
- views for displaying all or a portion of the data,
- and controllers for handling events that affect the model or view(s).
- Because of this separation, multiple views and controllers can interface with the same model. Even new types of views and controllers that never existed before can interface with a model without forcing a change in the model design.
How It Works
The MVC abstraction can be graphically represented as follows.
- Events typically cause a controller to change a model, or view, or both.
- Whenever a controller changes a model’s data or properties, all dependent views are automatically updated. Similarly, whenever a controller changes a view, for example, by revealing areas that were previously hidden, the view gets data from the underlying model to refresh itself.
A Example
We explain the MVC pattern with the help of a simple spinner component which consists of a text field and two arrow buttons that can be used to increment or decrement a numeric value shown in the text field. We currently do not have an element type that can directly represent a spinner component, but it easy is to synthesize a spinner using existing element types.
- The spinner’s data is held in a model that is shared with the text field.
- The text field provides a view of the spinner’s current value.
- Each button in the spinner is an event source; that spawns an action event every time it is clicked.
- The buttons receive action events and route them to an action listener that eventually handles that event.
- Recall that a trampoline is a predefined action listener that simply delegates action handling to another listener.
- Depending on the source of the event, the ultimate action listener either increments or decrements the value held in the model — The action listener is an example of a controller. The trampolines that initially receive the action events fired by the arrow buttons are also controllers — However, instead of modifying the spinner’s model directly, they delegate the task to a separate controller (action listener).
Design Pattern and Types
Introduction
There are so many books and articles on the internet that already explain these topics in depth. But sometimes what we look at is brief but up to date description of topics. In the coming days, I will be writing some articles which will explain different design patterns as short as possible. anyone can use this as Quick Reference material.
In day to day software development practice, many problems are repeated over and over again. Design patterns provide a reusable general solution to such problems. Patterns are just the blueprint of the overall code or program and we cannot transform design patterns into the finished code. They are only a formal description or template of how to solve a specific problem. Most of the patterns only describe interactions between classes and objects rather than large-scale problems of overall software architecture.
Design patterns are documented tried and tested solutions for recurring problems in a given context. Design patterns are a very powerful tool for software developers, but you must keep in mind, they are not silver bullets so do not overdo design patterns.
Design Patterns and their types
There are 3 main types of design patterns
- Creational Patterns
- Structural Patterns
- Behavioral Patterns
Creational patterns
- One of the main problems is how to create an object.
- Centralized and delegate the object creation to a different class for better management.
- They’re particularly useful when you are taking advantage of polymorphism and need to choose between different classes at run-time rather than compile time.
- Following are some most used Creational patterns
- Abstract factory: Provide an interface for creating families of related or dependent objects without specifying their concrete classes.
- Builder: Separate the construction of a complex object from its representation allowing the same construction process to create various representations.
- Factory method: Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses (dependency injection)
- Lazy initialization: Tactic of delaying the creation of an object, the calculation of a value, or some other expensive process until the first time it is needed.
- Multiton: Ensure a class has only named instances, and provide a global point of access to them.
- Object Pool: Avoid expensive acquisition and release of resources by recycling objects that are no longer in use. It can be considered a generalization of the connection pool and thread pool patterns.
- Prototype: Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.
- Resource acquisition is initialization: Ensure that resources are properly released by tying them to the lifespan of suitable objects.
- Singleton: Ensure a class has only one instance, and provide a global point of access to it.
Structural patterns
- Where we are changing the structure of existing-working stuff.
- Structural patterns form larger structures from individual parts, generally of different classes.
- Following are some most used Structural patterns
- Adapter or Wrapper or Translator: Convert the interface of a class into another interface clients expect. An adapter lets classes work together that could not otherwise because of incompatible interfaces. The enterprise integration pattern equivalent is the translator.
- Bridge: Decouple an abstraction from its implementation allowing the two to vary independently.
- Composite: Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.
- Decorator: Attach additional responsibilities to an object dynamically keeping the same interface. Decorators provide a flexible alternative to subclassing for extending functionality.
- Facade: Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use.
- Flyweight: Use sharing to support large numbers of similar objects efficiently.
- Front Controller: The pattern relates to the design of Web applications. It provides a centralized entry point for handling requests.
- Module: Group several related elements, such as classes, singletons, methods, globally used, into a single conceptual entity.
- Proxy: Provide a surrogate or placeholder for another object to control access to it.
Behavioral patterns
- Behavioral patterns describe interactions between objects.
- They focus on how objects communicate with each other.
- They can reduce complex flow charts to mere interconnections between objects of various classes.
- Here we change the behavior of the class.
- Following are some most used Behavioral patterns
- Blackboard: Generalized observer, which allows multiple readers and writers. Communicates information system-wide.
- Chain of responsibility: Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it.
- Command: Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.
- Interpreter: Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language.
- Iterator: Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.
- Mediator: Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently.
- Memento: Without violating encapsulation, capture, and externalize an object’s internal state allowing the object to be restored to this state later.
- Null object: Avoid null references by providing a default object.
- Observer or Publish/subscribe: Define a one-to-many dependency between objects where a state change in one object results in all its dependents being notified and updated automatically.
- Servant: Define common functionality for a group of classes
- Specification: Recombinable business logic in a Boolean fashion
- State: Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.
- Strategy: Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.
- Template method: Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. The template method lets subclasses redefine certain steps of an algorithm without changing the algorithm’s structure.
- Visitor: Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates.
Prototype Pattern
Introduction
- Is a Creational Pattern.
- This design pattern that is used to instantiate a class by copying, or cloning, the properties of an existing object.
- The new object is an exact copy of the prototype but permits modification without altering the original.
- Cloning can be achieved by implementing ICloneable of the System namespace.
- The only member of ICloneable interface is Clone method that returns a new instance of a class with the same value as an existing instance.
- C# ICloneable.Clone method signature is: object Clone();
Cloning Types
Shallow Copy
- Duplicates all of the object’s properties.
- In case a reference type, the reference is copied.
- This means that changes to the referenced object are visible in both the clone and the original object.
Deep Copy
- Clones the main object and all child objects.
- Reference types are also cloned, giving a truly independent copy.
- The prototype pattern usually generates deep copies, though this is dependent upon the situation.
Why & When
- When we want the new copy object changes should not affect the old object.
- When the construction of a brand new object, using the new operator, is inefficient.
- Generally used for complex classes or for classes those are costly to instantiate.
- When we need to hide the concrete product classes from the client.
- When we want to reduce the number of classes to the minimum.
- When we use dynamic loading.
- When we want to avoid using the complicated class hierarchy of factories.
- When the classes have a few different state combinations.
- Session replication from one server to another server
In an enterprise-level application managing a server pool, the application will monitor and maintain the optimum load on the individual server in the pool. In case of the catastrophic failure, one server may invalidate thousands of client connections. The enterprise application managing the server pool can take the responsibility of cloning the sessions from one server to another without disturbing the clients. - Generating the GUI having many numbers of similar controls
This is a quite frequent scenario. One can have a form or GUI that hosts many similar controls. In order to maintain the consistency, one needs to initialize every object to the same standard state. This process of initialization gets repeated again and again for each control increasing the number of lines of code. In order to optimize this part of the code, one can one have an object of a control initialized to a standard state and then replicate the same object to create as many controls needed.
Advantages
- Creates deep copy of the complex object hierarchy
- Reduced load of initialization
- Reusability – Optimized coding efforts
- Simplified object copy process
How to Achieve
— Abstract Parent Class
–– Child Class
— Using Child Class
Difference between MVC & MVP
Introduction
Model-View-Controller (MVC) and Model-View-Presenter (MVP) patterns are used for quite a time by many developers/ architects for designing applications. Both (MVC & MVP) patterns have been used for several years and address a key OO principal namely separation of concerns between the UI and the business layers. One question that keeps coming up over and over again is: What are the differences between the two patterns? Surprisingly the answer is more complex than what you would suspect. Part of reasons I think many developers shy away from using either pattern is the confusion over the differences. Before we dig into the differences let’s examine how the patterns work and the key benefits to using either one.
Model View Controller (MVC) Pattern
The MVC pattern is a UI presentation pattern that focuses on separating the UI (View) from its business layer (Model). The pattern separates responsibilities across three components:
- the view is responsible for rending UI elements
- the controller is responsible for responding to UI actions
- and the model is responsible for business behaviors and state management.
In most implementation, all three components can directly interact with each other and in some implementations, the controller is responsible for determining which view to display.
Model View Presenter (MVP) Pattern
The MVP pattern is a UI presentation pattern based on the concepts of the MVC pattern. The pattern separates responsibilities across four components:
- the view is responsible for rending UI elements
- the view interface is used to loosely couple the presenter from its view
- the presenter is responsible for interacting with the view/model
- and the model is responsible for business behaviors and state management
In some implementations the, presenter interacts with a service (controller) layer to retrieve/persist the model. The view interface and service layer are commonly used to make writing unit tests for the presenter and the model easier.
Differences
the main difference between the two are as follows:
Model View Presenter Pattern
Introduction
- MVP is a variation of MVC, Loosely couple modules.
- It separates the concerns of an application’s data, presentation, and user input into specialized components.
- The view and the model don’t know of each other.
- There are normally four main classes used in the MVP pattern (3 classes and 1 interface)
- View (WinForm/ WebForm/XAML-file).
- Interface (describes the fields in view).
- Presenter (executes the views actions and communicates with the model).
- Model (database).
MVP Explained
Variance of MVP
Passive view
- In Passive View, the presenter updates the view to reflect changes in the model.
- The interaction with the model is handled exclusively by the presenter; the view is not aware of changes in the model.
Fig explains about interaction by model is handled exclusively by the presenter and then the view is updated exclusively by the presenter which using the view interface.
Supervisory controller
- View interacts directly with the model to perform simple data-binding that can be defined declaratively, without presenter intervention.
- The presenter updates the model; it manipulates the state of the view only in cases where complex UI logic that cannot be specified declaratively is required. Examples of complex UI logic might include changing the color of a control or dynamically hiding/showing controls.
Figure illustrates the logical view of the Passive View and Supervising Controller variants.
When to use what
- The decision to use Passive View or Supervising Controller lies primarily on the testability level that you want to achieve.
- If testability is a primary concern in your application, Passive View might be more suitable because you can test all the UI logic by testing the presenter.
- If you prefer code simplicity over full testability, Supervising Controller might be a better option because you do not have to write code in the presenter to update the view for simple changes.
- Both variants allow you to increase the testability of your presentation logic.
Passive View usually provides a larger testing surface than Supervising Controller because all the view update logic is placed in the presenter. - Supervising Controller typically requires less code than Passive View because the presenter does not collaborate in simple view updates.
- If we are going for automated testing like nUnit then Passive View is good, if we are going for manual testing than Supervisory Controller is good.
Advantage—MVP
- Loose coupling – The presenter/controller are an intermediary between the UI code and the model. This allows the view and the model to evolve independently of each other.
- Clear separation of concerns/responsibility
- UI (Form or Page) – Responsible for rending UI elements
- Presenter/controller – Responsible for reacting to UI events and interacts with the model
- Model – Responsible for business behaviors and state management
- Test Driven – By isolating each major component (UI, Presenter/controller, and model) it is easier to write unit tests. This is especially true when using the MVP pattern which only interacts with the view using an interface.
- Code Reuse – By using a separation of concerns/responsible design approach you will increase code reuse. This is especially true when using a full blown domain model and keeping all the business/state management logic where it belongs.
- Hide Data Access – Using these patterns forces you to put the data access code where it belongs in a data access layer.
- Flexibility/Adaptable – By isolating most of your code into the presenter/controller and model components your code base is more adaptable to change. For example consider how much UI and data access technologies have changed over the years and the number of choices we have available today. A properly design solution using MVC or MVP can support multi UI and data access technologies at the same time.
Drawbacks
- The biggest drawbacks are additional complexity and learning curve.
- While the patterns may not be appropriate for simple solutions; advance solutions can greatly benefit from using the pattern.