TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# Protection Proxy Design Pattern

This C# article shows an example of the protection proxy design pattern. It covers the theory behind this pattern.

Protection proxy. A protection proxy controls resource acquisition.

It is used to fetch resources and authenticate users. An implementation must access the database only when required to, and only when the user is authenticated.

Intro. We want a class for database-related code—we will call it DatabaseLayer.cs. This file contains a class that does all the work with the database, and sends back DataTable or DataSet objects to the rest of the program.

DataSet

In this database layer file, we need an interface. An interface is a contract that will be used to "connect" the actual database-using code to the proxy class, which is called the protection proxy. The proxy implements methods.

Tip: The proxy may implement an interface containing five methods, but it doesn't include the actual SQL code in its methods.

Database layer methods. The database layer implements methods. It also implements the same interface with those five methods. It has the SQL commands and actual business logic built into it.

Passwords. The proxy checks on each method call that it has the password required to access the database. Then, it forwards all method calls to its database object. It inserts a password check before every call to the database layer.

Info: The proxy forwards method calls to its inner database object only if that check succeeds.

Proxy interface. Here we see the interface that is shared between the database layer and proxy. This interface will be shared by the proxy and database classes. An interface doesn't need to use the public keyword. It must not contain implementations.

Proxy interface definition: C#

public interface IJournalData
{
    void InsertNewRow(DateTime dateTime);
    DataTable GetSearchResults(string queryString);
}

Next, we see the proxy class implementation. The proxy sets between the database code itself, and the callers in the user interface. The Authenticate method here is not part of the interface above, but a special method on the proxy.

Proxy class implementation: C#

public class JournalProxy : IJournalData
{
    JournalLayer _journalLayer;
    string _password;

    public bool Authenticate(string suppliedPassword)
    {
	// User sends in the password, and we make sure it is correct.
	if (string.IsNullOrEmpty(suppliedPassword) ||
	    suppliedPassword != _password)
	{
	    return false;
	}

	// Password is correct.
	// Allocate the database layer,
	// ... and setup the connection to the database code.
	_journalLayer = new JournalLayer();
	return true;
    }

    public void InsertNewRow(DateTime dateTime)
    {
	// In every method that the proxy implements from the interface,
	// ... make sure that the user was authenticated.
	if (_journalLayer == null)
	{
	    return;
	}
	// Forward the call to the actual database code.
	_journalLayer.InsertNewRow(dateTime);
    }

    public DataTable GetSearchResults(string queryString)
    {
	if (_journalLayer == null)
	{
	    return null;
	}
	return _journalLayer.GetSearchResults(queryString);
    }
}

Usage. At this point, we use the protection proxy in the user interface code. We are using Windows Forms and this code is inside a class that implements a Form. Another framework, such as WPF, could be instead used.

Windows FormsWPF

Authenticate is only called when the user enters a password. You can use your database layer object, such as "_journal", without even worrying about passwords. It will abort attempts to use the database if the password has not been set.

PasswordEntered method implementation: C#

JournalProxy _journal = new JournalProxy();

private void PasswordEntered()
{
    if (_journal.Authenticate(passwordTextBox.Text))
    {
	// Show something from the database.
    }
    else
    {
	textBox1.Text = "Password is incorrect";
	// User must now enter a new password.
	passwordTextBox.Clear();
    }
}

Database layer. Here is the database-using layer. The big thing here is that we don't need to worry about passwords because the protection proxy takes care of all of that for us. It uses an abstraction to make this easier.

Code that uses the database: C#

class JournalLayer : IJournalData
{
    public void InsertNewRow(DateTime dateTime)
    {
	return;
    }

    public DataTable GetSearchResults(string queryString)
    {
	return new DataTable();
    }
}

Benefits. We consolidate the password authentication code. You can create code that accesses the database without worrying about the password stuff. You add the protection proxy object as a layer between the user interface code and database logic.

Benefits: Some of the benefits to the proxy are also found in other uses of interfaces in the C# language.

Interface

Note: Thanks to Igor Shkolnikov for pointing out a small error in the code. Older pages like this one sometimes tend to decay.

Summary. We used the protection proxy design pattern to manage accesses to important (or expensive) resources. Protection proxy makes C# applications easier to develop when requiring a password for a database.

Terms: There are fancy words like surrogate that you can use to describe these things. The term protected is sometimes used.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf