Archive

Archive for the ‘.Net’ Category

On the Run – PropertyTree in Action

December 4, 2009 5 comments

In the previous post in this series I introduced PropertyTree a dynamic data structure that can be used from .Net and JavaScript.

In this entry I will show you examples of using PropertyTree.

Working with Nodes

In it’s simplest form, you assign values to nodes of the tree (PropertyNodes) by specifying the name of the node and assigning an object to the Value property.

The following example shows how to create a PropertyTree, populate it with values and read back those values:

In C#:

PropertyTree pt = new PropertyTree();

pt.Node("FirstName").Value = "Pink";
pt.Node("LastName").Value = "Floyd";
pt.Node("Birthdate").Value = new DateTime(1969, 9, 1);
pt.Node("Salary").Value = 100000M;

string firstName = pt.Node("FirstName").Value;
string lastName = pt.Node("LastName").Value;
DateTime birthdate = pt.Node("Birthdate").Value;
decimal salary = pt.Node("Salary").Value;

In VB:

Dim pt As New PropertyTree()

pt.Node("FirstName").Value = "Pink"
pt.Node("LastName").Value = "Floyd"
pt.Node("Birthdate").Value = New Date(1969, 9, 1)
pt.Node("Salary").Value = 100000D

Dim firstName As String = pt.Node("FirstName").Value
Dim lastName As String = pt.Node("LastName").Value
Dim birthdate As DateTime = pt.Node("Birthdate").Value
Dim salary As Decimal = pt.Node("Salary").Value

In this case the type of the node value is the type of the object assigned. The .Net types that a property node can support are:

  • System.String
  • System.Char
  • System.DateTime
  • System.Boolean
  • System.Byte
  • System.Int16
  • System.Int32
  • System.Int64
  • System.Decimal
  • System.Single
  • System.Double
  • System.SByte
  • System.UInt16
  • System.UInt32
  • System.UInt64
  • System.Xml.XmlDocument
  • System.Byte[] (Array of Byte)

Now for the “tree” part of PropertyTree. The PropertyTree class inherits from PropertyNode and every node has a Node default property that is used to access sub-nodes. To add sub-nodes to a node you can do the following:

In C#:

// Add values hierarchically
pt.Node("Customer").Node("FirstName").Value = "Sponge Bob";
pt.Node("Customer").Node("LastName").Value = "Square Pants";
pt.Node("Customer").Node("Address").Node("Street").Value = "123 Pineapple Dr";
pt.Node("Customer").Node("Address").Node("City").Value = "Bikini Bottom";
pt.Node("Customer").Node("Address").Node("State").Value = "HI";
pt.Node("Customer").Node("Address").Node("Country").Value = "US";
pt.Node("Customer").Node("Address").Node("ZipCode").Value = 96850;

In VB:

' Add values hierarchically
pt.Node("Customer").Node("FirstName").Value = "Sponge Bob"
pt.Node("Customer").Node("LastName").Value = "Square Pants"
pt.Node("Customer").Node("Address").Node("Street").Value = "123 Pineapple Dr"
pt.Node("Customer").Node("Address").Node("City").Value = "Bikini Bottom" pt.Node("Customer").Node("Address").Node("State").Value = "HI"
pt.Node("Customer").Node("Address").Node("Country").Value = "US"
pt.Node("Customer").Node("Address").Node("ZipCode").Value = 96850

Since the Node property is the default property (an indexer in C#), you can use the following syntax to simplify the code:

In C#:

// Add values hierarchically
pt["Customer"]["FirstName"].Value = "Sponge Bob";
pt["Customer"]["LastName"].Value = "Square Pants";
pt["Customer"]["Address"]["Street"].Value = "123 Pineapple Dr";
pt["Customer"]["Address"]["City"].Value = "Bikini Bottom";
pt["Customer"]["Address"]["State"].Value = "HI";
pt["Customer"]["Address"]["Country"].Value = "US";
pt["Customer"]["Address"]["ZipCode"].Value = 96850;

In VB:

' Add values hierarchically
pt("Customer")("FirstName").Value = "Sponge Bob"
pt("Customer")("LastName").Value = "Square Pants"
pt("Customer")("Address")("Street").Value = "123 Pineapple Dr"
pt("Customer")("Address")("City").Value = "Bikini Bottom"
pt("Customer")("Address")("State").Value = "HI"
pt("Customer")("Address")("Country").Value = "US"
pt("Customer")("Address")("ZipCode").Value = 96850

Also, you can access a node using a “dot” notation in the node name parameter:

In C#:

// Doing the same thing using "dot" notation
pt["Customer.FirstName"].Value = "Sponge Bob";
pt["Customer.LastName"].Value = "Square Pants";
pt["Customer.Address.Street"].Value = "123 Pineapple Dr";
pt["Customer.Address.City"].Value = "Bikini Bottom";
pt["Customer.Address.State"].Value = "HI";
pt["Customer.Address.Country"].Value = "US";
pt["Customer.Address.ZipCode"].Value = 96850;

In VB:

' Doing the same thing using "dot" notation
pt("Customer.FirstName").Value = "Sponge Bob"
pt("Customer.LastName").Value = "Square Pants"
pt("Customer.Address.Street").Value = "123 Pineapple Dr"
pt("Customer.Address.City").Value = "Bikini Bottom"
pt("Customer.Address.State").Value = "HI"
pt("Customer.Address.Country").Value = "US"
pt("Customer.Address.ZipCode").Value = 96850

Notice how the parent node doesn’t have to exist in order to assign a value to a child node (that also doesn’t exist), all nodes in the path are created automatically.

JavaScript

With the exception of tree, node and type creation, PropertyTrees can be used from JavaScript. To do so, you create the PropertyTree on the server and serialize it to the client. In this next example assume that xml contains a string with the serialized version of the PropertyTree from the previous example:

In JavaScript:

var pt = new Properties.PropertyTree(xml)

// Retrieve values

var firstName = pt.node("Customer").node("FirstName").get_value()
var lastName = pt.node("Customer").node("LastName").get_value()
var zip = pt.node("Customer.Address.ZipCode").get_value()

// Update values
pt.node("Customer").node("LastName").set_value("Pink")
pt.node("Customer").node("LastName").set_value("Floyd")
pt.node("Customer.Address.Country").set_value("UK")
pt.node("Customer.Address.ZipCode").set_value(90210)

In a future post I’ll go deeper into this topic.

Creating Nodes

In the previous examples the property nodes are created implicitly, each node is typed with the value that was assigned to it and it can hold any valid value for that type.

To create nodes and set restrictions on the values that it can hold we create nodes explicitly with the CreateNode function:

In C#:

PropertyTree pt = new PropertyTree();

pt.CreateNode<String>("FirstName");

In VB:

Dim pt As New PropertyTree()

pt.CreateNode(Of String)("FirstName")

PropertyNode names are case-sensitive.

The CreateNode function returns an object of type PropertyNodeNew which has the following methods:

MinValue(obj) The minimum value accepted by the node.
MaxValue(obj) The maximum value accepted by the node.
MinLength(int) The minimum character length. Applies only to System.String.
MaxLength(int) The maximum character length. Applies only to System.String.
Mask(string) A Regular Expression to filter text. Applies only to System.String.
Format(string) A format string used when outputting the value as a String.
Value(string) The initial value of the node.
Attribute(string, string) Adds a user-defined attribute and it’s value to the node.
ReadOnly() Indicates that the property value can only be read.
Required() Indicates that a value must be assigned to the property node.

Each one of these functions returns a PropertyNodeNew object which allows for a more fluent interface:

In C#:

PropertyTree pt = new PropertyTree();

pt.CreateNode<String>("Name")
    .MaxLength(32)
    .Mask("^[a-zA-Z]{1}[a-zA-Z0-9_]*$")
    .Required();
pt.CreateNode<Decimal>("Salary")
    .MinValue(1)
    .MaxValue(100000)
    .Format("C");

pt["Name"].Value = "GoodName";
pt["Salary"].Value = 25000;

// The next two lines will raise a PropertyValidationException
pt["Name"].Value = "A Bad Name";	// Contains spaces.
pt["Salary"].Value = 250000;	// The new value is out of range.

In VB:

Dim pt As New PropertyTree()

pt.CreateNode(Of String)("Name") _
    .MaxLength(32) _
    .Mask("^[a-zA-Z]{1}[a-zA-Z0-9_]*$") _
    .Required()
pt.CreateNode(Of Decimal)("Salary") _
    .MinValue(1) _
    .MaxValue(100000) _
    .Format("C")

pt["Name"].Value = "GoodName"
pt["Salary"].Value = 25000

' The next two lines will raise a PropertyValidationException
pt["Name"].Value = "A Bad Name"     ' Contains spaces.
pt["Salary"].Value = 250000         ' The new value is out of range.

CreateNode is not available in JavaScript but all restrictions on a node such as validation rules and formatting are implemented.

Creating Types

After a while you may find that you are creating many different properties with the same restrictions or validation rules.

You can create PropertyTypes that can be used when defining a PropertyNode and can even be the basis for other PropertyTypes that can define more specific restrictions. To do this you use the CreateType method of the Types property:

In C#:

PropertyTree pt = new PropertyTree();

pt.Types.CreateType<Decimal>("SalaryType")
    .MinValue(1)
    .MaxValue(100000)
    .Format("C");

pt.CreateNode("Salary", "SalaryType");

pt["Salary"].Value = 25000;

In VB:

Dim pt As New PropertyTree()

pt.Types.CreateType(Of Decimal)("SalaryType") _
    .MinValue(1) _
    .MaxValue(100000) _
    .Format("C")

pt.CreateNode("Salary", "SalaryType")

pt("Salary").Value = 25000

PropertyType names are case-sensitive.

The CreateType method returns an object of type PropertyTypeNew that can have any of the following methods:

MinValue(obj) The minimum value accepted by the node.
MaxValue(obj) The maximum value accepted by the node.
MinLength(int) The minimum character length. Applies only to System.String.
MaxLength(int) The maximum character length. Applies only to System.String.
Mask(string) A Regular Expression to filter text. Applies only to System.String.
Format(string) A format string used when outputting the value as a String.
AllowedValue(obj,[string]) A value of the defined type that is allowed. Any number of values can be added to form lists of allowed values.An optional System.String can be included for each value to be returned when using the ToString() method of a PropertyNode value.

Type inheritance is also available to create a type based on another type:

In C#:

PropertyTree pt = new PropertyTree();

pt.Types.CreateType<Decimal>("SalaryType")
    .MinValue(1)
    .MaxValue(100000)
    .Format("C");
pt.Types.CreateType("ExecutiveSalaryType", "SalaryType")
    .MinValue(50000);

pt.CreateNode("Salary", "ExecutiveSalaryType");

pt["Salary"].Value = 80000;

In VB:

Dim pt As New PropertyTree()

pt.Types.CreateType(Of Decimal)("SalaryType") _
    .MinValue(1) _
    .MaxValue(100000) _
    .Format("C")

pt.Types.CreateType("ExecutiveSalaryType", "SalaryType") _
    .MinValue(50000)

pt.CreateNode("Salary", "ExecutiveSalaryType")

pt(Salary).Value = 80000

When inheriting from a another type, you can only set ranges within the limits of the base type otherwise an Exception will be raised.

CreateType is not available in JavaScript but all restrictions on a type such as validation rules and formatting are implemented.

What’s Next?

In future posts I’ll show more examples of how to use validation as well as programmatically navigating the tree along with the full PropertyTree API. Also I’ll show how to create a PropertyTree using an XML Document syntax and how to use a PropertyTree from JavaScript.

Although in the near future I may set it up as an open-source project, I would currently like to make the PropertyTree library bits available to download and I will as soon as I figure out a good (free) way to do so. If you have any suggestions, please add a comment.

Technorati Tags: ,,
Digg This
Categories: .Net, PropertyTree Tags: ,

Us and Them – Privilege Based versus Role Based Security

October 3, 2009 Leave a comment

I’d like to talk about Privilege-based security because I haven’t found anything on the Web about it and I really think you should consider it if you haven’t already done so.

A bit of history

A while back when programmers added security to their applications they would assign rights to access functions of a program directly to individual users defined in some Users table. They would then use code like the following to perform authorization to a given right:

if (user.CanCreateDocument == true) { 
        // Allow some document creation
}

Of course this meant that every right had to be assigned or denied individually to each user, this made for an administration nightmare.

With the introduction of Role based security a level of indirection was introduced that simplified administration. Rights to functions were granted to Roles and roles were assigned to Users, usually with entries in a security database.

Now when you performed authorization you used code like the following:

if (user.BelongsToRole("Administrators")) { 
        // Allow some code
}

This simplified administration because now you only needed to assign (or remove) a right to a role in the security database and all members of that role would acquire the right.

The problem I have with Role based security

Of course you probably know all this and have used it so you’re asking "What’s the problem?", well recently while working on the security system of a framework on my day job I came across the following problem: users can change their personal passwords on our system and also users who belong to the Administrators role can also change the password of any user. You can see this in this code example:

if (user == userToUpdate || user.BelongsToRole("Administrators")) { 
        // Change the password
}

Again you’re asking "So what’s the problem?", well the customer later required that a Supervisor be able to change a users password but that supervisor could not be member of the application Administrators role because that would grant Supervisors too many rights. "No problem, just create another role, right?" well you can but this is my problem, the authorization code would have to change like so:

if (user == userToUpdate || user.BelongsToRole("Administrators") 
    || user.BelongsToRole("Supervisors"))
        // Change the password
}

In fact any time you need to add a new role for an existing right you have to edit the code to test for the new role and recompile. Now maybe this doesn’t happen too often but if the code is already in the field you just traded an administration nightmare for a deployment one.

Why use Privilege based security

With Privilege based security you create a privilege for every function in code that needs authorization and you test for this:

if (user == userToUpdate || user.HasPrivilege("ChangeUserPassword")
        // Change the password
}

You then assign privileges to roles and when you need to, you can create new roles and assign existing privileges without needing to recompile.

In fact, you could assign (or deny) certain users privileges beyond those found in the roles that they belong to.

In the Real world

When applying this model in our framework, we did find that the more granular the security requirements of an application the more privileges where needed. This added more administrative work if the privileges were assigned individually to roles.

Our solution to this problem was to organize privileges hierarchically and permit the assignment or denial of privileges to be inherited to all sub-privileges of a privilege. For example we created the following privilege tree:

+ Security

+—+ User

      +–+ Create User

           + Delete User

           + View User Profile

           + Change User Password

If we assign the User privilege to a Role then that role is allowed all privileges underneath (i.e. Create User, Delete User, View User Profile and Change User Password). This is similar to how security works in the NTFS File system.

In conclusion

Privilege based security adds a level of flexibility to the already proven Role based security model by creating a single privilege in code for each function in a program that needs to be secured and then assigning that privilege to any roles that require it in a security database. Administrators can then customize and adapt security to real world requirements in the field without recompiling existing code.

Careful with That Axe, Eugene – Using ToString() with a .Net Decimal Type

September 11, 2009 Leave a comment

A Problem With Decimals

Yesterday I ran into a problem with the ToString() function on a .Net Decimal type.

Actually the problem was mine but it revealed something I didn’t know about Decimal types that actually IS in the documentation but no one really reads the documentation, do they? Well they do when they run into problems.

Try the following in a .Net console application (C# or VB.Net or whatever you prefer):

    decimal dec1 = 10.0M;
    decimal dec2 = Decimal.Parse("10.00");
    Console.Write("dec1 == dec2 : ");
    Console.WriteLine(dec1 == dec2);
    Console.Write("dec1.ToString() == dec2.ToString() : ");
    Console.WriteLine(dec1.ToString() == dec2.ToString());

The output is the following:

dec1 == dec2 : True

dec1.ToString() == dec2.ToString() : False

Now, both dec1 and dec2 contain a decimal 10 value so mathematically they are equal, but the output of ToString() for each of them is:

dec1.ToString() : 10.0

dec2.ToString() : 10.00

So you see the strings are not identical.

The Reason Behind It

The reason that the two ToString() calls are not equal is because Decimal preserves the position of the decimal point so when we parse the string “10.00” both zeros to the right of the decimal point are kept.

This is all detailed in the MSDN documentation on the Decimal structure :

The scaling factor also preserves any trailing zeroes in a Decimal number. Trailing zeroes do not affect the value of a Decimal number in arithmetic or comparison operations. However, trailing zeroes can be revealed by the ToString method if an appropriate format string is applied.

I stumbled upon this while working on the Serialize/De-serialize functions of PropertyTree a data structure that I will post about soon (really).

Technorati Tags: ,
Categories: .Net, Programming Tags: