public override IRegressionProblemData LoadData(IDataDescriptor id) {
      var descriptor = (ResourceRegressionDataDescriptor)id;

      var instanceArchiveName = GetResourceName(FileName + @"\.zip");
      using (var instancesZipFile = new ZipArchive(GetType().Assembly.GetManifestResourceStream(instanceArchiveName), ZipArchiveMode.Read)) {
        var entry = instancesZipFile.GetEntry(descriptor.ResourceName);
        NumberFormatInfo numberFormat;
        DateTimeFormatInfo dateFormat;
        char separator;
        using (Stream stream = entry.Open()) {
          TableFileParser.DetermineFileFormat(stream, out numberFormat, out dateFormat, out separator);
        }

        TableFileParser csvFileParser = new TableFileParser();
        using (Stream stream = entry.Open()) {
          csvFileParser.Parse(stream, numberFormat, dateFormat, separator, true);
        }

        Dataset dataset = new Dataset(csvFileParser.VariableNames, csvFileParser.Values);
        if (!descriptor.CheckVariableNames(csvFileParser.VariableNames)) {
          throw new ArgumentException("Parsed file contains variables which are not in the descriptor.");
        }

        return descriptor.GenerateRegressionData(dataset);
      }
    }
 public override IRegressionProblemData LoadData(IDataDescriptor descriptor) {
   var frfDescriptor = descriptor as FriedmanRandomFunction;
   if (frfDescriptor == null) throw new ArgumentException("FriedmanRandomFunctionInstanceProvider expects an FriedmanRandomFunction data descriptor.");
   // base call generates a regression problem data
   var problemData = base.LoadData(frfDescriptor);
   return problemData;
 }
 public override IRegressionProblemData LoadData(IDataDescriptor descriptor) {
   var varNetwork = descriptor as VariableNetwork;
   if (varNetwork == null) throw new ArgumentException("VariableNetworkInstanceProvider expects an VariableNetwork data descriptor.");
   // base call generates a regression problem data
   var problemData = base.LoadData(varNetwork);
   problemData.Description = varNetwork.Description + Environment.NewLine + varNetwork.NetworkDefinition;
   return problemData;
 }
 public bool Convert (IDataDescriptor[] values, Type targetType, object parameter, out object result)
 {
   foreach (IDataDescriptor dataDescriptor in values)
   {
     if (dataDescriptor !=  null)
     {
       result = dataDescriptor.Value;
       return true;
     }
   }
   result = false;
   return false;
 }
예제 #5
0
 void Detach()
 {
   if (!string.IsNullOrEmpty(Property))
   {
     if (_dataDescriptor != null)
     {
       _dataDescriptor.Detach(OnPropertyChanged);
       _dataDescriptor = null;
     }
   }
   else
   {
     _bindingProperty.Detach(OnBindingValueChanged);
   }
 }
예제 #6
0
        private static QueryAndParameters BuildSelectQueryAndParameters(IDataDescriptor descriptor,
                                                                        IList <string> columnFilter, dynamic where)
        {
            IDictionary <string, object> whereHash = Hash.FromAnonymousObject(where);
            var hashKeysRewrite = whereHash.Keys.ToDictionary(k => Dialect.ResolveColumnName(descriptor, k), v => v);

            var tableName   = Dialect.ResolveTableName(descriptor);
            var columnNames = Dialect.ResolveColumnNames(descriptor).ToArray();

            var whereFilter = columnNames.Intersect(hashKeysRewrite.Keys).ToArray();
            var parameters  =
                whereFilter.ToDictionary(key => $"{hashKeysRewrite[key]}", key => whereHash[hashKeysRewrite[key]]);

            var parameterKeys = parameters.Keys.ToArray();
            var sql           = Dialect.Select(tableName, descriptor.Schema,
                                               columnFilter ?? (Dialect.SelectStar ? SelectStar : columnNames), whereFilter, parameterKeys);

            return(new QueryAndParameters(sql, parameters));
        }
        public override GQAPData LoadData(IDataDescriptor id)
        {
            var descriptor          = (CordeauGQAPDataDescriptor)id;
            var instanceArchiveName = GetResourceName(FileName + @"\.zip");

            using (var instancesZipFile = new ZipArchive(GetType().Assembly.GetManifestResourceStream(instanceArchiveName), ZipArchiveMode.Read)) {
                var entry = instancesZipFile.GetEntry(descriptor.InstanceIdentifier);
                using (var stream = entry.Open()) {
                    var parser = new CordeauGQAPParser();
                    parser.Parse(stream);
                    var instance = Load(parser);

                    instance.Name        = id.Name;
                    instance.Description = id.Description;

                    return(instance);
                }
            }
        }
예제 #8
0
        public override CFGData LoadData(IDataDescriptor id)
        {
            CFGArtificialDataDescriptor descriptor = (CFGArtificialDataDescriptor)id;
            CFGData cfgData             = descriptor.GenerateData();
            var     instanceArchiveName = GetResourceName(FileName + @"\.zip");

            using (var instancesZipFile = new ZipArchive(GetType().Assembly.GetManifestResourceStream(instanceArchiveName), ZipArchiveMode.Read)) {
                IEnumerable <ZipArchiveEntry> entries = instancesZipFile.Entries.Where(e => e.FullName.StartsWith(descriptor.Identifier) && !String.IsNullOrWhiteSpace(e.Name));

                var embedEntry = entries.FirstOrDefault(x => x.Name.EndsWith(".py"));
                if (embedEntry != null)
                {
                    using (var stream = new StreamReader(embedEntry.Open())) {
                        cfgData.Embed = stream.ReadToEnd();
                    }
                }
            }
            return(cfgData);
        }
예제 #9
0
        public override void DeepCopy(IDeepCopyable source, ICopyManager copyManager)
        {
            base.DeepCopy(source, copyManager);
            BindingBase bb = (BindingBase)source;

            if (bb._targetDataDescriptor != null)
            {
                // Copy values initialized by the Prepare(IDataDescriptor) call,
                // retargeted to the newTarget.
                object newTarget = copyManager.GetCopy(bb._targetDataDescriptor.TargetObject);
                _targetDataDescriptor = bb._targetDataDescriptor.Retarget(newTarget);
            }
            else
            {
                _targetDataDescriptor = null;
            }
            AttachToTargetObject(copyManager.GetCopy(bb._contextObject));
            // Bindings have to be activated manually after copy procedure
        }
예제 #10
0
        /// <summary>
        /// Returns an <see cref="IDataDescriptor"/> for the binding in the nearest available
        /// data context of a parent element in the visual or logical tree.
        /// </summary>
        /// <param name="result">Returns the data descriptor for the data context, if it
        /// could be resolved.</param>
        /// <returns><c>true</c>, if a data context could be found and the data context
        /// could evaluate, <c>false</c> if it could not be resolved (yet).</returns>
        protected bool FindDataContext(out IDataDescriptor result)
        {
            result = null;
            DependencyObject current = _contextObject;

            if (current == null)
            {
#if DEBUG_BINDINGS
                DebugOutput("FindDataContext doesn't have a current context");
#endif
                return(false);
            }
            if (UsedAsDataContext)
            {
                // If we are already the data context, step one level up and start the search at our parent
                if (!FindParent(current, out current, FindParentMode.HybridPreferVisualTree))
                {
                    return(false);
                }
            }
            while (current != null)
            {
                BindingExtension parentBinding;
                if (GetDataContext(current, out parentBinding))
                { // Data context found
                    if (parentBinding.Evaluate(out result))
                    {
                        return(true);
                    }
#if DEBUG_BINDINGS
                    DebugOutput("FindDataContext found parent binding '{0}' but that binding could not evaluate", parentBinding);
#endif
                    AttachToSource(parentBinding.EvaluatedSourceValue);
                    result = null;
                    return(false);
                }
                if (!FindParent(current, out current, FindParentMode.HybridPreferVisualTree))
                {
                    return(false);
                }
            }
            return(false);
        }
예제 #11
0
 public bool Convert(IDataDescriptor[] values, Type targetType, object parameter, out object result)
 {
   var enumerable = values[1].Value as IEnumerable;
   if (enumerable != null)
   {
     var collection = new List<object>(enumerable.OfType<object>());
     var itemIndex = collection.IndexOf(values[0].Value);
     int indexOffset;
     // Support offset, usually "1" to show "1/50" instead "0/50"
     if (int.TryParse(parameter as string, out indexOffset))
       itemIndex += indexOffset;
     result = itemIndex;
   }
   else
   {
     result = -1;
   }
   return true;
 }
예제 #12
0
        public static string Update(this ISqlDialect d, IDataDescriptor descriptor, string table, string schema,
                                    List <string> columns, List <string> keys, List <string> setParameters, List <string> whereParameters,
                                    string setSuffix = SetSuffix)
        {
            Debug.Assert(columns != null);
            Debug.Assert(columns.Count == setParameters?.Count && columns.Count >= whereParameters?.Count);

            return(StringBuilderPool.Scoped(sb =>
            {
                if (!d.BeforeUpdate(descriptor, sb))
                {
                    return;
                }

                sb.Append("UPDATE ");
                sb.AppendTable(d, table, schema).Append(" SET ");

                if (!d.BeforeUpdateColumns(descriptor, sb, columns))
                {
                    return;
                }

                for (var i = 0; i < columns.Count; i++)
                {
                    var column = columns[i];
                    sb.AppendName(d, column).Append(" = ");
                    sb.AppendParameter(d, setParameters[i] + setSuffix);
                    if (i < columns.Count - 1)
                    {
                        sb.Append(", ");
                    }
                }

                if (!d.BeforeWhere(descriptor, sb, keys, whereParameters))
                {
                    return;
                }

                sb.AppendWhereClause(d, keys, whereParameters);

                d.AfterWhere(descriptor, sb, keys);
            }));
        }
예제 #13
0
        public static Query Update <T>(T instance, IDataDescriptor descriptor, List <string> fields)
        {
            if (fields == null || fields.Count == 0)
            {
                return(Update(instance));
            }

            IDictionary <string, object> set = new ExpandoObject();

            foreach (var updated in descriptor.Updated)
            {
                if (fields.Contains(updated.ColumnName))
                {
                    set.Add(updated.ColumnName, updated.Property.Get(instance));
                }
            }

            return(Update(set));
        }
예제 #14
0
 /// <summary>
 /// Does the lookup for the binding source data values of all child values.
 /// </summary>
 /// <param name="result">Array of evaluated values evaluated by our child bindings.</param>
 /// <returns><c>true</c>, if all values could be evaluated, <c>false</c> if not all values are
 /// available (yet).</returns>
 protected bool GetSourceValues(out IDataDescriptor[] result)
 {
     ResetBindingAttachments();
     result = null;
     IDataDescriptor[] values = new IDataDescriptor[_childBindings.Count];
     for (int i = 0; i < _childBindings.Count; i++)
     {
         BindingMarkupExtension bme = _childBindings[i];
         IDataDescriptor        evaluatedValue;
         AttachToSourceBinding(bme);
         if (!bme.Evaluate(out evaluatedValue))
         {
             return(false);
         }
         values[i] = evaluatedValue;
     }
     result = values;
     return(true);
 }
예제 #15
0
 /// <summary>
 /// Creates a new <see cref="BindingDependency"/> object.
 /// </summary>
 /// <param name="sourceDd">Souce data descriptor for the dependency.</param>
 /// <param name="targetDd">Target data descriptor for the dependency.</param>
 /// <param name="autoAttachToSource">If set to <c>true</c>, the new dependency object will be
 /// automatically attached to the <paramref name="sourceDd"/> data descriptor. This means it will
 /// capture changes from it and reflect them on the <paramref name="targetDd"/> data descriptor.</param>
 /// <param name="updateSourceTrigger">This parameter controls, which target object event makes this
 /// binding dependency copy the target value to the <paramref name="sourceDd"/> data descriptor.
 /// If set to <see cref="UpdateSourceTrigger.PropertyChanged"/>, the new binding dependency object
 /// will automatically attach to property changes of the <paramref name="targetDd"/> data descriptor and
 /// reflect the changed value to the <paramref name="sourceDd"/> data descriptor. If set to
 /// <see cref="UpdateSourceTrigger.LostFocus"/>, the new binding dependency will attach to the
 /// <see cref="UIElement.EventOccured"/> event of the <paramref name="parentUiElement"/> object.
 /// If set to <see cref="UpdateSourceTrigger.Explicit"/>, the new binding dependency won't attach to
 /// the target at all.</param>
 /// <param name="parentUiElement">The parent <see cref="UIElement"/> of the specified <paramref name="targetDd"/>
 /// data descriptor. This parameter is only used to attach to the lost focus event if
 /// <paramref name="updateSourceTrigger"/> is set to <see cref="UpdateSourceTrigger.LostFocus"/>.</param>
 /// <param name="customValueConverter">Set a custom value converter with this parameter. If this parameter
 /// is set to <c>null</c>, the default <see cref="TypeConverter"/> will be used.</param>
 /// <param name="customValueConverterParameter">Parameter to be used in the custom value converter, if one is
 /// set.</param>
 public BindingDependency(IDataDescriptor sourceDd, IDataDescriptor targetDd, bool autoAttachToSource,
                          UpdateSourceTrigger updateSourceTrigger, UIElement parentUiElement,
                          IValueConverter customValueConverter, object customValueConverterParameter)
 {
     _sourceDd           = sourceDd;
     _targetDd           = targetDd;
     _targetObject       = _targetDd.TargetObject as DependencyObject;
     _sourceObject       = _sourceDd.TargetObject as DependencyObject;
     _valueConverter     = customValueConverter;
     _converterParameter = customValueConverterParameter;
     if (autoAttachToSource && sourceDd.SupportsChangeNotification)
     {
         sourceDd.Attach(OnSourceChanged);
         _attachedToSource = true;
     }
     if (targetDd.SupportsChangeNotification)
     {
         if (updateSourceTrigger == UpdateSourceTrigger.PropertyChanged)
         {
             targetDd.Attach(OnTargetChanged);
             _attachedToTarget = true;
         }
         else if (updateSourceTrigger == UpdateSourceTrigger.LostFocus)
         {
             if (parentUiElement != null)
             {
                 parentUiElement.EventOccured += OnTargetElementEventOccured;
             }
             _attachedToLostFocus = parentUiElement;
         }
     }
     // Initially update endpoints
     if (autoAttachToSource)
     {
         UpdateTarget();
     }
     if (updateSourceTrigger != UpdateSourceTrigger.Explicit &&
         !autoAttachToSource) // If we are attached to both, only update one direction
     {
         UpdateSource();
     }
 }
예제 #16
0
 /// <summary>
 /// Schedules the specified <paramref name="value"/> to be set at the specified
 /// <paramref name="dataDescriptor"/> the next time the <see cref="Animate"/> method runs.
 /// If the specified <paramref name="dataDescriptor"/> is already scheduled to be set to another
 /// value, the other job will be overridden by this call.
 /// </summary>
 /// <param name="dataDescriptor">Data descriptor to be used as target for the
 /// <paramref name="value"/>.</param>
 /// <param name="value">Value to be set.</param>
 public void SetValue(IDataDescriptor dataDescriptor, object value)
 {
     lock (_syncObject)
     {
         object curVal;
         if (_valuesToSet.TryGetValue(dataDescriptor, out curVal))
         {
             if (curVal == value)
             {
                 return;
             }
             MPF.TryCleanupAndDispose(curVal);
         }
         else if (dataDescriptor.Value == value)
         {
             return;
         }
         _valuesToSet[dataDescriptor] = value;
     }
 }
예제 #17
0
        public virtual CFGData LoadDataLocal(IDataDescriptor id, bool treeStructure, int numberOfVariables = 3, bool recursion = false)
        {
            BenchmarkSuiteDataDescritpor descriptor = (BenchmarkSuiteDataDescritpor)id;
            CFGData cfgData             = descriptor.GenerateData(treeStructure, numberOfVariables, recursion, new PythonGrammarConstructor());
            var     instanceArchiveName = GetResourceName(FileName + @"\.zip");

            using (
                var instancesZipFile = new ZipArchive(GetType().Assembly.GetManifestResourceStream(instanceArchiveName), ZipArchiveMode.Read)) {
                IEnumerable <ZipArchiveEntry> entries = instancesZipFile.Entries.Where(e => e.FullName.StartsWith(descriptor.Identifier) && !String.IsNullOrWhiteSpace(e.Name));

                var embedEntry = entries.FirstOrDefault(x => x.Name.EndsWith("Embed.txt"));
                if (embedEntry != null)
                {
                    using (var stream = new StreamReader(embedEntry.Open())) {
                        cfgData.Embed = stream.ReadToEnd();
                    }
                }
            }
            return(cfgData);
        }
예제 #18
0
        private static Query Count(IDataDescriptor descriptor, dynamic where)
        {
            object instance = where ?? new { };
            var    accessor = ReadAccessor.Create(instance.GetType());

            var whereHash       = accessor.AsReadOnlyDictionary(instance);
            var hashKeysRewrite = whereHash.Keys.ToDictionary(k => Dialect.ResolveColumnName(descriptor, k), v => v);

            var tableName   = Dialect.ResolveTableName(descriptor);
            var columnNames = Dialect.ResolveColumnNames(descriptor).ToList();

            var whereFilter = columnNames.Intersect(hashKeysRewrite.Keys).ToList();
            var parameters  =
                whereFilter.ToDictionary(key => $"{hashKeysRewrite[key]}", key => whereHash[hashKeysRewrite[key]]);
            var parameterKeys = parameters.Keys.ToList();

            var sql = Dialect.Count(descriptor, tableName, descriptor.Schema, whereFilter, parameterKeys);

            return(new Query(sql, parameters));
        }
예제 #19
0
        /// <summary>
        /// Given a starting object (or type) in a data context object, this method
        /// checks this path expression, if it yields a method call in its last path segment.
        /// If this is the case, it evaluates all predecessor path segments based on the
        /// specified <paramref name="start"/> descriptor and returns the <paramref name="obj"/>
        /// and the <paramref name="mi"/> to call the resulting method.
        /// </summary>
        /// <remarks>
        /// This method handles static and non-static property and field access, attached property
        /// access and indexers. If the last path segment is a method invocation expression,
        /// this method returns <c>true</c>, else it returns <c>false</c>.
        /// </remarks>
        /// <param name="start">Object used as starting point for the path evaluation.
        /// This may be an <see cref="object"/> or a <see cref="Type"/>.</param>
        /// <param name="numParameters">Number of parameters to be used for the method call.</param>
        /// <param name="obj">Reflected object on which the <paramref name="mi"/> may be
        /// evaluated. This parameter is only valid if the return value us <c>true</c>.</param>
        /// <param name="mi">Reflected method info to be evaluated on <paramref name="obj"/>.
        /// This parameter is only valid if the return value us <c>true</c>.</param>
        /// <returns><c>true</c>, if the path could be evaluated on object <paramref name="start"/>
        /// and the last path segment is a method invocation expression, else <c>false</c>.</returns>
        /// <exception cref="XamlBindingException">If this path could not be evaluated
        /// on object <paramref name="start"/>.</exception>
        public bool GetMethod(IDataDescriptor start, int numParameters, out object obj, out MethodInfo mi)
        {
            obj = null;
            mi  = null;
            IDataDescriptor value = start;

            for (int i = 0; i < _pathSegments.Count - 1; i++)
            {
                IPathSegment ps = _pathSegments[i];
                if (!ps.Evaluate(value, out value))
                {
                    return(false);
                }
                if (value == null)
                {
                    return(false);
                }
            }
            return(_pathSegments[_pathSegments.Count - 1].GetMethod(value, numParameters, out obj, out mi));
        }
예제 #20
0
        public static string Update(this ISqlDialect d, IDataDescriptor descriptor, string table, string schema,
                                    List <PropertyToColumn> columns, List <string> keys, string setSuffix = SetSuffix)
        {
            return(StringBuilderPool.Scoped(sb =>
            {
                if (!d.BeforeUpdate(descriptor, sb))
                {
                    return;
                }

                sb.Append("UPDATE ");
                sb.AppendTable(d, table, schema).Append(" SET ");

                if (!d.BeforeUpdateColumns(descriptor, sb, columns.Select(x => x.ColumnName).ToList()))
                {
                    return;
                }

                for (var i = 0; i < columns.Count; i++)
                {
                    var column = columns[i];
                    sb.AppendName(d, column.ColumnName).Append(" = ")
                    .AppendParameter(d, column.ColumnName)
                    .Append(setSuffix);

                    if (i < columns.Count - 1)
                    {
                        sb.Append(", ");
                    }
                }

                if (!d.BeforeWhere(descriptor, sb, keys))
                {
                    return;
                }

                sb.AppendWhereClause(d, keys);

                d.AfterWhere(descriptor, sb, keys);
            }));
        }
예제 #21
0
파일: DeleteBuilder.cs 프로젝트: qiqi545/HQ
        public static string Delete(this ISqlDialect d, IDataDescriptor descriptor, string table, string schema,
                                    List <string> keys, List <string> parameters)
        {
            return(Pooling.StringBuilderPool.Scoped(sb =>
            {
                if (!d.BeforeDelete(descriptor, sb))
                {
                    return;
                }

                sb.Append("DELETE FROM ");
                sb.AppendTable(d, table, schema);

                if (!d.BeforeWhere(descriptor, sb, keys, parameters))
                {
                    return;
                }

                sb.AppendWhereClause(descriptor, d, keys, parameters);
            }));
        }
    public override IRegressionProblemData LoadData(IDataDescriptor descriptor) {
      var featureSelectionDescriptor = descriptor as FeatureSelection;
      if (featureSelectionDescriptor == null) throw new ArgumentException("FeatureSelectionInstanceProvider expects an FeatureSelection data descriptor.");
      // base call generates a regression problem data
      var regProblemData = base.LoadData(featureSelectionDescriptor);
      var problemData =
        new FeatureSelectionRegressionProblemData(
          regProblemData.Dataset, regProblemData.AllowedInputVariables, regProblemData.TargetVariable,
          featureSelectionDescriptor.SelectedFeatures, featureSelectionDescriptor.Weights,
          featureSelectionDescriptor.OptimalRSquared);

      // copy values from regProblemData to feature selection problem data
      problemData.Name = regProblemData.Name;
      problemData.Description = regProblemData.Description;
      problemData.TrainingPartition.Start = regProblemData.TrainingPartition.Start;
      problemData.TrainingPartition.End = regProblemData.TrainingPartition.End;
      problemData.TestPartition.Start = regProblemData.TestPartition.Start;
      problemData.TestPartition.End = regProblemData.TestPartition.End;

      return problemData;
    }
예제 #23
0
 public bool Evaluate(IDataDescriptor source, out IDataDescriptor result)
 {
     result = null;
     try
     {
         DefaultAttachedPropertyDataDescriptor dapdd;
         if (!DefaultAttachedPropertyDataDescriptor.CreateAttachedPropertyDataDescriptor(_namespaceHandler,
                                                                                         source.Value, _propertyProvider, _propertyName, out dapdd))
         {
             throw new InvalidOperationException(string.Format("Attached property '{0}.{1}' is not available on new target object '{2}'",
                                                               _propertyProvider, _propertyName, source.Value));
         }
         result = dapdd;
     }
     catch (Exception e)
     {
         ServiceRegistration.Get <ILogger>().Warn("AttachedPropertyPathSegment: Cannot evaluate attached property '{0}' on object '{1}'", e, ToString(), source.Value);
         return(false);
     }
     return(true);
 }
예제 #24
0
        private static Query Update(IDataDescriptor descriptor, List <string> setFilter, List <string> whereFilter,
                                    IReadOnlyDictionary <string, object> setHash, IReadOnlyDictionary <string, object> whereHash)
        {
            whereHash = whereHash ?? new Dictionary <string, object>();

            var setHashKeyRewrite   = setHash.Keys.ToDictionary(k => Dialect.ResolveColumnName(descriptor, k), v => v);
            var whereHashKeyRewrite = RuntimeHelpers.Equals(setHash, whereHash)
                                ? setHashKeyRewrite
                                : whereHash.Keys.ToDictionary(k => Dialect.ResolveColumnName(descriptor, k), v => v);

            var whereParams = new Dictionary <string, object>();

            foreach (var key in whereFilter)
            {
                if (whereHash.TryGetValue(key, out var value))
                {
                    whereParams.Add(whereHashKeyRewrite[key], value);
                }
            }

            var whereParameters = whereParams.Keys.ToList();

            var setParams =
                setFilter.ToDictionary(key => setHashKeyRewrite[key], key => setHash[setHashKeyRewrite[key]]);
            var setParameters = setParams.Keys.ToList();

            var sql = Dialect.Update(descriptor, Dialect.ResolveTableName(descriptor), descriptor.Schema, setFilter,
                                     whereFilter, setParameters, whereParameters, Dialect.SetSuffix);

            var parameters =
                setParams.ToDictionary(k => $"{Dialect.Parameter}{k.Key}{Dialect.SetSuffix}", v => v.Value);

            foreach (var entry in whereParams.ToDictionary(k => $"{Dialect.Parameter}{k.Key}", v => v.Value))
            {
                parameters[entry.Key] = entry.Value;
            }

            return(new Query(sql, parameters));
        }
예제 #25
0
        /// <summary>
        /// Will reset all change handler attachments to source property and
        /// source path properties. This should be called before the evaluation path
        /// to the binding's source will be processed again.
        /// </summary>
        protected void ResetChangeHandlerAttachments()
        {
            lock (_syncObj)
            {
                foreach (AbstractProperty property in _attachedPropertiesCollection)
                {
                    property.Detach(OnDataContextChanged);
                }

                _attachedPropertiesCollection.Clear();
                if (_attachedSource != null)
                {
                    _attachedSource.Detach(OnBindingSourceChange);
                    _attachedSource = null;
                }
                if (_attachedSourceObservable != null)
                {
                    _attachedSourceObservable.ObjectChanged -= OnBindingSourceChange;
                    _attachedSourceObservable = null;
                }
            }
        }
예제 #26
0
        public static Query Insert(object instance, IDataDescriptor descriptor)
        {
            var columns         = Dialect.ResolveColumnNames(descriptor, ColumnScope.Inserted).ToList();
            var sql             = Dialect.InsertInto(Dialect.ResolveTableName(descriptor), descriptor.Schema, columns, false);
            var hash            = Hash.FromAnonymousObject(instance, true);
            var hashKeysRewrite = hash.Keys.ToDictionary(k => Dialect.ResolveColumnName(descriptor, k), v => v);
            var keys            = columns.Intersect(hashKeysRewrite.Keys);

            var parameters = keys.ToDictionary(key => $"{Dialect.Parameter}{key}", key => hash[hashKeysRewrite[key]]);

            // TODO: rewrite this...
            foreach (var computed in descriptor.Computed.Where(x => hash.ContainsKey(x.Property.Name)))
            {
                if (computed.Property.HasAttribute <ExternalSurrogateKey>())
                {
                    var reverseKey = hashKeysRewrite.Single(x => x.Value == computed.Property.Name);
                    parameters.Remove($"{Dialect.Parameter}{reverseKey.Key}");
                }
            }

            return(new Query(sql, parameters));
        }
    public bool Convert(IDataDescriptor[] values, Type targetType, object parameter, out object result)
    {
      result = false;
      if (values.Length != 2)
      {
        ServiceRegistration.Get<ILogger>().Error("MediaItemAspectToBoolConverter: invalid number of arguments (expects MediaItem and Guid)");
        return false;
      }
      MediaItem mediaItem = values[0].Value as MediaItem;
      if (mediaItem == null || values[1].Value == null)
        return true;

      string aspectIdString = values[1].Value as string;
      Guid aspectId;
      if (values[1].Value is Guid)
        aspectId = (Guid)values[1].Value;
      else if (!Guid.TryParse(aspectIdString, out aspectId))
        return true;

      result = mediaItem.Aspects.ContainsKey(aspectId);
      return true;
    }
예제 #28
0
 protected static bool ExtractWorkingData(IDataDescriptor source, string memberName,
                                          out Type type, out object obj, out MemberInfo[] mis)
 {
     obj = source.Value;
     mis = null;
     if (obj == null)
     {
         type = null;
         return(false);
     }
     if (obj is Type)
     {
         type = (Type)obj;
         // Morpheus_xx 2013-10-09: we must not set obj to "null", this prevents accessing static fields (see FieldDescriptor)
         // obj = null;
     }
     else
     {
         type = obj.GetType();
     }
     MemberInfo[] members = type.GetMember(memberName);
     if (members.Length == 0)
     { // Check access problems
         members = type.GetMember(memberName,
                                  BindingFlags.NonPublic |
                                  BindingFlags.Instance |
                                  BindingFlags.Static |
                                  BindingFlags.FlattenHierarchy |
                                  BindingFlags.IgnoreCase);
         if (members.Length > 0)
         {
             ServiceRegistration.Get <ILogger>().Warn("MemberPathSegment: Binding engine could not find public member '{0}', but found {1} members with different capitalization or which are non-public");
         }
         return(false);
     }
     mis = members;
     return(true);
 }
예제 #29
0
 /// <summary>
 /// Given a starting object (or type) in a data context object, this method
 /// evaluates this path on it. The path must only contain evaluable fields in it,
 /// no method calls are supported.
 /// </summary>
 /// <remarks>
 /// This method handles static and non-static property and field access, attached property
 /// access and indexers.
 /// </remarks>
 /// <param name="start">Object used as starting point for the path evaluation.
 /// This may be an <see cref="object"/> or a <see cref="Type"/>.</param>
 /// <param name="result">Returns the reflected value, if it could be resolved.</param>
 /// <returns><c>true</c>, if this path could be resolved on object
 /// <paramref name="start"/>, else <c>false</c>.</returns>
 /// <exception cref="XamlBindingException">If an error occurs during evaluation
 /// of this path on object <paramref name="start"/>.</exception>
 public bool Evaluate(IDataDescriptor start, out IDataDescriptor result)
 {
     try
     {
         result = start;
         foreach (IPathSegment ps in _pathSegments)
         {
             if (result == null || result.Value == null)
             {
                 return(false);
             }
             if (!ps.Evaluate(result, out result))
             {
                 return(false);
             }
         }
         return(true);
     }
     catch (Exception e)
     {
         throw new XamlBindingException("PathExpression: Error evaluating path expression '{0}'", e, ToString());
     }
 }
예제 #30
0
        public async Task <(SqlServerPreBatchStatus, object)> BeforeAsync(IDbConnection connection,
                                                                          IDataDescriptor descriptor,
                                                                          IDbTransaction transaction = null,
                                                                          int?commandTimeout         = null)
        {
            var database = connection.Database;
            var settings = new SqlServerPreBatchStatus
            {
                PageVerify = (await connection
                              .ExecuteAsync("SELECT page_verify_option_desc FROM sys.databases WHERE [NAME] = @Database",
                                            new { Database = database }, transaction, commandTimeout)).ToString(),
                RecoveryModel = (await connection
                                 .ExecuteAsync("SELECT recovery_model_desc FROM sys.databases WHERE [NAME] =  @Database",
                                               new { Database = database }, transaction, commandTimeout)).ToString()
            };

            connection.Execute("USE master;");
            connection.Execute($"ALTER DATABASE [{database}] SET PAGE_VERIFY NONE;");
            connection.Execute($"ALTER DATABASE [{database}] SET RECOVERY BULK_LOGGED");
            connection.Execute($"USE [{database}]");

            return(settings, null);
        }
예제 #31
0
        public override GCPData LoadData(IDataDescriptor id)
        {
            var descriptor          = (GcolDataDescriptor)id;
            var instanceArchiveName = GetResourceName(FileName + @"\.zip");

            using (var instancesZipFile = new ZipArchive(GetType().Assembly.GetManifestResourceStream(instanceArchiveName), ZipArchiveMode.Read)) {
                var entry = instancesZipFile.GetEntry(descriptor.InstanceIdentifier);

                using (var stream = entry.Open()) {
                    var parser = new GcolParser();
                    parser.Parse(stream);
                    var instance = Load(parser);
                    instance.Name         = id.Name;
                    instance.Description += Environment.NewLine + id.Description;
                    int bestknown;
                    if (bkq.TryGetValue(instance.Name, out bestknown))
                    {
                        instance.BestKnownColors = bestknown;
                    }
                    return(instance);
                }
            }
        }
    public override CFGData LoadData(IDataDescriptor id) {
      CFGArtificialDataDescriptor descriptor = (CFGArtificialDataDescriptor)id;
      CFGData cfgData = descriptor.GenerateData();
      var instanceArchiveName = GetResourceName(FileName + @"\.zip");
      using (var instancesZipFile = new ZipArchive(GetType().Assembly.GetManifestResourceStream(instanceArchiveName), ZipArchiveMode.Read)) {
        IEnumerable<ZipArchiveEntry> entries = instancesZipFile.Entries.Where(e => e.FullName.StartsWith(descriptor.Identifier) && !String.IsNullOrWhiteSpace(e.Name));

        var bnfEntry = entries.Where(x => x.Name.EndsWith(".bnf")).FirstOrDefault();
        if (bnfEntry != null) {
          using (var stream = new StreamReader(bnfEntry.Open())) {
            cfgData.Grammar = stream.ReadToEnd();
          }
        }

        var embedEntry = entries.Where(x => x.Name.EndsWith("Embed.txt")).FirstOrDefault();
        if (embedEntry != null) {
          using (var stream = new StreamReader(embedEntry.Open())) {
            cfgData.Embed = stream.ReadToEnd();
          }
        }
      }
      return cfgData;
    }
예제 #33
0
        public static Query Update(IDataDescriptor descriptor, dynamic set, dynamic where = null)
        {
            ITypeReadAccessor setAccessor = ReadAccessor.Create(set.GetType());
            IReadOnlyDictionary <string, object> setHash = ReadAccessorExtensions.AsReadOnlyDictionary(setAccessor, set);
            var setFilter = descriptor.Updated.Select(c => c.ColumnName).Intersect(setHash.Keys).ToList();

            IReadOnlyDictionary <string, object> whereHash = null;

            if (where != null)
            {
                ITypeReadAccessor whereAccessor = ReadAccessor.Create(where.GetType());
                whereHash = ReadAccessorExtensions.AsReadOnlyDictionary(whereAccessor, where);
            }

            var whereFilter = Dialect.ResolveColumnNames(descriptor);

            if (whereHash != null)
            {
                whereFilter = whereFilter.Intersect(whereHash.Keys);
            }

            return(Update(descriptor, setFilter, whereFilter.ToList(), setHash, whereHash));
        }
        public override CTAPData LoadData(IDataDescriptor id)
        {
            var descriptor          = (ElloumiCTAPDataDescriptor)id;
            var instanceArchiveName = GetResourceName(FileName + @"\.dat\.zip");

            using (var instancesZipFile = new ZipArchive(GetType().Assembly.GetManifestResourceStream(instanceArchiveName), ZipArchiveMode.Read)) {
                var entry = instancesZipFile.GetEntry(descriptor.InstanceIdentifier);
                using (var stream = entry.Open()) {
                    var parser = new ElloumiCTAPParser();
                    parser.Parse(stream);
                    var instance = Load(parser);

                    instance.Name        = id.Name;
                    instance.Description = id.Description;

                    if (!String.IsNullOrEmpty(descriptor.SolutionIdentifier))
                    {
                        var solutionsArchiveName = GetResourceName(FileName + @"\.sol\.zip");
                        using (var solutionsZipFile = new ZipArchive(GetType().Assembly.GetManifestResourceStream(solutionsArchiveName), ZipArchiveMode.Read)) {
                            entry = solutionsZipFile.GetEntry(descriptor.SolutionIdentifier);
                            using (var solStream = entry.Open()) {
                                ElloumiCTAPSolutionParser slnParser = new ElloumiCTAPSolutionParser();
                                slnParser.Parse(solStream, instance.MemoryRequirements.Length);
                                if (slnParser.Error != null)
                                {
                                    throw slnParser.Error;
                                }

                                instance.BestKnownAssignment = slnParser.Assignment;
                                instance.BestKnownQuality    = slnParser.Quality;
                            }
                        }
                    }
                    return(instance);
                }
            }
        }
예제 #35
0
 /// <summary>
 /// Returns a data descriptor for the access to a collection-like instance
 /// <paramref name="maybeCollection"/> with an <paramref name="index"/>.
 /// </summary>
 /// <param name="maybeCollection">Instance which may be collection-like, like an
 /// <see cref="IList{T}"/>, <see cref="ICollection{T}"/> or <see cref="IEnumerable{T}"/>.
 /// The returned data descriptor will allow to read the value, and for an
 /// <see cref="IList{T}"/> it will also be writeable.</param>
 /// <param name="index">Index to access the collection-like instance.</param>
 /// <param name="result">Returns the data descriptor for the access to the
 /// <paramref name="index"/>th entry in <paramref name="maybeCollection"/>.</param>
 /// <returns><c>true</c>, if <paramref name="maybeCollection"/> is a collection-like
 /// instance and could be accessed by the specified <paramref name="index"/>, else
 /// <c>false</c>.</returns>
 public static bool GetEnumerationEntryByIndex(object maybeCollection, int index,
                                               out IDataDescriptor result)
 {
     if (maybeCollection is IList)
     {
         result = new IndexerDataDescriptor(maybeCollection, new object[] { index });
         return(true);
     }
     if (maybeCollection is IEnumerable)
     {
         int i = 0;
         foreach (object o in (IEnumerable)maybeCollection)
         {
             if (i++ == index)
             {
                 result = new ValueDataDescriptor(o);
                 return(true);
             }
         }
         throw new XamlBindingException("Index '{0}' is out of range (# elements={1})", index, i);
     }
     result = null;
     return(false);
 }
        public override BPPData LoadData(IDataDescriptor dd)
        {
            var randDd = dd as RandomDataDescriptor;

            if (randDd == null)
            {
                throw new NotSupportedException("Cannot load data descriptor " + dd);
            }

            var data = new BPPData()
            {
                BinShape = new PackingShape(binWidth, binHeight),
                Items    = new PackingItem[randDd.NumItems]
            };
            var instanceRand = new MersenneTwister((uint)randDd.Seed);

            for (int i = 0; i < randDd.NumItems; i++)
            {
                int w, h;
                SampleItemParameters(instanceRand, out w, out h);
                data.Items[i] = new PackingItem(w, h, data.BinShape);
            }
            return(data);
        }
예제 #37
0
        public static StringBuilder AppendWhereClause(this StringBuilder sb, IDataDescriptor descriptor, ISqlDialect d,
                                                      List <string> keys, List <string> parameters)
        {
            if (!d.BeforeWhere(descriptor, sb, keys, parameters))
            {
                return(sb);
            }

            if (keys != null)
            {
                for (var i = 0; i < keys.Count; i++)
                {
                    sb.Append(i == 0 ? " WHERE " : " AND ");
                    sb.AppendName(d, keys[i]).Append(" = ").AppendParameter(d, parameters[i]);
                }
            }

            if (keys?.Count > 0)
            {
                d.AfterWhere(descriptor, sb, keys, parameters);
            }

            return(sb);
        }
예제 #38
0
        public static string Count(this ISqlDialect d, IDataDescriptor descriptor, string table, string schema,
                                   List <string> keys, List <string> parameters)
        {
            return(Pooling.StringBuilderPool.Scoped(sb =>
            {
                if (descriptor != null && !d.BeforeSelect(descriptor, sb))
                {
                    return;
                }

                sb.Append("SELECT ");

                sb.Append(d.Count);

                sb.Append(" FROM ").AppendTable(d, table, schema);

                if (keys?.Count > 0)
                {
                    sb.AppendWhereClause(descriptor, d, keys, parameters);
                }

                d.AfterCount(descriptor, sb, keys?.Count > 0);
            }));
        }
예제 #39
0
 /// <summary>
 /// Creates a new <see cref="BindingDependency"/> object.
 /// </summary>
 /// <param name="sourceDd">Souce data descriptor for the dependency.</param>
 /// <param name="targetDd">Target data descriptor for the dependency.</param>
 /// <param name="autoAttachToSource">If set to <c>true</c>, the new dependency object will be
 /// automatically attached to the <paramref name="sourceDd"/> data descriptor. This means it will
 /// capture changes from it and reflect them on the <paramref name="targetDd"/> data descriptor.</param>
 /// <param name="updateSourceTrigger">This parameter controls, which target object event makes this
 /// binding dependency copy the target value to the <paramref name="sourceDd"/> data descriptor.
 /// If set to <see cref="UpdateSourceTrigger.PropertyChanged"/>, the new binding dependency object
 /// will automatically attach to property changes of the <paramref name="targetDd"/> data descriptor and
 /// reflect the changed value to the <paramref name="sourceDd"/> data descriptor. If set to
 /// <see cref="UpdateSourceTrigger.LostFocus"/>, the new binding dependency will attach to the
 /// <see cref="UIElement.EventOccured"/> event of the <paramref name="parentUiElement"/> object.
 /// If set to <see cref="UpdateSourceTrigger.Explicit"/>, the new binding dependency won't attach to
 /// the target at all.</param>
 /// <param name="parentUiElement">The parent <see cref="UIElement"/> of the specified <paramref name="targetDd"/>
 /// data descriptor. This parameter is only used to attach to the lost focus event if
 /// <paramref name="updateSourceTrigger"/> is set to <see cref="UpdateSourceTrigger.LostFocus"/>.</param>
 /// <param name="customValueConverter">Set a custom value converter with this parameter. If this parameter
 /// is set to <c>null</c>, the default <see cref="TypeConverter"/> will be used.</param>
 /// <param name="customValueConverterParameter">Parameter to be used in the custom value converter, if one is
 /// set.</param>
 public BindingDependency(IDataDescriptor sourceDd, IDataDescriptor targetDd, bool autoAttachToSource,
     UpdateSourceTrigger updateSourceTrigger, UIElement parentUiElement,
     IValueConverter customValueConverter, object customValueConverterParameter)
 {
   _sourceDd = sourceDd;
   _targetDd = targetDd;
   _targetObject = _targetDd.TargetObject as DependencyObject;
   _sourceObject = _sourceDd.TargetObject as DependencyObject;
   _valueConverter = customValueConverter;
   _converterParameter = customValueConverterParameter;
   if (autoAttachToSource && sourceDd.SupportsChangeNotification)
   {
     sourceDd.Attach(OnSourceChanged);
     _attachedToSource = true;
   }
   if (targetDd.SupportsChangeNotification)
   {
     if (updateSourceTrigger == UpdateSourceTrigger.PropertyChanged)
     {
       targetDd.Attach(OnTargetChanged);
       _attachedToTarget = true;
     }
     else if (updateSourceTrigger == UpdateSourceTrigger.LostFocus)
     {
       if (parentUiElement != null)
         parentUiElement.EventOccured += OnTargetElementEventOccured;
       _attachedToLostFocus = parentUiElement;
     }
   }
   // Initially update endpoints
   if (autoAttachToSource)
     UpdateTarget();
   if (updateSourceTrigger != UpdateSourceTrigger.Explicit &&
       !autoAttachToSource) // If we are attached to both, only update one direction
     UpdateSource();
 }
예제 #40
0
        public void HandleMemberAssignment(IDataDescriptor dd, object value)
        {
            IBinding binding = value as IBinding;

            if (binding != null && dd.DataType != typeof(IBinding)) // In case the property descriptor's type is IBinding, we want to assign the binding directly instead of binding it to the property
            {
                binding.SetTargetDataDescriptor(dd);
                return;
            }

            IEvaluableMarkupExtension evaluableMarkupExtension = value as IEvaluableMarkupExtension;

            if (evaluableMarkupExtension != null)
            {
                evaluableMarkupExtension.Initialize(this);
                if (!evaluableMarkupExtension.Evaluate(out value))
                {
                    _deferredMarkupExtensionActivations.Add(new EvaluatableMarkupExtensionActivator(this, evaluableMarkupExtension, dd));
                    return;
                }
            }

            AssignValue(dd, value);
        }
예제 #41
0
 public virtual bool FindContentProperty(out IDataDescriptor dd)
 {
   dd = new SimplePropertyDataDescriptor(this, GetType().GetProperty("BindingValue"));
   return true;
 }
예제 #42
0
 /// <summary>
 /// Returns a data descriptor for the access to a collection-like instance
 /// <paramref name="maybeCollection"/> with an <paramref name="index"/>.
 /// </summary>
 /// <param name="maybeCollection">Instance which may be collection-like, like an
 /// <see cref="IList{T}"/>, <see cref="ICollection{T}"/> or <see cref="IEnumerable{T}"/>.
 /// The returned data descriptor will allow to read the value, and for an
 /// <see cref="IList{T}"/> it will also be writeable.</param>
 /// <param name="index">Index to access the collection-like instance.</param>
 /// <param name="result">Returns the data descriptor for the access to the
 /// <paramref name="index"/>th entry in <paramref name="maybeCollection"/>.</param>
 /// <returns><c>true</c>, if <paramref name="maybeCollection"/> is a collection-like
 /// instance and could be accessed by the specified <paramref name="index"/>, else
 /// <c>false</c>.</returns>
 public static bool GetEnumerationEntryByIndex(object maybeCollection, int index,
     out IDataDescriptor result)
 {
   if (maybeCollection is IList)
   {
     result = new IndexerDataDescriptor(maybeCollection, new object[] { index });
     return true;
   }
   if (maybeCollection is IEnumerable)
   {
     int i = 0;
     foreach (object o in (IEnumerable)maybeCollection)
     {
       if (i++ == index)
       {
         result = new ValueDataDescriptor(o);
         return true;
       }
     }
     throw new XamlBindingException("Index '{0}' is out of range (# elements={1})", index, i);
   }
   result = null;
   return false;
 }
예제 #43
0
 /// <summary>
 /// Given the instance <paramref name="obj"/> and the <paramref name="memberName"/>,
 /// this method searches the best matching member on the instance. It first searches
 /// a property with name [PropertyName]Property, casts it to
 /// <see cref="AbstractProperty"/> and returns a <see cref="DependencyPropertyDataDescriptor"/>
 /// for it in the parameter <paramref name="dd"/>. If there is no such property, this method
 /// searches a simple property with the given name, returning a property descriptor for it.
 /// Then, the method will search for a field with the specified name, returning a
 /// <see cref="FieldDataDescriptor"/> for it.
 /// If there is no member found with the given name, this method returns false and a
 /// <c>null</c> value in <paramref name="dd"/>.
 /// </summary>
 /// <param name="obj">The object where to search the member with the
 /// specified <paramref name="memberName"/>.</param>
 /// <param name="memberName">The name of the member to be searched.</param>
 /// <param name="dd">Data descriptor which will be returned for the property or member,
 /// if it was found, else a <c>null</c> value will be returned.</param>
 /// <returns><c>true</c>, if a member with the specified name was found, else <c>false</c>.</returns>
 public static bool FindMemberDescriptor(object obj, string memberName, out IDataDescriptor dd)
 {
   if (obj == null)
     throw new NullReferenceException("Property target object 'null' is not supported");
   DependencyPropertyDataDescriptor dpdd;
   if (DependencyPropertyDataDescriptor.CreateDependencyPropertyDataDescriptor(
         obj, memberName, out dpdd))
   {
     dd = dpdd;
     return true;
   }
   SimplePropertyDataDescriptor spdd;
   if (SimplePropertyDataDescriptor.CreateSimplePropertyDataDescriptor(
       obj, memberName, out spdd))
   {
     dd = spdd;
     return true;
   }
   FieldDataDescriptor fdd;
   if (FieldDataDescriptor.CreateFieldDataDescriptor(obj, memberName, out fdd))
   {
     dd = fdd;
     return true;
   }
   dd = null;
   return false;
 }
 public override IClusteringProblemData LoadData(IDataDescriptor descriptor) {
   throw new NotImplementedException();
 }
 /// <summary>
 /// Initializes the <see cref="ItemsControl.ItemsSource"/> property with the <see cref="SubItemsProvider"/>.
 /// </summary>
 /// <returns><c>true</c>, if the <see cref="ItemsControl.ItemsSource"/> property was changed by this method, else <c>false</c>.</returns>
 protected virtual bool InitializeSubItemsSource()
 {
   SubItemsProvider sip = SubItemsProvider;
   IEnumerable oldItemsSource = ItemsSource;
   if (!_contextChangedAttached)
   {
     ContextChanged += OnContextChanged;
     _contextChangedAttached = true;
   }
   if (_attachedContextSource != null)
     _attachedContextSource.Detach(OnDataContextValueChanged);
   _attachedContextSource = DataContext.EvaluatedSourceValue;
   _attachedContextSource.Attach(OnDataContextValueChanged);
   object context = Context;
   if (context == null)
     return false;
   ItemsSource = sip == null ? null : sip.GetSubItems(context);
   if (oldItemsSource == ItemsSource)
     return false;
   MPF.TryCleanupAndDispose(oldItemsSource);
   CheckExpandable();
   return true;
 }
예제 #46
0
 protected void OnTargetChanged(IDataDescriptor target)
 {
   UpdateSource();
 }
예제 #47
0
 public void AssignValue(IDataDescriptor dd, object value)
 {
   if (dd.SupportsWrite &&
       (value == null || dd.DataType.IsAssignableFrom(value.GetType())))
     dd.Value = value;
   else if (ReflectionHelper.CheckHandleCollectionAssignment(dd.Value, value))
   { }
   else
     dd.Value = Convert(value, dd.DataType);
 }
예제 #48
0
 /// <summary>
 /// Gets either the value of the given <paramref name="dataDescriptor"/> or, if there is a value to be set in the
 /// render thread, that pending value.
 /// </summary>
 /// <param name="dataDescriptor">Data descriptor whose value should be returned.</param>
 /// <param name="value">Pending value or current value.</param>
 /// <returns><c>true</c>, if the returned value is pending to be set, else <c>false</c>.</returns>
 public bool GetPendingOrCurrentValue(IDataDescriptor dataDescriptor, out object value)
 {
   Screen screen = Screen;
   Animator animator = screen == null ? null : screen.Animator;
   try
   {
     if (animator != null)
     {
       Monitor.Enter(animator.SyncObject);
       if (animator.TryGetPendingValue(dataDescriptor, out value))
         return true;
     }
     value = dataDescriptor.Value;
   }
   finally
   {
     if (animator != null)
       Monitor.Exit(animator.SyncObject);
   }
   return false;
 }
예제 #49
0
 /// <summary>
 /// Convenience method for calling <see cref="GetPendingOrCurrentValue(IDataDescriptor,out object)"/> if it is not
 /// interesting whether the value was still pending or whether the current value was returned.
 /// </summary>
 /// <param name="dataDescriptor">Data descriptor whose value should be returned.</param>
 /// <returns>Pending value or current value.</returns>
 public object GetPendingOrCurrentValue(IDataDescriptor dataDescriptor)
 {
   object value;
   GetPendingOrCurrentValue(dataDescriptor, out value);
   return value;
 }
예제 #50
0
 public void SetValueInRenderThread(IDataDescriptor dataDescriptor, object value)
 {
   if (_elementState == ElementState.Disposing)
     return;
   Screen screen = Screen;
   if (screen == null || _elementState == ElementState.Available || _elementState == ElementState.Preparing ||
       Thread.CurrentThread == SkinContext.RenderThread)
     dataDescriptor.Value = value;
   else
     screen.Animator.SetValue(dataDescriptor, value);
 }
예제 #51
0
 public override void SetBindingValue(IDataDescriptor dd, object value)
 {
   SetValueInRenderThread(dd, value);
 }
예제 #52
0
 public bool FindContentProperty(out IDataDescriptor dd)
 {
   return ReflectionHelper.FindMemberDescriptor(this, "Content", out dd);
 }
예제 #53
0
 protected void OnSourceValueChange(IDataDescriptor dd)
 {
   if (_valueChanged != null)
     _valueChanged(this);
 }
 void OnDataContextValueChanged(IDataDescriptor dd)
 {
   InitializeSubItemsSource();
 }
예제 #55
0
    public void HandleMemberAssignment(IDataDescriptor dd, object value)
    {
      IBinding binding = value as IBinding;
      if (binding != null && dd.DataType != typeof(IBinding)) // In case the property descriptor's type is IBinding, we want to assign the binding directly instead of binding it to the property
      {
        binding.SetTargetDataDescriptor(dd);
        return;
      }

      IEvaluableMarkupExtension evaluableMarkupExtension = value as IEvaluableMarkupExtension;
      if (evaluableMarkupExtension != null)
      {
        evaluableMarkupExtension.Initialize(this);
        if (!evaluableMarkupExtension.Evaluate(out value))
        {
          _deferredMarkupExtensionActivations.Add(new EvaluatableMarkupExtensionActivator(this, evaluableMarkupExtension, dd));
          return;
        }
      }

      AssignValue(dd, value);
    }
예제 #56
0
 /// <summary>
 /// Schedules the specified <paramref name="value"/> to be set at the specified
 /// <paramref name="dataDescriptor"/> the next time the <see cref="Animate"/> method runs.
 /// If the specified <paramref name="dataDescriptor"/> is already scheduled to be set to another
 /// value, the other job will be overridden by this call.
 /// </summary>
 /// <param name="dataDescriptor">Data descriptor to be used as target for the
 /// <paramref name="value"/>.</param>
 /// <param name="value">Value to be set.</param>
 public void SetValue(IDataDescriptor dataDescriptor, object value)
 {
   lock (_syncObject)
   {
     object curVal;
     if (_valuesToSet.TryGetValue(dataDescriptor, out curVal))
     {
       if (curVal == value)
         return;
       MPF.TryCleanupAndDispose(curVal);
     }
     else if (dataDescriptor.Value == value)
       return;
     _valuesToSet[dataDescriptor] = value;
   }
 }
예제 #57
0
 protected void OnSourceChanged(IDataDescriptor source)
 {
   UpdateTarget();
 }
예제 #58
0
 /// <summary>
 /// Returns the information if we have a value pending to be set. This can be the case if
 /// <see cref="SetValue"/> was called before with the specified <paramref name="dataDescriptor"/>
 /// but the <see cref="Animate"/> method wasn't called since then.
 /// </summary>
 /// <param name="dataDescriptor">Data descriptor to search for.</param>
 /// <param name="value">Will be set to the value which is pending to be set to the
 /// <paramref name="dataDescriptor"/>.</param>
 /// <returns><c>true</c>, if the method found a pending value for the specified
 /// <paramref name="dataDescriptor"/>, else <c>false</c>.</returns>
 public bool TryGetPendingValue(IDataDescriptor dataDescriptor, out object value)
 {
   lock (_syncObject)
     return _valuesToSet.TryGetValue(dataDescriptor, out value);
 }
    /// <summary>
    /// Evaluates a simple expression, given via the parameter <paramref name="parameter"/>.
    /// </summary>
    /// <remarks>
    /// This converter will often be used in XAML files. Note that in XAML, an attribute beginning with a <c>'{'</c> character
    /// is interpreted as an invocation of a markup extension. So the expression "{0} + 5" must be escaped like this:
    /// <c>"{}{0} + 5"</c>. Note also that the boolean AND operator (<c>"&&"</c>) must be escaped too like this: <c>"{}{0} &amp;&amp; true"</c>.
    /// </remarks>
    /// <param name="values">The values used for the variables {0} .. {n}.</param>
    /// <param name="targetType">Type to that the evaluated result should be converted.</param>
    /// <param name="parameter">String containing the expression. Variables can be accessed via numbers in
    /// curly braces, for example "!({0} || {2})". The variables are mapped to the values specified by
    /// the <paramref name="values"/> array.</param>
    /// <param name="result">Will return the evaluated result of the given <paramref name="targetType"/>.</param>
    public bool Convert(IDataDescriptor[] values, Type targetType, object parameter, out object result)
    {
      result = null;
      string expression = parameter as string;
      if (string.IsNullOrEmpty(expression))
        return false;
      try
      {
        // We're using an expression parser from "devilplusplus", "C# Eval function"
        // See http://www.codeproject.com/KB/dotnet/Expr.aspx
        // The parser was slightly adapted to our needs:
        // - To access a variable, the variable identifier has to be written in curly braces, for example:
        //   {0} + {1}

        Parser ep = new Parser();
        Evaluator evaluator = new Evaluator();
        ParameterVariableHolder pvh = new ParameterVariableHolder();

        // The used expression parser supports access to static functions for those of the parameters whose type is a class.
        // We could add classes here like the code commented out below. To access a static member on the string class,
        // the expression could be for example: {string}.{Empty}
        // For now, we don't need this functionality, so we don't add types (Albert, 2009-04-22).

        //pvh.Parameters["char"] = new Parameter(typeof(char));
        //pvh.Parameters["sbyte"] = new Parameter(typeof(sbyte));
        //pvh.Parameters["byte"] = new Parameter(typeof(byte));
        //pvh.Parameters["short"] = new Parameter(typeof(short)); 
        //pvh.Parameters["ushort"] = new Parameter(typeof(ushort)); 
        //pvh.Parameters["int"] = new Parameter(typeof(int));
        //pvh.Parameters["uint"] = new Parameter(typeof(uint));
        //pvh.Parameters["long"] = new Parameter(typeof(string));
        //pvh.Parameters["ulong"] = new Parameter(typeof(ulong));
        //pvh.Parameters["float"] = new Parameter(typeof(float));
        //pvh.Parameters["double"] = new Parameter(typeof(double));
        //pvh.Parameters["decimal"] = new Parameter(typeof(decimal));
        //pvh.Parameters["DateTime"] = new Parameter(typeof(DateTime));
        //pvh.Parameters["string"] = new Parameter(typeof(string));

        //pvh.Parameters["Guid"] = new Parameter(typeof(Guid));

        //pvh.Parameters["Convert"] = new Parameter(typeof(Convert));
        //pvh.Parameters["Math"] = new Parameter(typeof(Math));
        //pvh.Parameters["Array"] = new Parameter(typeof(Array));
        //pvh.Parameters["Random"] = new Parameter(typeof(Random));
        //pvh.Parameters["TimeZone"] = new Parameter(typeof(TimeZone));

        // Add child binding values
        for (int i = 0; i < values.Length; i++)
        {
          IDataDescriptor value = values[i];
          Type type = value.DataType;
          if (type != null && !pvh.Parameters.Contains(type.Name))
            pvh.Parameters[type.Name] = new Parameter(type);
          pvh.Parameters[i.ToString()] = new Parameter(value.Value, type);
        }
        evaluator.VariableHolder = pvh;
        Tree tree = ep.Parse(expression);
        result = evaluator.Eval(tree);
        return TypeConverter.Convert(result, targetType, out result);
      }
      catch (Exception)
      {
        return false;
      }
    }
 protected override double[] GetProbabilities(IDataDescriptor descriptor, PTSPData instance) {
   var random = new MarsagliaRandom(GetInstanceHash(instance.Name));
   return Enumerable.Range(0, instance.Dimension).Select(_ => (int)Math.Round((0.1 + 0.9 * random.NextDouble()) * 100) / 100.0).ToArray();
 }