Пример #1
0
        /// <summary>
        /// Finds out expired resources in the <paramref name="resourceStorage"/> and deletes them.
        /// </summary>
        /// <typeparam name="T"> The type of an identifier of a resource. </typeparam>
        /// <param name="resourceStorage">
        /// The storage where to perform cleanup in.
        /// </param>
        /// <param name="expirationPolicy">
        /// The resource expiration policy.
        /// </param>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="resourceStorage"/> is <see langword="null"/> or
        /// <paramref name="expirationPolicy"/> is <see langword="null"/>.
        /// </exception>
        public async Task ExecuteStorageCleanup <T>(
            [NotNull] IResourceStorage <T> resourceStorage,
            [NotNull] IResourceExpirationPolicy expirationPolicy)
        {
            AssertArg.NotNull(resourceStorage, nameof(resourceStorage));
            AssertArg.NotNull(expirationPolicy, nameof(expirationPolicy));

            _log?.Debug($"Calling {resourceStorage.GetType().Name} storage for resource details.");

            var resources = (await resourceStorage.GetResourceDetails()).ToArray();

            _log?.Debug($"Fetched details about {resources.Length} resources.");

            var resourceIdsToDelete = expirationPolicy
                                      .FindExpiredResources(resources)
                                      .ToArray();

            if (!resourceIdsToDelete.Any())
            {
                _log?.Info("No expired resources were found thus no resource is deleted.");

                return;
            }

            _log?.Debug($"Calling {resourceStorage.GetType().Name} storage for expired resources deletion.");

            await resourceStorage.DeleteResources(resourceIdsToDelete);

            _log?.Debug($"Deleted {resourceIdsToDelete.Length} expired resources.");
        }
        public RemainingBatteryChargeEvent(object sender, int percentRemaining, TimeSpan dischargeTimeRemaining)
        {
            Sender = AssertArg.IsNotNull(sender, nameof(sender));

            PercentRemaining       = percentRemaining;
            DischargeTimeRemaining = dischargeTimeRemaining;
        }
Пример #3
0
        public Task SendAsync(
            Func <Task> action,
            bool ignoreExceptionHandler = false,
            string memberName           = null,
            string filePath             = null,
            int lineNumber = 0)
        {
            AssertArg.IsNotNull(action, nameof(action));
            EnsureInitialized();

            bool isBackground = InvokeRequired;

            TaskCompletionSource <object> source = isBackground
                                                                ? new TaskCompletionSource <object>()
                                                                : null;

            Func <Task> wrappedAction
                = GetWrappedAction(
                      action, source, ignoreExceptionHandler,
                      memberName, filePath, lineNumber);

            if (isBackground)
            {
                Context.Send(state => wrappedAction(), null);
                return(source.Task);
            }

            return(wrappedAction());
        }
Пример #4
0
        protected override void InsertItem(int index, T item)
        {
            AssertArg.IsNotNull(item, nameof(item));

            if (ignoreChanges)
            {
                base.InsertItem(index, item);
                return;
            }

            TInner obj = item.GetObject();

            if (obj == null)
            {
                throw new Exception("Item must have an existing attached object " +
                                    "to insert into an AdaptiveCollection.");
            }

            try
            {
                ignoreChanges = true;

                monitoredCollection.Insert(index, obj);
            }
            finally
            {
                ignoreChanges = false;
            }

            base.InsertItem(index, item);
        }
Пример #5
0
        public void RegisterState <T>(
            string stateKey,
            Func <T> getterFunc,
            Action <T> setterAction,
            ApplicationStateType stateType)
        {
            AssertArg.IsNotNull(stateKey, nameof(stateKey));
            AssertArg.IsNotNull(getterFunc, nameof(getterFunc));
            AssertArg.IsNotNull(setterAction, nameof(setterAction));

            if (stateType == ApplicationStateType.Persistent)
            {
                lock (persistentStateLock)
                {
                    persistentState[stateKey]
                        = new Accessor <T>(getterFunc, setterAction);
                }
            }
            else
            {
                lock (transientStateLock)
                {
                    transientState[stateKey]
                        = new Accessor <T>(getterFunc, setterAction);
                }
            }
        }
Пример #6
0
        public virtual void Navigate(
            string relativeUrl,
            object navigationArgument = null)
        {
            AssertArg.IsNotNullOrWhiteSpace(relativeUrl, nameof(relativeUrl));

            bool            hasAction;
            Action <object> action;

            dictionaryLock.EnterReadLock();
            try
            {
                hasAction = pathDictionary.TryGetValue(relativeUrl, out action);
            }
            finally
            {
                dictionaryLock.ExitReadLock();
            }

            if (hasAction)
            {
                action(navigationArgument);
            }
            else
            {
                throw new ArgumentException(
                          "Unknown path: " + relativeUrl);
            }
        }
Пример #7
0
        public async Task DecryptAsync(
            Stream encryptedStream, string password, Stream outputStream)
        {
            AssertArg.IsNotNull(encryptedStream, nameof(encryptedStream));
            AssertArg.IsNotNull(password, nameof(password));

            byte[] salt = new byte[SaltLength];
            await encryptedStream.ReadAsync(salt, 0, SaltLength);

            using (Aes aes = Aes.Create())
            {
                var deriveBytes = new Rfc2898DeriveBytes(password, salt);
                aes.Key = deriveBytes.GetBytes(128 / 8);
                aes.IV  = aes.Key;

                /* A temporary stream is used because CryptoStream automatically closes
                 * the output stream. This behaviour is changable in .NET 4.7.2,
                 * which includes a new CryptoStream constructor
                 * with a leaveOpen parameter. */
                using (var tempStream = new MemoryStream())
                {
                    using (var cryptoStream = new CryptoStream(
                               tempStream, aes.CreateDecryptor(), CryptoStreamMode.Write))
                    {
                        await encryptedStream.CopyToAsync(cryptoStream);

                        cryptoStream.FlushFinalBlock();
                        tempStream.Position = 0;
                        await tempStream.CopyToAsync(outputStream);
                    }
                }
            }
        }
        public object ConvertToType(object value, Type type)
        {
            AssertArg.IsNotNull(type, nameof(type));
            AssertArg.IsNotNull(value, nameof(value));

            if (value == null || type.IsAssignableFrom(value.GetType()))

            {
                return(value);
            }

            Type valueType = value.GetType();

            TypeConverter converter = GetTypeConverter(valueType);

            if (converter != null && converter.CanConvertTo(type))
            {
                value = converter.ConvertTo(value, type);
                return(value);
            }

            converter = GetTypeConverter(type);
            if (converter != null && converter.CanConvertFrom(valueType))
            {
                value = converter.ConvertFrom(value);
                return(value);
            }

            return(null);
        }
Пример #9
0
        public static Action BindTarget(PropertyBinding propertyBinding, object dataContext)
        {
            AssertArg.IsNotNull(propertyBinding.View, "propertyBinding.View");

            var view = propertyBinding.View as INotifyPropertyChanged;

            if (view == null)
            {
                throw new InvalidOperationException("Binding target does not implement INotifyPropertyChanged.");
            }

            string propertyName = propertyBinding.TargetProperty.Name;

            PropertyChangedEventHandler handler = (sender, args) =>
            {
                if (args.PropertyName == propertyName)
                {
                    var rawValue = propertyBinding.TargetProperty.GetValue(propertyBinding.View);
                    ViewValueChangedHandler.HandleTargetValueChanged(propertyBinding, rawValue, dataContext);
                }
            };

            view.PropertyChanged += handler;

            Action removeAction = () => { view.PropertyChanged -= handler; };

            return(removeAction);
        }
Пример #10
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Log4NetWrapper" /> class.
        /// </summary>
        /// <param name="logImpl">
        /// The implementation of the <see cref="T:log4net.ILog"/> interface.
        /// </param>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="logImpl"/> is <see langword="null"/>.
        /// </exception>
        public Log4NetWrapper(
            [NotNull] log4net.ILog logImpl)
        {
            AssertArg.NotNull(logImpl, nameof(logImpl));

            _logImpl = logImpl;
        }
Пример #11
0
        /// <summary>
        /// Creates a handler for the specified event,
        /// so that when the event is raised, the specified
        /// action is invoked.
        /// </summary>
        /// <param name="eventInfo">The event.</param>
        /// <param name="action">
        /// The action to invoke when the event is raised.</param>
        /// <returns>A delegate that can be used
        /// to subscribe to the event.</returns>
        /// <example>
        /// var handler = ReflectionCompiler.CreateEventHandler(eventInfo, ExecuteCommand);
        /// eventInfo.AddEventHandler(element, handler);
        /// </example>
        public static Delegate CreateEventHandler(
            EventInfo eventInfo, Action action)
        {
            AssertArg.IsNotNull(eventInfo, nameof(eventInfo));
            AssertArg.IsNotNull(action, nameof(action));

            /* Source: http://stackoverflow.com/questions/3478218/using-reflection-emit-to-implement-a-interface */
            Type       handlerType      = eventInfo.EventHandlerType;
            MethodInfo invokeMethodInfo = handlerType.GetTypeInfo().GetDeclaredMethod("Invoke");

            ParameterInfo[] eventParams = invokeMethodInfo.GetParameters();

            //lambda: (object x0, EventArgs x1) => d()
            IEnumerable <ParameterExpression> parameters
                = eventParams.Select(p => Expression.Parameter(p.ParameterType, p.Name));
            // - assumes void method with no arguments but can be
            //   changed to accomodate any supplied method
            MethodCallExpression body = Expression.Call(
                Expression.Constant(action), action.GetType().GetTypeInfo().GetDeclaredMethod("Invoke"));
            LambdaExpression lambda = Expression.Lambda(body, parameters.ToArray());

            Delegate compiledLambda = lambda.Compile();
            Delegate result         = invokeMethodInfo.CreateDelegate(handlerType, compiledLambda);

            return(result);
        }
Пример #12
0
        public AdaptiveCollection(ObservableCollection <TInner> monitoredCollection)
        {
            AssertArg.IsNotNull(monitoredCollection, nameof(monitoredCollection));

            this.monitoredCollection = monitoredCollection;
            monitoredCollection.CollectionChanged += OnCollectionChanged;

            try
            {
                ignoreChanges = true;

                foreach (var command in monitoredCollection)
                {
                    var attacher = new T();
                    attacher.AttachObject(command);
                    lookupDictionary[command] = attacher;

                    base.Add(attacher);
                }
            }
            finally
            {
                ignoreChanges = false;
            }
        }
Пример #13
0
        object GetSettingCore(string key, Type settingType, object defaultValue, out bool settingExists)
        {
            AssertArg.IsNotNull(key, nameof(key));

            /* [DV] We first test if the setting type is IXmlConvertible.
             * If it isn't then it may mean that the type <c>object</c> has been passed in via an overload.
             * The type of the return value may be IXmlConvertible and hence we test the default value
             * as a secondary precaution. It means that in some edge scenario you may find a type that is passed
             * as the default value has implemented IXmlConvertible whereas the stored value doesn't implement it. */
            bool xmlConvertible = typeof(IXmlConvertible).IsAssignableFromEx(settingType);

            xmlConvertible |= settingType == typeof(object) && defaultValue is IXmlConvertible;

            bool   returningDefaultValue;
            object result;

            lockSlim.EnterReadLock();
            try
            {
                result = GetSettingFromStore(key, xmlConvertible, settingType, defaultValue, out returningDefaultValue);
            }
            finally
            {
                lockSlim.ExitReadLock();
            }

            settingExists = !returningDefaultValue;

            return(result);
        }
Пример #14
0
        /// <summary>
        /// Determines whether the specified text contains
        /// the specified substring.
        /// </summary>
        /// <param name="text">The text.</param>
        /// <param name="substring">The substring.</param>
        /// <returns>
        /// <c>true</c> if the specified text contains
        /// the specified substring;
        /// otherwise, <c>false</c>.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        /// Occurs if either parameter is <c>null</c>.</exception>
        public static bool ContainsIgnoreCase(this string text, string substring)
        {
            AssertArg.IsNotNull(text, nameof(text));
            AssertArg.IsNotNull(substring, nameof(substring));

            return(text.IndexOf(substring, StringComparison.OrdinalIgnoreCase) > -1);
        }
Пример #15
0
        public IocContainerExtension(string namespaceAliasedTypeName, string containerKey)
        {
            this.namespaceAliasedTypeName = AssertArg.IsNotNullOrWhiteSpace(namespaceAliasedTypeName, nameof(namespaceAliasedTypeName));
            SetAliasAndTypeName(namespaceAliasedTypeName);

            this.containerKey = AssertArg.IsNotNull(containerKey, nameof(containerKey));
        }
Пример #16
0
        static void FocusControl(UIElement element)
        {
            AssertArg.IsNotNull(element, nameof(element));

            Keyboard.Focus(element);
            var focusResult = element.Focus();

            if (focusResult)
            {
                return;
            }

            element.Dispatcher.Invoke(DispatcherPriority.Background, (Action) delegate
            {
                focusResult = element.Focus();
                Keyboard.Focus(element);

                if (!focusResult)
                {
                    CommitFocusedElement();
                    focusResult = element.Focus();
                    Keyboard.Focus(element);
                }

                if (!focusResult)
                {
                    WriteLog(string.Format("Unable to focus UIElement {0} "
                                           + "IsVisible: {1}, Focusable: {2}, Enabled: {3}",
                                           element, element.IsVisible, element.Focusable,
                                           element.IsEnabled));
                }
            });
        }
Пример #17
0
        public void RegisterConverter(
            string tagName, Func <object, object> convertFunc)
        {
            AssertArg.IsNotNull(tagName, nameof(tagName));
            AssertArg.IsNotNull(convertFunc, nameof(convertFunc));

            RegisterConverterCore(tagName, new DelegateConverter(convertFunc));
        }
Пример #18
0
        /// <summary>
        /// Initializes a new instance of <c>ValueChangingMessageBase</c>
        /// </summary>
        /// <param name="sender">
        /// Commonly this is the initiator of the message.
        /// Cannot be <c>null</c>.</param>
        /// <param name="currentValue">
        /// The current value.</param>
        /// <param name="newValue">
        /// What the new value will be if not cancelled.</param>
        protected ValueChangingMessageBase(
            object sender, TValue currentValue, TValue newValue)
        {
            Sender = AssertArg.IsNotNull(sender, nameof(sender));

            CurrentValue = currentValue;
            NewValue     = newValue;
        }
Пример #19
0
        /// <summary>
        /// Compares two lists for equivalence.
        /// Objects in both lists must be the same
        /// and in the same position.
        /// </summary>
        /// <param name="list1">The first list to compare.
        /// Can not be null.</param>
        /// <param name="list2">The second list to compare.
        /// Can be null.</param>
        /// <returns><c>true</c> if the collections
        /// are equal; <c>false</c> otherwise.</returns>
        /// <exception cref="ArgumentNullException">
        /// Raised if <c>list1</c> is <c>null</c>.</exception>
        public static bool IsEqualList(
            this IList list1,
            IList list2)
        {
            AssertArg.IsNotNull(list1, nameof(list1));

            return(CollectionComparer.AreEqualLists(list1, list2));
        }
Пример #20
0
        /// <summary>
        /// Initializes a new instance of <c>ValueChangedMessageBase</c>
        /// </summary>
        /// <param name="sender">
        /// Commonly this is the initiator of the message.
        /// Cannot be <c>null</c>.</param>
        /// <param name="oldValue">The previous value.</param>
        /// <param name="newValue">The new value.</param>
        protected ValueChangedMessageBase(
            object sender, TValue oldValue, TValue newValue)
        {
            Sender = AssertArg.IsNotNull(sender, nameof(sender));

            OldValue = oldValue;
            NewValue = newValue;
        }
Пример #21
0
        public void Register(
            Type type,
            Func <object> getInstanceFunc,
            bool singleton = false,
            string key     = null)
        {
            AssertArg.IsNotNull(type, nameof(type));
            AssertArg.IsNotNull(getInstanceFunc, nameof(getInstanceFunc));

            key = GetKeyValueOrDefault(key);

            bool useLock = ThreadSafe;

            if (useLock)
            {
                lockSlim.EnterWriteLock();
            }

            try
            {
                if (!typeDictionary.TryGetValue(type,
                                                out ResolverDictionary resolverDictionary))
                {
                    resolverDictionary = new ResolverDictionary();
                }

                Resolver resolver = new Resolver {
                    Singleton = singleton
                };

                Func <object> getObjectFunc = () =>
                {
                    var result = getInstanceFunc();

                    if (resolver.Singleton)
                    {
                        resolver.CreateInstanceFunc = null;
                        resolver.Instance           = result;
                    }

                    return(result);
                };

                resolver.CreateInstanceFunc = getObjectFunc;

                resolverDictionary[key] = resolver;
                keyDictionary[key]      = type;

                typeDictionary[type] = resolverDictionary;
            }
            finally
            {
                if (useLock)
                {
                    lockSlim.ExitWriteLock();
                }
            }
        }
Пример #22
0
        /// <summary>
        /// Focuses the specified control.
        /// If the control resides in a <see cref="TabControl"/>
        /// the <see cref="TabItem"/> is made visible
        /// and the control is focussed.
        /// </summary>
        /// <param name="control">The control.</param>
        public static void Focus(UIElement control)
        {
            AssertArg.IsNotNull(control, nameof(control));
            DependencyObject parent;
            var childControl = control as FrameworkElement;

            if (childControl == null)
            {
                /* What else can we do in this scenario? */
                FocusControl(control);
                return;
            }

            var listBoxItem = control as ListBoxItem;

            if (listBoxItem != null)
            {
                var itemParent = (VirtualizingStackPanel)VisualTreeHelper.GetParent(listBoxItem);
                childControl = ItemsControl.GetItemsOwner(itemParent);
            }

            var expander = control as Expander;

            if (expander != null)
            {
                expander.IsExpanded = true;
            }

            while (childControl != null && (parent = childControl.Parent) != null)
            {
                var tabItem = parent as TabItem;
                if (tabItem != null)
                {
                    var tabControl = tabItem.Parent as TabControl;
                    if (tabControl != null)
                    {
                        tabControl.SelectedItem = tabItem;
                        break;
                    }
                }

                expander = parent as Expander;
                if (expander != null)
                {
                    expander.IsExpanded = true;
                }

                childControl = parent as FrameworkElement;
                if (childControl == null)
                {
                    return;                     /* Shouldn't get here. */
                }
            }

            listBoxItem?.BringIntoView();

            FocusControl(control);
        }
Пример #23
0
        void DeregisterTransientState(string stateKey)
        {
            AssertArg.IsNotNull(stateKey, nameof(stateKey));

            lock (transientStateLock)
            {
                transientState.Remove(stateKey);
            }
        }
Пример #24
0
        public override async Task <MultipleChoiceResponse <TSelectableItem> > AskMultipleChoiceQuestionAsync <TSelectableItem>(
            MultipleChoiceQuestion <TSelectableItem> question)
        {
            AssertArg.IsNotNull(question, nameof(question));

            var r = await AskMultipleChoiceAsync(question);

            return(r);
        }
Пример #25
0
        void DeregisterPersistentState(string stateKey)
        {
            AssertArg.IsNotNull(stateKey, nameof(stateKey));

            lock (persistentStateLock)
            {
                persistentState.Remove(stateKey);
            }
        }
Пример #26
0
 public SerializableSetting(
     string name,
     object settingValue,
     StorageLocation?storageLocation)
 {
     Name            = AssertArg.IsNotNull(name, nameof(name));
     SettingValue    = settingValue;
     StorageLocation = storageLocation;
 }
Пример #27
0
        /// <summary>
        /// Performs validation of the <paramref name="rules"/>.
        /// </summary>
        /// <param name="rules"> The set of retention rules to validate. </param>
        public void Validate([NotNull, ItemNotNull] IReadOnlyCollection <RetentionRule> rules)
        {
            AssertArg.NotNullOrEmpty(rules, nameof(rules));
            AssertArg.NoNullItems(rules, nameof(rules));

            AssertNoDuplicates(rules);

            AssertNoContradictions(rules);
        }
Пример #28
0
        /// <summary>
        /// Encryptes a <c>byte</c> array using
        /// the specified password. The encrypted data
        /// is returned as a byte array.
        /// </summary>
        /// <param name="encryptor">An <c>IEncryptor</c> instance.</param>
        /// <param name="plainBytes">The bytes to be encrypted.
        /// It is not modified.</param>
        /// <param name="password">A password to use for encryption.</param>
        /// <returns>An array of encrypted bytes.</returns>
        /// <exception cref="System.ArgumentNullException">
        /// Occurs if any of the arguments are null.</exception>
        public static async Task <byte[]> EncryptAsync(this IEncryptor encryptor,
                                                       byte[] plainBytes, string password)
        {
            AssertArg.IsNotNull(encryptor, nameof(encryptor));
            AssertArg.IsNotNull(plainBytes, nameof(plainBytes));
            AssertArg.IsNotNull(password, nameof(password));

            return(await EncryptCoreAsync(encryptor, plainBytes, password));
        }
Пример #29
0
 /// <summary>
 /// Creates a new instance.
 /// </summary>
 /// <param name="result">The user response.</param>
 /// <param name="question">The original question.</param>
 /// <param name="error">
 /// If an error occurs while asking the question
 /// it is passed to the constructor.</param>
 public QuestionResponse(
     TResponse result,
     IQuestion <TResponse> question,
     Exception error = null)
 {
     Response = result;
     Question = AssertArg.IsNotNull(question, nameof(question));
     Error    = error;
 }
Пример #30
0
        public void Register(IEnumerable <IUserOption> userOptions, IOptionCategory optionCategory)
        {
            AssertArg.IsNotNull(userOptions, nameof(userOptions));
            AssertArg.IsNotNull(optionCategory, nameof(optionCategory));

            /* We regect all options if any are already registered. */
            Tuple <IOptionCategory, List <IUserOption> > existingCategoryOptions = null;

            foreach (KeyValuePair <IOptionCategory, List <IUserOption> > pair in categoryDictionary)
            {
                foreach (IUserOption userOption in userOptions)
                {
                    IUserOption existingOption = null;

                    foreach (IUserOption option in pair.Value)
                    {
                        if (!string.IsNullOrEmpty(option.SettingKey) &&
                            object.Equals(option.SettingKey, userOption.SettingKey))
                        {
                            existingOption = option;
                            break;
                        }
                    }
                    //IUserOption existingOption = (from option in pair.Value
                    //					            where object.Equals(option.SettingKey, userOption.SettingKey)
                    //					            select option).FirstOrDefault();

                    if (existingOption != null)
                    {
                        throw new DuplicateItemException(existingOption, userOption);
                    }
                }

                if (pair.Key.Id == optionCategory.Id)
                {
                    existingCategoryOptions = new Tuple <IOptionCategory, List <IUserOption> >(pair.Key, pair.Value);
                }
            }

            List <IUserOption> list;

            if (existingCategoryOptions != null)
            {
                list = existingCategoryOptions.Item2;
            }
            else
            {
                list = new List <IUserOption>();
                categoryDictionary.Add(optionCategory, list);
            }

            foreach (IUserOption userOption in userOptions)
            {
                list.Add(userOption);
            }
        }