Beispiel #1
0
        internal void Load()
        {
            var configType      = config.GetType();
            var holderAttribute = configType.GetCustomAttribute <ConfigurationHolderAttribute>();

            foreach (PropertyInfo item in configType.GetProperties())
            {
                if (item.PropertyType == typeof(ConfigurationElement))
                {
                    ConfigurationElement element = ConfigurationIO.Read(item.Name, name + "." + config.GetType().Name /*,item.GetValue(config).ToString()*/);

                    if (!string.IsNullOrWhiteSpace(element))
                    {
                        if (CheckValueVaild(item, element, holderAttribute))
                        {
                            item.SetValue(config, element);
                        }
                    }
                    else
                    {
                        //if not exist,write to config.ini immediately
                        ConfigurationIO.Write(item.Name, (ConfigurationElement)item.GetValue(config), name + "." + config.GetType().Name);
                    }
                }
            }
        }
        public static string[] GetConfiguration(IConfigurable configurable)
        {
            List <string> output = new List <string>();

            PropertyInfo[] properties = configurable.GetType().GetProperties();
            for (int i = 0; i < properties.Length; i++)
            {
                PropertyInfo    property         = properties[i];
                MakeConfigrable makeConfigurable = Attribute.GetCustomAttribute(property, typeof(MakeConfigrable)) as MakeConfigrable;
                if (makeConfigurable != null)
                {
                    if (property.PropertyType.IsArray)
                    {
                        string outputEntry = property.Name + ": ";
                        Array  array       = (Array)property.GetValue(configurable, null);
                        for (int i2 = 0; i2 < array.Length; i2++)
                        {
                            outputEntry += ((object)array.GetValue(i2)).ToString() + VALUE_SEPERATOR;
                        }
                        output.Add(outputEntry);
                    }
                    else
                    {
                        output.Add(property.Name + ": " + property.GetValue(configurable, null).ToString());
                    }
                }
            }
            FieldInfo[] fields = configurable.GetType().GetFields();
            for (int i = 0; i < fields.Length; i++)
            {
                FieldInfo       field            = fields[i];
                MakeConfigrable makeConfigurable = Attribute.GetCustomAttribute(field, typeof(MakeConfigrable)) as MakeConfigrable;
                if (makeConfigurable != null)
                {
                    if (field.FieldType.IsArray)
                    {
                        string outputEntry = field.Name + ": ";
                        Array  array       = (Array)field.GetValue(configurable);
                        for (int i2 = 0; i2 < array.Length; i2++)
                        {
                            outputEntry += ((object)array.GetValue(i2)).ToString() + VALUE_SEPERATOR;
                        }
                        output.Add(outputEntry);
                    }
                    else
                    {
                        output.Add(field.Name + ": " + field.GetValue(configurable).ToString());
                    }
                }
            }
            return(output.ToArray());
        }
Beispiel #3
0
        // Token: 0x0600606F RID: 24687 RVA: 0x00147B24 File Offset: 0x00145D24
        public virtual void Provision(ADProvisioningPolicy templatePolicy, IConfigurable writablePresentationObject)
        {
            if (templatePolicy == null)
            {
                throw new ArgumentNullException("templatePolicy");
            }
            if (writablePresentationObject == null)
            {
                throw new ArgumentNullException("writablePresentationObject");
            }
            if (!base.TargetObjectTypes.Contains(writablePresentationObject.GetType()))
            {
                throw new ArgumentOutOfRangeException("writablePresentationObject");
            }
            if (!(writablePresentationObject is ADObject))
            {
                throw new ArgumentOutOfRangeException("writablePresentationObject");
            }
            object obj = templatePolicy[base.PolicyProperty];

            if (!this.IsNullOrUnlimited(obj) && !this.IsNullOrEmptyMvp(obj))
            {
                if (base.ValueConverter != null)
                {
                    obj = base.ValueConverter(obj);
                }
                ((ADObject)writablePresentationObject)[base.ObjectProperty] = obj;
                return;
            }
        }
Beispiel #4
0
        public void Delete(IConfigurable instance)
        {
            if (instance == null)
            {
                throw new ArgumentNullException("instance");
            }
            if (this.configurationSession.ReadOnly)
            {
                throw new InvalidOperationException("read only");
            }
            if (this.serviceInstanceName == null)
            {
                throw new InvalidOperationException("Delete can be performed only for specific service instance.");
            }
            FullSyncObjectRequest fullSyncObjectRequest = instance as FullSyncObjectRequest;

            if (fullSyncObjectRequest == null)
            {
                throw new NotSupportedException(instance.GetType().FullName);
            }
            this.RefreshRidMasterInformation();
            MsoMainStreamCookieContainer msoMainStreamCookieContainer = this.configurationSession.GetMsoMainStreamCookieContainer(this.serviceInstanceName);
            MultiValuedProperty <FullSyncObjectRequest> msoForwardSyncObjectFullSyncRequests = msoMainStreamCookieContainer.MsoForwardSyncObjectFullSyncRequests;

            if (msoForwardSyncObjectFullSyncRequests.Contains(fullSyncObjectRequest))
            {
                msoForwardSyncObjectFullSyncRequests.Remove(fullSyncObjectRequest);
                this.configurationSession.Save(msoMainStreamCookieContainer);
                return;
            }
            throw new ADNoSuchObjectException(DirectoryStrings.ExceptionADOperationFailedNoSuchObject(this.configurationSession.DomainController, fullSyncObjectRequest.ToString()));
        }
Beispiel #5
0
 public static void Configure(this IConfigurable leftHand)
 {
     if (leftHand == null)
     {
         return;
     }
     if (leftHand.Properties == null)
     {
         return;
     }
     foreach (var property in leftHand.Properties)
     {
         System.Reflection.PropertyInfo prop = null;
         try
         {
             prop = leftHand.GetType().GetProperty(property);                   //can be null if property not exists, can throw exceptions
             var value = leftHand.Config.GetValue(leftHand.Section, prop.Name); //can throw exceptions
             prop.SetValue(leftHand, value);
         }
         catch
         {
             if (prop != null)
             {
                 leftHand.Config.SetValue(leftHand.Section, prop.Name, (string)prop.GetValue(leftHand));
             }
         }
     }
 }
Beispiel #6
0
        public void Initialize(String workingDirPath, string[] arguments)
        {
            if (arguments.Length != 1)
            {
                throw new Exception(GetType() + " expects one argument: \"<className>;<configFile>");
            }
            string[] splitArguments         = arguments[0].Split(new[] { ';' });
            string   dotNetFactoryClassName = splitArguments[0];

            string[] dotNetFactoryArguments = new string[splitArguments.Length - 1];
            for (int i = 0; i < dotNetFactoryArguments.Length; i++)
            {
                dotNetFactoryArguments[i] = splitArguments[i + 1];
            }
            if (_insertedModelFactory != null)
            {
                // Model factory already set. Check class name
                if (!_insertedModelFactory.GetType().ToString().Equals(dotNetFactoryClassName))
                {
                    throw new Exception("Inserted ModelFactory is not of the type specified in the OpenDA config file");
                }
                _actualModelFactory = _insertedModelFactory;
            }
            else
            {
                // Note: this dynamic object creation
                IConfigurable modelFactoryObject = Utils.CreateConfigurableInstance(dotNetFactoryClassName, typeof(IModelFactory));
                if (!(modelFactoryObject is IModelFactory))
                {
                    throw new Exception("Unexpected object type " + modelFactoryObject.GetType());
                }
                _actualModelFactory = (IModelFactory)modelFactoryObject;
            }
            _actualModelFactory.Initialize(workingDirPath, dotNetFactoryArguments);
        }
Beispiel #7
0
        public void ForceLoad()
        {
            foreach (PropertyInfo item in config.GetType().GetProperties())
            {
                if (item.PropertyType == typeof(ConfigurationElement))
                {
                    ConfigurationElement element = ConfigurationIO.Read(item.Name, instance.Name + "." + config.GetType().Name /*,item.GetValue(config).ToString()*/);

                    if (!string.IsNullOrWhiteSpace(element))
                    {
                        item.SetValue(config, element);
                    }
                }
            }
            config.onConfigurationLoad();
        }
Beispiel #8
0
 public PluginConfiuration GetInstance(IConfigurable obj)
 {
     foreach (var item in items)
     {
         if (item.GetType() == obj.GetType())
         {
             return(item);
         }
     }
     return(null);
 }
 // Token: 0x06006075 RID: 24693 RVA: 0x00147CC4 File Offset: 0x00145EC4
 public virtual bool IsApplicable(IConfigurable readOnlyPresentationObject)
 {
     if (readOnlyPresentationObject == null)
     {
         throw new ArgumentNullException("readOnlyPresentationObject");
     }
     if (!base.TargetObjectTypes.Contains(readOnlyPresentationObject.GetType()))
     {
         throw new ArgumentOutOfRangeException("readOnlyPresentationObject");
     }
     return(ObjectState.New == readOnlyPresentationObject.ObjectState);
 }
Beispiel #10
0
        private void PopulateObject(IConfigurable obj)
        {
            string key;
            string typeName = obj.GetType().Name;

            PropertyInfo[] properties = obj.GetType().GetProperties();
            foreach (PropertyInfo p in properties)
            {
                //if (p.PropertyType.Name == "String"
                //    || p.PropertyType.Name == "Int32")
                if (p.GetCustomAttributes(typeof(ConfigItem), true).Length > 0)
                {
                    key = typeName + "." + p.Name;
                    if (!ConfigData.ContainsKey(key))
                    {
                        continue;
                    }

                    switch (p.PropertyType.Name)
                    {
                    case "String":
                        p.SetValue(obj, Get <String>(key), null);
                        break;

                    case "Int32":
                        p.SetValue(obj, Get <int>(key), null);
                        break;

                    case "Boolean":
                        p.SetValue(obj, Get <bool>(key), null);
                        break;
                    }
                    //if (p.PropertyType.Name == "System.String")
                    //    p.SetValue(obj, Get<string>(key), null);
                    //Set(typeName + "." + p.Name, p.GetValue(obj, null)?.ToString());
                }
            }
        }
Beispiel #11
0
        public void Save(IConfigurable instance)
        {
            if (instance == null)
            {
                throw new ArgumentNullException("instance");
            }
            if (this.configurationSession.ReadOnly)
            {
                throw new InvalidOperationException("read only");
            }
            if (this.serviceInstanceName == null)
            {
                throw new InvalidOperationException("Save can be performed only for specific service instance.");
            }
            FullSyncObjectRequest request = instance as FullSyncObjectRequest;

            if (request == null)
            {
                throw new NotSupportedException(instance.GetType().FullName);
            }
            this.RefreshRidMasterInformation();
            MsoMainStreamCookieContainer msoMainStreamCookieContainer = this.configurationSession.GetMsoMainStreamCookieContainer(this.serviceInstanceName);
            MultiValuedProperty <FullSyncObjectRequest> msoForwardSyncObjectFullSyncRequests = msoMainStreamCookieContainer.MsoForwardSyncObjectFullSyncRequests;
            FullSyncObjectRequest fullSyncObjectRequest = msoForwardSyncObjectFullSyncRequests.Find((FullSyncObjectRequest r) => request.Identity.Equals(r.Identity) && request.ServiceInstanceId == r.ServiceInstanceId);

            if (fullSyncObjectRequest != null)
            {
                if (request.ObjectState == ObjectState.New)
                {
                    throw new ADObjectAlreadyExistsException(DirectoryStrings.ExceptionADOperationFailedAlreadyExist(this.configurationSession.DomainController, request.ToString()));
                }
                if (request.ObjectState == ObjectState.Changed)
                {
                    msoForwardSyncObjectFullSyncRequests.Remove(fullSyncObjectRequest);
                }
            }
            else
            {
                IEnumerable <FullSyncObjectRequest> source = from r in msoForwardSyncObjectFullSyncRequests
                                                             where request.ServiceInstanceId == r.ServiceInstanceId
                                                             select r;
                int maxObjectFullSyncRequestsPerServiceInstance = ProvisioningTasksConfigImpl.MaxObjectFullSyncRequestsPerServiceInstance;
                if (source.Count <FullSyncObjectRequest>() >= maxObjectFullSyncRequestsPerServiceInstance)
                {
                    throw new DataSourceOperationException(Strings.OperationExceedsPerServiceInstanceFullSyncObjectRequestLimit(maxObjectFullSyncRequestsPerServiceInstance, request.ServiceInstanceId));
                }
            }
            msoForwardSyncObjectFullSyncRequests.Add(request);
            this.configurationSession.Save(msoMainStreamCookieContainer);
        }
        private static string CheckInputType(IConfigurable obj)
        {
            if (obj == null)
            {
                throw new ArgumentNullException("AsyncQueueSession input");
            }
            string name = obj.GetType().Name;

            if (!(obj is AsyncQueueRequest) && !(obj is AsyncQueueRequestStatusUpdate) && !(obj is AsyncQueueLog) && !(obj is AsyncQueueLogBatch))
            {
                throw new InvalidObjectTypeForSessionException(HygieneDataStrings.ErrorInvalidObjectTypeForSession("AsyncQueueSession", name));
            }
            return(name);
        }
        // Token: 0x06001085 RID: 4229 RVA: 0x000327DC File Offset: 0x000309DC
        private void GenerateSchema(PSObject template)
        {
            ExTraceGlobals.IntegrationTracer.Information <PSObject>((long)this.GetHashCode(), "-->MonadDataReader.GenerateSchema({0})", template);
            this.properties = new COPropertyInfoCollection();
            IConfigurable configurable = this.UnWrappPSObject(template) as IConfigurable;

            if (configurable != null)
            {
                ExTraceGlobals.IntegrationTracer.Information((long)this.GetHashCode(), "\tTemplate is a IConfigurable");
                if (template.Properties["Identity"] != null)
                {
                    Type typeFromHandle = typeof(string);
                    this.properties.Add(new COPropertyInfo("Identity", typeFromHandle));
                    ExTraceGlobals.IntegrationTracer.Information <string, Type>((long)this.GetHashCode(), "\tProperty added to schema: {0}, {1}", "Identity", typeFromHandle);
                }
                foreach (PSPropertyInfo pspropertyInfo in template.Properties)
                {
                    if (!("Fields" == pspropertyInfo.Name) && !("Identity" == pspropertyInfo.Name))
                    {
                        Type type = Type.GetType(pspropertyInfo.TypeNameOfValue);
                        if (null == type)
                        {
                            PropertyInfo property = configurable.GetType().GetProperty(pspropertyInfo.Name);
                            if (!(null != property))
                            {
                                ExTraceGlobals.IntegrationTracer.Information <string>((long)this.GetHashCode(), "\tProperty skipped: {0}", pspropertyInfo.Name);
                                continue;
                            }
                            type = property.PropertyType;
                        }
                        this.properties.Add(new COPropertyInfo(pspropertyInfo.Name, type));
                        ExTraceGlobals.IntegrationTracer.Information <string>((long)this.GetHashCode(), "\tProperty added to schema: {0}", pspropertyInfo.Name);
                    }
                }
                if (!string.IsNullOrEmpty(this.preservedObjectProperty))
                {
                    this.properties.Add(new COPropertyInfo(this.preservedObjectProperty, configurable.GetType()));
                    ExTraceGlobals.IntegrationTracer.Information <string>((long)this.GetHashCode(), "\tProperty added to schema: {0}", this.preservedObjectProperty);
                }
            }
            else
            {
                ExTraceGlobals.IntegrationTracer.Information((long)this.GetHashCode(), "\tTemplate is NOT a IConfigurable.");
                this.properties.Add(new COPropertyInfo("Value", this.UnWrappPSObject(template).GetType()));
                this.useBaseObject = true;
            }
            ExTraceGlobals.IntegrationTracer.Information((long)this.GetHashCode(), "<--MonadDataReader.GenerateSchema()");
        }
 // Token: 0x06006076 RID: 24694 RVA: 0x00147CFB File Offset: 0x00145EFB
 public virtual ProvisioningValidationError[] Validate(ADProvisioningPolicy enforcementPolicy, IConfigurable readOnlyPresentationObject)
 {
     if (enforcementPolicy == null)
     {
         throw new ArgumentNullException("enforcementPolicy");
     }
     if (readOnlyPresentationObject == null)
     {
         throw new ArgumentNullException("readOnlyPresentationObject");
     }
     if (!base.TargetObjectTypes.Contains(readOnlyPresentationObject.GetType()))
     {
         throw new ArgumentOutOfRangeException("readOnlyPresentationObject");
     }
     return(null);
 }
        public void AddConfigurable(IConfigurable configurable, String name)
        {
            if (_symbolTable.ContainsKey(name))
            {
                throw new ArgumentException("tried to override existing component name");
            }

            var dummyRPD = new RawPropertyData(name, configurable.GetType().Name);

            var ps = new PropertySheet(configurable, name, dummyRPD, this);

            _symbolTable.Put(name, ps);
            _rawPropertyMap.Put(name, dummyRPD);

            foreach (IConfigurationChangeListener changeListener in _changeListeners)
            {
                changeListener.ComponentAdded(this, ps);
            }
        }
        public virtual void Save(IConfigurable instance)
        {
            if (instance == null)
            {
                throw new ArgumentNullException("instance");
            }
            ConfigurableObject configurableObject = instance as ConfigurableObject;

            if (configurableObject == null)
            {
                throw new NotSupportedException("Save: " + instance.GetType().FullName);
            }
            ValidationError[] array = configurableObject.Validate();
            if (array.Length > 0)
            {
                throw new DataValidationException(array[0]);
            }
            this.InternalSave(configurableObject);
            configurableObject.ResetChangeTracking(true);
        }
        public void Delete(IConfigurable instance)
        {
            if (instance == null)
            {
                throw new ArgumentNullException("instance");
            }
            ConfigurableObject configurableObject = instance as ConfigurableObject;

            if (configurableObject == null)
            {
                throw new NotSupportedException("Delete: " + instance.GetType().FullName);
            }
            if (configurableObject.ObjectState == ObjectState.Deleted)
            {
                throw new InvalidOperationException(ServerStrings.ExceptionObjectHasBeenDeleted);
            }
            this.InternalDelete(configurableObject);
            configurableObject.ResetChangeTracking();
            configurableObject.MarkAsDeleted();
        }
 public void Save(IConfigurable obj)
 {
     if (obj == null)
     {
         throw new ArgumentNullException(obj.GetType().Name);
     }
     if (obj is OnDemandQueryRequest)
     {
         OnDemandQueryRequest reportRequest = obj as OnDemandQueryRequest;
         this.Save(reportRequest);
     }
     else
     {
         if (!(obj is ReportSchedule))
         {
             throw new NotSupportedException("This object type cannot be saved through this session object");
         }
         ReportSchedule reportSchedule = obj as ReportSchedule;
         this.Save(reportSchedule);
     }
     this.dataProviderDirectory.Save(obj);
 }
        // Token: 0x0600607A RID: 24698 RVA: 0x00147E54 File Offset: 0x00146054
        public override ProvisioningValidationError[] Validate(ADProvisioningPolicy enforcementPolicy, IConfigurable readOnlyPresentationObject)
        {
            base.Validate(enforcementPolicy, readOnlyPresentationObject);
            ADObject adobject;

            if (readOnlyPresentationObject is ADPublicFolder)
            {
                adobject = (ADPublicFolder)readOnlyPresentationObject;
            }
            else
            {
                adobject = (MailEnabledRecipient)readOnlyPresentationObject;
            }
            Unlimited <int> fromValue = (Unlimited <int>)enforcementPolicy[base.CountQuotaProperty];

            if (!fromValue.IsUnlimited && (T)fromValue >= 0)
            {
                int  num = (T)fromValue;
                bool flag;
                if (num == 0)
                {
                    flag = true;
                }
                else
                {
                    string domainController = null;
                    if (base.Context != null && base.Context.UserSpecifiedParameters != null && base.Context.UserSpecifiedParameters.Contains("DomainController"))
                    {
                        object obj = base.Context.UserSpecifiedParameters["DomainController"];
                        if (obj != null)
                        {
                            domainController = obj.ToString();
                        }
                    }
                    ADSessionSettings     sessionSettings = ADSessionSettings.FromOrganizationIdWithoutRbacScopes(ADSystemConfigurationSession.GetRootOrgContainerIdForLocalForest(), adobject.OrganizationId, null, false);
                    IConfigurationSession tenantOrTopologyConfigurationSession = DirectorySessionFactory.Default.GetTenantOrTopologyConfigurationSession(domainController, true, ConsistencyMode.FullyConsistent, sessionSettings, 178, "Validate", "f:\\15.00.1497\\sources\\dev\\data\\src\\directory\\Provisioning\\RecipientResourceCountQuota.cs");
                    flag = SystemAddressListMemberCount.IsQuotaExceded(tenantOrTopologyConfigurationSession, adobject.OrganizationId, base.SystemAddressListName, num);
                }
                if (flag)
                {
                    string          policyId = string.Format("{0}: {1}", enforcementPolicy.Identity.ToString(), base.CountQuotaProperty.Name);
                    LocalizedString description;
                    if (adobject.OrganizationalUnitRoot == null)
                    {
                        description = DirectoryStrings.ErrorExceededHosterResourceCountQuota(policyId, (readOnlyPresentationObject.GetType() == typeof(ADPublicFolder)) ? "MailPublicFolder" : ProvisioningHelper.GetProvisioningObjectTag(readOnlyPresentationObject.GetType()), num);
                    }
                    else
                    {
                        description = DirectoryStrings.ErrorExceededMultiTenantResourceCountQuota(policyId, (readOnlyPresentationObject.GetType() == typeof(ADPublicFolder)) ? "MailPublicFolder" : ProvisioningHelper.GetProvisioningObjectTag(readOnlyPresentationObject.GetType()), adobject.OrganizationalUnitRoot.Name, num);
                    }
                    return(new ProvisioningValidationError[]
                    {
                        new ProvisioningValidationError(description, ExchangeErrorCategory.ServerOperation, null)
                    });
                }
            }
            return(null);
        }
        void IConfigurable.CopyChangesFrom(IConfigurable source)
        {
            DatabaseEventWatermark databaseEventWatermark = source as DatabaseEventWatermark;

            if (databaseEventWatermark == null)
            {
                throw new NotImplementedException(string.Format("Cannot copy changes from type {0}.", source.GetType()));
            }
            this.watermark            = databaseEventWatermark.watermark;
            this.consumerGuid         = databaseEventWatermark.consumerGuid;
            this.databaseId           = databaseEventWatermark.databaseId;
            this.server               = databaseEventWatermark.server;
            this.isDatabaseCopyActive = databaseEventWatermark.isDatabaseCopyActive;
        }
 internal void Delete(IConfigurable configurable)
 {
     if (!(configurable is ProbeOrganizationInfo) && !(configurable is TenantConfigurationCacheEntry))
     {
         throw new ArgumentException(string.Format("The type {0} is not supported for the global session; please use a scoped DAL session instead.", configurable.GetType().ToString()));
     }
     this.WebStoreDataProvider.Delete(configurable);
 }
Beispiel #22
0
        void IConfigurable.CopyChangesFrom(IConfigurable source)
        {
            DatabaseEvent databaseEvent = source as DatabaseEvent;

            if (databaseEvent == null)
            {
                throw new NotImplementedException(string.Format("Cannot copy changes from type {0}.", source.GetType()));
            }
            this.mapiEvent            = databaseEvent.mapiEvent;
            this.databaseId           = databaseEvent.databaseId;
            this.server               = databaseEvent.server;
            this.isDatabaseCopyActive = databaseEvent.isDatabaseCopyActive;
        }
Beispiel #23
0
 public PropertySheet(IConfigurable configurable, string name, RawPropertyData rpd, ConfigurationManager configurationManager)
     : this(configurable.GetType(), name, configurationManager, rpd)
 {
     _owner = configurable;
 }
 public static void SetConfiguration(IConfigurable configurable)
 {
     PropertyInfo[] properties = configurable.GetType().GetProperties();
     for (int i = 0; i < properties.Length; i++)
     {
         PropertyInfo    property         = properties[i];
         MakeConfigrable makeConfigurable = Attribute.GetCustomAttribute(property, typeof(MakeConfigrable)) as MakeConfigrable;
         if (makeConfigurable != null)
         {
             if (property.PropertyType.IsArray)
             {
                 string value = fileReader.ReadLine();
                 value = value.Replace(property.Name + ": ", "");
                 Array array = (Array)property.GetValue(configurable, null);
                 for (int i2 = 0; i2 < array.Length; i2++)
                 {
                     if (array.GetValue(i2) is float)
                     {
                         property.SetValue(configurable, float.Parse(value.Substring(0, value.IndexOf(", "))), new object[] { i2 });
                     }
                     else if (array.GetValue(i2) is int)
                     {
                         property.SetValue(configurable, int.Parse(value), new object[] { i2 });
                     }
                     else if (array.GetValue(i2) is bool)
                     {
                         property.SetValue(configurable, bool.Parse(value), new object[] { i2 });
                     }
                     value = value.Remove(0, value.IndexOf(", "));
                 }
             }
             else
             {
                 string value = fileReader.ReadLine();
                 value = value.Replace(property.Name + ": ", "");
                 if (property.PropertyType == typeof(float))
                 {
                     property.SetValue(configurable, float.Parse(value), null);
                 }
                 else if (property.PropertyType == typeof(int))
                 {
                     property.SetValue(configurable, int.Parse(value), null);
                 }
                 else if (property.PropertyType == typeof(bool))
                 {
                     property.SetValue(configurable, bool.Parse(value), null);
                 }
             }
         }
     }
     FieldInfo[] fields = configurable.GetType().GetFields();
     for (int i = 0; i < fields.Length; i++)
     {
         FieldInfo       field            = fields[i];
         MakeConfigrable makeConfigurable = Attribute.GetCustomAttribute(field, typeof(MakeConfigrable)) as MakeConfigrable;
         if (makeConfigurable != null)
         {
             if (field.FieldType.IsArray)
             {
                 string value = fileReader.ReadLine();
                 value = value.Replace(field.Name + ": ", "");
                 if (field.GetValue(configurable) is float[])
                 {
                     List <float> values = new List <float>();
                     while (value.Contains(VALUE_SEPERATOR))
                     {
                         values.Add(float.Parse(value.Substring(0, value.IndexOf(VALUE_SEPERATOR))));
                         value = value.Remove(0, value.IndexOf(VALUE_SEPERATOR) + VALUE_SEPERATOR.Length);
                     }
                     field.SetValue(configurable, values.ToArray());
                 }
                 else if (field.GetValue(configurable) is int[])
                 {
                     List <int> values = new List <int>();
                     while (value.Contains(VALUE_SEPERATOR))
                     {
                         values.Add(int.Parse(value.Substring(0, value.IndexOf(VALUE_SEPERATOR))));
                         value = value.Remove(0, value.IndexOf(VALUE_SEPERATOR) + VALUE_SEPERATOR.Length);
                     }
                     field.SetValue(configurable, values.ToArray());
                 }
                 else if (field.GetValue(configurable) is bool[])
                 {
                     List <bool> values = new List <bool>();
                     while (value.Contains(VALUE_SEPERATOR))
                     {
                         values.Add(bool.Parse(value.Substring(0, value.IndexOf(VALUE_SEPERATOR))));
                         value = value.Remove(0, value.IndexOf(VALUE_SEPERATOR) + VALUE_SEPERATOR.Length);
                     }
                     field.SetValue(configurable, values.ToArray());
                 }
             }
             else
             {
                 string value = fileReader.ReadLine();
                 value = value.Replace(field.Name + ": ", "");
                 if (field.FieldType == typeof(float))
                 {
                     field.SetValue(configurable, float.Parse(value));
                 }
                 else if (field.FieldType == typeof(int))
                 {
                     field.SetValue(configurable, int.Parse(value));
                 }
                 else if (field.FieldType == typeof(bool))
                 {
                     field.SetValue(configurable, bool.Parse(value));
                 }
             }
         }
     }
 }
        /// <summary>
        ///
        /// </summary>
        /// <param name="content">Raw configuration file content.</param>
        /// <param name="configuration">The configuration object, implementing IConfigurable.</param>
        /// <param name="customParsers">Optional array of parser allowing to parse any type the way you want.</param>
        public static void AssignConfiguration(string content, IConfigurable configuration, params ICustomParser[] customParsers)
        {
            Dictionary <string, string> rawConfiguration = ParseConfiguration(content);
            var configurableProperties =
                (from p in configuration.GetType().GetProperties()
                 let attr = p.GetCustomAttributes(typeof(MatchingKeyAttribute), true)
                            where attr.Length == 1
                            select new { Property = p, Attribute = attr.First() as MatchingKeyAttribute })
                .ToList();

            foreach (var item in rawConfiguration)
            {
                string               key               = item.Key.ToLowerInvariant();
                var                  matchingProps     = configurableProperties.Where(x => x.Attribute.Key == key);
                PropertyInfo         matchingProp      = null;
                MatchingKeyAttribute matchingAttribute = null;
                if (matchingProps.Any())
                {
                    try
                    {
                        // try to find a matching property for this key
                        var single = matchingProps.Single();
                        matchingProp      = single.Property;
                        matchingAttribute = single.Attribute;
                        configurableProperties.Remove(single);
                    }
                    catch (Exception ex)
                    {
                        throw new Exception(string.Format("The key \"{0}\" was found multiple times!", key), ex);
                    }
                    // parse value
                    var appropriateParser = customParsers.FirstOrDefault(x => x.ReturnType == matchingProp.PropertyType);
                    if (appropriateParser != null)
                    {
                        object parsed = appropriateParser.Parse(item.Value, matchingAttribute.CustomParameter);
                        matchingProp.SetValue(configuration, parsed, null);
                    }
                    // default parsers
                    else if (matchingProp.PropertyType == typeof(string))
                    {
                        // todo: handle default values for strings
                        matchingProp.SetValue(configuration, item.Value, null);
                    }
                    else if (matchingProp.PropertyType == typeof(bool))
                    {
                        if (matchingAttribute.CustomParameter is bool)
                        {
                            matchingProp.SetValue(configuration, ParseBool(item.Value, (bool)matchingAttribute.CustomParameter), null);
                        }
                        else
                        {
                            matchingProp.SetValue(configuration, ParseBool(item.Value), null);
                        }
                    }
                    else if (matchingProp.PropertyType == typeof(int))
                    {
                        if (matchingAttribute.CustomParameter is int)
                        {
                            matchingProp.SetValue(configuration, ParseInt(item.Value, (int)matchingAttribute.CustomParameter), null);
                        }
                        else
                        {
                            matchingProp.SetValue(configuration, ParseInt(item.Value), null);
                        }
                    }
                    // TODO: default parser for other simple types (int, float...)
                    else
                    {
                        throw new Exception(string.Format("Could not find a parser for type \"{0}\"!", matchingProp.PropertyType));
                    }
                }
                else
                {
                    // no matching assignable property
                    configuration.HandleDynamicKey(item.Key, item.Value);
                }
            }
            // assign default value if present for remaining properties not found in configuration
            foreach (var remainingPropery in configurableProperties)
            {
                // todo : throw exception if no default parameter to avoid impredictable errors?
                // >> need to differentiate default null from provided null
                if (remainingPropery.Attribute.CustomParameter != null)
                {
                    remainingPropery.Property.SetValue(configuration, remainingPropery.Attribute.CustomParameter, null);
                }
            }
        }
        private void CacheDeleteInternal(IConfigurable instance)
        {
            string    error     = null;
            Stopwatch stopwatch = Stopwatch.StartNew();

            CachePerformanceTracker.StartLogging();
            bool   isNewProxyObject = false;
            int    retryCount       = 0;
            string callerInfo       = null;
            Guid   activityId       = Guid.Empty;

            try
            {
                TSession tsession = this.GetCacheSession();
                tsession.Delete(instance);
                CacheDirectorySession cacheDirectorySession = this.GetCacheSession() as CacheDirectorySession;
                if (cacheDirectorySession != null)
                {
                    isNewProxyObject = cacheDirectorySession.IsNewProxyObject;
                    retryCount       = cacheDirectorySession.RetryCount;
                }
                TSession session = this.GetSession();
                if (session.ActivityScope != null)
                {
                    TSession session2 = this.GetSession();
                    if (session2.ActivityScope.Status == ActivityContextStatus.ActivityStarted)
                    {
                        TSession session3 = this.GetSession();
                        activityId = session3.ActivityScope.ActivityId;
                    }
                }
                TSession session4 = this.GetSession();
                callerInfo = session4.CallerInfo;
            }
            catch (Exception ex)
            {
                error = ex.ToString();
                throw;
            }
            finally
            {
                stopwatch.Stop();
                string     cachePerformanceTracker = CachePerformanceTracker.StopLogging();
                ADRawEntry adrawEntry = instance as ADRawEntry;
                CacheProtocolLog.BeginAppend("Remove", (adrawEntry != null) ? adrawEntry.GetDistinguishedNameOrName() : "<NULL>", DateTime.MinValue, stopwatch.ElapsedMilliseconds, -1L, stopwatch.ElapsedMilliseconds, -1L, -1L, isNewProxyObject, retryCount, instance.GetType().Name, cachePerformanceTracker, activityId, callerInfo, error);
            }
        }
Beispiel #27
0
 internal virtual void ProvisionCustomDefaultProperties(IConfigurable provisionedDefault)
 {
     if (provisionedDefault == null)
     {
         throw new ArgumentNullException("provisionedDefault");
     }
     if (this.SupportedPresentationObjectTypes == null || !this.SupportedPresentationObjectTypes.Contains(provisionedDefault.GetType()))
     {
         throw new InvalidOperationException(DirectoryStrings.ErrorPolicyDontSupportedPresentationObject(provisionedDefault.GetType(), base.GetType()));
     }
 }
 void IConfigurable.CopyChangesFrom(IConfigurable source)
 {
     if (!(source is RestrictionRow))
     {
         throw new NotImplementedException(string.Format("Cannot copy changes from type {0}.", source.GetType()));
     }
 }
Beispiel #29
0
 internal virtual ProvisioningValidationError[] ProvisioningCustomValidate(IConfigurable roPresentationObject)
 {
     if (roPresentationObject == null)
     {
         throw new ArgumentNullException("roPresentationObject");
     }
     if (this.SupportedPresentationObjectTypes == null || !this.SupportedPresentationObjectTypes.Contains(roPresentationObject.GetType()))
     {
         throw new InvalidOperationException(DirectoryStrings.ErrorPolicyDontSupportedPresentationObject(roPresentationObject.GetType(), base.GetType()));
     }
     return(null);
 }
Beispiel #30
0
        public void CopyChangesFrom(IConfigurable source)
        {
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }
            IPListEntry iplistEntry = source as IPListEntry;

            if (iplistEntry == null)
            {
                throw new ArgumentException(DirectoryStrings.ExceptionCopyChangesForIncompatibleTypes(source.GetType(), base.GetType()), "source");
            }
            if (iplistEntry.identity != null)
            {
                this.identity = new IPListEntryIdentity(iplistEntry.identity.Index);
            }
            if (iplistEntry.range != null)
            {
                this.range = new IPRange(new IPvxAddress(iplistEntry.range.LowerBound), new IPvxAddress(iplistEntry.range.UpperBound), iplistEntry.range.RangeFormat);
            }
            this.expirationTimeUtc  = iplistEntry.expirationTimeUtc;
            this.isMachineGenerated = iplistEntry.IsMachineGenerated;
            this.listType           = iplistEntry.ListType;
            this.isValid            = iplistEntry.IsValid;
            this.comment            = iplistEntry.Comment;
        }