/// <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); }
/// <summary> /// Creates a new view model. /// </summary> /// <param name="viewModelType">Type of the view model that needs to be created.</param> /// <param name="dataContext">The data context of the view model.</param> /// <param name="tag">The preferred tag to use when resolving dependencies.</param> /// <returns>The newly created <see cref="IViewModel"/> or <c>null</c> if no view model could be created.</returns> /// <exception cref="ArgumentNullException">The <paramref name="viewModelType"/> is <c>null</c>.</exception> /// <exception cref="ArgumentException">The <paramref name="viewModelType"/> does not implement the <see cref="IViewModel"/> interface.</exception> public virtual IViewModel CreateViewModel(Type viewModelType, object dataContext, object tag = null) { Argument.IsNotNull("viewModelType", viewModelType); Argument.ImplementsInterface("viewModelType", viewModelType, typeof(IViewModel)); IViewModel viewModel = null; // Only try to construct the view model when the injection object is not null, otherwise every // view model can be constructed with a nullable object. If a user wants a view model to be constructed // without any datacontext or injection, he/she should use an empty default constructor which will only // be used when injection is not possible if (dataContext != null) { viewModel = _typeFactory.CreateInstanceWithParametersAndAutoCompletionWithTag(viewModelType, tag, dataContext) as IViewModel; if (viewModel != null) { Log.Debug("Constructed view model '{0}' using injection of data context '{1}'", viewModelType.FullName, ObjectToStringHelper.ToTypeString(dataContext)); return(viewModel); } } // Try to construct view model using dependency injection viewModel = _typeFactory.CreateInstanceWithTag(viewModelType, tag) as IViewModel; if (viewModel != null) { Log.Debug("Constructed view model '{0}' using dependency injection or empty constructor", viewModelType.FullName); return(viewModel); } Log.Debug("Could not construct view model '{0}' using injection of data context '{1}'", viewModelType.FullName, ObjectToStringHelper.ToTypeString(dataContext)); return(viewModel); }
/// <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; } } } }
/// <summary> /// Unregisters the model of a view model. /// </summary> /// <param name="viewModel">The view model.</param> /// <param name="model">The model.</param> /// <exception cref="ArgumentNullException">The <paramref name="viewModel"/> is <c>null</c>.</exception> /// <exception cref="ArgumentNullException">The <paramref name="model"/> is <c>null</c>.</exception> public void UnregisterModel(IViewModel viewModel, object model) { Argument.IsNotNull("viewModel", viewModel); Argument.IsNotNull("model", model); var viewModelTypeName = ObjectToStringHelper.ToTypeString(viewModel); var modelTypeName = ObjectToStringHelper.ToTypeString(model); Log.Debug("Unregistering model '{0}' with view model '{1}' (id = '{2}')", modelTypeName, viewModelTypeName, viewModel.UniqueIdentifier); var modelWasRemoved = false; lock (_viewModelModelsLock) { if (_viewModelModels.TryGetValue(viewModel.UniqueIdentifier, out var models)) { models.Remove(model); modelWasRemoved = true; } } if (modelWasRemoved) { Log.Debug("Unregistered model '{0}' with view model '{1}' (id = '{2}')", modelTypeName, viewModelTypeName, viewModel.UniqueIdentifier); } else { Log.Debug("Model '{0}' was not registered with view model '{1}' (id = '{2}') or has already been unregistered.", modelTypeName, viewModelTypeName, viewModel.UniqueIdentifier); } }
/// <summary> /// Gets the view models of a model. /// </summary> /// <param name="model">The model to find the linked view models for.</param> /// <returns>An array containing all the view models.</returns> /// <exception cref="ArgumentNullException">The <paramref name="model"/> is <c>null</c>.</exception> public IViewModel[] GetViewModelsOfModel(object model) { Argument.IsNotNull("model", model); var modelType = ObjectToStringHelper.ToTypeString(model); Log.Debug("Getting all view models that are linked to model '{0}'", modelType); var viewModels = new List <IViewModel>(); lock (_viewModelModelsLock) { foreach (var viewModelModel in _viewModelModels) { var viewModelIdentifiers = (from m in viewModelModel.Value where ObjectHelper.AreEqualReferences(m, model) select viewModelModel.Key); foreach (var viewModelIdentifier in viewModelIdentifiers) { var vm = GetViewModel(viewModelIdentifier); if (vm != null) { viewModels.Add(vm); } } } } Log.Debug("Found '{0}' view models that are linked to model '{1}'", viewModels.Count, modelType); return(viewModels.ToArray()); }
/// <summary> /// Modifies the target data before passing it to the source object. /// </summary> /// <param name="value">The target data being passed to the source.</param> /// <param name="targetType">The <see cref="T:System.Type" /> of data expected by the source object.</param> /// <param name="parameter">An optional parameter to be used in the converter logic.</param> /// <param name="culture">The culture of the conversion.</param> /// <returns>The value to be passed to the source object.</returns> public virtual object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { CurrentCulture = culture; var returnValue = value; if (!IsConvertable <TConvertBack>(value)) { Log.Warning("Cannot convert back value of type '{0}', expected type '{1}', ignoring converter results", ObjectToStringHelper.ToTypeString(returnValue), typeof(TConvertBack)); returnValue = ConverterHelper.UnsetValue; } // Call ConvertBack first because we are doing this in reverse order returnValue = ConvertBack((TConvertBack)returnValue, targetType, parameter); if (Link != null) { #if NETFX_CORE var cultureToUse = culture.Name; #else var cultureToUse = culture; #endif returnValue = Link.ConvertBack(returnValue, BackOverrideType ?? targetType, parameter, cultureToUse); } return(returnValue); }
/// <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"); }
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); }
/// <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> /// <param name="culture">The culture of the conversion.</param> /// <returns>The value to be passed to the target dependency property.</returns> public virtual object Convert(object value, Type targetType, object parameter, CultureInfo culture) { CurrentCulture = culture; var returnValue = value; if (Link != null) { #if NETFX_CORE var cultureToUse = culture.Name; #else var cultureToUse = culture; #endif // Linked converter is set, this is not the last in the chain // call the linked converter, i.e. the next in the chain returnValue = Link.Convert(returnValue, OverrideType ?? targetType, parameter, cultureToUse); } if (!IsConvertable <TConvert>(value)) { Log.Warning("Cannot convert value of type '{0}', expected type '{1}', ignoring converter results", ObjectToStringHelper.ToTypeString(returnValue), typeof(TConvert)); return(ConverterHelper.UnsetValue); } returnValue = Convert((TConvert)returnValue, targetType, parameter); return(returnValue); }
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}'"); } }
/// <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); }
/// <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); }
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)); }
/// <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)); }
/// <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); }
/// <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); }
/// <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); }
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); }
/// <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); }
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 ConstructorCacheKey(Type type, object[] parameters) { string key = type.GetSafeFullName(); foreach (var parameter in parameters) { key += "_" + ObjectToStringHelper.ToFullTypeString(parameter); } Key = key; _hashCode = Key.GetHashCode(); }
public ConstructorCacheKey(Type type, bool autoCompleteDependecies, object[] parameters) { string key = type.GetSafeFullName(true); foreach (var parameter in parameters) { key += "_" + ObjectToStringHelper.ToFullTypeString(parameter); } Key = key; AutoCompleteDependecies = autoCompleteDependecies; _hashCode = Key.GetHashCode(); }
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); }
/// <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); }
/// <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)); } }
private static async Task <bool> ClosingAsync(CloseApplicationWatcherBase watcher) { try { Log.Debug($"Executing ClosingAsync() for '{ObjectToStringHelper.ToFullTypeString(watcher)}'"); var result = await watcher.ClosingAsync(); return(result); } catch (Exception ex) { Log.Error(ex, $"Failed to execute ClosingAsync() for '{ObjectToStringHelper.ToFullTypeString(watcher)}'"); throw; } }
/// <summary> /// Initializes the created object after its construction. /// </summary> /// <param name="obj">The object to initialize.</param> private void InitializeAfterConstruction(object obj) { if (obj == null) { return; } string objectType = ObjectToStringHelper.ToTypeString(obj); Log.Debug("Initializing type '{0}' after construction", objectType); // TODO: Consider to cache for performance var dependencyResolverManager = DependencyResolverManager.Default; var dependencyResolver = _serviceLocator.ResolveType <IDependencyResolver>(); dependencyResolverManager.RegisterDependencyResolverForInstance(obj, dependencyResolver); Log.Debug("Injecting properties into type '{0}' after construction", objectType); var type = obj.GetType(); var typeMetaData = GetTypeMetaData(type); foreach (var injectedProperty in typeMetaData.GetInjectedProperties()) { var propertyInfo = injectedProperty.Key; var injectAttribute = injectedProperty.Value; try { var dependency = _serviceLocator.ResolveType(injectAttribute.Type, injectAttribute.Tag); propertyInfo.SetValue(obj, dependency, null); } catch (Exception ex) { string error = string.Format("Failed to set property '{0}.{1}' during property dependency injection", type.Name, propertyInfo.Name); Log.Error(ex, error); throw new InvalidOperationException(error); } } var objAsINeedCustomInitialization = obj as INeedCustomInitialization; if (objAsINeedCustomInitialization != null) { objAsINeedCustomInitialization.Initialize(); } }
/// <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); }
/// <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); }
/// <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(); } } }