IAzManAuthorization / GetAttribute / Without Exception?

Topics: NetSqlAzMan Core
Jan 4, 2012 at 7:30 PM

Is there a way to test for the existence of an Attribute, without throwing an exception?

 

My code:

 

            //Create a custom attribute
            IAzManAttribute<IAzManAuthorization> attr = auth.GetAttribute("New Key");
            if (null == attr)
            {
                attr = auth.CreateAttribute("New Key", "New Value");
            }

 

But the above throws an exception.

Suggestions.  1.  Change behavior.  2.  Implement CheckFor method that returns null if the attribute is null.

 

Below is the framework code:

 

        public IAzManAttribute<IAzManAuthorization> GetAttribute(string key)
        {
            AuthorizationAttributesResult attr;
            if ((attr = (from t in this.db.AuthorizationAttributes() where t.AuthorizationId == this.authorizationId && t.AttributeKey == key select t).FirstOrDefault()) != null)
            {
                IAzManAttribute<IAzManAuthorization> result = new SqlAzManAuthorizationAttribute(this.db, this, attr.AuthorizationAttributeId.Value, attr.AttributeKey, attr.AttributeValue, this.ens);
                if (this.ens != null) this.ens.AddPublisher(result);
                return result;
            }
            else
            {
                throw SqlAzManException.AttributeNotFoundException(key, this, null);
            }
        }

Jan 6, 2012 at 10:14 AM

Yes,

use the Auth.Attributes properties to enumerate all attributes or use the Auth.Attributes.ContainsKey(“keyName”) method to check the existence.

__________________________________
Andrea Ferendeles
NetSqlAzMan Project Coordinator
E-mail aferende@hotmail.com Web http://netsqlazman.codeplex.com

Jan 6, 2012 at 2:24 PM

 

Thanks.

 

Here is my revamped code:

 

            IAzManAttribute<IAzManAuthorization> attr = null;
            if (auth.Attributes.ContainsKey("New Key"))
            {
                attr = auth.GetAttribute("New Key");
            }
            else
            {
                //Create a custom attribute
                attr = auth.CreateAttribute("New Key", "New Value");
            }