Example #1
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);
        }
        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);
        }
Example #3
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;
            }
        }
Example #4
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());
        }
        /// <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);
        }
Example #6
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);
        }
Example #7
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));
                }
            });
        }
Example #8
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);
        }
Example #9
0
        public IocContainerExtension(string namespaceAliasedTypeName, string containerKey)
        {
            this.namespaceAliasedTypeName = AssertArg.IsNotNullOrWhiteSpace(namespaceAliasedTypeName, nameof(namespaceAliasedTypeName));
            SetAliasAndTypeName(namespaceAliasedTypeName);

            this.containerKey = AssertArg.IsNotNull(containerKey, nameof(containerKey));
        }
Example #10
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);
        }
Example #11
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);
                }
            }
        }
        public RemainingBatteryChargeEvent(object sender, int percentRemaining, TimeSpan dischargeTimeRemaining)
        {
            Sender = AssertArg.IsNotNull(sender, nameof(sender));

            PercentRemaining       = percentRemaining;
            DischargeTimeRemaining = dischargeTimeRemaining;
        }
Example #13
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);
                    }
                }
            }
        }
        /// <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;
        }
Example #15
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));
        }
        /// <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;
        }
Example #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));
        }
Example #18
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();
                }
            }
        }
Example #19
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);
        }
Example #20
0
        void DeregisterTransientState(string stateKey)
        {
            AssertArg.IsNotNull(stateKey, nameof(stateKey));

            lock (transientStateLock)
            {
                transientState.Remove(stateKey);
            }
        }
Example #21
0
 public SerializableSetting(
     string name,
     object settingValue,
     StorageLocation?storageLocation)
 {
     Name            = AssertArg.IsNotNull(name, nameof(name));
     SettingValue    = settingValue;
     StorageLocation = storageLocation;
 }
Example #22
0
        void DeregisterPersistentState(string stateKey)
        {
            AssertArg.IsNotNull(stateKey, nameof(stateKey));

            lock (persistentStateLock)
            {
                persistentState.Remove(stateKey);
            }
        }
Example #23
0
        public override async Task <MultipleChoiceResponse <TSelectableItem> > AskMultipleChoiceQuestionAsync <TSelectableItem>(
            MultipleChoiceQuestion <TSelectableItem> question)
        {
            AssertArg.IsNotNull(question, nameof(question));

            var r = await AskMultipleChoiceAsync(question);

            return(r);
        }
Example #24
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));
        }
Example #25
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;
 }
Example #26
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);
            }
        }
Example #27
0
        /// <summary>
        /// Encryptes a <c>byte</c> array using
        /// the specified password. The encrypted data
        /// is placed in the <c>outputStream</c>.
        /// </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>
        /// <param name="outputStream">A stream to copy the encrypted bytes.</param>
        /// <exception cref="System.ArgumentNullException">
        /// Occurs if any of the arguments are null.</exception>
        public static async Task EncryptAsync(this IEncryptor encryptor,
                                              byte[] plainBytes, string password, Stream outputStream)
        {
            AssertArg.IsNotNull(encryptor, nameof(encryptor));
            AssertArg.IsNotNull(plainBytes, nameof(plainBytes));
            AssertArg.IsNotNull(password, nameof(password));
            AssertArg.IsNotNull(outputStream, nameof(outputStream));

            await EncryptCoreAsync(encryptor, plainBytes, password, outputStream);
        }
Example #28
0
        public static bool IsInterface(this Type type)
        {
            AssertArg.IsNotNull(type, nameof(type));

#if NETSTANDARD || WINDOWS_UWP || NETFX_CORE
            return(type.GetTypeInfo().IsInterface);
#else
            return(type.IsInterface);
#endif
        }
Example #29
0
        public static bool IsAssignableFromEx(this Type type, Type otherType)
        {
            AssertArg.IsNotNull(type, nameof(type));

#if NETSTANDARD || WINDOWS_UWP || NETFX_CORE
            return(type.GetTypeInfo().IsAssignableFrom(otherType.GetTypeInfo()));
#else
            return(type.IsAssignableFrom(otherType.GetTypeInfo()));
#endif
        }
Example #30
0
        public static Assembly GetAssembly(this Type type)
        {
            AssertArg.IsNotNull(type, nameof(type));

#if NETSTANDARD || WINDOWS_UWP || NETFX_CORE
            return(type.GetTypeInfo().Assembly);
#else
            return(type.Assembly);
#endif
        }