Пример #1
0
            public void ReturnsInvariantValueForDateTime()
            {
                var input  = new DateTime(1984, 08, 01, 9, 42, 00);
                var output = ObjectToStringHelper.ToString(input);

                Assert.AreEqual("08/01/1984 09:42:00", output);
            }
Пример #2
0
        /// <summary>
        /// Converts the specified value.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <param name="targetType">Type of the target.</param>
        /// <param name="parameter">The parameter.</param>
        /// <returns>System.Object.</returns>
        protected override object Convert(object value, System.Type targetType, object parameter)
        {
            var parameterAsString = ObjectToStringHelper.ToString(parameter);

            var isSupported        = false;
            var supportedPlatforms = parameterAsString.Split(new[] { '|' });

            foreach (var supportedPlatform in supportedPlatforms)
            {
                KnownPlatforms platform = KnownPlatforms.Unknown;
                if (Enum <KnownPlatforms> .TryParse(supportedPlatform, out platform))
                {
                    if (Platforms.IsPlatformSupported(platform))
                    {
                        isSupported = true;
                        break;
                    }
                }
            }

            if (SupportInversionUsingCommandParameter && ConverterHelper.ShouldInvert(parameter))
            {
                isSupported = !isSupported;
            }

            return(isSupported);
        }
Пример #3
0
        /// <summary>
        /// Cleans up the list of registered handlers. All handlers that are no longer alive
        /// are removed from the list.
        /// <para />
        /// This method is automatically invoked after each call to <see cref="SendMessage{TMessage}(TMessage, object)"/>, but
        /// can also be invoked manually.
        /// </summary>
        public void CleanUp()
        {
            Log.Debug("Cleaning up handlers");

            lock (_lockObject)
            {
                foreach (var handlerKeyPair in _registeredHandlers)
                {
                    var handlers = handlerKeyPair.Value;
                    for (int i = 0; i < handlers.Count; i++)
                    {
                        var handler = handlers[i];
                        if (!((IWeakReference)handler.Action).IsTargetAlive)
                        {
                            handlers.RemoveAt(i--);

                            Log.Debug("Removed handler for message type '{0}' with tag '{1}' because target is no longer alive",
                                      handlerKeyPair.Key.Name, ObjectToStringHelper.ToString(handler.Tag));
                        }
                    }
                }
            }

            Log.Debug("Cleaned up handlers");
        }
Пример #4
0
        /// <summary>
        /// Resolves the type using parameters. This method combines the <see cref="IServiceLocator.GetRegistrationInfo" /> and
        /// the <see cref="ITypeFactory.CreateInstanceWithParameters" /> to provide the functionality.
        /// </summary>
        /// <param name="serviceLocator">The service locator.</param>
        /// <param name="serviceType">Type of the service.</param>
        /// <param name="parameters">The parameters.</param>
        /// <param name="tag">The tag.</param>
        /// <returns>The instantiated type constructed with the specified parameters.</returns>
        /// <exception cref="ArgumentNullException">The <paramref name="serviceLocator" /> is <c>null</c>.</exception>
        /// <exception cref="ArgumentNullException">The <paramref name="serviceType" /> is <c>null</c>.</exception>
        /// <exception cref="ArgumentNullException">The <paramref name="parameters" /> is <c>null</c>.</exception>
        /// <exception cref="InvalidOperationException">The type is not registered in the container as transient type.</exception>
        public static object ResolveTypeUsingParameter(this IServiceLocator serviceLocator, Type serviceType, object[] parameters, object tag = null)
        {
            Argument.IsNotNull("serviceLocator", serviceLocator);
            Argument.IsNotNull("serviceType", serviceType);
            Argument.IsNotNull("parameters", parameters);

            var registrationInfo = serviceLocator.GetRegistrationInfo(serviceType, tag);

            if (registrationInfo == null)
            {
                string error = string.Format("The service locator could not return the registration info for type '{0}' with tag '{1}', cannot resolve type",
                                             serviceType.FullName, ObjectToStringHelper.ToString(tag));
                Log.Error(error);
                throw new InvalidOperationException(error);
            }

            var typeFactory = serviceLocator.ResolveType <ITypeFactory>();

            if (registrationInfo.RegistrationType == RegistrationType.Singleton)
            {
                if (registrationInfo.IsTypeInstantiatedForSingleton)
                {
                    return(serviceLocator.ResolveType(serviceType));
                }

                Log.Debug("Type '{0}' is registered as singleton but has not yet been instantiated. Instantiated it with the specified parameters now and registering it in the ServiceLocator", serviceType.FullName);

                var instance = typeFactory.CreateInstanceWithParameters(registrationInfo.ImplementingType, parameters);
                serviceLocator.RegisterInstance(serviceType, instance);
                return(instance);
            }

            return(typeFactory.CreateInstanceWithParameters(registrationInfo.ImplementingType, parameters));
        }
Пример #5
0
        /// <summary>
        /// Serializes the member.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="memberValue">The member value.</param>
        public override void SerializeMember(ISerializationContext context, MemberValue memberValue)
        {
            base.SerializeMember(context, memberValue);

            var value = memberValue.Value;

            if (value != null)
            {
                var valueType = value.GetType();
                if (valueType.IsGenericTypeEx())
                {
                    if (valueType.GetGenericTypeDefinitionEx() == typeof(KeyValuePair <,>))
                    {
                        var keyProperty   = valueType.GetPropertyEx("Key");
                        var valueProperty = valueType.GetPropertyEx("Value");

                        var kvpKey   = keyProperty.GetValue(value, null);
                        var kvpValue = valueProperty.GetValue(value, null);

                        var finalValue = string.Format("{0}{1}{2}{1}{3}{1}{4}{1}{5}", Prefix, Splitter,
                                                       keyProperty.PropertyType, valueProperty.PropertyType,
                                                       ObjectToStringHelper.ToString(kvpKey), ObjectToStringHelper.ToString(kvpValue));

                        memberValue.Value = finalValue;
                    }
                }
            }
        }
Пример #6
0
        /// <summary>
        /// Writes the XML attribute to the xml element.
        /// </summary>
        /// <param name="element">The element.</param>
        /// <param name="attributeName">Name of the attribute.</param>
        /// <param name="memberValue">The member value.</param>
        private void WriteXmlAttribute(XElement element, string attributeName, MemberValue memberValue)
        {
            var attributeValue = ObjectToStringHelper.ToString(memberValue.Value);

            var attribute = new XAttribute(attributeName, attributeValue);
            element.Add(attribute);
        }
Пример #7
0
        /// <summary>
        /// Converts value <see cref="DropdownArrowLocation "/> values into <see cref="Dock"/> or <see cref="HorizontalAlignment"/>.
        /// </summary>
        /// <param name="value">
        /// The value.
        /// </param>
        /// <param name="targetType">The target type.</param>
        /// <param name="parameter">The parementer</param>
        /// <returns>
        /// A converted value.
        /// </returns>
        protected override object Convert(object value, Type targetType, object parameter)
        {
            Argument.IsOfOneOfTheTypes(nameof(targetType), targetType, new[] { typeof(Dock), typeof(HorizontalAlignment) });

            object result = null;

            if (targetType == typeof(Dock))
            {
                result = value == null ? default(Dock) : Enum.Parse(targetType, ObjectToStringHelper.ToString(value), true);
            }
            else if (targetType == typeof(HorizontalAlignment))
            {
                if (value == null)
                {
                    result = default(HorizontalAlignment);
                }
                else
                {
                    var dropdownArrowLocation = (DropdownArrowLocation)value;
                    if (dropdownArrowLocation == DropdownArrowLocation.Top || dropdownArrowLocation == DropdownArrowLocation.Bottom)
                    {
                        result = HorizontalAlignment.Center;
                    }
                    else
                    {
                        result = Enum.Parse(targetType, ObjectToStringHelper.ToString(value), true);
                    }
                }
            }

            return(result);
        }
Пример #8
0
        public TValue GetValue <TValue>(object instance)
        {
            Argument.IsNotNull(() => instance);

            object value = null;

            if (_propertyInfo != null)
            {
                value = _propertyInfo.GetValue(instance, null);
            }
            else if (_propertyData != null)
            {
                var modelEditor = instance as IModelEditor;
                if (modelEditor != null)
                {
                    value = modelEditor.GetValue(_propertyData.Name);
                }
            }

            if (value != null)
            {
                if (typeof(TValue) == typeof(string))
                {
                    value = (value != null) ? ObjectToStringHelper.ToString(value) : null;
                }

                return((TValue)value);
            }

            return(default(TValue));
        }
Пример #9
0
        public static void SaveWindowSize(this Window window, string tag)
        {
            Argument.IsNotNull(() => window);

            var windowName = window.GetType().Name;

            Log.Debug($"Saving window size for '{windowName}'");

            var storageFile = GetWindowStorageFile(window, tag);

            try
            {
                var culture = CultureInfo.InvariantCulture;

                var width  = ObjectToStringHelper.ToString(window.Width, culture);
                var height = ObjectToStringHelper.ToString(window.Height, culture);
                var left   = ObjectToStringHelper.ToString(window.Left, culture);
                var top    = ObjectToStringHelper.ToString(window.Top, culture);
                var state  = ObjectToStringHelper.ToString(window.WindowState, culture);

                var contents = $"{width}{SizeSeparator}{height}{SizeSeparator}{state}{SizeSeparator}{left}{SizeSeparator}{top}";

                File.WriteAllText(storageFile, contents);
            }
            catch (Exception ex)
            {
                Log.Warning(ex, $"Failed to save window size to file '{storageFile}'");
            }
        }
Пример #10
0
        /// <summary>
        /// Converts the type to a string.
        /// </summary>
        /// <returns>The string.</returns>
        public override string ToString()
        {
            if (_string == null)
            {
                _string = string.Format("{0} (tag = {1})", Type.FullName, ObjectToStringHelper.ToString(Tag));
            }

            return(_string);
        }
Пример #11
0
        /// <summary>
        /// Gets the log listener which this configuration represents.
        /// </summary>
        /// <param name="assembly">The assembly to load the product info from. If <c>null</c>, the entry assembly will be used.</param>
        /// <returns>The <see cref="ILogListener"/>.</returns>
        public ILogListener GetLogListener(Assembly assembly = null)
        {
            string typeAsString = ObjectToStringHelper.ToString(Type);

            Log.Debug("Creating ILogListener based on configuration for type '{0}'", typeAsString);

            ILogListener logListener = null;

            var type = TypeCache.GetType(Type);

            if (type == null)
            {
                string error = string.Format("Failed to retrieve type '{0}'", typeAsString);
                Log.Error(error);
                throw new InvalidOperationException(error);
            }

            var typeFactory = IoCConfiguration.DefaultTypeFactory;

            logListener = typeFactory.CreateInstanceWithParametersAndAutoCompletion(type, assembly) as ILogListener;
            if (logListener == null)
            {
                logListener = typeFactory.CreateInstance(type) as ILogListener;
            }

            if (logListener == null)
            {
                string error = string.Format("Failed to instantiate type '{0}' or it does not implement ILogListener and thus cannot be used as such", typeAsString);
                Log.Error(error);
                throw new InvalidOperationException(error);
            }

            foreach (var dynamicProperty in _dynamicProperties)
            {
                if (string.Equals(dynamicProperty.Key, TypePropertyName, StringComparison.InvariantCulture))
                {
                    continue;
                }

                var propertyInfo = type.GetPropertyEx(dynamicProperty.Key);
                if (propertyInfo == null)
                {
                    Log.Warning("Property '{0}.{1}' cannot be found, make sure that it exists to load the value correctly", typeAsString, dynamicProperty.Key);
                    continue;
                }

                Log.Debug("Setting property '{0}' to value '{1}'", dynamicProperty.Key, ObjectToStringHelper.ToString(dynamicProperty.Value));

                var propertyValue = StringToObjectHelper.ToRightType(propertyInfo.PropertyType, dynamicProperty.Value);
                PropertyHelper.SetPropertyValue(logListener, dynamicProperty.Key, propertyValue);
            }

            Log.Debug("Created ILogListener based on configuration for type '{0}'", typeAsString);

            return(logListener);
        }
Пример #12
0
        public virtual void AddObjects(IEnumerable <ISearchable> searchables)
        {
            Initialize();

            Updating?.Invoke(this, EventArgs.Empty);

            lock (_lockObject)
            {
                using (var analyzer = new StandardAnalyzer(LuceneDefaults.Version))
                {
                    using (var writer = new IndexWriter(_indexDirectory, CreateIndexWriterConfig(analyzer)))
                    {
                        foreach (var searchable in searchables)
                        {
                            var index = _currentIndex++;
                            _indexedObjects.Add(index, searchable);
                            _searchableIndexes.Add(searchable, index);

                            var document = new Document();

                            var indexField = new StringField(IndexId, index.ToString(), Field.Store.YES);

                            document.Add(indexField);

                            var metadata            = searchable.MetadataCollection;
                            var searchableMetadatas = metadata.All.OfType <ISearchableMetadata>();

                            foreach (var searchableMetadata in searchableMetadatas)
                            {
                                if (searchableMetadata.GetValue <object>(searchable.Instance, out var searchableMetadataValue))
                                {
                                    var searchableMetadataValueAsString = ObjectToStringHelper.ToString(searchableMetadataValue);

                                    var field = new TextField(searchableMetadata.SearchName, searchableMetadataValueAsString, Field.Store.YES);
                                    document.Add(field);

                                    if (!_searchableMetadata.ContainsKey(searchableMetadata.SearchName))
                                    {
                                        _searchableMetadata.Add(searchableMetadata.SearchName, searchableMetadata);
                                    }
                                }
                            }

                            writer.AddDocument(document);
                        }

                        writer.PrepareCommit();
                        writer.Commit();
                    }
                }
            }

            Updated?.Invoke(this, EventArgs.Empty);
        }
Пример #13
0
        /// <summary>
        /// Modifies the source data before passing it to the target for display in the UI.
        /// </summary>
        /// <param name="value">The source data being passed to the target.</param>
        /// <param name="targetType">The <see cref="T:System.Type" /> of data expected by the target dependency property.</param>
        /// <param name="parameter">An optional parameter to be used in the converter logic.</param>
        /// <returns>The value to be passed to the target dependency property.</returns>
        protected override object Convert(object value, Type targetType, object parameter)
        {
            Log.Debug("Debugging converter");
            Log.Indent();
            Log.Debug("Value: {0}", ObjectToStringHelper.ToString(value));
            Log.Debug("TargetType: {0}", targetType.Name);
            Log.Debug("Parameter: {0}", ObjectToStringHelper.ToString(parameter));
            Log.Unindent();

            return(value);
        }
Пример #14
0
        /// <summary>
        /// Determines whether the specified constructor can be used for dependency injection.
        /// </summary>
        /// <param name="constructor">The constructor.</param>
        /// <param name="autoCompleteDependencies">if set to <c>true</c>, additional dependencies can be completed from the <see cref="IServiceLocator"/>.</param>
        /// <param name="parameters">The parameters.</param>
        /// <returns><c>true</c> if this instance [can constructor be used] the specified constructor; otherwise, <c>false</c>.</returns>
        private bool CanConstructorBeUsed(ConstructorInfo constructor, bool autoCompleteDependencies, params object[] parameters)
        {
            Log.Debug("Checking if constructor '{0}' can be used", constructor.GetSignature());

            if (constructor.IsStatic)
            {
                Log.Debug("Constructor is not valid because it is static");
                return(false);
            }

            bool validConstructor = true;
            var  ctorParameters   = constructor.GetParameters();

            for (int i = 0; i < parameters.Length; i++)
            {
                var ctorParameter     = ctorParameters[i];
                var ctorParameterType = ctorParameter.ParameterType;

                if (!IsValidParameterValue(ctorParameterType, parameters[i]))
                {
                    Log.Debug("Constructor is not valid because value '{0}' cannot be used for parameter '{0}'",
                              ObjectToStringHelper.ToString(parameters[i]), ctorParameter.Name);

                    validConstructor = false;
                    break;
                }
            }

            if (validConstructor && autoCompleteDependencies)
            {
                if (ctorParameters.Length > parameters.Length)
                {
                    // check if all the additional parameters are registered in the service locator
                    for (int j = parameters.Length; j < ctorParameters.Length; j++)
                    {
                        var parameterToResolve     = ctorParameters[j];
                        var parameterTypeToResolve = parameterToResolve.ParameterType;

                        if (!_serviceLocator.IsTypeRegistered(parameterTypeToResolve))
                        {
                            Log.Debug("Constructor is not valid because parameter '{0}' cannot be resolved from the dependency resolver", parameterToResolve.Name);

                            validConstructor = false;
                            break;
                        }
                    }
                }
            }

            Log.Debug("The constructor is valid and can be used");

            return(validConstructor);
        }
Пример #15
0
        public void CreateVersion(Jira jira, string project, string version)
        {
            Argument.IsNotNull(() => jira);
            Argument.IsNotNullOrWhitespace(() => project);
            Argument.IsNotNullOrWhitespace(() => version);

            Log.Info("Creating version {0}", version);

            Log.Debug("Checking if version already exists");

            var existingVersion = GetProjectVersion(jira, project, version);

            if (existingVersion != null)
            {
                Log.Info("Version {0} already exists", version);

                if (existingVersion.IsReleased)
                {
                    string error = string.Format("Version {0} is already released, are you re-releasing an existing version?", version);
                    Log.Error(error);
                    throw new InvalidOperationException(error);
                }

                return;
            }

            Log.Debug("Version does not yet exist, creating version");

            var token       = jira.GetToken();
            var jiraService = jira.GetJiraSoapService();

            var nextSequence   = 0L;
            var remoteVersions = jiraService.GetVersions(token, project).OrderBy(x => x.name);

            foreach (var remoteVersion in remoteVersions)
            {
                Log.Debug("  {0} => {1}", remoteVersion.name, ObjectToStringHelper.ToString(remoteVersion.sequence));

                if (string.Compare(remoteVersion.name, version, StringComparison.OrdinalIgnoreCase) > 0 && (nextSequence == 0L))
                {
                    nextSequence = remoteVersion.sequence.Value;
                }
            }

            jiraService.AddVersion(token, project, new RemoteVersion
            {
                name     = version,
                archived = false,
                sequence = nextSequence
            });

            Log.Info("Created version {0}", version);
        }
        public virtual void AddObjects(IEnumerable <ISearchable> searchables)
        {
            Initialize();

            Updating.SafeInvoke(this);

            lock (_lockObject)
            {
                using (var analyzer = new StandardAnalyzer(LuceneDefaults.Version))
                {
                    using (var writer = new IndexWriter(_indexDirectory, analyzer, IndexWriter.MaxFieldLength.UNLIMITED))
                    {
                        foreach (var searchable in searchables)
                        {
                            var index = _currentIndex++;
                            _indexedObjects.Add(index, searchable);
                            _searchableIndexes.Add(searchable, index);

                            var document = new Document();
                            document.Add(new Field(IndexId, index.ToString(), Field.Store.YES, Field.Index.NOT_ANALYZED));

                            var metadata            = searchable.MetadataCollection;
                            var searchableMetadatas = metadata.All.OfType <ISearchableMetadata>();

                            foreach (var searchableMetadata in searchableMetadatas)
                            {
                                var searchableMetadataValue         = searchableMetadata.GetValue(searchable.Instance);
                                var searchableMetadataValueAsString = ObjectToStringHelper.ToString(searchableMetadataValue);

                                var field = new Field(searchableMetadata.SearchName, searchableMetadataValueAsString, Field.Store.YES, searchableMetadata.Analyze ? Field.Index.ANALYZED : Field.Index.NOT_ANALYZED, Field.TermVector.NO);

                                document.Add(field);

                                if (!_searchableMetadata.ContainsKey(searchableMetadata.SearchName))
                                {
                                    _searchableMetadata.Add(searchableMetadata.SearchName, searchableMetadata);
                                }
                            }

                            writer.AddDocument(document);
                        }

                        writer.Optimize();
                        writer.Commit();
                    }
                }
            }

            Updated.SafeInvoke(this);
        }
Пример #17
0
        /// <summary>
        /// Sets the configuration value.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <param name="value">The value.</param>
        /// <exception cref="ArgumentException">The <paramref name="key"/> is <c>null</c> or whitespace.</exception>
        public void SetValue(string key, object value)
        {
            Argument.IsNotNullOrWhitespace("key", key);

            var originalKey = key;

            key = GetFinalKey(key);

            var stringValue = ObjectToStringHelper.ToString(value);

            SetValueToStore(key, stringValue);

            RaiseConfigurationChanged(originalKey, value);
        }
Пример #18
0
        /// <summary>
        /// Sets the configuration value.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <param name="value">The value.</param>
        /// <exception cref="ArgumentException">The <paramref name="key"/> is <c>null</c> or whitespace.</exception>
        public void SetValue(string key, object value)
        {
            Argument.IsNotNullOrWhitespace("key", key);

            var stringValue = ObjectToStringHelper.ToString(value);

            SetValueToStore(key, stringValue);

            var handler = ConfigurationChanged;

            if (handler != null)
            {
                handler.Invoke(this, new ConfigurationChangedEventArgs(key, value));
            }
        }
Пример #19
0
        /// <summary>
        /// Begins a new batch.
        /// <para />
        /// Note that this method will always call <see cref="EndBatch"/> before creating the new batch to ensure
        /// that a new batch is actually created.
        /// <para />
        /// All operations added via the <see cref="Add(Catel.Memento.IMementoSupport,bool)"/> will belong the this batch
        /// and be handled as a single operation.
        /// </summary>
        /// <param name="title">The title which can be used to display this batch i a user interface.</param>
        /// <param name="description">The description which can be used to display this batch i a user interface.</param>
        /// <returns>The <see cref="IMementoBatch" /> that has just been created.</returns>
        public IMementoBatch BeginBatch(string title = null, string description = null)
        {
            EndBatch();

            var batch = new Batch
            {
                Title       = title,
                Description = description
            };

            Log.Debug("Starting batch with title '{0}' and description '{1}'", ObjectToStringHelper.ToString(batch.Title),
                      ObjectToStringHelper.ToString(batch.Description));

            _currentBatch = batch;

            return(batch);
        }
Пример #20
0
        /// <summary>
        /// Ends the current batch and adds it to the stack by calling <see cref="Add(Catel.Memento.IMementoBatch,bool)"/>.
        /// <para />
        /// If there is currently no batch, this method will silently exit.
        /// </summary>
        /// <returns>The <see cref="IMementoBatch"/> that has just been ended or <c>null</c> if there was no current batch.</returns>
        public IMementoBatch EndBatch()
        {
            if (_currentBatch == null)
            {
                return(null);
            }

            var batch = _currentBatch;

            Add(batch);

            _currentBatch = null;

            Log.Debug("Ended batch with title '{0}' and description '{1}' with '{2}' actions", ObjectToStringHelper.ToString(batch.Title),
                      ObjectToStringHelper.ToString(batch.Description), batch.ActionCount);

            return(batch);
        }
Пример #21
0
        /// <summary>
        /// Called when the <see cref="Behavior{T}.AssociatedObject"/> has been loaded.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        /// <exception cref="InvalidOperationException">No instance of <see cref="IAuthenticationProvider"/> is registered in the <see cref="IServiceLocator"/>.</exception>
        /// <exception cref="InvalidOperationException">The <see cref="Action"/> is set to <see cref="AuthenticationAction.Disable"/> and the <see cref="Behavior{T}.AssociatedObject"/> is not a <see cref="Control"/>.</exception>
        protected override void OnAssociatedObjectLoaded(object sender, EventArgs e)
        {
            if (!ServiceLocator.Default.IsTypeRegistered <IAuthenticationProvider>())
            {
                throw new InvalidOperationException("IAuthenticationProvider is not registered in the IServiceLocator");
            }

            if (!_authenticationProvider.HasAccessToUIElement(AssociatedObject, AssociatedObject.Tag, AuthenticationTag))
            {
                Log.Debug("User has no access to UI element with tag '{0}' and authentication tag '{1}'",
                          ObjectToStringHelper.ToString(AssociatedObject.Tag), ObjectToStringHelper.ToString(AuthenticationTag));

                switch (Action)
                {
#if NET
                case AuthenticationAction.Hide:
                    AssociatedObject.Visibility = Visibility.Hidden;
                    break;
#endif

                case AuthenticationAction.Collapse:
                    AssociatedObject.Visibility = Visibility.Collapsed;
                    break;

                case AuthenticationAction.Disable:
#if SILVERLIGHT
                    if (!(AssociatedObject is Control))
                    {
                        throw new InvalidOperationException("The AssociatedObject is not a Control instance, only AuthenticationAction.Collapse is allowed in Silverlight");
                    }

                    ((Control)AssociatedObject).IsEnabled = false;
#else
                    AssociatedObject.IsEnabled = false;
#endif
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }
            }
        }
Пример #22
0
        /// <summary>
        /// Converts the specified value.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <param name="targetType">Type of the target.</param>
        /// <param name="parameter">The parameter.</param>
        /// <returns>System.Object.</returns>
        protected override object Convert(object value, System.Type targetType, object parameter)
        {
            var parameterAsString = ObjectToStringHelper.ToString(parameter);

            var supportedPlatforms = parameterAsString.Split(new[] { '|' });

            foreach (var supportedPlatform in supportedPlatforms)
            {
                KnownPlatforms platform = KnownPlatforms.Unknown;
                if (Enum <KnownPlatforms> .TryParse(supportedPlatform, out platform))
                {
                    if (Platforms.IsPlatformSupported(platform))
                    {
                        return(true);
                    }
                }
            }

            return(false);
        }
Пример #23
0
        private static string GetPropertyValue(object obj, string propertyName)
        {
            object value = null;

            var modelBase = obj as ModelBase;

            if (modelBase != null)
            {
                if (modelBase.IsPropertyRegistered(propertyName))
                {
                    value = modelBase.GetValueFast(propertyName);
                }
            }
            else
            {
                value = PropertyHelper.GetPropertyValue(obj, propertyName);
            }

            return(ObjectToStringHelper.ToString(value));
        }
Пример #24
0
        /// <summary>
        ///   Creates the command inside the command manager.
        ///   <para />
        ///   If the <paramref name="throwExceptionWhenCommandIsAlreadyCreated" /> is <c>false</c> and the
        ///   command is already created, only the input gesture is updated for the existing command.
        /// </summary>
        /// <param name="commandName">Name of the command.</param>
        /// <param name="inputGesture">The input gesture.</param>
        /// <param name="compositeCommand">
        ///   The composite command. If <c>null</c>, this will default to a
        ///   new instance of <see cref="CompositeCommand" />.
        /// </param>
        /// <param name="throwExceptionWhenCommandIsAlreadyCreated">
        ///   if set to <c>true</c>, this method
        ///   will throw an exception when the command is already created.
        /// </param>
        /// <exception cref="ArgumentException">
        ///   The <paramref name="commandName" /> is <c>null</c> or
        ///   whitespace.
        /// </exception>
        /// <exception cref="InvalidOperationException">
        ///   The specified command is already created using the
        ///   <see cref="CreateCommand" /> method.
        /// </exception>
        public void CreateCommand(
            string commandName, InputGesture inputGesture  = null,
            ICompositeCommand compositeCommand             = null,
            bool throwExceptionWhenCommandIsAlreadyCreated = true)
        {
            Argument.IsNotNullOrWhitespace("commandName", commandName);

            lock (_lockObject)
            {
                Log.Debug(
                    "Creating command '{0}' with input gesture '{1}'", commandName,
                    ObjectToStringHelper.ToString(inputGesture));

                if (_commands.ContainsKey(commandName))
                {
                    if (throwExceptionWhenCommandIsAlreadyCreated)
                    {
                        var error =
                            $"Command '{commandName}' is already created using the CreateCommand method";
                        Log.Error(error);

                        throw new InvalidOperationException(error);
                    }

                    _commandGestures[commandName].Add(inputGesture);
                    return;
                }

                if (compositeCommand == null)
                {
                    compositeCommand = new CompositeCommand();
                }

                _commands.Add(commandName, compositeCommand);
                _originalCommandGestures.Add(commandName, inputGesture);
                _commandGestures.Add(commandName, new List <InputGesture>(new[] { inputGesture }));

                CommandCreated.SafeInvoke(
                    this, () => new CommandCreatedEventArgs(compositeCommand, commandName));
            }
        }
Пример #25
0
        /// <summary>Updates the input gesture for the specified command.</summary>
        /// <param name="commandName">Name of the command.</param>
        /// <param name="inputGesture">The new input gesture.</param>
        /// <exception cref="ArgumentException">
        ///   The <paramref name="commandName" /> is <c>null</c> or
        ///   whitespace.
        /// </exception>
        /// <exception cref="InvalidOperationException">
        ///   The specified command is not created using the
        ///   <see cref="CreateCommand" /> method.
        /// </exception>
        public void UpdateInputGesture(string commandName, InputGesture inputGesture = null)
        {
            Argument.IsNotNullOrWhitespace("commandName", commandName);

            lock (_lockObject)
            {
                Log.Debug(
                    "Updating input gesture of command '{0}' to '{1}'", commandName,
                    ObjectToStringHelper.ToString(inputGesture));

                if (!_commands.ContainsKey(commandName))
                {
                    throw Log.ErrorAndCreateException <InvalidOperationException>(
                              "Command '{0}' is not yet created using the CreateCommand method", commandName);
                }

                if (!_commandGestures[commandName].Contains(inputGesture))
                {
                    _commandGestures[commandName].Add(inputGesture);
                }
            }
        }
Пример #26
0
        /// <summary>
        /// Called when the <see cref="Behavior{T}.AssociatedObject"/> has been loaded.
        /// </summary>
        /// <exception cref="InvalidOperationException">No instance of <see cref="IAuthenticationProvider"/> is registered in the <see cref="IServiceLocator"/>.</exception>
        /// <exception cref="InvalidOperationException">The <see cref="Action"/> is set to <see cref="AuthenticationAction.Disable"/> and the <see cref="Behavior{T}.AssociatedObject"/> is not a <see cref="Control"/>.</exception>
        protected override void OnAssociatedObjectLoaded()
        {
            if (!_authenticationProvider.HasAccessToUIElement(AssociatedObject, AssociatedObject.Tag, AuthenticationTag))
            {
                Log.Debug("User has no access to UI element with tag '{0}' and authentication tag '{1}'",
                          ObjectToStringHelper.ToString(AssociatedObject.Tag), ObjectToStringHelper.ToString(AuthenticationTag));

                switch (Action)
                {
#if NET || NETCORE
                case AuthenticationAction.Hide:
                    AssociatedObject.Visibility = Visibility.Hidden;
                    break;
#endif

                case AuthenticationAction.Collapse:
                    AssociatedObject.Visibility = Visibility.Collapsed;
                    break;

                case AuthenticationAction.Disable:
#if NETFX_CORE
                    if (!(AssociatedObject is Control))
                    {
                        throw new InvalidOperationException("The AssociatedObject is not a Control instance, only AuthenticationAction.Collapse is allowed in SL, Windows Phone and WinRT");
                    }

                    ((Control)AssociatedObject).IsEnabled = false;
#else
                    AssociatedObject.IsEnabled = false;
#endif
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }
            }
        }
Пример #27
0
        /// <summary>
        /// Serializes the member.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="memberValue">The member value.</param>
        protected override void SerializeMember(ISerializationContext <JsonSerializationContextInfo> context, MemberValue memberValue)
        {
            var serializationContext = context.Context;
            var jsonSerializer       = serializationContext.JsonSerializer;
            var jsonWriter           = serializationContext.JsonWriter;

            // Only write property names when this is not the root and not a collection
            var isRootDictionary = IsRootDictionary(context, memberValue);
            var isRootCollection = IsRootCollection(context, memberValue);

            if (!isRootDictionary && !isRootCollection)
            {
                // Write reference id *before* serializing, otherwise we might get into a circular loop
                if (PreserveReferences)
                {
                    var value = memberValue.Value;
                    if (value != null)
                    {
                        // Ignore basic types (value types, strings, etc) and ModelBase (already gets the graph id written)
                        var memberType = memberValue.ActualMemberType;
                        if (!memberType.IsBasicType()) // && !(value is ModelBase))
                        {
                            var referenceManager = context.ReferenceManager;
                            var referenceInfo    = referenceManager.GetInfo(memberValue.Value);

                            var idPropertyName = string.Format("${0}_{1}", memberValue.NameForSerialization, referenceInfo.IsFirstUsage ? GraphId : GraphRefId);

                            jsonWriter.WritePropertyName(idPropertyName);
                            jsonSerializer.Serialize(jsonWriter, referenceInfo.Id);

                            if (!referenceInfo.IsFirstUsage)
                            {
                                return;
                            }
                        }
                    }
                }

                jsonWriter.WritePropertyName(memberValue.NameForSerialization);
            }

            if (ReferenceEquals(memberValue.Value, null) || ShouldExternalSerializerHandleMember(memberValue))
            {
                jsonSerializer.Serialize(jsonWriter, memberValue.Value);
            }
            else if (ShouldSerializeAsDictionary(memberValue))
            {
                // Serialize as an object with properties
                var sourceDictionary = memberValue.Value as IDictionary;
                if (sourceDictionary != null)
                {
                    jsonWriter.WriteStartObject();

                    foreach (var key in sourceDictionary.Keys)
                    {
                        var stringKey = key as string;
                        if (stringKey == null)
                        {
                            stringKey = ObjectToStringHelper.ToString(key);
                        }

                        jsonWriter.WritePropertyName(stringKey);

                        var item = sourceDictionary[key];
                        if (item != null)
                        {
                            var itemType = item.GetType();
                            if (ShouldExternalSerializerHandleMember(itemType))
                            {
                                jsonSerializer.Serialize(jsonWriter, item);
                            }
                            else
                            {
                                Serialize(item, jsonWriter, context.Configuration);
                            }
                        }
                    }

                    jsonWriter.WriteEndObject();
                }
            }
            else if (ShouldSerializeAsCollection(memberValue))
            {
                jsonWriter.WriteStartArray();

                foreach (var item in (IList)memberValue.Value)
                {
                    // Note: we don't support null values for now
                    if (item != null)
                    {
                        var itemType = item.GetType();
                        if (ShouldExternalSerializerHandleMember(itemType))
                        {
                            jsonSerializer.Serialize(jsonWriter, item);
                        }
                        else
                        {
                            Serialize(item, jsonWriter, context.Configuration);
                        }
                    }
                }

                jsonWriter.WriteEndArray();
            }
            else
            {
                Serialize(memberValue.Value, jsonWriter, context.Configuration);
            }
        }
Пример #28
0
        /// <summary>
        /// Returns a <see cref="System.String" /> that represents this instance.
        /// </summary>
        /// <returns>A <see cref="System.String" /> that represents this instance.</returns>
        public override string ToString()
        {
            var value = string.Format("{0} (Tag: {1})", Message, ObjectToStringHelper.ToString(Tag));

            return(value);
        }
Пример #29
0
        /// <summary>
        /// Returns a <see cref="System.String" /> that represents this instance.
        /// </summary>
        /// <returns>A <see cref="System.String" /> that represents this instance.</returns>
        public override string ToString()
        {
            var value = string.Format("{0} (Field: {1} | Tag: {2})", Message, PropertyName, ObjectToStringHelper.ToString(Tag));

            return(value);
        }
Пример #30
0
 /// <summary>
 /// Retrieves an object from a SerializationInfo object.
 /// </summary>
 /// <param name="info">SerializationInfo object.</param>
 /// <param name="name">Name of the value to retrieve.</param>
 /// <param name="type">Type of the object to retrieve.</param>
 /// <param name="defaultValue">Default value when value does not exist.</param>
 /// <returns>object value.</returns>
 public static object GetObject(SerializationInfo info, string name, Type type, object defaultValue)
 {
     try
     {
         object obj = info.GetValue(name, type);
         return(obj ?? defaultValue);
     }
     catch (InvalidCastException)
     {
         Log.Debug("Value for '{0}' must implement IConvertible, probably because it's trying to convert nothing to an object", name);
         return(defaultValue);
     }
     catch (SerializationException)
     {
         Log.Debug("Name '{0}' is not found in the SerializationInfo, returning default value '{1}'", name, ObjectToStringHelper.ToString(defaultValue));
         return(defaultValue);
     }
 }