context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
using System;
using System.Collections.Generic;
using System.Linq;
[System.Diagnostics.DebuggerDisplay("Count = {Count}")]
public sealed class SegmentTree<T>
: IReadOnlyList<T>
, IList<T>
{
public T Empty { get; }
public Func<T, T, T> Append { get; }
private readonly int _cacheCount;
private readonly int _itemCount;
/// <summary>
/// A complete binary tree.
/// The first <see cref="_cacheCount"/> items are inner nodes
/// whose value is cache of the query result.
/// The next <see cref="_itemCount"/> items are leaf nodes.
/// The rest are filled with <see cref="Empty"/>.
/// </summary>
private readonly T[] _nodes;
public SegmentTree(T[] nodes, int cacheCount, int itemCount, T empty, Func<T, T, T> append)
{
_nodes = nodes;
_cacheCount = cacheCount;
_itemCount = itemCount;
Empty = empty;
Append = append;
}
public int Count => _itemCount;
private int LeafCount => _nodes.Length - _cacheCount;
private void SetItem(int index, T item)
{
var i = _cacheCount + index;
_nodes[i] = item;
while (i != 0)
{
var parentIndex = (i - 1) / 2;
var childIndex = parentIndex * 2 + 1;
_nodes[parentIndex] = Append(_nodes[childIndex], _nodes[childIndex + 1]);
i = parentIndex;
}
}
public T this[int index]
{
get => (uint)index < (uint)Count
? _nodes[_cacheCount + index]
: throw new ArgumentOutOfRangeException(nameof(index));
set
{
if ((uint)index >= (uint)Count)
throw new ArgumentOutOfRangeException(nameof(index));
SetItem(index, value);
}
}
/// <summary>
/// Updates all items.
/// </summary>
public void CopyFrom(IReadOnlyList<T> list)
{
if (list.Count != _itemCount)
throw new ArgumentException();
for (var k = 0; k < _itemCount; k++)
{
_nodes[_cacheCount + k] = list[k];
}
for (var i = _cacheCount + _itemCount; i < _nodes.Length; i++)
{
_nodes[i] = Empty;
}
for (var i = _cacheCount - 1; i >= 0; i--)
{
var l = i * 2 + 1;
var r = i * 2 + 2;
_nodes[i] = Append(_nodes[l], _nodes[r]);
}
}
private T QueryCore(int i, int nl, int nr, int ql, int qr)
{
if (qr <= nl || nr <= ql)
return Empty;
if (ql <= nl && nr <= qr)
return _nodes[i];
var m = nl + (nr - nl) / 2;
var l = QueryCore(i * 2 + 1, nl, m, ql, qr);
var r = QueryCore(i * 2 + 2, m, nr, ql, qr);
return Append(l, r);
}
/// <summary>
/// Calculates the sum of items in the specified range.
/// </summary>
public T Query(int index, int count) =>
(uint)index > (uint)_itemCount ?
throw new ArgumentOutOfRangeException(nameof(index))
: count < 0 || index + count > _itemCount ?
throw new ArgumentOutOfRangeException(nameof(count))
: count == 0 ?
Empty
: QueryCore(0, 0, LeafCount, index, index + count);
/// <summary>
/// Gets the sum of items.
/// </summary>
public T Query() => _nodes[0];
#region IReadOnlyList<_>, IList<_>
private IEnumerator<T> GetEnumerator()
{
for (var i = 0; i < Count; i++)
{
yield return this[i];
}
}
private void CopyTo(T[] array, int index)
{
for (var i = 0; i < Count; i++)
{
array[index + i] = this[i];
}
}
private int IndexOf(T item)
{
for (var i = 0; i < Count; i++)
{
if (EqualityComparer<T>.Default.Equals(this[i], item))
return i;
}
return -1;
}
private bool Contains(T item) =>
IndexOf(item) >= 0;
IEnumerator<T> IEnumerable<T>.GetEnumerator() =>
GetEnumerator();
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() =>
((IEnumerable<T>)this).GetEnumerator();
int IReadOnlyCollection<T>.Count => Count;
T IReadOnlyList<T>.this[int index] => this[index];
bool ICollection<T>.IsReadOnly => false;
int ICollection<T>.Count => Count;
bool ICollection<T>.Contains(T item) => Contains(item);
void ICollection<T>.CopyTo(T[] array, int arrayIndex) =>
CopyTo(array, arrayIndex);
void ICollection<T>.Add(T item) =>
throw new NotSupportedException();
bool ICollection<T>.Remove(T item) =>
throw new NotSupportedException();
void ICollection<T>.Clear() =>
throw new NotSupportedException();
T IList<T>.this[int index]
{
get => this[index];
set => this[index] = value;
}
int IList<T>.IndexOf(T item) =>
IndexOf(item);
void IList<T>.Insert(int index, T item) =>
throw new NotSupportedException();
void IList<T>.RemoveAt(int index) =>
throw new NotSupportedException();
#endregion
}
public static class SegmentTree
{
private static int CalculateHeight(int count)
{
var h = 0;
while ((1 << h) < count)
{
h++;
}
return h;
}
public static SegmentTree<T> Create<T>(IEnumerable<T> items, T empty, Func<T, T, T> append)
{
var buffer = items as IReadOnlyList<T> ?? items.ToList();
var count = buffer.Count;
if (count == 0)
throw new NotSupportedException("Empty segment tree is not supported.");
var height = CalculateHeight(count);
var nodes = new T[(1 << height) * 2 - 1];
var innerNodeCount = (1 << height) - 1;
var tree = new SegmentTree<T>(nodes, innerNodeCount, count, empty, append);
tree.CopyFrom(buffer);
return tree;
}
public static SegmentTree<(bool ok, T value)> FromSemigroup<T>(IEnumerable<T> source, Func<T, T, T> append) =>
Create(
source.Select(value => (ok: true, value)),
default,
(opt1, opt2) => opt1.ok
? (opt2.ok ?
(true, append(opt1.value, opt2.value))
: opt1)
: opt2
);
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Linq.Impl
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Cache;
using Apache.Ignite.Core.Cache.Query;
using Apache.Ignite.Core.Impl.Cache;
using Apache.Ignite.Core.Impl.Common;
using Remotion.Linq;
/// <summary>
/// Fields query executor.
/// </summary>
internal class CacheFieldsQueryExecutor : IQueryExecutor
{
/** */
private readonly ICacheInternal _cache;
/** */
private readonly QueryOptions _options;
/** */
private static readonly CopyOnWriteConcurrentDictionary<ConstructorInfo, object> CtorCache =
new CopyOnWriteConcurrentDictionary<ConstructorInfo, object>();
/// <summary>
/// Initializes a new instance of the <see cref="CacheFieldsQueryExecutor" /> class.
/// </summary>
/// <param name="cache">The executor function.</param>
/// <param name="options">Query options.</param>
public CacheFieldsQueryExecutor(ICacheInternal cache, QueryOptions options)
{
Debug.Assert(cache != null);
Debug.Assert(options != null);
_cache = cache;
_options = options;
}
/** <inheritdoc /> */
public T ExecuteScalar<T>(QueryModel queryModel)
{
return ExecuteSingle<T>(queryModel, false);
}
/** <inheritdoc /> */
public T ExecuteSingle<T>(QueryModel queryModel, bool returnDefaultWhenEmpty)
{
var col = ExecuteCollection<T>(queryModel);
return returnDefaultWhenEmpty ? col.SingleOrDefault() : col.Single();
}
/** <inheritdoc /> */
[SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods")]
public IEnumerable<T> ExecuteCollection<T>(QueryModel queryModel)
{
Debug.Assert(queryModel != null);
var qryData = GetQueryData(queryModel);
Debug.WriteLine("\nFields Query: {0} | {1}", qryData.QueryText,
string.Join(", ", qryData.Parameters.Select(x => x == null ? "null" : x.ToString())));
var qry = GetFieldsQuery(qryData.QueryText, qryData.Parameters.ToArray());
var selector = GetResultSelector<T>(queryModel.SelectClause.Selector);
return _cache.Query(qry, selector);
}
/// <summary>
/// Compiles the query without regard to number or order of arguments.
/// </summary>
public Func<object[], IQueryCursor<T>> CompileQuery<T>(QueryModel queryModel)
{
Debug.Assert(queryModel != null);
var qryText = GetQueryData(queryModel).QueryText;
var selector = GetResultSelector<T>(queryModel.SelectClause.Selector);
return args => _cache.Query(GetFieldsQuery(qryText, args), selector);
}
/// <summary>
/// Compiles the query.
/// </summary>
/// <typeparam name="T">Result type.</typeparam>
/// <param name="queryModel">The query model.</param>
/// <param name="queryLambdaModel">The query model generated from lambda body.</param>
/// <param name="queryLambda">The query lambda.</param>
/// <returns>Compiled query func.</returns>
public Func<object[], IQueryCursor<T>> CompileQuery<T>(QueryModel queryModel, QueryModel queryLambdaModel,
LambdaExpression queryLambda)
{
Debug.Assert(queryModel != null);
// Get model from lambda to map arguments properly.
var qryData = GetQueryData(queryLambdaModel);
var qryText = GetQueryData(queryModel).QueryText;
var qryTextLambda = qryData.QueryText;
if (qryText != qryTextLambda)
{
Debug.WriteLine(qryText);
Debug.WriteLine(qryTextLambda);
throw new InvalidOperationException("Error compiling query: entire LINQ expression should be " +
"specified within lambda passed to Compile method. " +
"Part of the query can't be outside the Compile method call.");
}
var selector = GetResultSelector<T>(queryModel.SelectClause.Selector);
var qryParams = qryData.Parameters.ToArray();
// Compiled query is a delegate with query parameters
// Delegate parameters order and query parameters order may differ
// Simple case: lambda with no parameters. Only embedded parameters are used.
if (!queryLambda.Parameters.Any())
{
return argsUnused => _cache.Query(GetFieldsQuery(qryText, qryParams), selector);
}
// These are in order of usage in query
var qryOrderArgs = qryParams.OfType<ParameterExpression>().Select(x => x.Name).ToArray();
// These are in order they come from user
var userOrderArgs = queryLambda.Parameters.Select(x => x.Name).ToList();
// Simple case: all query args directly map to the lambda args in the same order
if (qryOrderArgs.Length == qryParams.Length
&& qryOrderArgs.SequenceEqual(userOrderArgs))
{
return args => _cache.Query(GetFieldsQuery(qryText, args), selector);
}
// General case: embedded args and lambda args are mixed; same args can be used multiple times.
// Produce a mapping that defines where query arguments come from.
var mapping = qryParams.Select(x =>
{
var pe = x as ParameterExpression;
if (pe != null)
return userOrderArgs.IndexOf(pe.Name);
return -1;
}).ToArray();
return args => _cache.Query(
GetFieldsQuery(qryText, MapQueryArgs(args, qryParams, mapping)), selector);
}
/// <summary>
/// Maps the query arguments.
/// </summary>
private static object[] MapQueryArgs(object[] userArgs, object[] embeddedArgs, int[] mapping)
{
var mappedArgs = new object[embeddedArgs.Length];
for (var i = 0; i < mappedArgs.Length; i++)
{
var map = mapping[i];
mappedArgs[i] = map < 0 ? embeddedArgs[i] : userArgs[map];
}
return mappedArgs;
}
/// <summary>
/// Gets the fields query.
/// </summary>
internal SqlFieldsQuery GetFieldsQuery(string text, object[] args)
{
return new SqlFieldsQuery(text)
{
EnableDistributedJoins = _options.EnableDistributedJoins,
PageSize = _options.PageSize,
EnforceJoinOrder = _options.EnforceJoinOrder,
Timeout = _options.Timeout,
#pragma warning disable 618
ReplicatedOnly = _options.ReplicatedOnly,
#pragma warning restore 618
Colocated = _options.Colocated,
Local = _options.Local,
Arguments = args,
Lazy = _options.Lazy,
UpdateBatchSize = _options.UpdateBatchSize,
Partitions = _options.Partitions
};
}
/// <summary>
/// Generates <see cref="QueryData"/> from specified <see cref="QueryModel"/>.
/// </summary>
public static QueryData GetQueryData(QueryModel queryModel)
{
Debug.Assert(queryModel != null);
return new CacheQueryModelVisitor().GenerateQuery(queryModel);
}
/// <summary>
/// Gets the result selector.
/// </summary>
private static Func<IBinaryRawReader, int, T> GetResultSelector<T>(Expression selectorExpression)
{
var newExpr = selectorExpression as NewExpression;
if (newExpr != null)
return GetCompiledCtor<T>(newExpr.Constructor);
var entryCtor = GetCacheEntryCtorInfo(typeof(T));
if (entryCtor != null)
return GetCompiledCtor<T>(entryCtor);
if (typeof(T) == typeof(bool))
return ReadBool<T>;
return (reader, count) => reader.ReadObject<T>();
}
/// <summary>
/// Reads the bool. Actual data may be bool or int/long.
/// </summary>
private static T ReadBool<T>(IBinaryRawReader reader, int count)
{
var obj = reader.ReadObject<object>();
if (obj is bool)
return (T) obj;
if (obj is long)
return TypeCaster<T>.Cast((long) obj != 0);
if (obj is int)
return TypeCaster<T>.Cast((int) obj != 0);
throw new InvalidOperationException("Expected bool, got: " + obj);
}
/// <summary>
/// Gets the cache entry constructor.
/// </summary>
private static ConstructorInfo GetCacheEntryCtorInfo(Type entryType)
{
if (!entryType.IsGenericType || entryType.GetGenericTypeDefinition() != typeof(ICacheEntry<,>))
return null;
var args = entryType.GetGenericArguments();
var targetType = typeof (CacheEntry<,>).MakeGenericType(args);
return targetType.GetConstructors().Single();
}
/// <summary>
/// Gets the compiled constructor.
/// </summary>
private static Func<IBinaryRawReader, int, T> GetCompiledCtor<T>(ConstructorInfo ctorInfo)
{
object result;
if (CtorCache.TryGetValue(ctorInfo, out result))
return (Func<IBinaryRawReader, int, T>) result;
return (Func<IBinaryRawReader, int, T>) CtorCache.GetOrAdd(ctorInfo, x =>
{
var innerCtor1 = DelegateConverter.CompileCtor<T>(x, GetCacheEntryCtorInfo);
return (Func<IBinaryRawReader, int, T>) ((r, c) => innerCtor1(r));
});
}
}
}
| |
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Reflection;
namespace WebsitePanel.VmConfig
{
/// <summary>
/// Log.
/// </summary>
internal sealed class ServiceLog
{
/// <summary>
/// Initializes a new instance of the class.
/// </summary>
private ServiceLog()
{
}
/// <summary>
/// Initializes trace listeners.
/// </summary>
static ServiceLog()
{
string fileName = LogFile;
FileStream fileLog = new FileStream(fileName, FileMode.Append);
TextWriterTraceListener fileListener = new TextWriterTraceListener(fileLog);
fileListener.TraceOutputOptions = TraceOptions.DateTime;
Trace.UseGlobalLock = true;
Trace.Listeners.Clear();
Trace.Listeners.Add(fileListener);
TextWriterTraceListener consoleListener = new TextWriterTraceListener(Console.Out);
Trace.Listeners.Add(consoleListener);
Trace.AutoFlush = true;
}
private static string LogFile
{
get
{
Assembly assembly = typeof(ServiceLog).Assembly;
return Path.Combine(Path.GetDirectoryName(assembly.Location), assembly.GetName().Name + ".log");
}
}
/// <summary>
/// Write error to the log.
/// </summary>
/// <param name="message">Error message.</param>
/// <param name="ex">Exception.</param>
internal static void WriteError(string message, Exception ex)
{
try
{
string line = string.Format("[{0:G}] ERROR: {1}", DateTime.Now, message);
Trace.WriteLine(line);
Trace.WriteLine(ex);
}
catch { }
}
/// <summary>
/// Write error to the log.
/// </summary>
/// <param name="message">Error message.</param>
internal static void WriteError(string message)
{
try
{
string line = string.Format("[{0:G}] ERROR: {1}", DateTime.Now, message);
Trace.WriteLine(line);
}
catch { }
}
/// <summary>
/// Write to log
/// </summary>
/// <param name="message"></param>
internal static void Write(string message)
{
try
{
string line = string.Format("[{0:G}] {1}", DateTime.Now, message);
Trace.Write(line);
}
catch { }
}
/// <summary>
/// Write line to log
/// </summary>
/// <param name="message"></param>
internal static void WriteLine(string message)
{
try
{
string line = string.Format("[{0:G}] {1}", DateTime.Now, message);
Trace.WriteLine(line);
}
catch { }
}
/// <summary>
/// Write info message to log
/// </summary>
/// <param name="message"></param>
internal static void WriteInfo(string message)
{
try
{
string line = string.Format("[{0:G}] INFO: {1}", DateTime.Now, message);
Trace.WriteLine(line);
}
catch { }
}
/// <summary>
/// Write start message to log
/// </summary>
/// <param name="message"></param>
internal static void WriteStart(string message)
{
try
{
string line = string.Format("[{0:G}] START: {1}", DateTime.Now, message);
Trace.WriteLine(line);
}
catch { }
}
/// <summary>
/// Write end message to log
/// </summary>
/// <param name="message"></param>
internal static void WriteEnd(string message)
{
try
{
string line = string.Format("[{0:G}] END: {1}", DateTime.Now, message);
Trace.WriteLine(line);
}
catch { }
}
internal static void WriteApplicationStart()
{
try
{
string name = typeof(ServiceLog).Assembly.GetName().Name;
string version = typeof(ServiceLog).Assembly.GetName().Version.ToString();
string line = string.Format("[{0:G}] APP: {1} {2} started successfully", DateTime.Now, name, version);
Trace.WriteLine(line);
}
catch { }
}
internal static void WriteApplicationStop()
{
try
{
string name = typeof(ServiceLog).Assembly.GetName().Name;
string version = typeof(ServiceLog).Assembly.GetName().Version.ToString();
string line = string.Format("[{0:G}] APP: {1} {2} stopped successfully", DateTime.Now, name, version);
Trace.WriteLine(line);
}
catch { }
}
/// <summary>
/// Opens notepad to view log file.
/// </summary>
public static void ShowLogFile()
{
try
{
string path = LogFile;
path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, path);
Process.Start("notepad.exe", path);
}
catch { }
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using GammaJul.ReSharper.ForTea.Tree;
using JetBrains.Annotations;
using JetBrains.Application.changes;
using JetBrains.Application.Threading;
using JetBrains.DocumentManagers;
using JetBrains.Lifetimes;
using JetBrains.ProjectModel;
using JetBrains.ProjectModel.Build;
using JetBrains.ProjectModel.model2.Assemblies.Interfaces;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.Psi.Modules;
using JetBrains.ReSharper.Resources.Shell;
using JetBrains.Util;
namespace GammaJul.ReSharper.ForTea.Psi {
/// <summary>
/// Manages <see cref="T4PsiModule"/> for T4 files.
/// Contains common implementation for <see cref="T4ProjectPsiModuleHandler"/> and <see cref="T4MiscFilesProjectPsiModuleProvider"/>.
/// </summary>
public sealed class T4PsiModuleProvider : IDisposable {
[NotNull] private readonly Dictionary<IProjectFile, ModuleWrapper> _modules = new Dictionary<IProjectFile, ModuleWrapper>();
private readonly Lifetime _lifetime;
[NotNull] private readonly IShellLocks _shellLocks;
[NotNull] private readonly ChangeManager _changeManager;
[NotNull] private readonly T4Environment _t4Environment;
private readonly struct ModuleWrapper {
[NotNull] public readonly T4PsiModule Module;
[NotNull] public readonly LifetimeDefinition LifetimeDefinition;
public ModuleWrapper([NotNull] T4PsiModule module, [NotNull] LifetimeDefinition lifetimeDefinition) {
Module = module;
LifetimeDefinition = lifetimeDefinition;
}
}
/// <summary>Gets all <see cref="T4PsiModule"/>s for opened files.</summary>
/// <returns>A collection of <see cref="T4PsiModule"/>.</returns>
[NotNull]
[ItemNotNull]
public IEnumerable<IPsiModule> GetModules() {
_shellLocks.AssertReadAccessAllowed();
return _modules.Values.Select(wrapper => (IPsiModule) wrapper.Module);
}
/// <summary>Gets all source files for a given project file.</summary>
/// <param name="projectFile">The project file whose source files will be returned.</param>
[NotNull]
[ItemNotNull]
public IList<IPsiSourceFile> GetPsiSourceFilesFor([CanBeNull] IProjectFile projectFile) {
_shellLocks.AssertReadAccessAllowed();
return projectFile != null
&& projectFile.IsValid()
&& _modules.TryGetValue(projectFile, out ModuleWrapper wrapper)
&& wrapper.Module.IsValid()
? new[] { wrapper.Module.SourceFile }
: EmptyList<IPsiSourceFile>.InstanceList;
}
/// <summary>Processes changes for specific project file and returns a list of corresponding source file changes.</summary>
/// <param name="projectFile">The project file.</param>
/// <param name="changeType">Type of the change.</param>
/// <param name="changeBuilder">The change builder used to populate changes.</param>
/// <returns>Whether the provider has handled the file change.</returns>
public bool OnProjectFileChanged(
[NotNull] IProjectFile projectFile,
ref PsiModuleChange.ChangeType changeType,
[NotNull] PsiModuleChangeBuilder changeBuilder
) {
if (!_t4Environment.IsSupported)
return false;
_shellLocks.AssertWriteAccessAllowed();
ModuleWrapper moduleWrapper;
switch (changeType) {
case PsiModuleChange.ChangeType.Added:
// Preprocessed .tt files should be handled by R# itself as if it's a normal project file,
// so that it has access to the current project types.
if (projectFile.LanguageType.Is<T4ProjectFileType>() && !projectFile.IsPreprocessedT4Template()) {
AddFile(projectFile, changeBuilder);
return true;
}
break;
case PsiModuleChange.ChangeType.Removed:
if (_modules.TryGetValue(projectFile, out moduleWrapper)) {
RemoveFile(projectFile, changeBuilder, moduleWrapper);
return true;
}
break;
case PsiModuleChange.ChangeType.Modified:
if (_modules.TryGetValue(projectFile, out moduleWrapper)) {
if (!projectFile.IsPreprocessedT4Template()) {
ModifyFile(changeBuilder, moduleWrapper);
return true;
}
// The T4 file went from Transformed to Preprocessed, it doesn't need a T4PsiModule anymore.
RemoveFile(projectFile, changeBuilder, moduleWrapper);
changeType = PsiModuleChange.ChangeType.Added;
return false;
}
// The T4 file went from Preprocessed to Transformed, it now needs a T4PsiModule.
if (projectFile.LanguageType.Is<T4ProjectFileType>() && !projectFile.IsPreprocessedT4Template()) {
AddFile(projectFile, changeBuilder);
changeType = PsiModuleChange.ChangeType.Removed;
return false;
}
break;
}
return false;
}
private void AddFile([NotNull] IProjectFile projectFile, [NotNull] PsiModuleChangeBuilder changeBuilder) {
ISolution solution = projectFile.GetSolution();
// creates a new T4PsiModule for the file
LifetimeDefinition lifetimeDefinition = Lifetime.Define(_lifetime, "[T4]" + projectFile.Name);
var psiModule = new T4PsiModule(
lifetimeDefinition.Lifetime,
solution.GetComponent<IPsiModules>(),
solution.GetComponent<DocumentManager>(),
_changeManager,
solution.GetComponent<IAssemblyFactory>(),
_shellLocks,
projectFile,
solution.GetComponent<T4FileDataCache>(),
_t4Environment,
solution.GetComponent<OutputAssemblies>()
);
_modules[projectFile] = new ModuleWrapper(psiModule, lifetimeDefinition);
changeBuilder.AddModuleChange(psiModule, PsiModuleChange.ChangeType.Added);
changeBuilder.AddFileChange(psiModule.SourceFile, PsiModuleChange.ChangeType.Added);
// Invalidate files that had this specific files as an include,
// and whose IPsiSourceFile was previously managed by T4OutsideSolutionSourceFileManager.
// Those files will be reparsed with the new source file.
var fileManager = solution.GetComponent<T4OutsideSolutionSourceFileManager>();
FileSystemPath location = projectFile.Location;
if (fileManager.HasSourceFile(location)) {
fileManager.DeleteSourceFile(location);
InvalidateFilesHavingInclude(location, solution.GetPsiServices());
}
}
private void RemoveFile([NotNull] IProjectFile projectFile, [NotNull] PsiModuleChangeBuilder changeBuilder, ModuleWrapper moduleWrapper) {
_modules.Remove(projectFile);
changeBuilder.AddFileChange(moduleWrapper.Module.SourceFile, PsiModuleChange.ChangeType.Removed);
changeBuilder.AddModuleChange(moduleWrapper.Module, PsiModuleChange.ChangeType.Removed);
InvalidateFilesHavingInclude(projectFile.Location, moduleWrapper.Module.GetPsiServices());
moduleWrapper.LifetimeDefinition.Terminate();
}
private static void ModifyFile([NotNull] PsiModuleChangeBuilder changeBuilder, ModuleWrapper moduleWrapper)
=> changeBuilder.AddFileChange(moduleWrapper.Module.SourceFile, PsiModuleChange.ChangeType.Modified);
private void InvalidateFilesHavingInclude([NotNull] FileSystemPath includeLocation, [NotNull] IPsiServices psiServices) {
psiServices.GetComponent<T4FileDependencyManager>().UpdateIncludes(includeLocation, EmptyList<FileSystemPath>.InstanceList);
foreach (ModuleWrapper moduleWrapper in _modules.Values) {
IPsiSourceFile sourceFile = moduleWrapper.Module.SourceFile;
if (sourceFile.GetTheOnlyPsiFile(T4Language.Instance) is IT4File t4File
&& t4File.GetNonEmptyIncludePaths().Any(path => path == includeLocation))
psiServices.MarkAsDirty(sourceFile);
}
}
public void Dispose() {
using (WriteLockCookie.Create()) {
foreach (var wrapper in _modules.Values)
wrapper.LifetimeDefinition.Terminate();
_modules.Clear();
}
}
public T4PsiModuleProvider(
Lifetime lifetime,
[NotNull] IShellLocks shellLocks,
[NotNull] ChangeManager changeManager,
[NotNull] T4Environment t4Environment
) {
_lifetime = lifetime;
_shellLocks = shellLocks;
_changeManager = changeManager;
_t4Environment = t4Environment;
}
}
}
| |
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/
// Portions Copyright 2000-2004 Jonathan de Halleux
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using Gallio.Common.Collections;
using Gallio.Common.Diagnostics;
using Gallio.Common.Markup;
using MbUnit.Framework;
namespace Gallio.Tests.Common.Diagnostics
{
[TestsOn(typeof(ExceptionData))]
public class ExceptionDataTest
{
[Test, ExpectedArgumentNullException]
public void ConstructorThrowsIfExceptionIsNull()
{
new ExceptionData(null);
}
[Test, ExpectedArgumentNullException]
public void ConstructorThrowsIfTypeIsNull()
{
new ExceptionData(null, "message", "stacktrace", ExceptionData.NoProperties, null);
}
[Test, ExpectedArgumentNullException]
public void ConstructorThrowsIfMessageIsNull()
{
new ExceptionData("type", null, "stacktrace", ExceptionData.NoProperties, null);
}
[Test, ExpectedArgumentNullException]
public void ConstructorThrowsIfStackTraceIsNull()
{
new ExceptionData("type", "message", (string)null, ExceptionData.NoProperties, null);
}
[Test, ExpectedArgumentNullException]
public void ConstructorThrowsIfStackTraceDataIsNull()
{
new ExceptionData("type", "message", (StackTraceData)null, ExceptionData.NoProperties, null);
}
[Test, ExpectedArgumentNullException]
public void ConstructorThrowsIfPropertiesIsNull()
{
new ExceptionData("type", "message", "stacktrace", null, null);
}
[Test]
public void PopulatesPropertiesFromException()
{
Exception inner = new Exception("Foo");
PopulateStackTrace(inner);
SampleException outer = new SampleException("Bar", inner)
{
Prop1 = "Value1",
Prop2 = "Value2"
};
PopulateStackTrace(outer);
ExceptionData outerData = new ExceptionData(outer);
Assert.AreEqual(outer.GetType().FullName, outerData.Type);
Assert.AreEqual(outer.Message, outerData.Message);
Assert.AreEqual(new PropertySet() {
{ "Prop1", "Value1" },
{ "Prop2", "Value2" }
}, outerData.Properties);
Assert.AreEqual(outer.StackTrace, outerData.StackTrace.ToString());
Assert.IsNotNull(outerData.InnerException);
ExceptionData innerData = outerData.InnerException;
Assert.AreEqual(inner.GetType().FullName, innerData.Type);
Assert.AreEqual(inner.Message, innerData.Message);
Assert.AreEqual(inner.StackTrace, innerData.StackTrace.ToString());
Assert.IsNull(innerData.InnerException);
}
[Test]
public void PopulatesPropertiesFromRawValues()
{
ExceptionData innerData = new ExceptionData("type", "message", "stacktrace", ExceptionData.NoProperties, null);
ExceptionData outerData = new ExceptionData("type", "message", "stacktrace",
new PropertySet() {
{ "Prop1", "Value1" },
{ "Prop2", "Value2" }
}, innerData);
Assert.AreEqual("type", innerData.Type);
Assert.AreEqual("message", innerData.Message);
Assert.AreEqual("stacktrace", innerData.StackTrace.ToString());
Assert.IsNull(innerData.InnerException);
Assert.AreEqual("type", outerData.Type);
Assert.AreEqual("message", outerData.Message);
Assert.AreEqual("stacktrace", outerData.StackTrace.ToString());
Assert.AreEqual(new PropertySet() {
{ "Prop1", "Value1" },
{ "Prop2", "Value2" }
}, outerData.Properties);
Assert.AreSame(innerData, outerData.InnerException);
}
[Test]
public void WriteToThrowsIfArgumentIsNull()
{
ExceptionData data = new ExceptionData("type", "message", "stacktrace", ExceptionData.NoProperties, null);
Assert.Throws<ArgumentNullException>(() => data.WriteTo(null));
}
[Test]
public void ToStringBareBones()
{
ExceptionData data = new ExceptionData("type", "message", "stacktrace", ExceptionData.NoProperties, null);
Assert.AreEqual("type: message\nstacktrace",
data.ToString());
}
[Test]
[Row(false), Row(true)]
public void ToStringEverything(bool useStandardFormatting)
{
ExceptionData innerData = new ExceptionData("type", "message", "stacktrace", ExceptionData.NoProperties, null);
ExceptionData outerData = new ExceptionData("type", "message", "stacktrace",
new PropertySet() {
{ "Prop1", "Value1" },
{ "Prop2", "Value2" }
}, innerData);
Assert.AreEqual("type: message ---> type: message\n"
+ "stacktrace\n --- End of inner exception stack trace ---\n"
+ (useStandardFormatting ? "" : "Prop1: Value1\nProp2: Value2\n")
+ "stacktrace",
outerData.ToString(useStandardFormatting));
}
[Test]
public void WriteToBareBones()
{
ExceptionData data = new ExceptionData("type", "message", "stacktrace", ExceptionData.NoProperties, null);
StringMarkupDocumentWriter writer = new StringMarkupDocumentWriter(true);
data.WriteTo(writer.Failures);
Assert.AreEqual("[Marker \'Exception\'][Marker \'ExceptionType\']type[End]: [Marker \'ExceptionMessage\']message[End]\n[Marker \'StackTrace\']stacktrace[End][End]",
writer.ToString());
}
[Test]
[Row(false), Row(true)]
public void WriteToEverything(bool useStandardFormatting)
{
ExceptionData innerData = new ExceptionData("type", "message", "stacktrace", ExceptionData.NoProperties, null);
ExceptionData outerData = new ExceptionData("type", "message", "stacktrace",
new PropertySet() {
{ "Prop1", "Value1" },
{ "Prop2", "Value2" }
}, innerData);
StringMarkupDocumentWriter writer = new StringMarkupDocumentWriter(true);
outerData.WriteTo(writer.Failures, useStandardFormatting);
Assert.AreEqual("[Marker \'Exception\'][Marker \'ExceptionType\']type[End]: [Marker \'ExceptionMessage\']message[End] ---> [Marker \'Exception\'][Marker \'ExceptionType\']type[End]: [Marker \'ExceptionMessage\']message[End]\n"
+ "[Marker \'StackTrace\']stacktrace[End][End]\n --- End of inner exception stack trace ---\n"
+ (useStandardFormatting ? "" : "[Marker \'ExceptionPropertyName\']Prop1[End]: [Marker \'ExceptionPropertyValue\']Value1[End]\n[Marker \'ExceptionPropertyName\']Prop2[End]: [Marker \'ExceptionPropertyValue\']Value2[End]\n")
+ "[Marker \'StackTrace\']stacktrace[End][End]",
writer.ToString());
}
private static void PopulateStackTrace(Exception ex)
{
try
{
throw ex;
}
catch
{
}
}
private class SampleException : Exception
{
public SampleException(string message, Exception innerException)
: base(message, innerException)
{
}
public object Prop1 { get; set; }
public string Prop2 { get; set; }
// will be ignored because the value is null
public string PropNull { get { return null; } }
// will be ignored because of the attribute
[SystemInternal]
public object PropInternal { get; set; }
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void ShiftRightLogicalUInt321()
{
var test = new SimpleUnaryOpTest__ShiftRightLogicalUInt321();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleUnaryOpTest__ShiftRightLogicalUInt321
{
private const int VectorSize = 16;
private const int Op1ElementCount = VectorSize / sizeof(UInt32);
private const int RetElementCount = VectorSize / sizeof(UInt32);
private static UInt32[] _data = new UInt32[Op1ElementCount];
private static Vector128<UInt32> _clsVar;
private Vector128<UInt32> _fld;
private SimpleUnaryOpTest__DataTable<UInt32, UInt32> _dataTable;
static SimpleUnaryOpTest__ShiftRightLogicalUInt321()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (uint)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar), ref Unsafe.As<UInt32, byte>(ref _data[0]), VectorSize);
}
public SimpleUnaryOpTest__ShiftRightLogicalUInt321()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (uint)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld), ref Unsafe.As<UInt32, byte>(ref _data[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (uint)(random.Next(0, int.MaxValue)); }
_dataTable = new SimpleUnaryOpTest__DataTable<UInt32, UInt32>(_data, new UInt32[RetElementCount], VectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse2.ShiftRightLogical(
Unsafe.Read<Vector128<UInt32>>(_dataTable.inArrayPtr),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Sse2.ShiftRightLogical(
Sse2.LoadVector128((UInt32*)(_dataTable.inArrayPtr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse2.ShiftRightLogical(
Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArrayPtr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftRightLogical), new Type[] { typeof(Vector128<UInt32>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<UInt32>>(_dataTable.inArrayPtr),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftRightLogical), new Type[] { typeof(Vector128<UInt32>), typeof(byte) })
.Invoke(null, new object[] {
Sse2.LoadVector128((UInt32*)(_dataTable.inArrayPtr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftRightLogical), new Type[] { typeof(Vector128<UInt32>), typeof(byte) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArrayPtr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Sse2.ShiftRightLogical(
_clsVar,
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var firstOp = Unsafe.Read<Vector128<UInt32>>(_dataTable.inArrayPtr);
var result = Sse2.ShiftRightLogical(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var firstOp = Sse2.LoadVector128((UInt32*)(_dataTable.inArrayPtr));
var result = Sse2.ShiftRightLogical(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var firstOp = Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArrayPtr));
var result = Sse2.ShiftRightLogical(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleUnaryOpTest__ShiftRightLogicalUInt321();
var result = Sse2.ShiftRightLogical(test._fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Sse2.ShiftRightLogical(_fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<UInt32> firstOp, void* result, [CallerMemberName] string method = "")
{
UInt32[] inArray = new UInt32[Op1ElementCount];
UInt32[] outArray = new UInt32[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
UInt32[] inArray = new UInt32[Op1ElementCount];
UInt32[] outArray = new UInt32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(UInt32[] firstOp, UInt32[] result, [CallerMemberName] string method = "")
{
if ((uint)(firstOp[0] >> 1) != result[0])
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((uint)(firstOp[i] >> 1) != result[i])
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.ShiftRightLogical)}<UInt32>(Vector128<UInt32><9>): {method} failed:");
Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
using System;
using Glass.Mapper.Sc.Configuration;
using Glass.Mapper.Sc.DataMappers;
using NUnit.Framework;
using Sitecore.Data;
namespace Glass.Mapper.Sc.FakeDb.DataMappers
{
[TestFixture]
public class SitecoreFieldNullableEnumMapperFixture : AbstractMapperFixture
{
#region Method - GetField
[Test]
public void GetField_FieldContainsValidEnum_ReturnsEnum()
{
//Assign
string fieldValue = "Value1";
StubEnum expected = StubEnum.Value1;
var fieldId = Guid.NewGuid();
var item = Helpers.CreateFakeItem(fieldId, fieldValue);
var field = item.Fields[new ID(fieldId)];
var config = new SitecoreFieldConfiguration();
config.PropertyInfo = typeof (Stub).GetProperty("Property");
var mapper = new SitecoreFieldNullableEnumMapper();
//Act
var result = (StubEnum?)mapper.GetField(field, config, null);
//Assert
Assert.IsTrue(result.HasValue);
Assert.AreEqual(expected, result.Value);
}
[Test]
public void GetField_FieldContainsValidEnumInLowercase_ReturnsEnum()
{
//Assign
string fieldValue = "value1";
StubEnum expected = StubEnum.Value1;
var fieldId = Guid.NewGuid();
var item = Helpers.CreateFakeItem(fieldId, fieldValue);
var field = item.Fields[new ID(fieldId)];
var config = new SitecoreFieldConfiguration();
config.PropertyInfo = typeof(Stub).GetProperty("Property");
var mapper = new SitecoreFieldNullableEnumMapper();
//Act
var result = (StubEnum?)mapper.GetField(field, config, null);
//Assert
Assert.IsTrue(result.HasValue);
Assert.AreEqual(expected, result.Value);
}
[Test]
public void GetField_FieldContainsValidEnumInteger_ReturnsEnum()
{
//Assign
string fieldValue = "2";
StubEnum expected = StubEnum.Value2;
var fieldId = Guid.NewGuid();
var item = Helpers.CreateFakeItem(fieldId, fieldValue);
var field = item.Fields[new ID(fieldId)];
var config = new SitecoreFieldConfiguration();
config.PropertyInfo = typeof(Stub).GetProperty("Property");
var mapper = new SitecoreFieldNullableEnumMapper();
//Act
var result = (StubEnum?)mapper.GetField(field, config, null);
//Assert
Assert.IsTrue(result.HasValue);
Assert.AreEqual(expected, result.Value);
}
[Test]
public void GetField_FieldContainsEmptyString_ReturnsNull()
{
//Assign
string fieldValue = string.Empty;
var fieldId = Guid.NewGuid();
var item = Helpers.CreateFakeItem(fieldId, fieldValue);
var field = item.Fields[new ID(fieldId)];
var config = new SitecoreFieldConfiguration();
config.PropertyInfo = typeof(Stub).GetProperty("Property");
var mapper = new SitecoreFieldNullableEnumMapper();
//Act
var result = (StubEnum?)mapper.GetField(field, config, null);
//Assert
Assert.IsNull(result);
}
[Test]
public void GetField_FieldContainsInvalidValidEnum_ThrowsException()
{
//Assign
string fieldValue = "hello world";
var fieldId = Guid.NewGuid();
var item = Helpers.CreateFakeItem(fieldId, fieldValue);
var field = item.Fields[new ID(fieldId)];
var config = new SitecoreFieldConfiguration();
config.PropertyInfo = typeof(Stub).GetProperty("Property");
var mapper = new SitecoreFieldNullableEnumMapper();
//Act
Assert.Throws<MapperException>(() =>
{
var result = (StubEnum?) mapper.GetField(field, config, null);
});
//Assert
}
#endregion
#region Method - SetField
[Test]
public void SetField_ObjectisValidEnum_SetsFieldValue()
{
//Assign
string expected = "Value2";
StubEnum objectValue = StubEnum.Value2;
var fieldId = Guid.NewGuid();
var item = Helpers.CreateFakeItem(fieldId, string.Empty);
var field = item.Fields[new ID(fieldId)];
var config = new SitecoreFieldConfiguration();
config.PropertyInfo = typeof(Stub).GetProperty("Property");
var mapper = new SitecoreFieldNullableEnumMapper();
item.Editing.BeginEdit();
//Act
mapper.SetField(field, objectValue, config, null);
//Assert
Assert.AreEqual(expected, field.Value);
}
[Test]
public void SetField_ObjectIsInt_ThrowsException()
{
//Assign
string objectValue = "hello world";
var fieldId = Guid.NewGuid();
var item = Helpers.CreateFakeItem(fieldId, string.Empty);
var field = item.Fields[new ID(fieldId)];
var config = new SitecoreFieldConfiguration();
config.PropertyInfo = typeof(Stub).GetProperty("Property");
var mapper = new SitecoreFieldNullableEnumMapper();
//Act
Assert.Throws<ArgumentException>(() =>
{
mapper.SetField(field, objectValue, config, null);
});
//Assert
}
#endregion
#region Method - CanHandle
[Test]
public void CanHandle_PropertyIsNullableEnum_ReturnsTrue()
{
//Assign
var config = new SitecoreFieldConfiguration();
config.PropertyInfo = typeof (Stub).GetProperty("Property");
var mapper = new SitecoreFieldNullableEnumMapper();
//Act
var result = mapper.CanHandle(config, null);
//Assert
Assert.IsTrue(result);
}
[Test]
public void CanHandle_PropertyIsNotNullableEnum_ReturnsFalse()
{
//Assign
var config = new SitecoreFieldConfiguration();
config.PropertyInfo = typeof(Stub).GetProperty("PropertyNotNullableEnum");
var mapper = new SitecoreFieldNullableEnumMapper();
//Act
var result = mapper.CanHandle(config, null);
//Assert
Assert.IsFalse(result);
}
#endregion
#region Stub
public enum StubEnum
{
Value1 =1,
Value2 = 2
}
public class Stub
{
public StubEnum? Property { get; set; }
public StubEnum PropertyNotNullableEnum { get; set; }
}
#endregion
}
}
| |
using System;
using NUnit.Framework;
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Asn1.Nist;
using Org.BouncyCastle.Asn1.Oiw;
using Org.BouncyCastle.Asn1.Pkcs;
using Org.BouncyCastle.Asn1.TeleTrust;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities;
using Org.BouncyCastle.Utilities.Encoders;
using Org.BouncyCastle.Utilities.Test;
namespace Org.BouncyCastle.Tests
{
[TestFixture]
public class RsaTest
: SimpleTest
{
/**
* a fake random number generator - we just want to make sure the random numbers
* aren't random so that we get the same output, while still getting to test the
* key generation facilities.
*/
// TODO Use FixedSecureRandom instead?
private class MyFixedSecureRandom
: SecureRandom
{
byte[] seed =
{
(byte)0xaa, (byte)0xfd, (byte)0x12, (byte)0xf6, (byte)0x59,
(byte)0xca, (byte)0xe6, (byte)0x34, (byte)0x89, (byte)0xb4,
(byte)0x79, (byte)0xe5, (byte)0x07, (byte)0x6d, (byte)0xde,
(byte)0xc2, (byte)0xf0, (byte)0x6c, (byte)0xb5, (byte)0x8f
};
public override void NextBytes(
byte[] bytes)
{
int offset = 0;
while ((offset + seed.Length) < bytes.Length)
{
seed.CopyTo(bytes, offset);
offset += seed.Length;
}
Array.Copy(seed, 0, bytes, offset, bytes.Length - offset);
}
}
private static readonly byte[] seed =
{
(byte)0xaa, (byte)0xfd, (byte)0x12, (byte)0xf6, (byte)0x59,
(byte)0xca, (byte)0xe6, (byte)0x34, (byte)0x89, (byte)0xb4,
(byte)0x79, (byte)0xe5, (byte)0x07, (byte)0x6d, (byte)0xde,
(byte)0xc2, (byte)0xf0, (byte)0x6c, (byte)0xb5, (byte)0x8f
};
private RsaKeyParameters pubKeySpec = new RsaKeyParameters(
false,
new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16),
new BigInteger("11", 16));
private RsaPrivateCrtKeyParameters privKeySpec = new RsaPrivateCrtKeyParameters(
new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16),
new BigInteger("11", 16),
new BigInteger("9f66f6b05410cd503b2709e88115d55daced94d1a34d4e32bf824d0dde6028ae79c5f07b580f5dce240d7111f7ddb130a7945cd7d957d1920994da389f490c89", 16),
new BigInteger("c0a0758cdf14256f78d4708c86becdead1b50ad4ad6c5c703e2168fbf37884cb", 16),
new BigInteger("f01734d7960ea60070f1b06f2bb81bfac48ff192ae18451d5e56c734a5aab8a5", 16),
new BigInteger("b54bb9edff22051d9ee60f9351a48591b6500a319429c069a3e335a1d6171391", 16),
new BigInteger("d3d83daf2a0cecd3367ae6f8ae1aeb82e9ac2f816c6fc483533d8297dd7884cd", 16),
new BigInteger("b8f52fc6f38593dabb661d3f50f8897f8106eee68b1bce78a95b132b4e5b5d19", 16));
private RsaKeyParameters isoPubKeySpec = new RsaKeyParameters(
false,
new BigInteger("0100000000000000000000000000000000bba2d15dbb303c8a21c5ebbcbae52b7125087920dd7cdf358ea119fd66fb064012ec8ce692f0a0b8e8321b041acd40b7", 16),
new BigInteger("03", 16));
private RsaKeyParameters isoPrivKeySpec = new RsaKeyParameters(
true,
new BigInteger("0100000000000000000000000000000000bba2d15dbb303c8a21c5ebbcbae52b7125087920dd7cdf358ea119fd66fb064012ec8ce692f0a0b8e8321b041acd40b7", 16),
new BigInteger("2aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaac9f0783a49dd5f6c5af651f4c9d0dc9281c96a3f16a85f9572d7cc3f2d0f25a9dbf1149e4cdc32273faadd3fda5dcda7", 16));
internal static RsaKeyParameters pub2048KeySpec = new RsaKeyParameters(
false,
new BigInteger("a7295693155b1813bb84877fb45343556e0568043de5910872a3a518cc11e23e2db74eaf4545068c4e3d258a2718fbacdcc3eafa457695b957e88fbf110aed049a992d9c430232d02f3529c67a3419935ea9b569f85b1bcd37de6b899cd62697e843130ff0529d09c97d813cb15f293751ff56f943fbdabb63971cc7f4f6d5bff1594416b1f5907bde5a84a44f9802ef29b43bda1960f948f8afb8766c1ab80d32eec88ed66d0b65aebe44a6d0b3c5e0ab051aaa1b912fbcc17b8e751ddecc5365b6db6dab0020c3057db4013a51213a5798a3aab67985b0f4d88627a54a0f3f0285fbcb4afdfeb65cb153af66825656d43238b75503231500753f4e421e3c57", 16),
new BigInteger("10001", 16));
internal static RsaPrivateCrtKeyParameters priv2048KeySpec = new RsaPrivateCrtKeyParameters(
new BigInteger("a7295693155b1813bb84877fb45343556e0568043de5910872a3a518cc11e23e2db74eaf4545068c4e3d258a2718fbacdcc3eafa457695b957e88fbf110aed049a992d9c430232d02f3529c67a3419935ea9b569f85b1bcd37de6b899cd62697e843130ff0529d09c97d813cb15f293751ff56f943fbdabb63971cc7f4f6d5bff1594416b1f5907bde5a84a44f9802ef29b43bda1960f948f8afb8766c1ab80d32eec88ed66d0b65aebe44a6d0b3c5e0ab051aaa1b912fbcc17b8e751ddecc5365b6db6dab0020c3057db4013a51213a5798a3aab67985b0f4d88627a54a0f3f0285fbcb4afdfeb65cb153af66825656d43238b75503231500753f4e421e3c57", 16),
new BigInteger("10001", 16),
new BigInteger("65dad56ac7df7abb434e4cb5eeadb16093aa6da7f0033aad3815289b04757d32bfee6ade7749c8e4a323b5050a2fb9e2a99e23469e1ed4ba5bab54336af20a5bfccb8b3424cc6923db2ffca5787ed87aa87aa614cd04cedaebc8f623a2d2063017910f436dff18bb06f01758610787f8b258f0a8efd8bd7de30007c47b2a1031696c7d6523bc191d4d918927a7e0b09584ed205bd2ff4fc4382678df82353f7532b3bbb81d69e3f39070aed3fb64fce032a089e8e64955afa5213a6eb241231bd98d702fba725a9b205952fda186412d9e0d9344d2998c455ad8c2bae85ee672751466d5288304032b5b7e02f7e558c7af82c7fbf58eea0bb4ef0f001e6cd0a9", 16),
new BigInteger("d4fd9ac3474fb83aaf832470643609659e511b322632b239b688f3cd2aad87527d6cf652fb9c9ca67940e84789444f2e99b0cb0cfabbd4de95396106c865f38e2fb7b82b231260a94df0e01756bf73ce0386868d9c41645560a81af2f53c18e4f7cdf3d51d80267372e6e0216afbf67f655c9450769cca494e4f6631b239ce1b", 16),
new BigInteger("c8eaa0e2a1b3a4412a702bccda93f4d150da60d736c99c7c566fdea4dd1b401cbc0d8c063daaf0b579953d36343aa18b33dbf8b9eae94452490cc905245f8f7b9e29b1a288bc66731a29e1dd1a45c9fd7f8238ff727adc49fff73991d0dc096206b9d3a08f61e7462e2b804d78cb8c5eccdb9b7fbd2ad6a8fea46c1053e1be75", 16),
new BigInteger("10edcb544421c0f9e123624d1099feeb35c72a8b34e008ac6fa6b90210a7543f293af4e5299c8c12eb464e70092805c7256e18e5823455ba0f504d36f5ccacac1b7cd5c58ff710f9c3f92646949d88fdd1e7ea5fed1081820bb9b0d2a8cd4b093fecfdb96dabd6e28c3a6f8c186dc86cddc89afd3e403e0fcf8a9e0bcb27af0b", 16),
new BigInteger("97fc25484b5a415eaa63c03e6efa8dafe9a1c8b004d9ee6e80548fefd6f2ce44ee5cb117e77e70285798f57d137566ce8ea4503b13e0f1b5ed5ca6942537c4aa96b2a395782a4cb5b58d0936e0b0fa63b1192954d39ced176d71ef32c6f42c84e2e19f9d4dd999c2151b032b97bd22aa73fd8c5bcd15a2dca4046d5acc997021", 16),
new BigInteger("4bb8064e1eff7e9efc3c4578fcedb59ca4aef0993a8312dfdcb1b3decf458aa6650d3d0866f143cbf0d3825e9381181170a0a1651eefcd7def786b8eb356555d9fa07c85b5f5cbdd74382f1129b5e36b4166b6cc9157923699708648212c484958351fdc9cf14f218dbe7fbf7cbd93a209a4681fe23ceb44bab67d66f45d1c9d", 16));
public override void PerformTest()
{
byte[] input = new byte[]
{ (byte)0x54, (byte)0x85, (byte)0x9b, (byte)0x34, (byte)0x2c, (byte)0x49, (byte)0xea, (byte)0x2a };
byte[][] output = new byte[][]
{
Hex.Decode("8b427f781a2e59dd9def386f1956b996ee07f48c96880e65a368055ed8c0a8831669ef7250b40918b2b1d488547e72c84540e42bd07b03f14e226f04fbc2d929"),
Hex.Decode("2ec6e1a1711b6c7b8cd3f6a25db21ab8bb0a5f1d6df2ef375fa708a43997730ffc7c98856dbbe36edddcdd1b2d2a53867d8355af94fea3aeec128da908e08f4c"),
Hex.Decode("0850ac4e5a8118323200c8ed1e5aaa3d5e635172553ccac66a8e4153d35c79305c4440f11034ab147fccce21f18a50cf1c0099c08a577eb68237a91042278965"),
Hex.Decode("1c9649bdccb51056751fe43837f4eb43bada472accf26f65231666d5de7d11950d8379b3596dfdf75c6234274896fa8d18ad0865d3be2ac4d6687151abdf01e93941dcef18fa63186c9351d1506c89d09733c5ff4304208c812bdd21a50f56fde115e629e0e973721c9fcc87e89295a79853dee613962a0b2f2fc57163fd99057a3c776f13c20c26407eb8863998d7e53b543ba8d0a295a9a68d1a149833078c9809ad6a6dad7fc22a95ad615a73138c54c018f40d99bf8eeecd45f5be526f2d6b01aeb56381991c1ab31a2e756f15e052b9cd5638b2eff799795c5bae493307d5eb9f8c21d438de131fe505a4e7432547ab19224094f9e4be1968bd0793b79d"),
Hex.Decode("4c4afc0c24dddaedd4f9a3b23be30d35d8e005ffd36b3defc5d18acc830c3ed388ce20f43a00e614fd087c814197bc9fc2eff9ad4cc474a7a2ef3ed9c0f0a55eb23371e41ee8f2e2ed93ea3a06ca482589ab87e0d61dcffda5eea1241408e43ea1108726cdb87cc3aa5e9eaaa9f72507ca1352ac54a53920c94dccc768147933d8c50aefd9d1da10522a40133cd33dbc0524669e70f771a88d65c4716d471cd22b08b9f01f24e4e9fc7ffbcfa0e0a7aed47b345826399b26a73be112eb9c5e06fc6742fc3d0ef53d43896403c5105109cfc12e6deeaf4a48ba308e039774b9bdb31a9b9e133c81c321630cf0b4b2d1f90717b24c3268e1fea681ea9cdc709342"),
Hex.Decode("06b5b26bd13515f799e5e37ca43cace15cd82fd4bf36b25d285a6f0998d97c8cb0755a28f0ae66618b1cd03e27ac95eaaa4882bc6dc0078cd457d4f7de4154173a9c7a838cfc2ac2f74875df462aae0cfd341645dc51d9a01da9bdb01507f140fa8a016534379d838cc3b2a53ac33150af1b242fc88013cb8d914e66c8182864ee6de88ce2879d4c05dd125409620a96797c55c832fb2fb31d4310c190b8ed2c95fdfda2ed87f785002faaec3f35ec05cf70a3774ce185e4882df35719d582dd55ac31257344a9cba95189dcbea16e8c6cb7a235a0384bc83b6183ca8547e670fe33b1b91725ae0c250c9eca7b5ba78bd77145b70270bf8ac31653006c02ca9c"),
Hex.Decode("135f1be3d045526235bf9d5e43499d4ee1bfdf93370769ae56e85dbc339bc5b7ea3bee49717497ee8ac3f7cd6adb6fc0f17812390dcd65ac7b87fef7970d9ff9"),
Hex.Decode("03c05add1e030178c352face07cafc9447c8f369b8f95125c0d311c16b6da48ca2067104cce6cd21ae7b163cd18ffc13001aecebdc2eb02b9e92681f84033a98"),
Hex.Decode("00319bb9becb49f3ed1bca26d0fcf09b0b0a508e4d0bd43b350f959b72cd25b3af47d608fdcd248eada74fbe19990dbeb9bf0da4b4e1200243a14e5cab3f7e610c")
};
SecureRandom rand = new MyFixedSecureRandom();
// KeyFactory fact = KeyFactory.GetInstance("RSA");
//
// PrivateKey privKey = fact.generatePrivate(privKeySpec);
// PublicKey pubKey = fact.generatePublic(pubKeySpec);
AsymmetricKeyParameter privKey = privKeySpec;
AsymmetricKeyParameter pubKey = pubKeySpec;
// PrivateKey priv2048Key = fact.generatePrivate(priv2048KeySpec);
// PublicKey pub2048Key = fact.generatePublic(pub2048KeySpec);
AsymmetricKeyParameter priv2048Key = priv2048KeySpec;
AsymmetricKeyParameter pub2048Key = pub2048KeySpec;
//
// No Padding
//
// Cipher c = Cipher.GetInstance("RSA");
IBufferedCipher c = CipherUtilities.GetCipher("RSA");
// c.init(Cipher.ENCRYPT_MODE, pubKey, rand);
c.Init(true, pubKey);// new ParametersWithRandom(pubKey, rand));
byte[] outBytes = c.DoFinal(input);
if (!AreEqual(outBytes, output[0]))
{
Fail("NoPadding test failed on encrypt expected " + Hex.ToHexString(output[0]) + " got " + Hex.ToHexString(outBytes));
}
// c.init(Cipher.DECRYPT_MODE, privKey);
c.Init(false, privKey);
outBytes = c.DoFinal(outBytes);
if (!AreEqual(outBytes, input))
{
Fail("NoPadding test failed on decrypt expected " + Hex.ToHexString(input) + " got " + Hex.ToHexString(outBytes));
}
//
// No Padding - incremental
//
// c = Cipher.GetInstance("RSA");
c = CipherUtilities.GetCipher("RSA");
// c.init(Cipher.ENCRYPT_MODE, pubKey, rand);
c.Init(true, pubKey);// new ParametersWithRandom(pubKey, rand));
c.ProcessBytes(input);
outBytes = c.DoFinal();
if (!AreEqual(outBytes, output[0]))
{
Fail("NoPadding test failed on encrypt expected " + Hex.ToHexString(output[0]) + " got " + Hex.ToHexString(outBytes));
}
// c.init(Cipher.DECRYPT_MODE, privKey);
c.Init(false, privKey);
outBytes = c.DoFinal(outBytes);
if (!AreEqual(outBytes, input))
{
Fail("NoPadding test failed on decrypt expected " + Hex.ToHexString(input) + " got " + Hex.ToHexString(outBytes));
}
//
// No Padding - incremental - explicit use of NONE in mode.
//
c = CipherUtilities.GetCipher("RSA/NONE/NoPadding");
// c.init(Cipher.ENCRYPT_MODE, pubKey, rand);
c.Init(true, pubKey);// new ParametersWithRandom(pubKey, rand));
c.ProcessBytes(input);
outBytes = c.DoFinal();
if (!AreEqual(outBytes, output[0]))
{
Fail("NoPadding test failed on encrypt expected " + Hex.ToHexString(output[0]) + " got " + Hex.ToHexString(outBytes));
}
// c.init(Cipher.DECRYPT_MODE, privKey);
c.Init(false, privKey);
outBytes = c.DoFinal(outBytes);
if (!AreEqual(outBytes, input))
{
Fail("NoPadding test failed on decrypt expected " + Hex.ToHexString(input) + " got " + Hex.ToHexString(outBytes));
}
//
// No Padding - maximum.Length
//
c = CipherUtilities.GetCipher("RSA");
byte[] modBytes = ((RsaKeyParameters) pubKey).Modulus.ToByteArray();
byte[] maxInput = new byte[modBytes.Length - 1];
maxInput[0] |= 0x7f;
c.Init(true, pubKey);// new ParametersWithRandom(pubKey, rand));
outBytes = c.DoFinal(maxInput);
c.Init(false, privKey);
outBytes = c.DoFinal(outBytes);
if (!AreEqual(outBytes, maxInput))
{
Fail("NoPadding test failed on decrypt expected "
+ Hex.ToHexString(maxInput) + " got "
+ Hex.ToHexString(outBytes));
}
//
// PKCS1 V 1.5
//
c = CipherUtilities.GetCipher("RSA//PKCS1Padding");
c.Init(true, new ParametersWithRandom(pubKey, rand));
outBytes = c.DoFinal(input);
if (!AreEqual(outBytes, output[1]))
{
Fail("PKCS1 test failed on encrypt expected " + Hex.ToHexString(output[1]) + " got " + Hex.ToHexString(outBytes));
}
c.Init(false, privKey);
outBytes = c.DoFinal(outBytes);
if (!AreEqual(outBytes, input))
{
Fail("PKCS1 test failed on decrypt expected " + Hex.ToHexString(input) + " got " + Hex.ToHexString(outBytes));
}
//
// PKCS1 V 1.5 - NONE
//
c = CipherUtilities.GetCipher("RSA/NONE/PKCS1Padding");
c.Init(true, new ParametersWithRandom(pubKey, rand));
outBytes = c.DoFinal(input);
if (!AreEqual(outBytes, output[1]))
{
Fail("PKCS1 test failed on encrypt expected " + Hex.ToHexString(output[1]) + " got " + Hex.ToHexString(outBytes));
}
c.Init(false, privKey);
outBytes = c.DoFinal(outBytes);
if (!AreEqual(outBytes, input))
{
Fail("PKCS1 test failed on decrypt expected " + Hex.ToHexString(input) + " got " + Hex.ToHexString(outBytes));
}
//
// OAEP - SHA1
//
c = CipherUtilities.GetCipher("RSA/NONE/OAEPPadding");
c.Init(true, new ParametersWithRandom(pubKey, rand));
outBytes = c.DoFinal(input);
if (!AreEqual(outBytes, output[2]))
{
Fail("OAEP test failed on encrypt expected " + Hex.ToHexString(output[2]) + " got " + Hex.ToHexString(outBytes));
}
c = CipherUtilities.GetCipher("RSA/NONE/OAEPWithSHA1AndMGF1Padding");
c.Init(false, privKey);
outBytes = c.DoFinal(outBytes);
if (!AreEqual(outBytes, input))
{
Fail("OAEP test failed on decrypt expected " + Hex.ToHexString(input) + " got " + Hex.ToHexString(outBytes));
}
// TODO
// AlgorithmParameters oaepP = c.getParameters();
byte[] rop = new RsaesOaepParameters(
new AlgorithmIdentifier(OiwObjectIdentifiers.IdSha1, DerNull.Instance),
new AlgorithmIdentifier(PkcsObjectIdentifiers.IdMgf1, new AlgorithmIdentifier(OiwObjectIdentifiers.IdSha1, DerNull.Instance)),
new AlgorithmIdentifier(PkcsObjectIdentifiers.IdPSpecified, new DerOctetString(new byte[0]))).GetEncoded();
// if (!AreEqual(oaepP.getEncoded(), rop.getEncoded()))
// {
// Fail("OAEP test failed default sha-1 parameters");
// }
//
// OAEP - SHA224
//
c = CipherUtilities.GetCipher("RSA/NONE/OAEPWithSHA224AndMGF1Padding");
c.Init(true, new ParametersWithRandom(pub2048Key, rand));
outBytes = c.DoFinal(input);
if (!AreEqual(outBytes, output[3]))
{
Fail("OAEP SHA-224 test failed on encrypt expected " + Hex.ToHexString(output[2]) + " got " + Hex.ToHexString(outBytes));
}
c.Init(false, priv2048Key);
outBytes = c.DoFinal(outBytes);
if (!AreEqual(outBytes, input))
{
Fail("OAEP SHA-224 test failed on decrypt expected " + Hex.ToHexString(input) + " got " + Hex.ToHexString(outBytes));
}
// oaepP = c.getParameters();
rop = new RsaesOaepParameters(
new AlgorithmIdentifier(NistObjectIdentifiers.IdSha224, DerNull.Instance),
new AlgorithmIdentifier(PkcsObjectIdentifiers.IdMgf1, new AlgorithmIdentifier(NistObjectIdentifiers.IdSha224, DerNull.Instance)),
new AlgorithmIdentifier(PkcsObjectIdentifiers.IdPSpecified, new DerOctetString(new byte[0]))).GetEncoded();
// if (!AreEqual(oaepP.getEncoded(), rop.getEncoded())
// {
// Fail("OAEP test failed default sha-224 parameters");
// }
//
// OAEP - SHA 256
//
c = CipherUtilities.GetCipher("RSA/NONE/OAEPWithSHA256AndMGF1Padding");
c.Init(true, new ParametersWithRandom(pub2048Key, rand));
outBytes = c.DoFinal(input);
if (!AreEqual(outBytes, output[4]))
{
Fail("OAEP SHA-256 test failed on encrypt expected " + Hex.ToHexString(output[2]) + " got " + Hex.ToHexString(outBytes));
}
c.Init(false, priv2048Key);
outBytes = c.DoFinal(outBytes);
if (!AreEqual(outBytes, input))
{
Fail("OAEP SHA-256 test failed on decrypt expected " + Hex.ToHexString(input) + " got " + Hex.ToHexString(outBytes));
}
// oaepP = c.getParameters();
rop = new RsaesOaepParameters(
new AlgorithmIdentifier(NistObjectIdentifiers.IdSha256, DerNull.Instance),
new AlgorithmIdentifier(PkcsObjectIdentifiers.IdMgf1, new AlgorithmIdentifier(NistObjectIdentifiers.IdSha256, DerNull.Instance)),
new AlgorithmIdentifier(PkcsObjectIdentifiers.IdPSpecified, new DerOctetString(new byte[0]))).GetEncoded();
// if (!AreEqual(oaepP.getEncoded(), rop.getEncoded())
// {
// Fail("OAEP test failed default sha-256 parameters");
// }
//
// OAEP - SHA 384
//
c = CipherUtilities.GetCipher("RSA/NONE/OAEPWithSHA384AndMGF1Padding");
c.Init(true, new ParametersWithRandom(pub2048Key, rand));
outBytes = c.DoFinal(input);
if (!AreEqual(outBytes, output[5]))
{
Fail("OAEP SHA-384 test failed on encrypt expected " + Hex.ToHexString(output[2]) + " got " + Hex.ToHexString(outBytes));
}
c.Init(false, priv2048Key);
outBytes = c.DoFinal(outBytes);
if (!AreEqual(outBytes, input))
{
Fail("OAEP SHA-384 test failed on decrypt expected " + Hex.ToHexString(input) + " got " + Hex.ToHexString(outBytes));
}
// oaepP = c.getParameters();
rop = new RsaesOaepParameters(
new AlgorithmIdentifier(NistObjectIdentifiers.IdSha384, DerNull.Instance),
new AlgorithmIdentifier(PkcsObjectIdentifiers.IdMgf1, new AlgorithmIdentifier(NistObjectIdentifiers.IdSha384, DerNull.Instance)),
new AlgorithmIdentifier(PkcsObjectIdentifiers.IdPSpecified, new DerOctetString(new byte[0]))).GetEncoded();
// if (!AreEqual(oaepP.getEncoded(), rop.getEncoded())
// {
// Fail("OAEP test failed default sha-384 parameters");
// }
//
// OAEP - MD5
//
c = CipherUtilities.GetCipher("RSA/NONE/OAEPWithMD5AndMGF1Padding");
c.Init(true, new ParametersWithRandom(pubKey, rand));
outBytes = c.DoFinal(input);
if (!AreEqual(outBytes, output[6]))
{
Fail("OAEP MD5 test failed on encrypt expected " + Hex.ToHexString(output[2]) + " got " + Hex.ToHexString(outBytes));
}
c.Init(false, privKey);
outBytes = c.DoFinal(outBytes);
if (!AreEqual(outBytes, input))
{
Fail("OAEP MD5 test failed on decrypt expected " + Hex.ToHexString(input) + " got " + Hex.ToHexString(outBytes));
}
// oaepP = c.getParameters();
rop = new RsaesOaepParameters(
new AlgorithmIdentifier(PkcsObjectIdentifiers.MD5, DerNull.Instance),
new AlgorithmIdentifier(PkcsObjectIdentifiers.IdMgf1, new AlgorithmIdentifier(PkcsObjectIdentifiers.MD5, DerNull.Instance)),
new AlgorithmIdentifier(PkcsObjectIdentifiers.IdPSpecified, new DerOctetString(new byte[0]))).GetEncoded();
// if (!AreEqual(oaepP.getEncoded(), rop.getEncoded())
// {
// Fail("OAEP test failed default md5 parameters");
// }
//
// OAEP - SHA1 with default parameters
//
c = CipherUtilities.GetCipher("RSA/NONE/OAEPPadding");
// TODO
// c.init(Cipher.ENCRYPT_MODE, pubKey, OAEPParameterSpec.DEFAULT, rand);
//
// outBytes = c.DoFinal(input);
//
// if (!AreEqual(outBytes, output[2]))
// {
// Fail("OAEP test failed on encrypt expected " + Encoding.ASCII.GetString(Hex.Encode(output[2])) + " got " + Encoding.ASCII.GetString(Hex.Encode(outBytes)));
// }
//
// c = CipherUtilities.GetCipher("RSA/NONE/OAEPWithSHA1AndMGF1Padding");
//
// c.Init(false, privKey);
//
// outBytes = c.DoFinal(outBytes);
//
// if (!AreEqual(outBytes, input))
// {
// Fail("OAEP test failed on decrypt expected " + Encoding.ASCII.GetString(Hex.Encode(input)) + " got " + Encoding.ASCII.GetString(Hex.Encode(outBytes)));
// }
//
// oaepP = c.getParameters();
//
// if (!AreEqual(oaepP.getEncoded(), new byte[] { 0x30, 0x00 }))
// {
// Fail("OAEP test failed default parameters");
// }
//
// OAEP - SHA1 with specified string
//
c = CipherUtilities.GetCipher("RSA/NONE/OAEPPadding");
// TODO
// c.init(Cipher.ENCRYPT_MODE, pubKey, new OAEPParameterSpec("SHA1", "MGF1", new MGF1ParameterSpec("SHA1"), new PSource.PSpecified(new byte[] { 1, 2, 3, 4, 5 })), rand);
//
// outBytes = c.DoFinal(input);
//
// oaepP = c.getParameters();
rop = new RsaesOaepParameters(
new AlgorithmIdentifier(OiwObjectIdentifiers.IdSha1, DerNull.Instance),
new AlgorithmIdentifier(PkcsObjectIdentifiers.IdMgf1, new AlgorithmIdentifier(OiwObjectIdentifiers.IdSha1, DerNull.Instance)),
new AlgorithmIdentifier(PkcsObjectIdentifiers.IdPSpecified, new DerOctetString(new byte[] { 1, 2, 3, 4, 5 }))).GetEncoded();
// if (!AreEqual(oaepP.getEncoded())
// {
// Fail("OAEP test failed changed sha-1 parameters");
// }
//
// if (!AreEqual(outBytes, output[7]))
// {
// Fail("OAEP test failed on encrypt expected " + Encoding.ASCII.GetString(Hex.Encode(output[2])) + " got " + Encoding.ASCII.GetString(Hex.Encode(outBytes)));
// }
c = CipherUtilities.GetCipher("RSA/NONE/OAEPWithSHA1AndMGF1Padding");
// TODO
// c.init(Cipher.DECRYPT_MODE, privKey, oaepP);
//
// outBytes = c.DoFinal(outBytes);
//
// if (!AreEqual(outBytes, input))
// {
// Fail("OAEP test failed on decrypt expected " + Encoding.ASCII.GetString(Hex.Encode(input)) + " got " + Encoding.ASCII.GetString(Hex.Encode(outBytes)));
// }
//
// iso9796-1
//
byte[] isoInput = Hex.Decode("fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210");
// PrivateKey isoPrivKey = fact.generatePrivate(isoPrivKeySpec);
// PublicKey isoPubKey = fact.generatePublic(isoPubKeySpec);
AsymmetricKeyParameter isoPrivKey = isoPrivKeySpec;
AsymmetricKeyParameter isoPubKey = isoPubKeySpec;
c = CipherUtilities.GetCipher("RSA/NONE/ISO9796-1Padding");
c.Init(true, isoPrivKey);
outBytes = c.DoFinal(isoInput);
if (!AreEqual(outBytes, output[8]))
{
Fail("ISO9796-1 test failed on encrypt expected " + Hex.ToHexString(output[3]) + " got " + Hex.ToHexString(outBytes));
}
c.Init(false, isoPubKey);
outBytes = c.DoFinal(outBytes);
if (!AreEqual(outBytes, isoInput))
{
Fail("ISO9796-1 test failed on decrypt expected " + Hex.ToHexString(input) + " got " + Hex.ToHexString(outBytes));
}
//
//
// generation with parameters test.
//
IAsymmetricCipherKeyPairGenerator keyPairGen = GeneratorUtilities.GetKeyPairGenerator("RSA");
//
// 768 bit RSA with e = 2^16-1
//
keyPairGen.Init(
new RsaKeyGenerationParameters(
BigInteger.ValueOf(0x10001),
new SecureRandom(),
768,
25));
AsymmetricCipherKeyPair kp = keyPairGen.GenerateKeyPair();
pubKey = kp.Public;
privKey = kp.Private;
c.Init(true, new ParametersWithRandom(pubKey, rand));
outBytes = c.DoFinal(input);
c.Init(false, privKey);
outBytes = c.DoFinal(outBytes);
if (!AreEqual(outBytes, input))
{
Fail("key generation test failed on decrypt expected " + Hex.ToHexString(input) + " got " + Hex.ToHexString(outBytes));
}
//
// comparison check
//
// KeyFactory keyFact = KeyFactory.GetInstance("RSA");
//
// RSAPrivateCrtKey crtKey = (RSAPrivateCrtKey)keyFact.translateKey(privKey);
RsaPrivateCrtKeyParameters crtKey = (RsaPrivateCrtKeyParameters) privKey;
if (!privKey.Equals(crtKey))
{
Fail("private key equality check failed");
}
// RSAPublicKey copyKey = (RSAPublicKey)keyFact.translateKey(pubKey);
RsaKeyParameters copyKey = (RsaKeyParameters) pubKey;
if (!pubKey.Equals(copyKey))
{
Fail("public key equality check failed");
}
SecureRandom random = new SecureRandom();
rawModeTest("SHA1withRSA", X509ObjectIdentifiers.IdSha1, priv2048Key, pub2048Key, random);
rawModeTest("MD5withRSA", PkcsObjectIdentifiers.MD5, priv2048Key, pub2048Key, random);
rawModeTest("RIPEMD128withRSA", TeleTrusTObjectIdentifiers.RipeMD128, priv2048Key, pub2048Key, random);
}
private void rawModeTest(string sigName, DerObjectIdentifier digestOID,
AsymmetricKeyParameter privKey, AsymmetricKeyParameter pubKey, SecureRandom random)
{
byte[] sampleMessage = new byte[1000 + random.Next() % 100];
random.NextBytes(sampleMessage);
ISigner normalSig = SignerUtilities.GetSigner(sigName);
normalSig.Init(true, privKey);
normalSig.BlockUpdate(sampleMessage, 0, sampleMessage.Length);
byte[] normalResult = normalSig.GenerateSignature();
byte[] hash = DigestUtilities.CalculateDigest(digestOID.Id, sampleMessage);
byte[] digInfo = derEncode(digestOID, hash);
ISigner rawSig = SignerUtilities.GetSigner("RSA");
rawSig.Init(true, privKey);
rawSig.BlockUpdate(digInfo, 0, digInfo.Length);
byte[] rawResult = rawSig.GenerateSignature();
if (!Arrays.AreEqual(normalResult, rawResult))
{
Fail("raw mode signature differs from normal one");
}
rawSig.Init(false, pubKey);
rawSig.BlockUpdate(digInfo, 0, digInfo.Length);
if (!rawSig.VerifySignature(rawResult))
{
Fail("raw mode signature verification failed");
}
}
private byte[] derEncode(DerObjectIdentifier oid, byte[] hash)
{
AlgorithmIdentifier algId = new AlgorithmIdentifier(oid, DerNull.Instance);
DigestInfo dInfo = new DigestInfo(algId, hash);
return dInfo.GetEncoded(Asn1Encodable.Der);
}
public override string Name
{
get { return "RSATest"; }
}
public static void Main(
string[] args)
{
ITest test = new RsaTest();
ITestResult result = test.Perform();
Console.WriteLine(result);
}
[Test]
public void TestFunction()
{
string resultText = Perform().ToString();
Assert.AreEqual(Name + ": Okay", resultText);
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace TestCases.XWPF.UserModel
{
using NPOI;
using NPOI.OpenXml4Net.OPC;
using NPOI.Util;
using NPOI.XWPF;
using NPOI.XWPF.Extractor;
using NPOI.XWPF.UserModel;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.IO;
using TestCases;
[TestFixture]
public class TestXWPFDocument
{
[Test]
public void TestContainsMainContentType()
{
XWPFDocument doc = XWPFTestDataSamples.OpenSampleDocument("sample.docx");
OPCPackage pack = doc.Package;
bool found = false;
foreach (PackagePart part in pack.GetParts())
{
if (part.ContentType.Equals(XWPFRelation.DOCUMENT.ContentType))
{
found = true;
}
if (false == found)
{
// successful tests should be silent
System.Console.WriteLine(part);
}
}
Assert.IsTrue(found);
}
[Test]
public void TestOpen()
{
XWPFDocument xml;
// Simple file
xml = XWPFTestDataSamples.OpenSampleDocument("sample.docx");
// Check it has key parts
Assert.IsNotNull(xml.Document);
Assert.IsNotNull(xml.Document.body);
Assert.IsNotNull(xml.GetStyles());
// Complex file
xml = XWPFTestDataSamples.OpenSampleDocument("IllustrativeCases.docx");
Assert.IsNotNull(xml.Document);
Assert.IsNotNull(xml.Document.body);
Assert.IsNotNull(xml.GetStyles());
}
[Test]
public void TestMetadataBasics()
{
XWPFDocument xml = XWPFTestDataSamples.OpenSampleDocument("sample.docx");
Assert.IsNotNull(xml.GetProperties().CoreProperties);
Assert.IsNotNull(xml.GetProperties().ExtendedProperties);
Assert.AreEqual("Microsoft Office Word", xml.GetProperties().ExtendedProperties.GetUnderlyingProperties().Application);
Assert.AreEqual(1315, xml.GetProperties().ExtendedProperties.GetUnderlyingProperties().Characters);
Assert.AreEqual(10, xml.GetProperties().ExtendedProperties.GetUnderlyingProperties().Lines);
Assert.AreEqual(null, xml.GetProperties().CoreProperties.Title);
Assert.AreEqual(null, xml.GetProperties().CoreProperties.GetUnderlyingProperties().GetSubjectProperty());
}
[Test]
public void TestMetadataComplex()
{
XWPFDocument xml = XWPFTestDataSamples.OpenSampleDocument("IllustrativeCases.docx");
Assert.IsNotNull(xml.GetProperties().CoreProperties);
Assert.IsNotNull(xml.GetProperties().ExtendedProperties);
Assert.AreEqual("Microsoft Office Outlook", xml.GetProperties().ExtendedProperties.GetUnderlyingProperties().Application);
Assert.AreEqual(5184, xml.GetProperties().ExtendedProperties.GetUnderlyingProperties().Characters);
Assert.AreEqual(0, xml.GetProperties().ExtendedProperties.GetUnderlyingProperties().Lines);
Assert.AreEqual(" ", xml.GetProperties().CoreProperties.Title);
Assert.AreEqual(" ", xml.GetProperties().CoreProperties.GetUnderlyingProperties().GetSubjectProperty());
}
[Test]
public void TestWorkbookProperties()
{
XWPFDocument doc = new XWPFDocument();
POIXMLProperties props = doc.GetProperties();
Assert.IsNotNull(props);
Assert.AreEqual("NPOI", props.ExtendedProperties.GetUnderlyingProperties().Application);
}
[Test]
public void TestAddParagraph()
{
XWPFDocument doc = XWPFTestDataSamples.OpenSampleDocument("sample.docx");
Assert.AreEqual(3, doc.Paragraphs.Count);
XWPFParagraph p = doc.CreateParagraph();
Assert.AreEqual(p, doc.Paragraphs[(3)]);
Assert.AreEqual(4, doc.Paragraphs.Count);
Assert.AreEqual(3, doc.GetParagraphPos(3));
Assert.AreEqual(3, doc.GetPosOfParagraph(p));
//CTP ctp = p.CTP;
//XWPFParagraph newP = doc.GetParagraph(ctp);
//Assert.AreSame(p, newP);
//XmlCursor cursor = doc.Document.Body.GetPArray(0).newCursor();
//XWPFParagraph cP = doc.InsertNewParagraph(cursor);
//Assert.AreSame(cP, doc.Paragraphs[(0)]);
//Assert.AreEqual(5, doc.Paragraphs.Count);
}
[Test]
public void TestAddPicture()
{
XWPFDocument doc = XWPFTestDataSamples.OpenSampleDocument("sample.docx");
byte[] jpeg = XWPFTestDataSamples.GetImage("nature1.jpg");
String relationId = doc.AddPictureData(jpeg, (int)PictureType.JPEG);
byte[] newJpeg = ((XWPFPictureData)doc.GetRelationById(relationId)).Data;
Assert.AreEqual(newJpeg.Length, jpeg.Length);
for (int i = 0; i < jpeg.Length; i++)
{
Assert.AreEqual(newJpeg[i], jpeg[i]);
}
}
[Test]
public void TestAllPictureFormats()
{
XWPFDocument doc = new XWPFDocument();
doc.AddPictureData(new byte[10], (int)PictureType.EMF);
doc.AddPictureData(new byte[11], (int)PictureType.WMF);
doc.AddPictureData(new byte[12], (int)PictureType.PICT);
doc.AddPictureData(new byte[13], (int)PictureType.JPEG);
doc.AddPictureData(new byte[14], (int)PictureType.PNG);
doc.AddPictureData(new byte[15], (int)PictureType.DIB);
doc.AddPictureData(new byte[16], (int)PictureType.GIF);
doc.AddPictureData(new byte[17], (int)PictureType.TIFF);
doc.AddPictureData(new byte[18], (int)PictureType.EPS);
doc.AddPictureData(new byte[19], (int)PictureType.BMP);
doc.AddPictureData(new byte[20], (int)PictureType.WPG);
Assert.AreEqual(11, doc.AllPictures.Count);
doc = XWPFTestDataSamples.WriteOutAndReadBack(doc);
Assert.AreEqual(11, doc.AllPictures.Count);
}
[Test]
public void TestRemoveBodyElement()
{
XWPFDocument doc = XWPFTestDataSamples.OpenSampleDocument("sample.docx");
Assert.AreEqual(3, doc.Paragraphs.Count);
Assert.AreEqual(3, doc.BodyElements.Count);
XWPFParagraph p1 = doc.Paragraphs[(0)];
XWPFParagraph p2 = doc.Paragraphs[(1)];
XWPFParagraph p3 = doc.Paragraphs[(2)];
Assert.AreEqual(p1, doc.BodyElements[(0)]);
Assert.AreEqual(p1, doc.Paragraphs[(0)]);
Assert.AreEqual(p2, doc.BodyElements[(1)]);
Assert.AreEqual(p2, doc.Paragraphs[(1)]);
Assert.AreEqual(p3, doc.BodyElements[(2)]);
Assert.AreEqual(p3, doc.Paragraphs[(2)]);
// Add another
XWPFParagraph p4 = doc.CreateParagraph();
Assert.AreEqual(4, doc.Paragraphs.Count);
Assert.AreEqual(4, doc.BodyElements.Count);
Assert.AreEqual(p1, doc.BodyElements[(0)]);
Assert.AreEqual(p1, doc.Paragraphs[(0)]);
Assert.AreEqual(p2, doc.BodyElements[(1)]);
Assert.AreEqual(p2, doc.Paragraphs[(1)]);
Assert.AreEqual(p3, doc.BodyElements[(2)]);
Assert.AreEqual(p3, doc.Paragraphs[(2)]);
Assert.AreEqual(p4, doc.BodyElements[(3)]);
Assert.AreEqual(p4, doc.Paragraphs[(3)]);
// Remove the 2nd
Assert.AreEqual(true, doc.RemoveBodyElement(1));
Assert.AreEqual(3, doc.Paragraphs.Count);
Assert.AreEqual(3, doc.BodyElements.Count);
Assert.AreEqual(p1, doc.BodyElements[(0)]);
Assert.AreEqual(p1, doc.Paragraphs[(0)]);
Assert.AreEqual(p3, doc.BodyElements[(1)]);
Assert.AreEqual(p3, doc.Paragraphs[(1)]);
Assert.AreEqual(p4, doc.BodyElements[(2)]);
Assert.AreEqual(p4, doc.Paragraphs[(2)]);
// Remove the 1st
Assert.AreEqual(true, doc.RemoveBodyElement(0));
Assert.AreEqual(2, doc.Paragraphs.Count);
Assert.AreEqual(2, doc.BodyElements.Count);
Assert.AreEqual(p3, doc.BodyElements[(0)]);
Assert.AreEqual(p3, doc.Paragraphs[(0)]);
Assert.AreEqual(p4, doc.BodyElements[(1)]);
Assert.AreEqual(p4, doc.Paragraphs[(1)]);
// Remove the last
Assert.AreEqual(true, doc.RemoveBodyElement(1));
Assert.AreEqual(1, doc.Paragraphs.Count);
Assert.AreEqual(1, doc.BodyElements.Count);
Assert.AreEqual(p3, doc.BodyElements[(0)]);
Assert.AreEqual(p3, doc.Paragraphs[(0)]);
}
[Test]
public void TestRegisterPackagePictureData()
{
XWPFDocument doc = XWPFTestDataSamples.OpenSampleDocument("issue_51265_1.docx");
/* manually assemble a new image package part*/
OPCPackage opcPckg = doc.Package;
XWPFRelation jpgRelation = XWPFRelation.IMAGE_JPEG;
PackagePartName partName = PackagingUriHelper.CreatePartName(jpgRelation.DefaultFileName.Replace('#', '2'));
PackagePart newImagePart = opcPckg.CreatePart(partName, jpgRelation.ContentType);
byte[] nature1 = XWPFTestDataSamples.GetImage("abstract4.jpg");
Stream os = newImagePart.GetOutputStream();
os.Write(nature1, 0, nature1.Length);
os.Close();
XWPFHeader xwpfHeader = doc.HeaderList[(0)];
PackageRelationship relationship = xwpfHeader.GetPackagePart().AddRelationship(partName, TargetMode.Internal, jpgRelation.Relation);
XWPFPictureData newPicData = new XWPFPictureData(newImagePart, relationship);
/* new part is now Ready to rumble */
Assert.IsFalse(xwpfHeader.AllPictures.Contains(newPicData));
Assert.IsFalse(doc.AllPictures.Contains(newPicData));
Assert.IsFalse(doc.AllPackagePictures.Contains(newPicData));
doc.RegisterPackagePictureData(newPicData);
Assert.IsFalse(xwpfHeader.AllPictures.Contains(newPicData));
Assert.IsFalse(doc.AllPictures.Contains(newPicData));
Assert.IsTrue(doc.AllPackagePictures.Contains(newPicData));
doc.Package.Revert();
}
[Test]
public void TestFindPackagePictureData()
{
XWPFDocument doc = XWPFTestDataSamples.OpenSampleDocument("issue_51265_1.docx");
byte[] nature1 = XWPFTestDataSamples.GetImage("nature1.gif");
XWPFPictureData part = doc.FindPackagePictureData(nature1, (int)PictureType.GIF);
Assert.IsNotNull(part);
Assert.IsTrue(doc.AllPictures.Contains(part));
Assert.IsTrue(doc.AllPackagePictures.Contains(part));
doc.Package.Revert();
}
[Test]
public void TestGetAllPictures()
{
XWPFDocument doc = XWPFTestDataSamples.OpenSampleDocument("issue_51265_3.docx");
IList<XWPFPictureData> allPictures = doc.AllPictures;
IList<XWPFPictureData> allPackagePictures = doc.AllPackagePictures;
Assert.IsNotNull(allPictures);
Assert.AreEqual(3, allPictures.Count);
foreach (XWPFPictureData xwpfPictureData in allPictures)
{
Assert.IsTrue(allPackagePictures.Contains(xwpfPictureData));
}
try
{
allPictures.Add(allPictures[0]);
Assert.Fail("This list must be unmodifiable!");
}
catch (NotSupportedException)
{
// all ok
}
doc.Package.Revert();
}
[Test]
public void TestGetAllPackagePictures()
{
XWPFDocument doc = XWPFTestDataSamples.OpenSampleDocument("issue_51265_3.docx");
IList<XWPFPictureData> allPackagePictures = doc.AllPackagePictures;
Assert.IsNotNull(allPackagePictures);
Assert.AreEqual(5, allPackagePictures.Count);
try
{
allPackagePictures.Add(allPackagePictures[0]);
Assert.Fail("This list must be unmodifiable!");
}
catch (NotSupportedException)
{
// all ok
}
doc.Package.Revert();
}
[Test]
public void TestPictureHandlingSimpleFile()
{
XWPFDocument doc = XWPFTestDataSamples.OpenSampleDocument("issue_51265_1.docx");
Assert.AreEqual(1, doc.AllPackagePictures.Count);
byte[] newPic = XWPFTestDataSamples.GetImage("abstract4.jpg");
String id1 = doc.AddPictureData(newPic, (int)PictureType.JPEG);
Assert.AreEqual(2, doc.AllPackagePictures.Count);
/* copy data, to avoid instance-Equality */
byte[] newPicCopy = Arrays.CopyOf(newPic, newPic.Length);
String id2 = doc.AddPictureData(newPicCopy, (int)PictureType.JPEG);
Assert.AreEqual(id1, id2);
doc.Package.Revert();
}
[Test]
public void TestPictureHandlingHeaderDocumentImages()
{
XWPFDocument doc = XWPFTestDataSamples.OpenSampleDocument("issue_51265_2.docx");
Assert.AreEqual(1, doc.AllPictures.Count);
Assert.AreEqual(1, doc.AllPackagePictures.Count);
Assert.AreEqual(1, doc.HeaderList[(0)].AllPictures.Count);
doc.Package.Revert();
}
[Test]
public void TestPictureHandlingComplex()
{
XWPFDocument doc = XWPFTestDataSamples.OpenSampleDocument("issue_51265_3.docx");
XWPFHeader xwpfHeader = doc.HeaderList[(0)];
Assert.AreEqual(3, doc.AllPictures.Count);
Assert.AreEqual(3, xwpfHeader.AllPictures.Count);
Assert.AreEqual(5, doc.AllPackagePictures.Count);
byte[] nature1 = XWPFTestDataSamples.GetImage("nature1.jpg");
String id = doc.AddPictureData(nature1, (int)PictureType.JPEG);
POIXMLDocumentPart part1 = xwpfHeader.GetRelationById("rId1");
XWPFPictureData part2 = (XWPFPictureData)doc.GetRelationById(id);
Assert.AreSame(part1, part2);
doc.Package.Revert();
}
[Test]
public void TestZeroLengthLibreOfficeDocumentWithWaterMarkHeader()
{
XWPFDocument doc = XWPFTestDataSamples.OpenSampleDocument("zero-length.docx");
POIXMLProperties properties = doc.GetProperties();
Assert.IsNotNull(properties.CoreProperties);
XWPFHeader headerArray = doc.GetHeaderArray(0);
Assert.AreEqual(1, headerArray.AllPictures.Count);
Assert.AreEqual("image1.png", headerArray.AllPictures[0].FileName);
Assert.AreEqual("", headerArray.Text);
ExtendedProperties extendedProperties = properties.ExtendedProperties;
Assert.IsNotNull(extendedProperties);
Assert.AreEqual(0, extendedProperties.GetUnderlyingProperties().Characters);
}
[Test]
public void TestSettings()
{
XWPFSettings settings = new XWPFSettings();
settings.SetZoomPercent(50);
Assert.AreEqual(50, settings.GetZoomPercent());
}
[Test]
public void TestEnforcedWith()
{
XWPFDocument docx = XWPFTestDataSamples.OpenSampleDocument("EnforcedWith.docx");
Assert.IsTrue(docx.IsEnforcedProtection());
docx.Close();
}
[Test]
[Ignore("XWPF should be able to write to a new Stream when opened Read-Only")]
public void TestWriteFromReadOnlyOPC() {
OPCPackage opc = OPCPackage.Open(
POIDataSamples.GetDocumentInstance().GetFileInfo("SampleDoc.docx"),
PackageAccess.READ
);
XWPFDocument doc = new XWPFDocument(opc);
XWPFWordExtractor ext = new XWPFWordExtractor(doc);
String origText = ext.Text;
doc = XWPFTestDataSamples.WriteOutAndReadBack(doc);
ext = new XWPFWordExtractor(doc);
Assert.AreEqual(origText, ext.Text);
}
}
}
| |
//------------------------------------------------------------------------------
// Microsoft Avalon
// Copyright (c) Microsoft Corporation, 2001
//
// File: MatrixStack.cs
//------------------------------------------------------------------------------
using System;
using System.Diagnostics;
using System.Collections;
using MS.Internal;
using System.Security;
using System.Security.Permissions;
namespace System.Windows.Media
{
/// <summary> MatrixStack class implementation</summary>
internal class MatrixStack
{
private Matrix[] _items;
private int _size;
#if DEBUG
private static readonly int s_initialSize = 4;
#else
private static readonly int s_initialSize = 40; // sizeof(Matrix) * 40 = 2240 bytes. Must be > 4
#endif
private static readonly int s_growFactor = 2;
private static readonly int s_shrinkFactor = s_growFactor + 1;
// The following members are used to lazily manage the memory allocated by the stack.
private int _highWaterMark;
private int _observeCount;
private static readonly int s_trimCount = 10;
public MatrixStack()
{
_items = new Matrix[s_initialSize];
}
/// <summary>
/// Ensures that there is space for at least one more element.
/// </summary>
private void EnsureCapacity()
{
// If we reached the capacity of the _items array we need to increase
// the size. We use an exponential growth to keep Push in average O(1).
if (_size == _items.Length)
{
Matrix[] newItems = new Matrix[s_growFactor * _size];
Array.Copy(_items, newItems, _size);
_items = newItems;
}
}
/// <summary>
/// Push new matrix on the stack.
/// </summary>
/// <param name="matrix">The new matrix to be pushed</param>
/// <param name="combine">Iff true, the matrix is multiplied with the current
/// top matrix on the stack and then pushed on the stack. If false the matrix
/// is pushed as is on top of the stack.</param>
public void Push(ref Matrix matrix, bool combine)
{
EnsureCapacity();
if (combine && (_size > 0))
{
// Combine means that we push the product of the top matrix and the new
// one on the stack. Note that there isn't a top-matrix if the stack is empty.
// In this case the top-matrix is assumed to be identity. See else case.
_items[_size] = matrix;
// _items[_size] = _items[_size] * _items[_size-1];
MatrixUtil.MultiplyMatrix(ref _items[_size], ref _items[_size - 1]);
}
else
{
// If the stack is empty or we are not combining, we just assign the matrix passed
// in to the next free slot in the array.
_items[_size] = matrix;
}
_size++;
// For memory optimization purposes we track the max usage of the stack here.
// See the optimze method for more details about this.
_highWaterMark = Math.Max(_highWaterMark, _size);
}
/// <summary>
/// Pushes a transformation on the stack. The transformation is multiplied with the top element
/// on the stack and then pushed on the stack.
/// </summary>
/// <param name="transform">2D transformation.</param>
/// <param name="combine">The combine argument indicates if the transform should be pushed multiplied with the
/// current top transform or as is.</param>
/// <remark>
/// The code duplication between Push(ref Matrix, bool) and Push(Transform, bool) is not ideal.
/// However, we did see a performance gain by optimizing the Push(Transform, bool) method
/// minimizing the copies of data.
/// </remark>
public void Push(Transform transform, bool combine)
{
EnsureCapacity();
if (combine && (_size > 0))
{
// Combine means that we push the product of the top matrix and transform
// on the stack. Note that there isn't a top-matrix if the stack is empty.
// In this case the top-matrix is assumed to be identity. See else case.
// _items[_size] is the new top of the stack, _items[_size - 1] is the
// previous top.
transform.MultiplyValueByMatrix(ref _items[_size], ref _items[_size - 1]);
}
else
{
// If we don't combine or if the stack is empty.
_items[_size] = transform.Value;
}
_size++;
// For memory optimization purposes we track the max usage of the stack here.
// See the optimze method for more details about this.
_highWaterMark = Math.Max(_highWaterMark, _size);
}
/// <summary>
/// Pushes the offset on the stack. If the combine flag is true, the offset is applied to the top element before
/// it is pushed onto the stack.
/// </summary>
public void Push(Vector offset, bool combine)
{
EnsureCapacity();
if (combine && (_size > 0))
{
// In combine mode copy the top element, but only if the stack is not empty.
_items[_size] = _items[_size-1];
}
else
{
// If combine is false, initialize the new top stack element with the identity
// matrix.
_items[_size] = Matrix.Identity;
}
// Apply the offset to the new top element.
MatrixUtil.PrependOffset(ref _items[_size], offset.X, offset.Y);
_size++;
// For memory optimization purposes we track the max usage of the stack here.
// See the optimze method for more details about this.
_highWaterMark = Math.Max(_highWaterMark, _size);
}
/// <summary>
/// Pops the top stack element from the stack.
/// </summary>
public void Pop()
{
Debug.Assert(!IsEmpty);
#if DEBUG
_items[_size-1] = new Matrix();
#endif
_size--;
}
/// <summary>
/// Peek returns the matrix on the top of the stack.
/// </summary>
public Matrix Peek()
{
Debug.Assert(!IsEmpty);
return _items[_size-1];
}
///<value>
/// This is true iff the stack is empty.
///</value>
public bool IsEmpty { get { return _size == 0; } }
/// <summary>
/// Instead of allocating and releasing memory continuously while pushing on
/// and popping off the stack, we call the optimize method after each frame
/// to readjust the internal stack capacity.
/// </summary>
public void Optimize()
{
Debug.Assert(_size == 0); // The stack must be empty before this is called.
Debug.Assert(_highWaterMark <= _items.Length);
// After s_trimCount calls to this method we check the past usage of the stack.
if (_observeCount == s_trimCount)
{
int newSize = Math.Max(_highWaterMark, s_initialSize);
if (newSize * (s_shrinkFactor) <= _items.Length)
{
// If the water mark is less or equal to capacity divided by the shrink
// factor, then we shrink the stack. Usually the shrink factor is greater
// than the grow factor. This avoids an oscillation of shrinking and growing
// the stack if the high water mark goes only slightly up and down.
// Note that we don't need to copy the array because the stack is empty.
_items = new Matrix[newSize];
}
_highWaterMark = 0;
_observeCount = 0;
}
else
{
// Keep incrementing our observe count
_observeCount++;
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Threading;
using System.Web.Script.Serialization;
using System.Net;
using System.Linq;
namespace Saklient {
using Hash = Dictionary<string, object>;
public class Util
{
private static JavaScriptSerializer serializer = new JavaScriptSerializer();
public static object DecodeJson(string json)
{
return ArrayList2List(serializer.Deserialize<Hash>(json));
}
public static string EncodeJson(object obj)
{
return serializer.Serialize(obj);
}
public static bool ExistsPath(object obj, string path)
{
string[] aPath = path.Split('.');
foreach (string key in aPath)
{
if (obj == null) return false;
if (key == "") continue;
if (Regex.IsMatch(key, @"^\d+$"))
{
int idx = Convert.ToInt32(key);
List<object> arr = obj as List<object>;
if (arr==null || arr.Count <= idx) return false;
obj = arr[idx];
}
else
{
Hash dic = obj as Hash;
if (dic==null || !dic.ContainsKey(key)) return false;
obj = dic[key];
}
}
return true;
}
public static object GetByPath(object obj, string path)
{
string[] aPath = path.Split('.');
foreach (string key in aPath)
{
if (obj == null) return null;
if (key == "") continue;
if (Regex.IsMatch(key, @"^\d+$"))
{
int idx = Convert.ToInt32(key);
List<object> arr = obj as List<object>;
if (arr==null || arr.Count <= idx) return null;
obj = arr[idx];
}
else
{
Hash dic = obj as Hash;
if (dic==null || !dic.ContainsKey(key)) return null;
obj = dic[key];
}
}
return obj;
}
public static object GetByPathAny(System.Collections.Generic.List<object> objects, System.Collections.Generic.List<string> pathes) {
foreach (object obj in objects)
{
foreach (string path in pathes)
{
object ret = GetByPath(obj, path);
if (ret != null) return ret;
}
}
return null;
}
public static void SetByPath(object obj, string path, object value)
{
string[] aPath = path.Split('.');
int n = aPath.Length;
while (0 < n && aPath[n-1] == "") n--;
for (int i=0; i<n; i++)
{
string key = aPath[i];
if (key == "") continue;
if (Regex.IsMatch(key, @"^\d+$"))
{
int idx = Convert.ToInt32(key);
List<object> arr = obj as List<object>;
if (i==n-1) arr[idx] = value; else obj = arr[idx];
}
else
{
Hash dic = obj as Hash;
if (i==n-1)
{
dic[key] = value;
}
else
{
if (!dic.ContainsKey(key))
{
bool isNum = Regex.IsMatch(aPath[i+1], @"^\d+$");
dic[key] = isNum ? (object)(new List<object> {}) : (object)(new Hash {});
}
obj = dic[key];
}
}
}
}
public static object CreateClassInstance(string classPath, System.Collections.Generic.List<object> args)
{
string[] aPath = classPath.Split('.');
for (int i=0; i<aPath.Length; i++) {
aPath[i] = aPath[i].Substring(0, 1).ToUpper() + aPath[i].Substring(1);
}
classPath = string.Join(".", aPath);
//Console.WriteLine("[CreateClassInstance] " + classPath + " " + EncodeJson(args));
object[] a = new object[args.Count];
args.CopyTo(a);
return Activator.CreateInstance(Type.GetType(classPath), a);
}
public static DateTime? Str2date(string s)
{
return (DateTime?)DateTime.Parse(s);
}
public static string Date2str(DateTime? d)
{
return d==null ? null : ((DateTime)d).ToString("s");
}
public static long Ip2long(string str)
{
if (!Regex.IsMatch(str, @"^\d+\.\d+\.\d+\.\d+$")) return -1;
IPAddress ip;
if (!IPAddress.TryParse(str, out ip)) return -1;
Byte[] b = ip.GetAddressBytes();
return ((long)b[0])<<24 | ((long)b[1])<<16 | ((long)b[2])<<8 | ((long)b[3]);
}
public static string Long2ip(long val)
{
IPAddress ip;
if (!IPAddress.TryParse(((UInt32)(long)val).ToString(), out ip)) return null;
return ip.ToString();
}
public static string UrlEncode(string s)
{
return Uri.EscapeDataString(s);
}
public static System.Collections.Generic.List<T> SortArray<T>(System.Collections.Generic.List<T> src) {
var ret = new List<T>(src);
ret.Sort();
return ret;
}
public static void Sleep(long sec)
{
Thread.Sleep(System.Convert.ToInt32(1000 * sec));
}
public static void ValidateArgCount(long actual, long expected)
{
}
public static void ValidateType(object value, string typeName, bool force=false)
{
}
public static System.Collections.Generic.List<U> CastArray<T, U>(System.Collections.Generic.List<T> a, U dummy)
{
return a.ConvertAll(new Converter<T, U>((T x) => {return (U)(object)x;}));
// System.Collections.Generic.List<U> ret = new System.Collections.Generic.List<U>();
// foreach (var t in a) ret.Add((U)(object)t);
// return ret;
}
public static System.Collections.Generic.List<string> DictionaryKeys(dynamic d)
{
var dict = d as System.Collections.Generic.Dictionary<string, object>;
string[] ret = new string[dict.Keys.Count];
dict.Keys.CopyTo(ret, 0);
return new System.Collections.Generic.List<string>(ret);
}
public static object ArrayList2List(object obj)
{
if (obj is ArrayList) {
var list = obj as ArrayList;
var ret = new List<object>();
for (int i=0; i<list.Count; i++) {
ret.Add(ArrayList2List(list[i]));
}
return ret;
}
else if (obj is Dictionary<string, object>) {
var dict = obj as Dictionary<string, object>;
List<string> keys = DictionaryKeys(dict);
foreach (string key in keys) {
dict[key] = ArrayList2List(dict[key]);
}
return dict;
}
return obj;
}
public static T Pop<T>(System.Collections.Generic.List<T> a)
{
int i = a.Count - 1;
if (i<0) return default(T);
T ret = a[i];
a.RemoveAt(i);
return ret;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using Object = UnityEngine.Object;
public class ObjectPool
{
private readonly Dictionary<NoteType, int> initialNoteObjectCount = new Dictionary<NoteType, int>
{
{NoteType.Click, 24},
{NoteType.Hold, 12},
{NoteType.LongHold, 6},
{NoteType.Flick, 12},
{NoteType.DragHead, 12},
{NoteType.DragChild, 48},
{NoteType.CDragHead, 12},
{NoteType.CDragChild, 48}
};
private int initialDragLineObjectCount = 48;
public readonly SortedDictionary<int, Note> SpawnedNotes = new SortedDictionary<int, Note>(); // Currently on-screen
public readonly SortedDictionary<int, DragLineElement> SpawnedDragLines = new SortedDictionary<int, DragLineElement>();
private readonly Dictionary<NoteType, NotePoolItem> notePoolItems = new Dictionary<NoteType, NotePoolItem>();
private readonly DragLinePoolItem dragLinePoolItem = new DragLinePoolItem();
private readonly Dictionary<EffectController.Effect, PrefabPoolItem> effectPoolItems = new Dictionary<EffectController.Effect, PrefabPoolItem>();
public Game Game { get; }
public ObjectPool(Game game)
{
Game = game;
foreach (var type in (NoteType[]) Enum.GetValues(typeof(NoteType)))
{
notePoolItems[type] = new NotePoolItem();
}
foreach (var effect in (EffectController.Effect[]) Enum.GetValues(typeof(EffectController.Effect)))
{
effectPoolItems[effect] = new PrefabPoolItem();
}
}
public void UpdateNoteObjectCount(NoteType type, int count)
{
initialNoteObjectCount[type] = count;
}
public void Initialize()
{
initialDragLineObjectCount = initialNoteObjectCount[NoteType.DragHead]
+ initialNoteObjectCount[NoteType.DragChild]
+ initialNoteObjectCount[NoteType.CDragHead]
+ initialNoteObjectCount[NoteType.CDragChild];
var timer = new BenchmarkTimer("Game ObjectPool");
foreach (var type in initialNoteObjectCount.Keys)
{
for (var i = 0; i < initialNoteObjectCount[type]; i++)
{
Collect(notePoolItems[type], Instantiate(notePoolItems[type], new NoteInstantiateProvider {Type = type}));
}
}
timer.Time("Notes");
for (var i = 0; i < initialDragLineObjectCount; i++)
{
Collect(dragLinePoolItem, Instantiate(dragLinePoolItem, new PoolItemInstantiateProvider()));
}
timer.Time("DragLines");
var chart = Game.Chart;
var map = new Dictionary<EffectController.Effect, int>
{
{
EffectController.Effect.Clear,
chart.MaxSamePageNonDragTypeNoteCount * 2
},
{
EffectController.Effect.ClearDrag,
chart.MaxSamePageDragTypeNoteCount * 2
},
{
EffectController.Effect.Miss,
chart.MaxSamePageNoteCount * 2
},
{
EffectController.Effect.Hold,
chart.MaxSamePageHoldTypeNoteCount * 16 * 2
}
};
foreach (var pair in map)
{
var effect = pair.Key;
var count = pair.Value;
Debug.Log($"{effect} => {count}");
for (var i = 0; i < count; i++)
{
Collect(effectPoolItems[effect], Instantiate(
effectPoolItems[effect], new ParticleSystemInstantiateProvider
{
Prefab = Game.effectController.GetPrefab(effect),
Parent = Game.effectController.EffectParentTransform
}));
}
}
timer.Time("Effects");
timer.Time();
}
public void Dispose()
{
SpawnedNotes.Values.ForEach(it => it.Dispose());
notePoolItems.Values.ForEach(it => it.Dispose());
dragLinePoolItem.Dispose();
}
public Note SpawnNote(ChartModel.Note model)
{
if (SpawnedNotes.ContainsKey(model.id)) return SpawnedNotes[model.id];
var note = Spawn(notePoolItems[(NoteType) model.type], new NoteInstantiateProvider{Type = (NoteType) model.type}, new NoteSpawnProvider{Model = model});
SpawnedNotes[model.id] = note;
return note;
}
public void CollectNote(Note note)
{
if (!SpawnedNotes.ContainsKey(note.Model.id)) return;
Game.inputController.OnNoteCollected(note);
Collect(notePoolItems[note.Type], note);
SpawnedNotes.Remove(note.Model.id);
}
public DragLineElement SpawnDragLine(ChartModel.Note from, ChartModel.Note to)
{
if (SpawnedDragLines.ContainsKey(from.id)) return SpawnedDragLines[from.id];
return SpawnedDragLines[from.id] = Spawn(dragLinePoolItem, new PoolItemInstantiateProvider(),
new DragLineSpawnProvider {From = from, To = to});
}
public void CollectDragLine(DragLineElement element)
{
if (!SpawnedDragLines.ContainsKey(element.FromNoteModel.id)) return;
Collect(dragLinePoolItem, element);
SpawnedDragLines.Remove(element.FromNoteModel.id);
}
public ParticleSystem SpawnEffect(EffectController.Effect effect, Vector3 position, Transform parent = default)
{
return Spawn(effectPoolItems[effect],
new ParticleSystemInstantiateProvider
{
Prefab = Game.effectController.GetPrefab(effect), Parent = Game.effectController.EffectParentTransform
},
new ParticleSystemSpawnProvider
{
Position = position,
Parent = parent
});
}
public void CollectEffect(EffectController.Effect effect, ParticleSystem particle)
{
Collect(effectPoolItems[effect], particle);
}
private T Instantiate<T, TI, TS>(PoolItem<T, TI, TS> poolItem, TI instantiateArguments)
where TI : PoolItemInstantiateProvider
where TS : PoolItemSpawnProvider
{
// Debug.Log("Instantiating " + typeof(T).Name);
return poolItem.OnInstantiate(Game, instantiateArguments);
}
private T Spawn<T, TI, TS>(PoolItem<T, TI, TS> poolItem, TI instantiateArguments, TS spawnArguments)
where TI : PoolItemInstantiateProvider
where TS : PoolItemSpawnProvider
{
var obj = poolItem.PooledItems.Count == 0 ? Instantiate(poolItem, instantiateArguments) : poolItem.PooledItems.Dequeue();
poolItem.OnSpawn(Game, obj, spawnArguments);
return obj;
}
private void Collect<T, TI, TS>(PoolItem<T, TI, TS> poolItem, T obj)
where TI : PoolItemInstantiateProvider
where TS : PoolItemSpawnProvider
{
poolItem.OnCollect(Game, obj);
poolItem.PooledItems.Enqueue(obj);
}
public class PoolItemInstantiateProvider
{
}
public class PoolItemSpawnProvider
{
}
public abstract class PoolItem<T, TI, TS> where TI : PoolItemInstantiateProvider where TS : PoolItemSpawnProvider
{
public readonly Queue<T> PooledItems = new Queue<T>();
public abstract T OnInstantiate(Game game, TI arguments);
public abstract void OnSpawn(Game game, T item, TS arguments);
public abstract void OnCollect(Game game, T item);
public abstract void Dispose();
}
public class NoteInstantiateProvider : PoolItemInstantiateProvider
{
public NoteType Type;
}
public class NoteSpawnProvider : PoolItemSpawnProvider
{
public ChartModel.Note Model;
}
public class NotePoolItem : PoolItem<Note, NoteInstantiateProvider, NoteSpawnProvider>
{
public override Note OnInstantiate(Game game, NoteInstantiateProvider arguments)
{
var provider = GameObjectProvider.Instance;
var type = arguments.Type;
Note note;
switch (type)
{
case NoteType.Click:
note = Object.Instantiate(provider.clickNotePrefab, game.contentParent.transform).GetComponent<Note>();
break;
case NoteType.CDragHead:
note = Object.Instantiate(provider.cDragHeadNotePrefab, game.contentParent.transform).GetComponent<Note>();
break;
case NoteType.Hold:
note = Object.Instantiate(provider.holdNotePrefab, game.contentParent.transform).GetComponent<Note>();
break;
case NoteType.LongHold:
note = Object.Instantiate(provider.longHoldNotePrefab, game.contentParent.transform).GetComponent<Note>();
break;
case NoteType.Flick:
note = Object.Instantiate(provider.flickNotePrefab, game.contentParent.transform).GetComponent<Note>();
break;
case NoteType.DragHead:
note = Object.Instantiate(provider.dragHeadNotePrefab, game.contentParent.transform).GetComponent<Note>();
break;
case NoteType.DragChild:
case NoteType.CDragChild:
note = Object.Instantiate(provider.dragChildNotePrefab, game.contentParent.transform).GetComponent<Note>();
break;
default:
throw new ArgumentOutOfRangeException();
}
return note;
}
public override void OnSpawn(Game game, Note note, NoteSpawnProvider arguments)
{
note.gameObject.SetActive(true);
note.Initialize(game);
note.SetData(arguments.Model.id);
note.gameObject.SetLayerRecursively(game.ContentLayer);
}
public override void OnCollect(Game game, Note note)
{
if (note == null || note.gameObject == null) return;
note.gameObject.SetActive(false);
}
public override void Dispose()
{
PooledItems.ForEach(it => it.Dispose());
}
}
public class DragLineSpawnProvider : PoolItemSpawnProvider
{
public ChartModel.Note From;
public ChartModel.Note To;
}
public class DragLinePoolItem : PoolItem<DragLineElement, PoolItemInstantiateProvider, DragLineSpawnProvider>
{
public override DragLineElement OnInstantiate(Game game, PoolItemInstantiateProvider arguments)
{
var dragLine = Object.Instantiate(GameObjectProvider.Instance.dragLinePrefab, game.contentParent.transform)
.GetComponent<DragLineElement>();
dragLine.gameObject.SetLayerRecursively(game.ContentLayer);
return dragLine;
}
public override void OnSpawn(Game game, DragLineElement dragLine, DragLineSpawnProvider arguments)
{
dragLine.gameObject.SetActive(true);
dragLine.Initialize(game);
dragLine.SetData(arguments.From, arguments.To);
}
public override void OnCollect(Game game, DragLineElement dragLine)
{
if (dragLine == null || dragLine.gameObject == null) return;
dragLine.gameObject.SetActive(false);
}
public override void Dispose()
{
PooledItems.ForEach(it => it.Dispose());
}
}
public class ParticleSystemInstantiateProvider : PoolItemInstantiateProvider
{
public ParticleSystem Prefab;
public Transform Parent;
}
public class ParticleSystemSpawnProvider : PoolItemSpawnProvider
{
public Transform Parent;
public Vector3 Position;
}
public class PrefabPoolItem : PoolItem<ParticleSystem, ParticleSystemInstantiateProvider, ParticleSystemSpawnProvider>
{
public override ParticleSystem OnInstantiate(Game game, ParticleSystemInstantiateProvider arguments)
{
return Object.Instantiate(arguments.Prefab, arguments.Parent, true);
}
public override void OnSpawn(Game game, ParticleSystem particle, ParticleSystemSpawnProvider arguments)
{
particle.gameObject.SetActive(true);
if (arguments.Parent != default)
{
var transform = particle.transform;
transform.SetParent(arguments.Parent);
transform.localPosition = arguments.Position;
}
else
{
particle.transform.position = arguments.Position;
}
// Play() is controlled by the caller
}
public override void OnCollect(Game game, ParticleSystem particle)
{
if (particle == null || particle.gameObject == null) return;
particle.Stop();
particle.gameObject.SetActive(false);
}
public override void Dispose()
{
PooledItems.ForEach(Object.Destroy);
}
}
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
/// <summary>
/// CompositionSettingsResource
/// </summary>
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using Twilio.Base;
using Twilio.Clients;
using Twilio.Converters;
using Twilio.Exceptions;
using Twilio.Http;
namespace Twilio.Rest.Video.V1
{
public class CompositionSettingsResource : Resource
{
private static Request BuildFetchRequest(FetchCompositionSettingsOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.Video,
"/v1/CompositionSettings/Default",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// fetch
/// </summary>
/// <param name="options"> Fetch CompositionSettings parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of CompositionSettings </returns>
public static CompositionSettingsResource Fetch(FetchCompositionSettingsOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// fetch
/// </summary>
/// <param name="options"> Fetch CompositionSettings parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of CompositionSettings </returns>
public static async System.Threading.Tasks.Task<CompositionSettingsResource> FetchAsync(FetchCompositionSettingsOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// fetch
/// </summary>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of CompositionSettings </returns>
public static CompositionSettingsResource Fetch(ITwilioRestClient client = null)
{
var options = new FetchCompositionSettingsOptions();
return Fetch(options, client);
}
#if !NET35
/// <summary>
/// fetch
/// </summary>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of CompositionSettings </returns>
public static async System.Threading.Tasks.Task<CompositionSettingsResource> FetchAsync(ITwilioRestClient client = null)
{
var options = new FetchCompositionSettingsOptions();
return await FetchAsync(options, client);
}
#endif
private static Request BuildCreateRequest(CreateCompositionSettingsOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Post,
Rest.Domain.Video,
"/v1/CompositionSettings/Default",
postParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// create
/// </summary>
/// <param name="options"> Create CompositionSettings parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of CompositionSettings </returns>
public static CompositionSettingsResource Create(CreateCompositionSettingsOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildCreateRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// create
/// </summary>
/// <param name="options"> Create CompositionSettings parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of CompositionSettings </returns>
public static async System.Threading.Tasks.Task<CompositionSettingsResource> CreateAsync(CreateCompositionSettingsOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildCreateRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// create
/// </summary>
/// <param name="friendlyName"> A descriptive string that you create to describe the resource </param>
/// <param name="awsCredentialsSid"> The SID of the stored Credential resource </param>
/// <param name="encryptionKeySid"> The SID of the Public Key resource to use for encryption </param>
/// <param name="awsS3Url"> The URL of the AWS S3 bucket where the compositions should be stored </param>
/// <param name="awsStorageEnabled"> Whether all compositions should be written to the aws_s3_url </param>
/// <param name="encryptionEnabled"> Whether all compositions should be stored in an encrypted form </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of CompositionSettings </returns>
public static CompositionSettingsResource Create(string friendlyName,
string awsCredentialsSid = null,
string encryptionKeySid = null,
Uri awsS3Url = null,
bool? awsStorageEnabled = null,
bool? encryptionEnabled = null,
ITwilioRestClient client = null)
{
var options = new CreateCompositionSettingsOptions(friendlyName){AwsCredentialsSid = awsCredentialsSid, EncryptionKeySid = encryptionKeySid, AwsS3Url = awsS3Url, AwsStorageEnabled = awsStorageEnabled, EncryptionEnabled = encryptionEnabled};
return Create(options, client);
}
#if !NET35
/// <summary>
/// create
/// </summary>
/// <param name="friendlyName"> A descriptive string that you create to describe the resource </param>
/// <param name="awsCredentialsSid"> The SID of the stored Credential resource </param>
/// <param name="encryptionKeySid"> The SID of the Public Key resource to use for encryption </param>
/// <param name="awsS3Url"> The URL of the AWS S3 bucket where the compositions should be stored </param>
/// <param name="awsStorageEnabled"> Whether all compositions should be written to the aws_s3_url </param>
/// <param name="encryptionEnabled"> Whether all compositions should be stored in an encrypted form </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of CompositionSettings </returns>
public static async System.Threading.Tasks.Task<CompositionSettingsResource> CreateAsync(string friendlyName,
string awsCredentialsSid = null,
string encryptionKeySid = null,
Uri awsS3Url = null,
bool? awsStorageEnabled = null,
bool? encryptionEnabled = null,
ITwilioRestClient client = null)
{
var options = new CreateCompositionSettingsOptions(friendlyName){AwsCredentialsSid = awsCredentialsSid, EncryptionKeySid = encryptionKeySid, AwsS3Url = awsS3Url, AwsStorageEnabled = awsStorageEnabled, EncryptionEnabled = encryptionEnabled};
return await CreateAsync(options, client);
}
#endif
/// <summary>
/// Converts a JSON string into a CompositionSettingsResource object
/// </summary>
/// <param name="json"> Raw JSON string </param>
/// <returns> CompositionSettingsResource object represented by the provided JSON </returns>
public static CompositionSettingsResource FromJson(string json)
{
// Convert all checked exceptions to Runtime
try
{
return JsonConvert.DeserializeObject<CompositionSettingsResource>(json);
}
catch (JsonException e)
{
throw new ApiException(e.Message, e);
}
}
/// <summary>
/// The SID of the Account that created the resource
/// </summary>
[JsonProperty("account_sid")]
public string AccountSid { get; private set; }
/// <summary>
/// The string that you assigned to describe the resource
/// </summary>
[JsonProperty("friendly_name")]
public string FriendlyName { get; private set; }
/// <summary>
/// The SID of the stored Credential resource
/// </summary>
[JsonProperty("aws_credentials_sid")]
public string AwsCredentialsSid { get; private set; }
/// <summary>
/// The URL of the AWS S3 bucket where the compositions are stored
/// </summary>
[JsonProperty("aws_s3_url")]
public Uri AwsS3Url { get; private set; }
/// <summary>
/// Whether all compositions are written to the aws_s3_url
/// </summary>
[JsonProperty("aws_storage_enabled")]
public bool? AwsStorageEnabled { get; private set; }
/// <summary>
/// The SID of the Public Key resource used for encryption
/// </summary>
[JsonProperty("encryption_key_sid")]
public string EncryptionKeySid { get; private set; }
/// <summary>
/// Whether all compositions are stored in an encrypted form
/// </summary>
[JsonProperty("encryption_enabled")]
public bool? EncryptionEnabled { get; private set; }
/// <summary>
/// The absolute URL of the resource
/// </summary>
[JsonProperty("url")]
public Uri Url { get; private set; }
private CompositionSettingsResource()
{
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.ComponentModel;
using System.Diagnostics.Contracts;
namespace System.IO.Compression
{
[EditorBrowsable(EditorBrowsableState.Never)]
public static class ZipFileExtensions
{
#region ZipArchive extensions
/// <summary>
/// <p>Adds a file from the file system to the archive under the specified entry name.
/// The new entry in the archive will contain the contents of the file.
/// The last write time of the archive entry is set to the last write time of the file on the file system.
/// If an entry with the specified name already exists in the archive, a second entry will be created that has an identical name.
/// If the specified source file has an invalid last modified time, the first datetime representable in the Zip timestamp format
/// (midnight on January 1, 1980) will be used.</p>
///
/// <p>If an entry with the specified name already exists in the archive, a second entry will be created that has an identical name.</p>
///
/// <p>Since no <code>CompressionLevel</code> is specified, the default provided by the implementation of the underlying compression
/// algorithm will be used; the <code>ZipArchive</code> will not impose its own default.
/// (Currently, the underlying compression algorithm is provided by the <code>System.IO.Compression.DeflateStream</code> class.)</p>
/// </summary>
///
/// <exception cref="ArgumentException">sourceFileName is a zero-length string, contains only white space, or contains one or more
/// invalid characters as defined by InvalidPathChars. -or- entryName is a zero-length string.</exception>
/// <exception cref="ArgumentNullException">sourceFileName or entryName is null.</exception>
/// <exception cref="PathTooLongException">In sourceFileName, the specified path, file name, or both exceed the system-defined maximum length.
/// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters.</exception>
/// <exception cref="DirectoryNotFoundException">The specified sourceFileName is invalid, (for example, it is on an unmapped drive).</exception>
/// <exception cref="IOException">An I/O error occurred while opening the file specified by sourceFileName.</exception>
/// <exception cref="UnauthorizedAccessException">sourceFileName specified a directory. -or- The caller does not have the
/// required permission.</exception>
/// <exception cref="FileNotFoundException">The file specified in sourceFileName was not found. </exception>
/// <exception cref="NotSupportedException">sourceFileName is in an invalid format or the ZipArchive does not support writing.</exception>
/// <exception cref="ObjectDisposedException">The ZipArchive has already been closed.</exception>
///
/// <param name="sourceFileName">The path to the file on the file system to be copied from. The path is permitted to specify
/// relative or absolute path information. Relative path information is interpreted as relative to the current working directory.</param>
/// <param name="entryName">The name of the entry to be created.</param>
/// <returns>A wrapper for the newly created entry.</returns>
public static ZipArchiveEntry CreateEntryFromFile(this ZipArchive destination, String sourceFileName, String entryName)
{
Contract.Ensures(Contract.Result<ZipArchiveEntry>() != null);
Contract.EndContractBlock();
return DoCreateEntryFromFile(destination, sourceFileName, entryName, null);
}
/// <summary>
/// <p>Adds a file from the file system to the archive under the specified entry name.
/// The new entry in the archive will contain the contents of the file.
/// The last write time of the archive entry is set to the last write time of the file on the file system.
/// If an entry with the specified name already exists in the archive, a second entry will be created that has an identical name.
/// If the specified source file has an invalid last modified time, the first datetime representable in the Zip timestamp format
/// (midnight on January 1, 1980) will be used.</p>
/// <p>If an entry with the specified name already exists in the archive, a second entry will be created that has an identical name.</p>
/// </summary>
/// <exception cref="ArgumentException">sourceFileName is a zero-length string, contains only white space, or contains one or more
/// invalid characters as defined by InvalidPathChars. -or- entryName is a zero-length string.</exception>
/// <exception cref="ArgumentNullException">sourceFileName or entryName is null.</exception>
/// <exception cref="PathTooLongException">In sourceFileName, the specified path, file name, or both exceed the system-defined maximum length.
/// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters.</exception>
/// <exception cref="DirectoryNotFoundException">The specified sourceFileName is invalid, (for example, it is on an unmapped drive).</exception>
/// <exception cref="IOException">An I/O error occurred while opening the file specified by sourceFileName.</exception>
/// <exception cref="UnauthorizedAccessException">sourceFileName specified a directory.
/// -or- The caller does not have the required permission.</exception>
/// <exception cref="FileNotFoundException">The file specified in sourceFileName was not found. </exception>
/// <exception cref="NotSupportedException">sourceFileName is in an invalid format or the ZipArchive does not support writing.</exception>
/// <exception cref="ObjectDisposedException">The ZipArchive has already been closed.</exception>
///
/// <param name="sourceFileName">The path to the file on the file system to be copied from. The path is permitted to specify relative
/// or absolute path information. Relative path information is interpreted as relative to the current working directory.</param>
/// <param name="entryName">The name of the entry to be created.</param>
/// <param name="compressionLevel">The level of the compression (speed/memory vs. compressed size trade-off).</param>
/// <returns>A wrapper for the newly created entry.</returns>
public static ZipArchiveEntry CreateEntryFromFile(this ZipArchive destination,
String sourceFileName, String entryName, CompressionLevel compressionLevel)
{
// Checking of compressionLevel is passed down to DeflateStream and the IDeflater implementation
// as it is a pugable component that completely encapsulates the meaning of compressionLevel.
Contract.Ensures(Contract.Result<ZipArchiveEntry>() != null);
Contract.EndContractBlock();
return DoCreateEntryFromFile(destination, sourceFileName, entryName, compressionLevel);
}
/// <summary>
/// Extracts all of the files in the archive to a directory on the file system. The specified directory may already exist.
/// This method will create all subdirectories and the specified directory if necessary.
/// If there is an error while extracting the archive, the archive will remain partially extracted.
/// Each entry will be extracted such that the extracted file has the same relative path to destinationDirectoryName as the
/// entry has to the root of the archive. If a file to be archived has an invalid last modified time, the first datetime
/// representable in the Zip timestamp format (midnight on January 1, 1980) will be used.
/// </summary>
///
/// <exception cref="ArgumentException">destinationDirectoryName is a zero-length string, contains only white space,
/// or contains one or more invalid characters as defined by InvalidPathChars.</exception>
/// <exception cref="ArgumentNullException">destinationDirectoryName is null.</exception>
/// <exception cref="PathTooLongException">The specified path, file name, or both exceed the system-defined maximum length.
/// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters.</exception>
/// <exception cref="DirectoryNotFoundException">The specified path is invalid, (for example, it is on an unmapped drive).</exception>
/// <exception cref="IOException">An archive entry?s name is zero-length, contains only white space, or contains one or more invalid
/// characters as defined by InvalidPathChars. -or- Extracting an archive entry would have resulted in a destination
/// file that is outside destinationDirectoryName (for example, if the entry name contains parent directory accessors).
/// -or- An archive entry has the same name as an already extracted entry from the same archive.</exception>
/// <exception cref="UnauthorizedAccessException">The caller does not have the required permission.</exception>
/// <exception cref="NotSupportedException">destinationDirectoryName is in an invalid format. </exception>
/// <exception cref="InvalidDataException">An archive entry was not found or was corrupt.
/// -or- An archive entry has been compressed using a compression method that is not supported.</exception>
///
/// <param name="destinationDirectoryName">The path to the directory on the file system.
/// The directory specified must not exist. The path is permitted to specify relative or absolute path information.
/// Relative path information is interpreted as relative to the current working directory.</param>
public static void ExtractToDirectory(this ZipArchive source, String destinationDirectoryName)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
if (destinationDirectoryName == null)
throw new ArgumentNullException(nameof(destinationDirectoryName));
Contract.EndContractBlock();
// Rely on Directory.CreateDirectory for validation of destinationDirectoryName.
// Note that this will give us a good DirectoryInfo even if destinationDirectoryName exists:
DirectoryInfo di = Directory.CreateDirectory(destinationDirectoryName);
String destinationDirectoryFullPath = di.FullName;
foreach (ZipArchiveEntry entry in source.Entries)
{
String fileDestinationPath = Path.GetFullPath(Path.Combine(destinationDirectoryFullPath, entry.FullName));
if (!fileDestinationPath.StartsWith(destinationDirectoryFullPath, PathInternal.StringComparison))
throw new IOException(SR.IO_ExtractingResultsInOutside);
if (Path.GetFileName(fileDestinationPath).Length == 0)
{
// If it is a directory:
if (entry.Length != 0)
throw new IOException(SR.IO_DirectoryNameWithData);
Directory.CreateDirectory(fileDestinationPath);
}
else
{
// If it is a file:
// Create containing directory:
Directory.CreateDirectory(Path.GetDirectoryName(fileDestinationPath));
entry.ExtractToFile(fileDestinationPath, overwrite: false);
}
}
}
internal static ZipArchiveEntry DoCreateEntryFromFile(ZipArchive destination,
String sourceFileName, String entryName, CompressionLevel? compressionLevel)
{
if (destination == null)
throw new ArgumentNullException(nameof(destination));
if (sourceFileName == null)
throw new ArgumentNullException(nameof(sourceFileName));
if (entryName == null)
throw new ArgumentNullException(nameof(entryName));
// Checking of compressionLevel is passed down to DeflateStream and the IDeflater implementation
// as it is a pugable component that completely encapsulates the meaning of compressionLevel.
// Argument checking gets passed down to FileStream's ctor and CreateEntry
Contract.Ensures(Contract.Result<ZipArchiveEntry>() != null);
Contract.EndContractBlock();
using (Stream fs = new FileStream(sourceFileName, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 0x1000, useAsync: false))
{
ZipArchiveEntry entry = compressionLevel.HasValue
? destination.CreateEntry(entryName, compressionLevel.Value)
: destination.CreateEntry(entryName);
DateTime lastWrite = File.GetLastWriteTime(sourceFileName);
// If file to be archived has an invalid last modified time, use the first datetime representable in the Zip timestamp format
// (midnight on January 1, 1980):
if (lastWrite.Year < 1980 || lastWrite.Year > 2107)
lastWrite = new DateTime(1980, 1, 1, 0, 0, 0);
entry.LastWriteTime = lastWrite;
using (Stream es = entry.Open())
fs.CopyTo(es);
return entry;
}
}
#endregion ZipArchive extensions
#region ZipArchiveEntry extensions
/// <summary>
/// Creates a file on the file system with the entry?s contents and the specified name. The last write time of the file is set to the
/// entry?s last write time. This method does not allow overwriting of an existing file with the same name. Attempting to extract explicit
/// directories (entries with names that end in directory separator characters) will not result in the creation of a directory.
/// </summary>
///
/// <exception cref="UnauthorizedAccessException">The caller does not have the required permission.</exception>
/// <exception cref="ArgumentException">destinationFileName is a zero-length string, contains only white space, or contains one or more
/// invalid characters as defined by InvalidPathChars. -or- destinationFileName specifies a directory.</exception>
/// <exception cref="ArgumentNullException">destinationFileName is null.</exception>
/// <exception cref="PathTooLongException">The specified path, file name, or both exceed the system-defined maximum length.
/// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters.</exception>
/// <exception cref="DirectoryNotFoundException">The path specified in destinationFileName is invalid (for example, it is on
/// an unmapped drive).</exception>
/// <exception cref="IOException">destinationFileName already exists.
/// -or- An I/O error has occurred. -or- The entry is currently open for writing.
/// -or- The entry has been deleted from the archive.</exception>
/// <exception cref="NotSupportedException">destinationFileName is in an invalid format
/// -or- The ZipArchive that this entry belongs to was opened in a write-only mode.</exception>
/// <exception cref="InvalidDataException">The entry is missing from the archive or is corrupt and cannot be read
/// -or- The entry has been compressed using a compression method that is not supported.</exception>
/// <exception cref="ObjectDisposedException">The ZipArchive that this entry belongs to has been disposed.</exception>
///
/// <param name="destinationFileName">The name of the file that will hold the contents of the entry.
/// The path is permitted to specify relative or absolute path information.
/// Relative path information is interpreted as relative to the current working directory.</param>
public static void ExtractToFile(this ZipArchiveEntry source, String destinationFileName)
{
ExtractToFile(source, destinationFileName, false);
}
/// <summary>
/// Creates a file on the file system with the entry?s contents and the specified name.
/// The last write time of the file is set to the entry?s last write time.
/// This method does allows overwriting of an existing file with the same name.
/// </summary>
///
/// <exception cref="UnauthorizedAccessException">The caller does not have the required permission.</exception>
/// <exception cref="ArgumentException">destinationFileName is a zero-length string, contains only white space,
/// or contains one or more invalid characters as defined by InvalidPathChars. -or- destinationFileName specifies a directory.</exception>
/// <exception cref="ArgumentNullException">destinationFileName is null.</exception>
/// <exception cref="PathTooLongException">The specified path, file name, or both exceed the system-defined maximum length.
/// For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters.</exception>
/// <exception cref="DirectoryNotFoundException">The path specified in destinationFileName is invalid
/// (for example, it is on an unmapped drive).</exception>
/// <exception cref="IOException">destinationFileName exists and overwrite is false.
/// -or- An I/O error has occurred.
/// -or- The entry is currently open for writing.
/// -or- The entry has been deleted from the archive.</exception>
/// <exception cref="NotSupportedException">destinationFileName is in an invalid format
/// -or- The ZipArchive that this entry belongs to was opened in a write-only mode.</exception>
/// <exception cref="InvalidDataException">The entry is missing from the archive or is corrupt and cannot be read
/// -or- The entry has been compressed using a compression method that is not supported.</exception>
/// <exception cref="ObjectDisposedException">The ZipArchive that this entry belongs to has been disposed.</exception>
/// <param name="destinationFileName">The name of the file that will hold the contents of the entry.
/// The path is permitted to specify relative or absolute path information.
/// Relative path information is interpreted as relative to the current working directory.</param>
/// <param name="overwrite">True to indicate overwrite.</param>
public static void ExtractToFile(this ZipArchiveEntry source, String destinationFileName, Boolean overwrite)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
if (destinationFileName == null)
throw new ArgumentNullException(nameof(destinationFileName));
// Rely on FileStream's ctor for further checking destinationFileName parameter
Contract.EndContractBlock();
FileMode fMode = overwrite ? FileMode.Create : FileMode.CreateNew;
using (Stream fs = new FileStream(destinationFileName, fMode, FileAccess.Write, FileShare.None, bufferSize: 0x1000, useAsync: false))
{
using (Stream es = source.Open())
es.CopyTo(fs);
}
File.SetLastWriteTime(destinationFileName, source.LastWriteTime.DateTime);
}
#endregion ZipArchiveEntry extensions
} // class ZipFileExtensions
} // namespace
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Runtime.InteropServices.Tests.Common;
using Xunit;
namespace System.Runtime.InteropServices.Tests
{
public class StructureToPtrTests
{
[Fact]
public void StructureToPtr_ByValBoolArray_Success()
{
var structure1 = new StructWithBoolArray()
{
array = new bool[] { true, true, true, true }
};
int size = Marshal.SizeOf(structure1);
IntPtr memory = Marshal.AllocHGlobal(size + sizeof(int));
try
{
Marshal.WriteInt32(memory, size, 0xFF);
Marshal.StructureToPtr(structure1, memory, false);
Marshal.StructureToPtr(structure1, memory, true);
Assert.Equal(0xFF, Marshal.ReadInt32(memory, size));
}
finally
{
Marshal.FreeHGlobal(memory);
}
}
[Fact]
public void StructureToPtr_ByValArrayInStruct_Success()
{
var structure = new StructWithByValArray()
{
array = new StructWithIntField[]
{
new StructWithIntField { value = 1 },
new StructWithIntField { value = 2 },
new StructWithIntField { value = 3 },
new StructWithIntField { value = 4 },
new StructWithIntField { value = 5 }
}
};
int size = Marshal.SizeOf(structure);
IntPtr memory = Marshal.AllocHGlobal(size);
try
{
Marshal.StructureToPtr(structure, memory, false);
Marshal.StructureToPtr(structure, memory, true);
}
finally
{
Marshal.FreeHGlobal(memory);
}
}
[Fact]
public void StructureToPtr_OverflowByValArrayInStruct_Success()
{
var structure = new StructWithByValArray()
{
array = new StructWithIntField[]
{
new StructWithIntField { value = 1 },
new StructWithIntField { value = 2 },
new StructWithIntField { value = 3 },
new StructWithIntField { value = 4 },
new StructWithIntField { value = 5 },
new StructWithIntField { value = 6 }
}
};
int size = Marshal.SizeOf(structure);
IntPtr memory = Marshal.AllocHGlobal(size);
try
{
Marshal.StructureToPtr(structure, memory, false);
Marshal.StructureToPtr(structure, memory, true);
}
finally
{
Marshal.FreeHGlobal(memory);
}
}
[Fact]
public void StructureToPtr_ByValDateArray_Success()
{
var structure = new StructWithDateArray()
{
array = new DateTime[]
{
DateTime.Now, DateTime.Now , DateTime.Now, DateTime.Now, DateTime.Now, DateTime.Now , DateTime.Now, DateTime.Now
}
};
int size = Marshal.SizeOf(structure);
IntPtr memory = Marshal.AllocHGlobal(size);
try
{
Marshal.StructureToPtr(structure, memory, false);
Marshal.StructureToPtr(structure, memory, true);
}
finally
{
Marshal.DestroyStructure(memory, structure.GetType());
Marshal.FreeHGlobal(memory);
}
}
[Fact]
public void StructureToPtr_NullPtr_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("ptr", () => Marshal.StructureToPtr((object)new SomeTestStruct_Auto(), IntPtr.Zero, fDeleteOld: true));
AssertExtensions.Throws<ArgumentNullException>("ptr", () => Marshal.StructureToPtr(new SomeTestStruct_Auto(), IntPtr.Zero, fDeleteOld: true));
}
[Fact]
public void StructureToPtr_NullStructure_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("structure", () => Marshal.StructureToPtr(null, (IntPtr)1, fDeleteOld: true));
AssertExtensions.Throws<ArgumentNullException>("structure", () => Marshal.StructureToPtr<object>(null, (IntPtr)1, fDeleteOld: true));
}
public static IEnumerable<object[]> StructureToPtr_GenericClass_TestData()
{
yield return new object[] { new GenericClass<string>() };
yield return new object[] { new GenericStruct<string>() };
}
[Theory]
[MemberData(nameof(StructureToPtr_GenericClass_TestData))]
public void StructureToPtr_GenericObject_ThrowsArgumentException(object o)
{
AssertExtensions.Throws<ArgumentException>("structure", () => Marshal.StructureToPtr(o, (IntPtr)1, fDeleteOld: true));
AssertExtensions.Throws<ArgumentException>("structure", () => Marshal.StructureToPtr<object>(o, (IntPtr)1, fDeleteOld: true));
}
public static IEnumerable<object[]> StructureToPtr_NonBlittableObject_TestData()
{
yield return new object[] { new NonGenericClass() };
yield return new object[] { "string" };
}
[Theory]
[MemberData(nameof(StructureToPtr_NonBlittableObject_TestData))]
public void StructureToPtr_NonBlittable_ThrowsArgumentException(object o)
{
AssertExtensions.Throws<ArgumentException>("structure", () => Marshal.StructureToPtr(o, (IntPtr)1, fDeleteOld: true));
AssertExtensions.Throws<ArgumentException>("structure", () => Marshal.StructureToPtr<object>(o, (IntPtr)1, fDeleteOld: true));
}
[Fact]
public void StructureToPtr_AutoLayout_ThrowsArgumentException()
{
var someTs_Auto = new SomeTestStruct_Auto();
AssertExtensions.Throws<ArgumentException>("structure", () => Marshal.StructureToPtr((object)someTs_Auto, (IntPtr)1, fDeleteOld: true));
AssertExtensions.Throws<ArgumentException>("structure", () => Marshal.StructureToPtr(someTs_Auto, (IntPtr)1, fDeleteOld: true));
}
[Fact]
public void StructureToPtr_InvalidLengthByValArrayInStruct_ThrowsArgumentException()
{
var structure = new StructWithByValArray
{
array = new StructWithIntField[]
{
new StructWithIntField { value = 1 },
new StructWithIntField { value = 2 },
new StructWithIntField { value = 3 },
new StructWithIntField { value = 4 }
}
};
int size = Marshal.SizeOf(structure);
IntPtr memory = Marshal.AllocHGlobal(size);
try
{
Assert.Throws<ArgumentException>(() => Marshal.StructureToPtr(structure, memory, false));
Assert.Throws<ArgumentException>(() => Marshal.StructureToPtr(structure, memory, true));
}
finally
{
Marshal.FreeHGlobal(memory);
}
}
[Fact]
public unsafe void StructureToPtr_StructWithBlittableFixedBuffer_In_NonBlittable_Success()
{
var str = default(NonBlittableContainingBuffer);
// Assign values to the bytes.
byte* ptr = (byte*)&str.bufferStruct;
for (int i = 0; i < sizeof(HasFixedBuffer); i++)
ptr[i] = (byte)(0x11 * (i + 1));
HasFixedBuffer* original = (HasFixedBuffer*)ptr;
// Marshal the parent struct.
var parentStructIntPtr = Marshal.AllocHGlobal(Marshal.SizeOf<NonBlittableContainingBuffer>());
Marshal.StructureToPtr(str, parentStructIntPtr, false);
try
{
HasFixedBuffer* bufferStructPtr = (HasFixedBuffer*)parentStructIntPtr.ToPointer();
Assert.Equal(original->buffer[0], bufferStructPtr->buffer[0]);
Assert.Equal(original->buffer[1], bufferStructPtr->buffer[1]);
}
finally
{
Marshal.DestroyStructure<NonBlittableContainingBuffer>(parentStructIntPtr);
Marshal.FreeHGlobal(parentStructIntPtr);
}
}
[Fact]
public unsafe void StructureToPtr_NonBlittableStruct_WithBlittableFixedBuffer_Success()
{
NonBlittableWithBlittableBuffer x = new NonBlittableWithBlittableBuffer();
x.f[0] = 1;
x.f[1] = 2;
x.f[2] = 3;
x.s = null;
int size = Marshal.SizeOf(typeof(NonBlittableWithBlittableBuffer));
byte* p = stackalloc byte[size];
Marshal.StructureToPtr(x, (IntPtr)p, false);
NonBlittableWithBlittableBuffer y = Marshal.PtrToStructure<NonBlittableWithBlittableBuffer>((IntPtr)p);
Assert.Equal(x.f[0], y.f[0]);
Assert.Equal(x.f[1], y.f[1]);
Assert.Equal(x.f[2], y.f[2]);
}
[Fact]
public unsafe void StructureToPtr_OpaqueStruct_In_NonBlittableStructure_Success()
{
NonBlittableWithOpaque x = new NonBlittableWithOpaque();
byte* opaqueData = (byte*)&x.opaque;
*opaqueData = 1;
int size = Marshal.SizeOf(typeof(NonBlittableWithOpaque));
byte* p = stackalloc byte[size];
Marshal.StructureToPtr(x, (IntPtr)p, false);
NonBlittableWithOpaque y = Marshal.PtrToStructure<NonBlittableWithOpaque>((IntPtr)p);
byte* marshaledOpaqueData = (byte*)&y.opaque;
Assert.Equal(*opaqueData, *marshaledOpaqueData);
}
public struct StructWithIntField
{
public int value;
}
public struct StructWithByValArray
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 5)]
public StructWithIntField[] array;
}
public struct StructWithBoolArray
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)]
public bool[] array;
}
public struct StructWithDateArray
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)]
public DateTime[] array;
}
[StructLayout(LayoutKind.Auto)]
public struct SomeTestStruct_Auto
{
public int i;
}
[StructLayout(LayoutKind.Sequential)]
public unsafe struct HasFixedBuffer
{
public short member;
public fixed byte buffer[2];
public short member2;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct NonBlittableContainingBuffer
{
public HasFixedBuffer bufferStruct;
public string str;
public IntPtr intPtr;
}
unsafe struct NonBlittableWithBlittableBuffer
{
public fixed int f[100];
public string s;
}
[StructLayout(LayoutKind.Explicit, Size = 1)]
public struct OpaqueStruct
{
}
public struct NonBlittableWithOpaque
{
public OpaqueStruct opaque;
public string str;
}
}
}
| |
using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CorePhoto.IO;
using CorePhoto.Numerics;
namespace CorePhoto.Tiff
{
public static class TiffIfdEntryReader
{
public static uint GetInteger(this TiffIfdEntry entry, ByteOrder byteOrder)
{
if (entry.Count != 1)
throw new ImageFormatException("Cannot read a single value from an array of multiple items.");
switch (entry.Type)
{
case TiffType.Byte:
return DataConverter.ToByte(entry.Value, 0);
case TiffType.Short:
return DataConverter.ToUInt16(entry.Value, 0, byteOrder);
case TiffType.Long:
return DataConverter.ToUInt32(entry.Value, 0, byteOrder);
default:
throw new ImageFormatException($"A value of type '{entry.Type}' cannot be converted to an unsigned integer.");
}
}
public static int GetSignedInteger(this TiffIfdEntry entry, ByteOrder byteOrder)
{
if (entry.Count != 1)
throw new ImageFormatException("Cannot read a single value from an array of multiple items.");
switch (entry.Type)
{
case TiffType.SByte:
return DataConverter.ToSByte(entry.Value, 0);
case TiffType.SShort:
return DataConverter.ToInt16(entry.Value, 0, byteOrder);
case TiffType.SLong:
return DataConverter.ToInt32(entry.Value, 0, byteOrder);
default:
throw new ImageFormatException($"A value of type '{entry.Type}' cannot be converted to a signed integer.");
}
}
public static TiffIfdReference GetIfdReference(this TiffIfdEntry entry, ByteOrder byteOrder)
{
if (entry.Count != 1)
throw new ImageFormatException("Cannot read a single value from an array of multiple items.");
if (entry.Type != TiffType.Long && entry.Type != TiffType.Ifd)
throw new ImageFormatException($"A value of type '{entry.Type}' cannot be converted to an IFD reference.");
return new TiffIfdReference(DataConverter.ToUInt32(entry.Value, 0, byteOrder));
}
public static Task<uint[]> ReadIntegerArrayAsync(this TiffIfdEntry entry, Stream stream, ByteOrder byteOrder)
{
var type = entry.Type;
if (type != TiffType.Byte && type != TiffType.Short && type != TiffType.Long)
throw new ImageFormatException($"A value of type '{entry.Type}' cannot be converted to an unsigned integer.");
return ReadIntegerArrayAsync_Internal(entry, stream, byteOrder);
}
private static async Task<uint[]> ReadIntegerArrayAsync_Internal(TiffIfdEntry entry, Stream stream, ByteOrder byteOrder)
{
switch (entry.Type)
{
case TiffType.Byte:
{
byte[] data = await entry.ReadDataAsync(stream, byteOrder);
return Enumerable.Range(0, entry.Count).Select(index => (uint)DataConverter.ToByte(data, index)).ToArray();
}
case TiffType.Short:
{
byte[] data = await entry.ReadDataAsync(stream, byteOrder);
return Enumerable.Range(0, entry.Count).Select(index => (uint)DataConverter.ToUInt16(data, index * 2, byteOrder)).ToArray();
}
case TiffType.Long:
case TiffType.Ifd:
{
byte[] data = await entry.ReadDataAsync(stream, byteOrder);
return Enumerable.Range(0, entry.Count).Select(index => DataConverter.ToUInt32(data, index * 4, byteOrder)).ToArray();
}
default:
throw new InvalidOperationException();
}
}
public static Task<int[]> ReadSignedIntegerArrayAsync(this TiffIfdEntry entry, Stream stream, ByteOrder byteOrder)
{
var type = entry.Type;
if (type != TiffType.SByte && type != TiffType.SShort && type != TiffType.SLong)
throw new ImageFormatException($"A value of type '{entry.Type}' cannot be converted to a signed integer.");
return ReadSignedIntegerArrayAsync_Internal(entry, stream, byteOrder);
}
private static async Task<int[]> ReadSignedIntegerArrayAsync_Internal(TiffIfdEntry entry, Stream stream, ByteOrder byteOrder)
{
switch (entry.Type)
{
case TiffType.SByte:
{
byte[] data = await entry.ReadDataAsync(stream, byteOrder);
return Enumerable.Range(0, entry.Count).Select(index => (int)DataConverter.ToSByte(data, index)).ToArray();
}
case TiffType.SShort:
{
byte[] data = await entry.ReadDataAsync(stream, byteOrder);
return Enumerable.Range(0, entry.Count).Select(index => (int)DataConverter.ToInt16(data, index * 2, byteOrder)).ToArray();
}
case TiffType.SLong:
{
byte[] data = await entry.ReadDataAsync(stream, byteOrder);
return Enumerable.Range(0, entry.Count).Select(index => DataConverter.ToInt32(data, index * 4, byteOrder)).ToArray();
}
default:
throw new InvalidOperationException();
}
}
public static Task<string> ReadStringAsync(this TiffIfdEntry entry, Stream stream, ByteOrder byteOrder)
{
if (entry.Type != TiffType.Ascii)
throw new ImageFormatException($"A value of type '{entry.Type}' cannot be converted to a string.");
return ReadStringAsync_Internal(entry, stream, byteOrder);
}
private static async Task<string> ReadStringAsync_Internal(TiffIfdEntry entry, Stream stream, ByteOrder byteOrder)
{
byte[] data = await entry.ReadDataAsync(stream, byteOrder);
if (data[data.Length - 1] != 0)
throw new ImageFormatException("The retrieved string is not null terminated.");
return Encoding.ASCII.GetString(data, 0, data.Length - 1);
}
public static Task<Rational> ReadRationalAsync(this TiffIfdEntry entry, Stream stream, ByteOrder byteOrder)
{
if (entry.Type != TiffType.Rational)
throw new ImageFormatException($"A value of type '{entry.Type}' cannot be converted to a Rational.");
if (entry.Count != 1)
throw new ImageFormatException("Cannot read a single value from an array of multiple items.");
return ReadRationalAsync_Internal(entry, stream, byteOrder);
}
private static async Task<Rational> ReadRationalAsync_Internal(TiffIfdEntry entry, Stream stream, ByteOrder byteOrder)
{
var array = await ReadRationalArrayAsync_Internal(entry, stream, byteOrder);
return array[0];
}
public static Task<SignedRational> ReadSignedRationalAsync(this TiffIfdEntry entry, Stream stream, ByteOrder byteOrder)
{
if (entry.Type != TiffType.SRational)
throw new ImageFormatException($"A value of type '{entry.Type}' cannot be converted to a SignedRational.");
if (entry.Count != 1)
throw new ImageFormatException("Cannot read a single value from an array of multiple items.");
return ReadSignedRationalAsync_Internal(entry, stream, byteOrder);
}
private static async Task<SignedRational> ReadSignedRationalAsync_Internal(TiffIfdEntry entry, Stream stream, ByteOrder byteOrder)
{
var array = await ReadSignedRationalArrayAsync_Internal(entry, stream, byteOrder);
return array[0];
}
public static Task<Rational[]> ReadRationalArrayAsync(this TiffIfdEntry entry, Stream stream, ByteOrder byteOrder)
{
if (entry.Type != TiffType.Rational)
throw new ImageFormatException($"A value of type '{entry.Type}' cannot be converted to a Rational.");
return ReadRationalArrayAsync_Internal(entry, stream, byteOrder);
}
private static async Task<Rational[]> ReadRationalArrayAsync_Internal(TiffIfdEntry entry, Stream stream, ByteOrder byteOrder)
{
byte[] data = await entry.ReadDataAsync(stream, byteOrder);
return Enumerable.Range(0, entry.Count).Select(index =>
{
var numerator = DataConverter.ToUInt32(data, index * 8, byteOrder);
var denominator = DataConverter.ToUInt32(data, index * 8 + 4, byteOrder);
return new Rational(numerator, denominator);
}).ToArray();
}
public static Task<SignedRational[]> ReadSignedRationalArrayAsync(this TiffIfdEntry entry, Stream stream, ByteOrder byteOrder)
{
if (entry.Type != TiffType.SRational)
throw new ImageFormatException($"A value of type '{entry.Type}' cannot be converted to a SignedRational.");
return ReadSignedRationalArrayAsync_Internal(entry, stream, byteOrder);
}
private static async Task<SignedRational[]> ReadSignedRationalArrayAsync_Internal(TiffIfdEntry entry, Stream stream, ByteOrder byteOrder)
{
byte[] data = await entry.ReadDataAsync(stream, byteOrder);
return Enumerable.Range(0, entry.Count).Select(index =>
{
var numerator = DataConverter.ToInt32(data, index * 8, byteOrder);
var denominator = DataConverter.ToInt32(data, index * 8 + 4, byteOrder);
return new SignedRational(numerator, denominator);
}).ToArray();
}
public static Task<float> ReadFloatAsync(this TiffIfdEntry entry, Stream stream, ByteOrder byteOrder)
{
if (entry.Type != TiffType.Float)
throw new ImageFormatException($"A value of type '{entry.Type}' cannot be converted to a float.");
if (entry.Count != 1)
throw new ImageFormatException("Cannot read a single value from an array of multiple items.");
return ReadFloatAsync_Internal(entry, stream, byteOrder);
}
private static async Task<float> ReadFloatAsync_Internal(TiffIfdEntry entry, Stream stream, ByteOrder byteOrder)
{
var array = await ReadFloatArrayAsync_Internal(entry, stream, byteOrder);
return array[0];
}
public static Task<float[]> ReadFloatArrayAsync(this TiffIfdEntry entry, Stream stream, ByteOrder byteOrder)
{
if (entry.Type != TiffType.Float)
throw new ImageFormatException($"A value of type '{entry.Type}' cannot be converted to a float.");
return ReadFloatArrayAsync_Internal(entry, stream, byteOrder);
}
private static async Task<float[]> ReadFloatArrayAsync_Internal(TiffIfdEntry entry, Stream stream, ByteOrder byteOrder)
{
byte[] data = await entry.ReadDataAsync(stream, byteOrder);
return Enumerable.Range(0, entry.Count).Select(index =>
{
return DataConverter.ToSingle(data, index * 4, byteOrder);
}).ToArray();
}
public static Task<double> ReadDoubleAsync(this TiffIfdEntry entry, Stream stream, ByteOrder byteOrder)
{
if (entry.Type != TiffType.Double)
throw new ImageFormatException($"A value of type '{entry.Type}' cannot be converted to a double.");
if (entry.Count != 1)
throw new ImageFormatException("Cannot read a single value from an array of multiple items.");
return ReadDoubleAsync_Internal(entry, stream, byteOrder);
}
private static async Task<double> ReadDoubleAsync_Internal(TiffIfdEntry entry, Stream stream, ByteOrder byteOrder)
{
var array = await ReadDoubleArrayAsync_Internal(entry, stream, byteOrder);
return array[0];
}
public static Task<double[]> ReadDoubleArrayAsync(this TiffIfdEntry entry, Stream stream, ByteOrder byteOrder)
{
if (entry.Type != TiffType.Double)
throw new ImageFormatException($"A value of type '{entry.Type}' cannot be converted to a double.");
return ReadDoubleArrayAsync_Internal(entry, stream, byteOrder);
}
private static async Task<double[]> ReadDoubleArrayAsync_Internal(TiffIfdEntry entry, Stream stream, ByteOrder byteOrder)
{
byte[] data = await entry.ReadDataAsync(stream, byteOrder);
return Enumerable.Range(0, entry.Count).Select(index =>
{
return DataConverter.ToDouble(data, index * 8, byteOrder);
}).ToArray();
}
public static Task<TiffIfdReference[]> ReadIfdReferenceArrayAsync(this TiffIfdEntry entry, Stream stream, ByteOrder byteOrder)
{
var type = entry.Type;
if (type != TiffType.Long && type != TiffType.Ifd)
throw new ImageFormatException($"A value of type '{entry.Type}' cannot be converted to an IFD reference.");
return ReadIfdReferenceArrayAsync_Internal(entry, stream, byteOrder); ;
}
private static async Task<TiffIfdReference[]> ReadIfdReferenceArrayAsync_Internal(TiffIfdEntry entry, Stream stream, ByteOrder byteOrder)
{
byte[] data = await entry.ReadDataAsync(stream, byteOrder);
return Enumerable.Range(0, entry.Count).Select(index => new TiffIfdReference(DataConverter.ToUInt32(data, index * 4, byteOrder))).ToArray();
}
public static Task<byte[]> ReadDataAsync(this TiffIfdEntry entry, Stream stream, ByteOrder byteOrder)
{
var sizeOfData = entry.SizeOfData();
if (sizeOfData <= 4)
{
return Task.FromResult(entry.Value);
}
else
{
var dataOffset = DataConverter.ToUInt32(entry.Value, 0, byteOrder);
stream.Seek(dataOffset, SeekOrigin.Begin);
return stream.ReadBytesAsync(sizeOfData);
}
}
public static int SizeOfData(this TiffIfdEntry entry) => TiffReader.SizeOfDataType(entry.Type) * entry.Count;
}
}
| |
#region License
/*
* Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Web;
using System.Web.Hosting;
using System.Xml;
using Common.Logging;
using Spring.Collections;
using Spring.Objects;
using Spring.Objects.Factory.Config;
using Spring.Objects.Factory.Support;
using Spring.Objects.Factory.Xml;
using Spring.Objects.Support;
using Spring.Reflection.Dynamic;
using Spring.Util;
using Spring.Core.IO;
namespace Spring.Context.Support
{
/// <summary>
/// Web application context, taking the context definition files
/// from the file system or from URLs.
///
/// Treats resource paths as web resources, when using
/// IApplicationContext.GetResource. Resource paths are considered relative
/// to the virtual directory.
///
/// Note: In case of multiple config locations, later object definitions will
/// override ones defined in earlier loaded files. This can be leveraged to
/// deliberately override certain object definitions via an extra XML file.
/// </summary>
/// <author>Aleksandar Seovic</author>
public class WebApplicationContext : AbstractXmlApplicationContext
{
// holds construction info for debugging output
private DateTime _constructionTimeStamp;
private string _constructionUrl;
private readonly string[] _configurationLocations;
private readonly IResource[] _configurationResources;
/// <summary>
/// Create a new WebApplicationContext, loading the definitions
/// from the given XML resource.
/// </summary>
/// <param name="configurationLocations">Names of configuration resources.</param>
public WebApplicationContext(params string[] configurationLocations)
: this(new WebApplicationContextArgs(string.Empty, null, configurationLocations, null, false))
{
}
/// <summary>
/// Create a new WebApplicationContext, loading the definitions
/// from the given XML resource.
/// </summary>
/// <param name="name">The application context name.</param>
/// <param name="caseSensitive">Flag specifying whether to make this context case sensitive or not.</param>
/// <param name="configurationLocations">Names of configuration resources.</param>
public WebApplicationContext(string name, bool caseSensitive, params string[] configurationLocations)
: this(new WebApplicationContextArgs(name, null, configurationLocations, null, caseSensitive))
{
}
/// <summary>
/// Create a new WebApplicationContext, loading the definitions
/// from the given XML resource.
/// </summary>
/// <param name="name">The application context name.</param>
/// <param name="caseSensitive">Flag specifying whether to make this context case sensitive or not.</param>
/// <param name="configurationLocations">Names of configuration resources.</param>
/// <param name="configurationResources">Configuration resources.</param>
public WebApplicationContext(string name, bool caseSensitive, string[] configurationLocations, IResource[] configurationResources)
: this(new WebApplicationContextArgs(name, null, configurationLocations, configurationResources, caseSensitive))
{
}
/// <summary>
/// Create a new WebApplicationContext with the given parent,
/// loading the definitions from the given XML resources.
/// </summary>
/// <param name="name">The application context name.</param>
/// <param name="caseSensitive">Flag specifying whether to make this context case sensitive or not.</param>
/// <param name="parentContext">The parent context.</param>
/// <param name="configurationLocations">Names of configuration resources.</param>
public WebApplicationContext(string name, bool caseSensitive, IApplicationContext parentContext,
params string[] configurationLocations)
: this(new WebApplicationContextArgs(name, parentContext, configurationLocations, null, caseSensitive))
{ }
/// <summary>
/// Initializes a new instance of the <see cref="WebApplicationContext"/> class.
/// </summary>
/// <param name="args">The args.</param>
public WebApplicationContext(WebApplicationContextArgs args)
: base(args.Name, args.CaseSensitive, args.ParentContext)
{
_configurationLocations = args.ConfigurationLocations;
_configurationResources = args.ConfigurationResources;
DefaultResourceProtocol = WebUtils.DEFAULT_RESOURCE_PROTOCOL;
Refresh();
// remember creation info for debug output
this._constructionTimeStamp = DateTime.Now;
this._constructionUrl = VirtualEnvironment.CurrentVirtualPathAndQuery;
if (log.IsDebugEnabled)
{
log.Debug("created instance " + this.ToString());
}
}
/// <summary>
/// returns detailed instance information for debugging
/// </summary>
/// <returns></returns>
public override string ToString()
{
//return base.ToString() + " - created on " + _constructionTimeStamp + "\n\ncreated by:" + _constructionUrl + "\n" + _constructionStackTrace.ToString();
return string.Format("[{0}]:{1}({2})", this.Name, this.GetType().Name, base.GetHashCode().ToString());
}
/// <summary>
/// Since the HttpRuntime discards it's configurationsection cache, we maintain our own context cache.
/// Despite it really speeds up context-lookup, since we don't have to go through the whole HttpConfigurationSystem
/// </summary>
private static readonly Hashtable s_webContextCache = new CaseInsensitiveHashtable();
static WebApplicationContext()
{
ILog s_weblog = LogManager.GetLogger(typeof(WebApplicationContext));
// register for ContextRegistry.Cleared event - we need to discard our cache in this case
ContextRegistry.Cleared += OnContextRegistryCleared;
#if !MONO_2_0
if (HttpRuntime.AppDomainAppVirtualPath != null) // check if we're within an ASP.NET AppDomain!
{
// ensure HttpRuntime has been fully initialized!
// this is a problem,.if ASP.NET Web Administration Application is used. This app does not fully set up the AppDomain...
HttpRuntime runtime =
(HttpRuntime)
typeof(HttpRuntime).GetField("_theRuntime", BindingFlags.Static | BindingFlags.NonPublic).GetValue(null);
bool beforeFirstRequest = false;
lock (runtime)
{
beforeFirstRequest =
(bool)
typeof(HttpRuntime).GetField("_beforeFirstRequest", BindingFlags.Instance | BindingFlags.NonPublic).
GetValue(runtime);
}
s_weblog.Debug("BeforeFirstRequest:" + beforeFirstRequest);
if (beforeFirstRequest)
{
try
{
string firstRequestPath = HttpRuntime.AppDomainAppVirtualPath.TrimEnd('/') + "/dummy.context";
s_weblog.Info("Forcing first request " + firstRequestPath);
SafeMethod fnProcessRequestNow = new SafeMethod(typeof(HttpRuntime).GetMethod("ProcessRequestNow", BindingFlags.Static | BindingFlags.NonPublic));
SimpleWorkerRequest wr = new SimpleWorkerRequest(firstRequestPath, string.Empty, new StringWriter());
fnProcessRequestNow.Invoke(null, new object[] { wr });
// HttpRuntime.ProcessRequest(
// wr);
s_weblog.Info("Successfully processed first request!");
}
catch (Exception ex)
{
s_weblog.Error("Failed processing first request", ex);
throw;
}
}
}
#endif
}
/// <summary>
/// EventHandler for ContextRegistry.Cleared event. Discards webContextCache.
/// </summary>
private static void OnContextRegistryCleared(object sender, EventArgs ev)
{
lock (s_webContextCache)
{
ILog s_weblog = LogManager.GetLogger(typeof(WebApplicationContext));
if (s_weblog.IsDebugEnabled)
{
s_weblog.Debug("received ContextRegistry.Cleared event - clearing webContextCache");
}
s_webContextCache.Clear();
}
}
/// <summary>
/// Returns the root context of this web application
/// </summary>
public static IApplicationContext GetRootContext()
{
return GetContextInternal(("" + HttpRuntime.AppDomainAppVirtualPath).TrimEnd('/') + "/dummy.context");
}
/// <summary>
/// Returns the web application context for the given (absolute!) virtual path
/// </summary>
public static IApplicationContext GetContext(string virtualPath)
{
return GetContextInternal(virtualPath);
}
/// <summary>
/// Returns the web application context for the current request's filepath
/// </summary>
public static IApplicationContext Current
{
get
{
string requestUrl = VirtualEnvironment.CurrentVirtualFilePath;
return GetContextInternal(requestUrl);
}
}
private static IApplicationContext GetContextInternal(string virtualPath)
{
string virtualDirectory = WebUtils.GetVirtualDirectory(virtualPath);
string contextName = virtualDirectory;
if (0 == string.Compare(contextName, ("" + HttpRuntime.AppDomainAppVirtualPath).TrimEnd('/') + "/", true))
{
contextName = DefaultRootContextName;
}
ILog s_weblog = LogManager.GetLogger(typeof(WebApplicationContext));
bool isLogDebugEnabled = s_weblog.IsDebugEnabled;
lock (s_webContextCache)
{
if (isLogDebugEnabled)
{
s_weblog.Debug(string.Format("looking up web context '{0}' in WebContextCache", contextName));
}
// first lookup in our own cache
IApplicationContext context = (IApplicationContext)s_webContextCache[contextName];
if (context != null)
{
// found - nothing to do anymore
if (isLogDebugEnabled)
{
s_weblog.Debug(
string.Format("returning WebContextCache hit '{0}' for vpath '{1}' ", context, contextName));
}
return context;
}
// lookup ContextRegistry
lock (ContextRegistry.SyncRoot)
{
if (isLogDebugEnabled)
{
s_weblog.Debug(string.Format("looking up web context '{0}' in ContextRegistry", contextName));
}
if (ContextRegistry.IsContextRegistered(contextName))
{
context = ContextRegistry.GetContext(contextName);
}
if (context == null)
{
// finally ask HttpConfigurationSystem for the requested context
try
{
if (isLogDebugEnabled)
{
s_weblog.Debug(
string.Format(
"web context for vpath '{0}' not found. Force creation using filepath '{1}'",
contextName, virtualPath));
}
// assure context is resolved to the given virtualDirectory
using (new HttpContextSwitch(virtualDirectory))
{
context = (IApplicationContext)ConfigurationUtils.GetSection(ContextSectionName);
}
if (context != null)
{
if (isLogDebugEnabled)
s_weblog.Debug(string.Format("got context '{0}' for vpath '{1}'", context, contextName));
}
else
{
if (isLogDebugEnabled)
s_weblog.Debug(string.Format("no context defined for vpath '{0}'", contextName));
}
}
catch (Exception ex)
{
if (s_weblog.IsErrorEnabled)
{
s_weblog.Error(string.Format("failed creating context '{0}', Stacktrace:\n{1}", contextName, new StackTrace()), ex);
}
throw;
}
}
}
// add it to the cache
// Note: use 'contextName' not 'context.Name' here - the same context may be used for different paths!
s_webContextCache.Add(contextName, context);
if (isLogDebugEnabled)
{
s_weblog.Debug(
string.Format("added context '{0}' to WebContextCache for vpath '{1}'", context, contextName));
}
if (context != null)
{
// register this context and all ParentContexts by their name - parent contexts may be additionally created by the HttpRuntime
IApplicationContext parentContext = context;
while (parentContext != null)
{
if (!s_webContextCache.ContainsKey(parentContext.Name))
{
s_webContextCache.Add(parentContext.Name, parentContext);
if (isLogDebugEnabled)
{
s_weblog.Debug(
string.Format("added parent context '{0}' to WebContextCache for vpath '{1}'",
parentContext, parentContext.Name));
}
}
parentContext = parentContext.ParentContext;
}
}
return context;
} // lock(s_webContextCache)
}
/// <summary>
/// Initializes object definition reader.
/// </summary>
/// <param name="objectDefinitionReader">Reader to initialize.</param>
protected override void InitObjectDefinitionReader(XmlObjectDefinitionReader objectDefinitionReader)
{
// NamespaceParserRegistry.RegisterParser(typeof(WebObjectsNamespaceParser));
}
/// <summary>
/// An array of resource locations, referring to the XML object
/// definition files with which this context is to be built.
/// </summary>
/// <returns>
/// An array of resource locations, or <see langword="null"/> if none.
/// </returns>
/// <seealso cref="Spring.Context.Support.AbstractXmlApplicationContext.ConfigurationLocations"/>
protected override string[] ConfigurationLocations
{
get { return _configurationLocations; }
}
/// <summary>
/// An array of resources instances with which this context is to be built.
/// </summary>
/// <returns>
/// An array of <see cref="Spring.Core.IO.IResource"/>s, or <see langword="null"/> if none.
/// </returns>
/// <seealso cref="Spring.Context.Support.AbstractXmlApplicationContext.ConfigurationLocations"/>
protected override IResource[] ConfigurationResources
{
get { return _configurationResources; }
}
/// <summary>
/// Creates web object factory for this context using parent context's factory as a parent.
/// </summary>
/// <returns>Web object factory to use.</returns>
protected override DefaultListableObjectFactory CreateObjectFactory()
{
string contextPath = GetContextPathWithTrailingSlash();
return new WebObjectFactory(contextPath, this.IsCaseSensitive, GetInternalParentObjectFactory());
}
/// <summary>
/// Returns the application-relative virtual path of this context (without leading '~'!).
/// </summary>
/// <returns></returns>
private string GetContextPathWithTrailingSlash()
{
string contextPath = this.Name;
if (contextPath == DefaultRootContextName)
{
contextPath = "/";
}
else
{
contextPath = contextPath + "/";
}
return contextPath;
}
/// <summary>
/// Create a reader instance capable of handling web objects (Pages,Controls) for importing o
/// bject definitions into the specified <paramref name="objectFactory"/>.
/// </summary>
protected override XmlObjectDefinitionReader CreateXmlObjectDefinitionReader(DefaultListableObjectFactory objectFactory)
{
return new WebObjectDefinitionReader(GetContextPathWithTrailingSlash(), objectFactory, new XmlUrlResolver());
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Text;
using Xunit;
namespace System.Net.Http.Tests
{
public class EntityTagHeaderValueTest
{
[Fact]
public void Ctor_ETagNull_Throw()
{
Assert.Throws<ArgumentException>(() => { new EntityTagHeaderValue(null); });
}
[Fact]
public void Ctor_ETagEmpty_Throw()
{
// null and empty should be treated the same. So we also throw for empty strings.
Assert.Throws<ArgumentException>(() => { new EntityTagHeaderValue(string.Empty); });
}
[Fact]
public void Ctor_ETagInvalidFormat_ThrowFormatException()
{
// When adding values using strongly typed objects, no leading/trailing LWS (whitespaces) are allowed.
AssertFormatException("tag");
AssertFormatException("*");
AssertFormatException(" tag ");
AssertFormatException("\"tag\" invalid");
AssertFormatException("\"tag");
AssertFormatException("tag\"");
AssertFormatException("\"tag\"\"");
AssertFormatException("\"\"tag\"\"");
AssertFormatException("\"\"tag\"");
AssertFormatException("W/\"tag\"");
}
[Fact]
public void Ctor_ETagValidFormat_SuccessfullyCreated()
{
EntityTagHeaderValue etag = new EntityTagHeaderValue("\"tag\"");
Assert.Equal("\"tag\"", etag.Tag);
Assert.False(etag.IsWeak);
}
[Fact]
public void Ctor_ETagValidFormatAndIsWeak_SuccessfullyCreated()
{
EntityTagHeaderValue etag = new EntityTagHeaderValue("\"e tag\"", true);
Assert.Equal("\"e tag\"", etag.Tag);
Assert.True(etag.IsWeak);
}
[Fact]
public void ToString_UseDifferentETags_AllSerializedCorrectly()
{
EntityTagHeaderValue etag = new EntityTagHeaderValue("\"e tag\"");
Assert.Equal("\"e tag\"", etag.ToString());
etag = new EntityTagHeaderValue("\"e tag\"", true);
Assert.Equal("W/\"e tag\"", etag.ToString());
etag = new EntityTagHeaderValue("\"\"", false);
Assert.Equal("\"\"", etag.ToString());
}
[Fact]
public void GetHashCode_UseSameAndDifferentETags_SameOrDifferentHashCodes()
{
EntityTagHeaderValue etag1 = new EntityTagHeaderValue("\"tag\"");
EntityTagHeaderValue etag2 = new EntityTagHeaderValue("\"TAG\"");
EntityTagHeaderValue etag3 = new EntityTagHeaderValue("\"tag\"", true);
EntityTagHeaderValue etag4 = new EntityTagHeaderValue("\"tag1\"");
EntityTagHeaderValue etag5 = new EntityTagHeaderValue("\"tag\"");
EntityTagHeaderValue etag6 = EntityTagHeaderValue.Any;
Assert.NotEqual(etag1.GetHashCode(), etag2.GetHashCode());
Assert.NotEqual(etag1.GetHashCode(), etag3.GetHashCode());
Assert.NotEqual(etag1.GetHashCode(), etag4.GetHashCode());
Assert.NotEqual(etag1.GetHashCode(), etag6.GetHashCode());
Assert.Equal(etag1.GetHashCode(), etag5.GetHashCode());
}
[Fact]
public void Equals_UseSameAndDifferentETags_EqualOrNotEqualNoExceptions()
{
EntityTagHeaderValue etag1 = new EntityTagHeaderValue("\"tag\"");
EntityTagHeaderValue etag2 = new EntityTagHeaderValue("\"TAG\"");
EntityTagHeaderValue etag3 = new EntityTagHeaderValue("\"tag\"", true);
EntityTagHeaderValue etag4 = new EntityTagHeaderValue("\"tag1\"");
EntityTagHeaderValue etag5 = new EntityTagHeaderValue("\"tag\"");
EntityTagHeaderValue etag6 = EntityTagHeaderValue.Any;
Assert.False(etag1.Equals(etag2));
Assert.False(etag2.Equals(etag1));
Assert.False(etag1.Equals(null));
Assert.False(etag1.Equals(etag3));
Assert.False(etag3.Equals(etag1));
Assert.False(etag1.Equals(etag4));
Assert.False(etag1.Equals(etag6));
Assert.True(etag1.Equals(etag5));
}
[Fact]
public void Clone_Call_CloneFieldsMatchSourceFields()
{
EntityTagHeaderValue source = new EntityTagHeaderValue("\"tag\"");
EntityTagHeaderValue clone = (EntityTagHeaderValue)((ICloneable)source).Clone();
Assert.Equal(source.Tag, clone.Tag);
Assert.Equal(source.IsWeak, clone.IsWeak);
source = new EntityTagHeaderValue("\"tag\"", true);
clone = (EntityTagHeaderValue)((ICloneable)source).Clone();
Assert.Equal(source.Tag, clone.Tag);
Assert.Equal(source.IsWeak, clone.IsWeak);
Assert.Same(EntityTagHeaderValue.Any, ((ICloneable)EntityTagHeaderValue.Any).Clone());
}
[Fact]
public void GetEntityTagLength_DifferentValidScenarios_AllReturnNonZero()
{
EntityTagHeaderValue result = null;
Assert.Equal(6, EntityTagHeaderValue.GetEntityTagLength("\"ta\u4F1Ag\"", 0, out result));
Assert.Equal("\"ta\u4F1Ag\"", result.Tag);
Assert.False(result.IsWeak);
Assert.Equal(9, EntityTagHeaderValue.GetEntityTagLength("W/\"tag\" ", 0, out result));
Assert.Equal("\"tag\"", result.Tag);
Assert.True(result.IsWeak);
// Note that even if after a valid tag & whitespaces there are invalid characters, GetEntityTagLength()
// will return the length of the valid tag and ignore the invalid characters at the end. It is the callers
// responsibility to consider the whole string invalid if after a valid ETag there are invalid chars.
Assert.Equal(11, EntityTagHeaderValue.GetEntityTagLength("\"tag\" \r\n !!", 0, out result));
Assert.Equal("\"tag\"", result.Tag);
Assert.False(result.IsWeak);
Assert.Equal(7, EntityTagHeaderValue.GetEntityTagLength("\"W/tag\"", 0, out result));
Assert.Equal("\"W/tag\"", result.Tag);
Assert.False(result.IsWeak);
Assert.Equal(9, EntityTagHeaderValue.GetEntityTagLength("W/ \"tag\"", 0, out result));
Assert.Equal("\"tag\"", result.Tag);
Assert.True(result.IsWeak);
// We also accept lower-case 'w': e.g. 'w/"tag"' rather than 'W/"tag"'
Assert.Equal(4, EntityTagHeaderValue.GetEntityTagLength("w/\"\"", 0, out result));
Assert.Equal("\"\"", result.Tag);
Assert.True(result.IsWeak);
Assert.Equal(2, EntityTagHeaderValue.GetEntityTagLength("\"\"", 0, out result));
Assert.Equal("\"\"", result.Tag);
Assert.False(result.IsWeak);
Assert.Equal(2, EntityTagHeaderValue.GetEntityTagLength(",* , ", 1, out result));
Assert.Same(EntityTagHeaderValue.Any, result);
}
[Fact]
public void GetEntityTagLength_DifferentInvalidScenarios_AllReturnZero()
{
EntityTagHeaderValue result = null;
// no leading spaces allowed.
Assert.Equal(0, EntityTagHeaderValue.GetEntityTagLength(" \"tag\"", 0, out result));
Assert.Null(result);
Assert.Equal(0, EntityTagHeaderValue.GetEntityTagLength("\"tag", 0, out result));
Assert.Null(result);
Assert.Equal(0, EntityTagHeaderValue.GetEntityTagLength("tag\"", 0, out result));
Assert.Null(result);
Assert.Equal(0, EntityTagHeaderValue.GetEntityTagLength("a/\"tag\"", 0, out result));
Assert.Null(result);
Assert.Equal(0, EntityTagHeaderValue.GetEntityTagLength("W//\"tag\"", 0, out result));
Assert.Null(result);
Assert.Equal(0, EntityTagHeaderValue.GetEntityTagLength("W", 0, out result));
Assert.Null(result);
Assert.Equal(0, EntityTagHeaderValue.GetEntityTagLength("W/", 0, out result));
Assert.Null(result);
Assert.Equal(0, EntityTagHeaderValue.GetEntityTagLength("W/\"", 0, out result));
Assert.Null(result);
Assert.Equal(0, EntityTagHeaderValue.GetEntityTagLength(null, 0, out result));
Assert.Null(result);
Assert.Equal(0, EntityTagHeaderValue.GetEntityTagLength(string.Empty, 0, out result));
Assert.Null(result);
}
[Fact]
public void Parse_SetOfValidValueStrings_ParsedCorrectly()
{
CheckValidParse("\"tag\"", new EntityTagHeaderValue("\"tag\""));
CheckValidParse(" \"tag\" ", new EntityTagHeaderValue("\"tag\""));
CheckValidParse("\r\n \"tag\"\r\n ", new EntityTagHeaderValue("\"tag\""));
CheckValidParse("\"tag\"", new EntityTagHeaderValue("\"tag\""));
CheckValidParse("\"tag\u4F1A\"", new EntityTagHeaderValue("\"tag\u4F1A\""));
CheckValidParse("W/\"tag\"", new EntityTagHeaderValue("\"tag\"", true));
}
[Fact]
public void Parse_SetOfInvalidValueStrings_Throws()
{
CheckInvalidParse(null);
CheckInvalidParse(string.Empty);
CheckInvalidParse(" ");
CheckInvalidParse(" !");
CheckInvalidParse("tag\" !");
CheckInvalidParse("!\"tag\"");
CheckInvalidParse("\"tag\",");
CheckInvalidParse("\"tag\" \"tag2\"");
CheckInvalidParse("/\"tag\"");
CheckInvalidParse("*"); // "any" is not allowed as ETag value.
}
[Fact]
public void TryParse_SetOfValidValueStrings_ParsedCorrectly()
{
CheckValidTryParse("\"tag\"", new EntityTagHeaderValue("\"tag\""));
CheckValidTryParse(" \"tag\" ", new EntityTagHeaderValue("\"tag\""));
CheckValidTryParse("\r\n \"tag\"\r\n ", new EntityTagHeaderValue("\"tag\""));
CheckValidTryParse("\"tag\"", new EntityTagHeaderValue("\"tag\""));
CheckValidTryParse("\"tag\u4F1A\"", new EntityTagHeaderValue("\"tag\u4F1A\""));
CheckValidTryParse("W/\"tag\"", new EntityTagHeaderValue("\"tag\"", true));
}
[Fact]
public void TryParse_SetOfInvalidValueStrings_ReturnsFalse()
{
CheckInvalidTryParse(null);
CheckInvalidTryParse(string.Empty);
CheckInvalidTryParse(" ");
CheckInvalidTryParse(" !");
CheckInvalidTryParse("tag\" !");
CheckInvalidTryParse("!\"tag\"");
CheckInvalidTryParse("\"tag\",");
CheckInvalidTryParse("\"tag\" \"tag2\"");
CheckInvalidTryParse("/\"tag\"");
CheckInvalidTryParse("*"); // "any" is not allowed as ETag value.
}
#region Helper methods
private void CheckValidParse(string input, EntityTagHeaderValue expectedResult)
{
EntityTagHeaderValue result = EntityTagHeaderValue.Parse(input);
Assert.Equal(expectedResult, result);
}
private void CheckInvalidParse(string input)
{
Assert.Throws<FormatException>(() => { EntityTagHeaderValue.Parse(input); });
}
private void CheckValidTryParse(string input, EntityTagHeaderValue expectedResult)
{
EntityTagHeaderValue result = null;
Assert.True(EntityTagHeaderValue.TryParse(input, out result));
Assert.Equal(expectedResult, result);
}
private void CheckInvalidTryParse(string input)
{
EntityTagHeaderValue result = null;
Assert.False(EntityTagHeaderValue.TryParse(input, out result));
Assert.Null(result);
}
private static void AssertFormatException(string tag)
{
Assert.Throws<FormatException>(() => { new EntityTagHeaderValue(tag); });
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Xml;
using System.Xml.Serialization;
using AgenaTrader.API;
using AgenaTrader.Custom;
using AgenaTrader.Plugins;
using AgenaTrader.Helper;
/// <summary>
/// Version: 1.3.0
/// -------------------------------------------------------------------------
/// Simon Pucher 2016
/// -------------------------------------------------------------------------
/// ****** Important ******
/// To compile this script without any error you also need access to the utility indicator to use global source code elements.
/// You will find this script on GitHub: https://raw.githubusercontent.com/simonpucher/AgenaTrader/master/Utilities/GlobalUtilities_Utility.cs
/// -------------------------------------------------------------------------
/// Namespace holds all indicators and is required. Do not change it.
/// </summary>
namespace AgenaTrader.UserCode
{
public enum IndicatorEnum_HighestHighValue
{
SMA = 1,
EMA = 2
}
[Description("Compare the current value of an indicator to latest high value of the indicator in a defined period of time.")]
public class HighestHighValue_Indicator : UserIndicator
{
//input
private Color _plot1color = Const.DefaultIndicatorColor;
private int _plot1width = Const.DefaultLineWidth;
private DashStyle _plot1dashstyle = Const.DefaultIndicatorDashStyle;
private int _indicatorEMAPeriod = 200;
private int _indicatorSMAPeriod = 200;
private int _comparisonPeriod = 30;
private IndicatorEnum_HighestHighValue _indicatorenum = IndicatorEnum_HighestHighValue.SMA;
//output
//internal
private DataSeries _DATA_List;
/// <summary>
/// Initalizie the OutputDescriptor.
/// </summary>
protected override void OnInit()
{
Add(new OutputDescriptor(new Pen(this.Plot1Color, this.Plot0Width), OutputSerieDrawStyle.Line, "HighestHighValue_Indicator"));
CalculateOnClosedBar = true;
IsOverlay = false;
}
/// <summary>
/// Init all variables on startup.
/// </summary>
protected override void OnStart()
{
this._DATA_List = new DataSeries(this);
}
/// <summary>
/// Recalculate all data on each each bar update.
/// </summary>
protected override void OnCalculate()
{
double currentvalue = 0.0;
switch (IndicatorEnum)
{
case IndicatorEnum_HighestHighValue.SMA:
currentvalue = SMA(IndicatorSMAPeriod)[0];
break;
case IndicatorEnum_HighestHighValue.EMA:
currentvalue = EMA(IndicatorEMAPeriod)[0];
break;
default:
break;
}
double lasthighvalue = _DATA_List.Reverse().Take(this.ComparisonPeriod).Max();
if (lasthighvalue < currentvalue)
{
MyPlot1.Set(1);
}
else
{
MyPlot1.Set(0);
}
this._DATA_List.Set(currentvalue);
//set the color
PlotColors[0][0] = this.Plot1Color;
OutputDescriptors[0].PenStyle = this.Dash0Style;
OutputDescriptors[0].Pen.Width = this.Plot0Width;
}
public override string ToString()
{
return "HHV";
}
public override string DisplayName
{
get
{
return "HHV";
}
}
#region Properties
#region InSeries
[Description("Type of the indicator")]
[InputParameter]
[DisplayName("Type of the indicator")]
public IndicatorEnum_HighestHighValue IndicatorEnum
{
get { return _indicatorenum; }
set { _indicatorenum = value; }
}
[Description("Period for the SMA")]
[InputParameter]
[DisplayName("Period SMA")]
public int IndicatorSMAPeriod
{
get { return _indicatorSMAPeriod; }
set { _indicatorSMAPeriod = value; }
}
[Description("Period for the EMA")]
[InputParameter]
[DisplayName("Period EMA")]
public int IndicatorEMAPeriod
{
get { return _indicatorEMAPeriod; }
set { _indicatorEMAPeriod = value; }
}
[Description("Period for comparison")]
[InputParameter]
[DisplayName("Period for comparison")]
public int ComparisonPeriod
{
get { return _comparisonPeriod; }
set { _comparisonPeriod = value; }
}
#region Plotstyle
[XmlIgnore()]
[Description("Select Color")]
[InputParameter]
[DisplayName("Pricline")]
public Color Plot1Color
{
get { return _plot1color; }
set { _plot1color = value; }
}
[Browsable(false)]
public string Plot1ColorSerialize
{
get { return SerializableColor.ToString(_plot1color); }
set { _plot1color = SerializableColor.FromString(value); }
}
/// <summary>
/// </summary>
[Description("Width for Indicator.")]
[InputParameter]
[DisplayName("Line Width Indicator")]
public int Plot0Width
{
get { return _plot1width; }
set { _plot1width = Math.Max(1, value); }
}
/// <summary>
/// </summary>
[Description("DashStyle for Indicator.")]
[InputParameter]
[DisplayName("Dash Style Indicator")]
public DashStyle Dash0Style
{
get { return _plot1dashstyle; }
set { _plot1dashstyle = value; }
}
#endregion
#endregion
#region Output
[Browsable(false)]
[XmlIgnore()]
public DataSeries MyPlot1
{
get { return Outputs[0]; }
}
#endregion
#endregion
}
}
| |
//
// DateRangeDialog.cs
//
// Author:
// Stephane Delcroix <stephane@delcroix.org>
// Bengt Thuree <bengt@thuree.com>
//
// Copyright (C) 2007-2009 Novell, Inc.
// Copyright (C) 2007-2009 Stephane Delcroix
// Copyright (C) 2007 Bengt Thuree
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using Gtk;
using Mono.Unix;
using FSpot.Query;
using FSpot.Widgets;
namespace FSpot.UI.Dialog
{
public class DateRangeDialog : BuilderDialog
{
#pragma warning disable 649
[GtkBeans.Builder.Object] Frame startframe;
[GtkBeans.Builder.Object] Frame endframe;
[GtkBeans.Builder.Object] ComboBox period_combobox;
#pragma warning restore 649
readonly DateEdit start_dateedit;
readonly DateEdit end_dateedit;
TreeStore rangestore;
static readonly string [] ranges = {
"today",
"yesterday",
"last7days",
"last30days",
"last90days",
"last360days",
"currentweek",
"previousweek",
"thismonth",
"previousmonth",
"thisyear",
"previousyear",
"alldates",
"customizedrange"
};
public DateRangeDialog (DateRange query_range, Gtk.Window parent_window) : base ("DateRangeDialog.ui", "date_range_dialog")
{
TransientFor = parent_window;
DefaultResponse = ResponseType.Ok;
(startframe.Child as Bin).Child = start_dateedit = new DateEdit ();
start_dateedit.Show ();
(endframe.Child as Bin).Child = end_dateedit = new DateEdit ();
end_dateedit.Show ();
var cell_renderer = new CellRendererText ();
// Build the combo box with years and month names
period_combobox.Model = rangestore = new TreeStore (typeof (string));
period_combobox.PackStart (cell_renderer, true);
period_combobox.SetCellDataFunc (cell_renderer, new CellLayoutDataFunc (RangeCellFunc));
foreach (string range in ranges)
rangestore.AppendValues (GetString(range));
period_combobox.Changed += HandlePeriodComboboxChanged;
period_combobox.Active = System.Array.IndexOf(ranges, "last7days"); // Default to Last 7 days
if (query_range != null) {
start_dateedit.DateTimeOffset = query_range.Start;
end_dateedit.DateTimeOffset = query_range.End;
}
}
void RangeCellFunc (CellLayout cell_layout, CellRenderer cell, TreeModel tree_model, TreeIter iter)
{
string name = (string)tree_model.GetValue (iter, 0);
(cell as CellRendererText).Text = name;
}
string GetString(string rangename)
{
DateTime today = DateTime.Today;
switch (rangename) {
case "today":
return Catalog.GetString("Today");
case "yesterday":
return Catalog.GetString("Yesterday");
case "last7days":
return Catalog.GetString("Last 7 days");
case "last30days":
return Catalog.GetString("Last 30 days");
case "last90days":
return Catalog.GetString("Last 90 days");
case "last360days":
return Catalog.GetString("Last 360 days");
case "currentweek":
return Catalog.GetString("Current Week (Mon-Sun)");
case "previousweek":
return Catalog.GetString("Previous Week (Mon-Sun)");
case "thismonth":
if (today.Year == (today.AddMonths(-1)).Year) // Same year for current and previous month. Present only MONTH
return today.ToString("MMMM");
else // Different year for current and previous month. Present both MONTH, and YEAR
return today.ToString("MMMM, yyyy");
case "previousmonth":
if (today.Year == (today.AddMonths(-1)).Year) // Same year for current and previous month. Present only MONTH
return (today.AddMonths(-1)).ToString("MMMM");
else // Different year for current and previous month. Present both MONTH, and YEAR
return (today.AddMonths(-1)).ToString("MMMM, yyyy");
case "thisyear":
return today.ToString("yyyy");
case "previousyear":
return today.AddYears(-1).ToString("yyyy");
case "alldates":
return Catalog.GetString("All Images");
case "customizedrange":
return Catalog.GetString("Customized Range");
default:
return rangename;
}
}
public DateRange Range {
get { return QueryRange (period_combobox.Active); }
}
DateRange QueryRange (int index)
{
return QueryRange ( ranges [index]);
}
DateRange QueryRange (string rangename)
{
DateTime today = DateTime.Today;
DateTime startdate = today;
DateTime enddate = today;
bool clear = false;
switch (rangename) {
case "today":
startdate = today;
enddate = today;
break;
case "yesterday":
startdate = today.AddDays (-1);
enddate = today.AddDays (-1);
break;
case "last7days":
startdate = today.AddDays (-6);
enddate = today;
break;
case "last30days":
startdate = today.AddDays (-29);
enddate = today;
break;
case "last90days":
startdate = today.AddDays (-89);
enddate = today;
break;
case "last360days":
startdate = today.AddDays (-359);
enddate = today;
break;
case "currentweek":
startdate = today.AddDays (System.DayOfWeek.Sunday - today.DayOfWeek); // Gets to Sunday
startdate = startdate.AddDays (1); // Advance to Monday according to ISO 8601
enddate = today;
break;
case "previousweek":
startdate = today.AddDays (System.DayOfWeek.Sunday - today.DayOfWeek); // Gets to Sunday
startdate = startdate.AddDays (1); // Advance to Monday according to ISO 8601
startdate = startdate.AddDays(-7); // Back 7 days
enddate = startdate.AddDays (6);
break;
case "thismonth":
startdate = new System.DateTime(today.Year, today.Month, 1); // the first of the month
enddate = today; // we don't have pictures in the future
break;
case "previousmonth":
startdate = new System.DateTime((today.AddMonths(-1)).Year, (today.AddMonths(-1)).Month, 1);
enddate = new System.DateTime((today.AddMonths(-1)).Year, (today.AddMonths(-1)).Month, System.DateTime.DaysInMonth((today.AddMonths(-1)).Year,(today.AddMonths(-1)).Month));
break;
case "thisyear":
startdate = new System.DateTime(today.Year, 1, 1); // Jan 1st of this year
enddate = today;
break;
case "previousyear":
startdate = new System.DateTime((today.AddYears(-1)).Year, 1, 1); // Jan 1st of prev year
enddate = new System.DateTime((today.AddYears(-1)).Year, 12, 31); // Dec, 31 of prev year
break;
case "alldates":
clear = true;
break;
case "customizedrange":
startdate = start_dateedit.DateTimeOffset.Date;
enddate = end_dateedit.DateTimeOffset.Date;
break;
default:
clear = true;
break;
}
if (!clear)
return new DateRange (startdate, enddate.Add (new System.TimeSpan(23,59,59)));
return null;
}
void HandleDateEditChanged (object o, EventArgs args)
{
period_combobox.Changed -= HandlePeriodComboboxChanged;
period_combobox.Active = Array.IndexOf (ranges, "customizedrange");
period_combobox.Changed += HandlePeriodComboboxChanged;
}
void HandlePeriodComboboxChanged (object o, EventArgs args)
{
start_dateedit.DateChanged -= HandleDateEditChanged;
(start_dateedit.Children [0] as Gtk.Entry).Changed -= HandleDateEditChanged;
end_dateedit.DateChanged -= HandleDateEditChanged;
(end_dateedit.Children [0] as Gtk.Entry).Changed -= HandleDateEditChanged;
ComboBox combo = o as ComboBox;
if (o == null)
return;
start_dateedit.Sensitive = (combo.Active != Array.IndexOf (ranges, "alldates"));
end_dateedit.Sensitive = (combo.Active != Array.IndexOf (ranges, "alldates"));
DateRange range = QueryRange (period_combobox.Active);
if (range != null) {
start_dateedit.DateTimeOffset = range.Start;
end_dateedit.DateTimeOffset = range.End;
}
start_dateedit.DateChanged += HandleDateEditChanged;
(start_dateedit.Children [0] as Gtk.Entry).Changed += HandleDateEditChanged;
end_dateedit.DateChanged += HandleDateEditChanged;
(end_dateedit.Children [0] as Gtk.Entry).Changed += HandleDateEditChanged;
}
}
}
| |
using SciChart.Charting.Common.Helpers;
using SciChart.Wpf.UI.Reactive;
using SciChart.Examples.ExternalDependencies.Common;
using SciChart.Wpf.UI.Reactive.Services;
using ActionCommand = SciChart.Charting.Common.Helpers.ActionCommand;
namespace SciChart.Examples.Demo.ViewModels
{
public class SmileFrownViewModel : BaseViewModel
{
private readonly ExampleViewModel _parent;
private bool _isSmile;
private bool _isFrown;
private bool _firstLoad;
private string _feedbackEmail = "";
private string _feedbackSubject = "";
private string _feedbackContent = "";
private bool _isFrownVisible;
private bool _isSmileVisible;
private bool _isVisible;
public SmileFrownViewModel(ExampleViewModel parent)
{
_parent = parent;
_firstLoad = true;
ExampleChanged();
}
public void ExampleChanged()
{
IsSmile = _parent.Usage.FeedbackType.GetValueOrDefault(ExampleFeedbackType.Frown) == ExampleFeedbackType.Smile;
IsFrown = _parent.Usage.FeedbackType.GetValueOrDefault(ExampleFeedbackType.Smile) == ExampleFeedbackType.Frown;
FeedbackEmail = _parent.Usage.Email;
if (!string.IsNullOrEmpty(_parent.Usage.FeedbackText))
{
FeedbackSubject = _parent.Usage.FeedbackText.Contains(":") ? _parent.Usage.FeedbackText.Substring(0, _parent.Usage.FeedbackText.IndexOf(":")) : "";
FeedbackContent = _parent.Usage.FeedbackText.Contains(":") ? _parent.Usage.FeedbackText.Substring(_parent.Usage.FeedbackText.IndexOf(":") + 1) : _parent.Usage.FeedbackText;
}
else
{
FeedbackSubject = null;
FeedbackContent = null;
}
FrownVisible = false;
SmileVisible = false;
}
public ActionCommand CloseCommand
{
get
{
return new ActionCommand(() =>
{
SmileVisible = false;
FrownVisible = false;
// Revert to original values
IsSmile = _parent.Usage.FeedbackType.GetValueOrDefault(ExampleFeedbackType.Frown) == ExampleFeedbackType.Smile;
IsFrown = _parent.Usage.FeedbackType.GetValueOrDefault(ExampleFeedbackType.Smile) == ExampleFeedbackType.Frown;
FeedbackEmail = _parent.Usage.Email;
if (!string.IsNullOrEmpty(_parent.Usage.FeedbackText))
{
FeedbackSubject = _parent.Usage.FeedbackText.Contains(":") ? _parent.Usage.FeedbackText.Substring(0, _parent.Usage.FeedbackText.IndexOf(":")) : "";
FeedbackContent = _parent.Usage.FeedbackText.Contains(":") ? _parent.Usage.FeedbackText.Substring(_parent.Usage.FeedbackText.IndexOf(":") + 1) : _parent.Usage.FeedbackText;
}
else
{
FeedbackSubject = null;
FeedbackContent = null;
}
});
}
}
public ActionCommand SubmitCommand
{
get
{
return new ActionCommand(() =>
{
_parent.Usage.FeedbackType = (ExampleFeedbackType?)(_isSmile ? ExampleFeedbackType.Smile : (_isFrown ? ExampleFeedbackType.Frown : (ExampleFeedbackType?)null));
_parent.Usage.FeedbackText = _feedbackSubject + ((_feedbackSubject + _feedbackContent).Length > 0 ? ": " : "") + _feedbackContent;
_parent.Usage.Email = _feedbackEmail;
SmileVisible = false;
FrownVisible = false;
});
}
}
public bool IsSmile
{
get { return _isSmile; }
set
{
if (_isSmile != value)
{
_isSmile = value;
if (IsSmile)
{
IsFrown = false;
}
}
}
}
public bool IsFrown
{
get { return _isFrown; }
set
{
if (_isFrown != value)
{
_isFrown = value;
if (IsFrown)
{
IsSmile = false;
}
}
}
}
public string FeedbackEmail
{
get { return _feedbackEmail; }
set
{
if (_feedbackEmail != value)
{
_feedbackEmail = value;
OnPropertyChanged("FeedbackEmail");
}
}
}
public string FeedbackSubject
{
get { return _feedbackSubject; }
set
{
if (_feedbackSubject != value)
{
_feedbackSubject = value;
OnPropertyChanged("FeedbackSubject");
}
}
}
public string FeedbackContent
{
get { return _feedbackContent; }
set
{
if (_feedbackContent != value)
{
_feedbackContent = value;
OnPropertyChanged("FeedbackContent");
}
}
}
public bool SmileVisible
{
get { return _isSmileVisible; }
set
{
if (_isSmileVisible != value)
{
_isSmileVisible = value;
OnPropertyChanged("SmileVisible");
}
if (SmileVisible)
{
_parent.ExportExampleViewModel.IsExportVisible = false;
_parent.BreadCrumbViewModel.IsShowingBreadcrumbNavigation = false;
FrownVisible = false;
}
else
{
FeedbackSubject = null;
FeedbackContent = null;
}
_parent.InvalidateDialogProperties();
}
}
public bool FrownVisible
{
get { return _isFrownVisible; }
set
{
if (_isFrownVisible != value)
{
_isFrownVisible = value;
OnPropertyChanged("FrownVisible");
}
if (FrownVisible)
{
_parent.ExportExampleViewModel.IsExportVisible = false;
_parent.BreadCrumbViewModel.IsShowingBreadcrumbNavigation = false;
SmileVisible = false;
}
else
{
FeedbackSubject = null;
FeedbackContent = null;
}
_parent.InvalidateDialogProperties();
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using Xunit;
public static class BitConverterTests
{
[Fact]
public static unsafe void IsLittleEndian()
{
short s = 1;
Assert.Equal(BitConverter.IsLittleEndian, *((byte*)&s) == 1);
}
[Fact]
public static void ValueArgumentNull()
{
Assert.Throws<ArgumentNullException>("value", () => BitConverter.ToBoolean(null, 0));
Assert.Throws<ArgumentNullException>("value", () => BitConverter.ToChar(null, 0));
Assert.Throws<ArgumentNullException>("value", () => BitConverter.ToDouble(null, 0));
Assert.Throws<ArgumentNullException>("value", () => BitConverter.ToInt16(null, 0));
Assert.Throws<ArgumentNullException>("value", () => BitConverter.ToInt32(null, 0));
Assert.Throws<ArgumentNullException>("value", () => BitConverter.ToInt64(null, 0));
Assert.Throws<ArgumentNullException>("value", () => BitConverter.ToSingle(null, 0));
Assert.Throws<ArgumentNullException>("value", () => BitConverter.ToUInt16(null, 0));
Assert.Throws<ArgumentNullException>("value", () => BitConverter.ToUInt32(null, 0));
Assert.Throws<ArgumentNullException>("value", () => BitConverter.ToUInt64(null, 0));
Assert.Throws<ArgumentNullException>("value", () => BitConverter.ToString(null));
Assert.Throws<ArgumentNullException>("value", () => BitConverter.ToString(null, 0));
Assert.Throws<ArgumentNullException>("value", () => BitConverter.ToString(null, 0, 0));
}
[Fact]
public static void StartIndexBeyondLength()
{
Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToBoolean(new byte[1], -1));
Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToBoolean(new byte[1], 1));
Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToBoolean(new byte[1], 2));
Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToChar(new byte[2], -1));
Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToChar(new byte[2], 2));
Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToChar(new byte[2], 3));
Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToDouble(new byte[8], -1));
Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToDouble(new byte[8], 8));
Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToDouble(new byte[8], 9));
Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToInt16(new byte[2], -1));
Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToInt16(new byte[2], 2));
Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToInt16(new byte[2], 3));
Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToInt32(new byte[4], -1));
Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToInt32(new byte[4], 4));
Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToInt32(new byte[4], 5));
Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToInt64(new byte[8], -1));
Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToInt64(new byte[8], 8));
Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToInt64(new byte[8], 9));
Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToSingle(new byte[4], -1));
Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToSingle(new byte[4], 4));
Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToSingle(new byte[4], 5));
Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToUInt16(new byte[2], -1));
Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToUInt16(new byte[2], 2));
Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToUInt16(new byte[2], 3));
Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToUInt32(new byte[4], -1));
Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToUInt32(new byte[4], 4));
Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToUInt32(new byte[4], 5));
Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToUInt64(new byte[8], -1));
Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToUInt64(new byte[8], 8));
Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToUInt64(new byte[8], 9));
Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToString(new byte[1], -1));
Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToString(new byte[1], 1));
Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToString(new byte[1], 2));
Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToString(new byte[1], -1, 0));
Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToString(new byte[1], 1, 0));
Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToString(new byte[1], 2, 0));
Assert.Throws<ArgumentOutOfRangeException>("length", () => BitConverter.ToString(new byte[1], 0, -1));
}
[Fact]
public static void StartIndexPlusNeededLengthTooLong()
{
Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToBoolean(new byte[0], 0));
Assert.Throws<ArgumentException>("value", () => BitConverter.ToChar(new byte[2], 1));
Assert.Throws<ArgumentException>("value", () => BitConverter.ToDouble(new byte[8], 1));
Assert.Throws<ArgumentException>("value", () => BitConverter.ToInt16(new byte[2], 1));
Assert.Throws<ArgumentException>("value", () => BitConverter.ToInt32(new byte[4], 1));
Assert.Throws<ArgumentException>("value", () => BitConverter.ToInt64(new byte[8], 1));
Assert.Throws<ArgumentException>("value", () => BitConverter.ToSingle(new byte[4], 1));
Assert.Throws<ArgumentException>("value", () => BitConverter.ToUInt16(new byte[2], 1));
Assert.Throws<ArgumentException>("value", () => BitConverter.ToUInt32(new byte[4], 1));
Assert.Throws<ArgumentException>("value", () => BitConverter.ToUInt64(new byte[8], 1));
Assert.Throws<ArgumentException>("value", () => BitConverter.ToString(new byte[2], 1, 2));
}
[Fact]
public static void DoubleToInt64Bits()
{
Double input = 123456.3234;
Int64 result = BitConverter.DoubleToInt64Bits(input);
Assert.Equal(4683220267154373240L, result);
Double roundtripped = BitConverter.Int64BitsToDouble(result);
Assert.Equal(input, roundtripped);
}
[Fact]
public static void RoundtripBoolean()
{
Byte[] bytes = BitConverter.GetBytes(true);
Assert.Equal(1, bytes.Length);
Assert.Equal(1, bytes[0]);
Assert.True(BitConverter.ToBoolean(bytes, 0));
bytes = BitConverter.GetBytes(false);
Assert.Equal(1, bytes.Length);
Assert.Equal(0, bytes[0]);
Assert.False(BitConverter.ToBoolean(bytes, 0));
}
[Fact]
public static void RoundtripChar()
{
Char input = 'A';
Byte[] expected = { 0x41, 0 };
VerifyRoundtrip(BitConverter.GetBytes, BitConverter.ToChar, input, expected);
}
[Fact]
public static void RoundtripDouble()
{
Double input = 123456.3234;
Byte[] expected = { 0x78, 0x7a, 0xa5, 0x2c, 0x05, 0x24, 0xfe, 0x40 };
VerifyRoundtrip(BitConverter.GetBytes, BitConverter.ToDouble, input, expected);
}
[Fact]
public static void RoundtripSingle()
{
Single input = 8392.34f;
Byte[] expected = { 0x5c, 0x21, 0x03, 0x46 };
VerifyRoundtrip(BitConverter.GetBytes, BitConverter.ToSingle, input, expected);
}
[Fact]
public static void RoundtripInt16()
{
Int16 input = 0x1234;
Byte[] expected = { 0x34, 0x12 };
VerifyRoundtrip(BitConverter.GetBytes, BitConverter.ToInt16, input, expected);
}
[Fact]
public static void RoundtripInt32()
{
Int32 input = 0x12345678;
Byte[] expected = { 0x78, 0x56, 0x34, 0x12 };
VerifyRoundtrip(BitConverter.GetBytes, BitConverter.ToInt32, input, expected);
}
[Fact]
public static void RoundtripInt64()
{
Int64 input = 0x0123456789abcdef;
Byte[] expected = { 0xef, 0xcd, 0xab, 0x89, 0x67, 0x45, 0x23, 0x01 };
VerifyRoundtrip(BitConverter.GetBytes, BitConverter.ToInt64, input, expected);
}
[Fact]
public static void RoundtripUInt16()
{
UInt16 input = 0x1234;
Byte[] expected = { 0x34, 0x12 };
VerifyRoundtrip(BitConverter.GetBytes, BitConverter.ToUInt16, input, expected);
}
[Fact]
public static void RoundtripUInt32()
{
UInt32 input = 0x12345678;
Byte[] expected = { 0x78, 0x56, 0x34, 0x12 };
VerifyRoundtrip(BitConverter.GetBytes, BitConverter.ToUInt32, input, expected);
}
[Fact]
public static void RoundtripUInt64()
{
UInt64 input = 0x0123456789abcdef;
Byte[] expected = { 0xef, 0xcd, 0xab, 0x89, 0x67, 0x45, 0x23, 0x01 };
VerifyRoundtrip(BitConverter.GetBytes, BitConverter.ToUInt64, input, expected);
}
[Fact]
public static void RoundtripString()
{
Byte[] bytes = { 0x12, 0x34, 0x56, 0x78, 0x9a };
Assert.Equal("12-34-56-78-9A", BitConverter.ToString(bytes));
Assert.Equal("56-78-9A", BitConverter.ToString(bytes, 2));
Assert.Equal("56", BitConverter.ToString(bytes, 2, 1));
Assert.Equal(String.Empty, BitConverter.ToString(new byte[0]));
}
[Fact]
public static void ToString_ByteArrayTooLong_Throws()
{
byte[] arr;
try
{
arr = new byte[int.MaxValue / 3 + 1];
}
catch (OutOfMemoryException)
{
// Exit out of the test if we don't have an enough contiguous memory
// available to create a big enough array.
return;
}
Assert.Throws<ArgumentOutOfRangeException>("length", () => BitConverter.ToString(arr));
}
private static void VerifyRoundtrip<TInput>(Func<TInput, Byte[]> getBytes, Func<Byte[], int, TInput> convertBack, TInput input, Byte[] expectedBytes)
{
Byte[] bytes = getBytes(input);
Assert.Equal(expectedBytes.Length, bytes.Length);
if (!BitConverter.IsLittleEndian)
{
Array.Reverse(expectedBytes);
}
Assert.Equal(expectedBytes, bytes);
Assert.Equal(input, convertBack(bytes, 0));
// Also try unaligned startIndex
byte[] longerBytes = new byte[bytes.Length + 1];
longerBytes[0] = 0;
Array.Copy(bytes, 0, longerBytes, 1, bytes.Length);
Assert.Equal(input, convertBack(longerBytes, 1));
}
}
| |
// Copyright 2004-2009 Castle Project - http://www.castleproject.org/
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Castle.VSNetIntegration.CastleWizards.Dialogs.Panels
{
using System;
using Castle.VSNetIntegration.CastleWizards.Shared;
/// <summary>
/// Summary description for ConnStringPanel.
/// </summary>
[System.Runtime.InteropServices.ComVisible(false)]
public class ConnStringPanel : WizardPanel
{
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.TextBox connectionString;
private System.Windows.Forms.ComboBox database;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
private String dependencyKey;
public ConnStringPanel()
{
InitializeComponent();
database.SelectedIndex = 0;
}
public String Database
{
get { return database.SelectedItem.ToString(); }
}
public String ConnectionString
{
get { return connectionString.Text; }
set { connectionString.Text = value; }
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.label3 = new System.Windows.Forms.Label();
this.connectionString = new System.Windows.Forms.TextBox();
this.database = new System.Windows.Forms.ComboBox();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.groupBox1.SuspendLayout();
this.SuspendLayout();
//
// groupBox1
//
this.groupBox1.Controls.Add(this.label3);
this.groupBox1.Controls.Add(this.connectionString);
this.groupBox1.Controls.Add(this.database);
this.groupBox1.Controls.Add(this.label1);
this.groupBox1.Controls.Add(this.label2);
this.groupBox1.Location = new System.Drawing.Point(-8, 8);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(480, 320);
this.groupBox1.TabIndex = 49;
this.groupBox1.TabStop = false;
//
// label3
//
this.label3.Location = new System.Drawing.Point(56, 64);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(200, 16);
this.label3.TabIndex = 48;
this.label3.Text = "Database:";
//
// connectionString
//
this.connectionString.Location = new System.Drawing.Point(56, 136);
this.connectionString.Multiline = true;
this.connectionString.Name = "connectionString";
this.connectionString.Size = new System.Drawing.Size(360, 64);
this.connectionString.TabIndex = 47;
this.connectionString.Text = "";
//
// database
//
this.database.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.database.Items.AddRange(new object[] {
"MS SQLServer",
"Oracle",
"MySql",
"Firebird",
"PostgreSQL",
"SQLite"});
this.database.Location = new System.Drawing.Point(56, 80);
this.database.Name = "database";
this.database.Size = new System.Drawing.Size(136, 21);
this.database.TabIndex = 45;
this.database.SelectedIndexChanged += new System.EventHandler(this.database_SelectedIndexChanged);
//
// label1
//
this.label1.Font = new System.Drawing.Font("Tahoma", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.label1.Location = new System.Drawing.Point(40, 16);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(408, 16);
this.label1.TabIndex = 44;
this.label1.Text = "Connection properties:";
//
// label2
//
this.label2.Location = new System.Drawing.Point(56, 120);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(200, 16);
this.label2.TabIndex = 46;
this.label2.Text = "Connection string:";
//
// ConnStringPanel
//
this.Controls.Add(this.groupBox1);
this.Name = "ConnStringPanel";
this.Size = new System.Drawing.Size(464, 336);
this.groupBox1.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
public override bool WantsToShow(ExtensionContext context)
{
return ((bool) context.Properties["enableWindsorIntegration"]) == true &&
context.Properties.Contains(DependencyKey) &&
((bool) context.Properties[DependencyKey]) == true;
}
private void database_SelectedIndexChanged(object sender, System.EventArgs e)
{
int index = database.SelectedIndex;
if (index < 0) return;
// Show connection string example
String selectedDb = Database;
foreach(Pair pair in NHUtil.GetSampleConnectionStrings())
{
if (pair.First.ToString() == selectedDb)
{
connectionString.Text = pair.Second.ToString();
break;
}
}
}
public String DependencyKey
{
get { return dependencyKey; }
set { dependencyKey = value; }
}
public String Title
{
get { return label1.Text; }
set { label1.Text = String.Format("{0} connection properties:", value); }
}
}
}
| |
using System;
using System.Linq;
using NUnit.Framework;
namespace MongoDB.IntegrationTests
{
[TestFixture]
public class TestDatabaseJavascript : MongoTestBase
{
private DatabaseJavascript _javascript;
public override string TestCollections
{
get { return "jsreads"; }
}
public override void OnInit()
{
DB["system.js"].Delete(new Document());
_javascript = DB.Javascript;
var jsreads = DB["jsreads"];
for(var j = 1; j < 10; j++)
jsreads.Insert(new Document {{"j", j}});
}
protected void AddFunction(string name)
{
var func = new Code("function(x,y){return x + y;}");
DB["system.js"].Insert(new Document().Add("_id", name).Add("value", func));
}
[Test]
public void TestCanAddAFunctionDoc()
{
const string name = "fadddoc";
var func = new Code("function(x, y){return x + y;}");
var doc = new Document().Add("_id", name).Add("value", func);
_javascript.Add(doc);
Assert.IsNotNull(_javascript[name]);
}
[Test]
public void TestCanAddAFunctionStrCode()
{
const string name = "faddsc";
var func = new Code("function(x, y){return x + y;}");
_javascript.Add(name, func);
Assert.IsNotNull(_javascript[name]);
}
[Test]
public void TestCanAddAFunctionStrStr()
{
const string name = "faddss";
var func = "function(x, y){return x + y;}";
_javascript.Add(name, func);
Assert.IsNotNull(_javascript[name]);
}
[Test]
public void TestCanAddFunctionByAssignment()
{
const string name = "fassignadd";
var func = new Code("function(x,y){return x + y;}");
var doc = new Document().Add("_id", name).Add("value", func);
_javascript[name] = doc;
Assert.IsNotNull(_javascript[name]);
}
[Test]
public void TestCanGetAFunction()
{
const string name = "fget";
AddFunction(name);
Assert.IsNotNull(_javascript[name]);
Assert.IsNotNull(_javascript.GetFunction(name));
}
[Test]
public void TestCanGetDatabaseJSObject()
{
Assert.IsNotNull(DB.Javascript);
}
[Test]
public void TestCanListFunctions()
{
const string name = "flist";
AddFunction(name);
var list = _javascript.GetFunctionNames();
Assert.IsTrue(list.Count > 0);
var found = false;
foreach(var l in list)
if(l == name)
found = true;
Assert.IsTrue(found, "Didn't find the function that was inserted.");
}
[Test]
public void TestCannotAddAFunctionTwice()
{
const string name = "faddtwice";
var func = new Code("function(x,y){return x + y;}");
_javascript.Add(name, func);
var thrown = false;
try
{
_javascript.Add(name, func);
}
catch(ArgumentException)
{
thrown = true;
}
Assert.IsTrue(thrown, "Shouldn't be able to add a function twice");
}
[Test]
public void TestClear()
{
AddFunction("clear");
Assert.IsTrue(_javascript.Count > 0);
_javascript.Clear();
Assert.IsTrue(_javascript.Count == 0);
}
[Test]
public void TestContains()
{
const string name = "fcontains";
AddFunction(name);
Assert.IsTrue(_javascript.Contains(name));
Assert.IsFalse(_javascript.Contains("none"));
Assert.IsTrue(_javascript.Contains(new Document().Add("_id", name).Add("value", new Code("dfs"))));
}
[Test]
public void TestCopyTo()
{
const int count = 5;
var functions = new Document[count];
var funcCode = new Code("function(x,y){return x+y;}");
for(var i = 0; i < count; i++)
{
var name = string.Format("_{0}fcopyTo", i);
_javascript[name] = new Document("_id", name).Add("value", funcCode);
}
_javascript.CopyTo(functions, 1);
Assert.IsNull(functions[0]);
Assert.IsNotNull(functions[1]);
Assert.IsNotNull(functions[4]);
Assert.AreEqual("_1fcopyTo", functions[1]["_id"]);
Assert.IsTrue(((string)functions[1]["_id"]).StartsWith("_1")); //as long as no other _ named functions get in.
}
[Test]
public void TestExec()
{
_javascript.Add("lt4", new Code("function(doc){return doc.j < 4;}"));
var cnt = DB["reads"].Find("lt4(this)").Documents.Count();
Assert.AreEqual(3, cnt);
}
[Test]
public void TestExecWithScope()
{
_javascript.Add("lt", new Code("function(doc){ return doc.j < limit;}"));
var scope = new Document().Add("limit", 5);
var query = new Document().Add("$where", new CodeWScope("lt(this)", scope));
var cnt = DB["jsreads"].Find(query).Documents.Count();
Assert.AreEqual(4, cnt);
}
[Test]
public void TestForEach()
{
var name = "foreach";
AddFunction(name);
var found = _javascript.Any(doc => name.Equals(doc["_id"]));
Assert.IsTrue(found, "Added function wasn't found during foreach");
}
[Test]
public void TestRemoveByDoc()
{
const string name = "fremoved";
var func = new Document().Add("_id", name);
AddFunction(name);
Assert.IsTrue(_javascript.Contains(name));
_javascript.Remove(func);
Assert.IsFalse(_javascript.Contains(name));
}
[Test]
public void TestRemoveByName()
{
const string name = "fremoven";
AddFunction(name);
Assert.IsTrue(_javascript.Contains(name));
_javascript.Remove(name);
Assert.IsFalse(_javascript.Contains(name));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using Hydra.Framework.Mapping.Styles;
namespace Hydra.Framework.Mapping.Rendering.Thematics
{
//
// **********************************************************************
/// <summary>
/// The GradientTheme class defines a gradient color thematic rendering of features based by a numeric attribute.
/// </summary>
// **********************************************************************
//
public class GradientTheme
: ITheme
{
#region Private Member Variables
//
// **********************************************************************
/// <summary>
/// Column StateName
/// </summary>
// **********************************************************************
//
private string m_ColumnName;
//
// **********************************************************************
/// <summary>
/// Minimum Value
/// </summary>
// **********************************************************************
//
private double m_Min;
//
// **********************************************************************
/// <summary>
/// Maximum Value
/// </summary>
// **********************************************************************
//
private double m_Max;
//
// **********************************************************************
/// <summary>
/// Minimum AbstractStyle
/// </summary>
// **********************************************************************
//
private Hydra.Framework.Mapping.Styles.IStyle m_MinStyle;
//
// **********************************************************************
/// <summary>
/// Maximum AbstractStyle
/// </summary>
// **********************************************************************
//
private Hydra.Framework.Mapping.Styles.IStyle m_MaxStyle;
//
// **********************************************************************
/// <summary>
/// Text Colour Blend
/// </summary>
// **********************************************************************
//
private ColorBlend m_TextColorBlend;
//
// **********************************************************************
/// <summary>
/// Line Colour Blend
/// </summary>
// **********************************************************************
//
private ColorBlend m_LineColorBlend;
//
// **********************************************************************
/// <summary>
/// Fill Colour Blend
/// </summary>
// **********************************************************************
//
private ColorBlend m_FillColorBlend;
#endregion
#region Constructors
//
// **********************************************************************
/// <summary>
/// Initializes a new instance of the GradientTheme class
/// </summary>
/// <param name="columnName">StateName of column to extract the attribute</param>
/// <param name="minValue">Minimum value</param>
/// <param name="maxValue">Maximum value</param>
/// <param name="minStyle">Color for minimum value</param>
/// <param name="maxStyle">Color for maximum value</param>
/// <remarks>
/// <para>The gradient theme interpolates linearly between two styles based on a numerical attribute in the datasource.
/// This is useful for scaling symbols, line widths, line and fill colors from numerical attributes.</para>
/// <para>Colors are interpolated between two colors, but if you want to interpolate through more colors (fx. a rainbow),
/// set the <see cref="TextColorBlend"/>, <see cref="LineColorBlend"/> and <see cref="FillColorBlend"/> properties
/// to a custom <see cref="ColorBlend"/>.
/// </para>
/// <para>The following properties are scaled (properties not mentioned here are not interpolated):
/// <list type="table">
/// <listheader><term>Property</term><description>Remarks</description></listheader>
/// <item><term><see cref="System.Drawing.Color"/></term><description>Red, Green, Blue and Alpha values are linearly interpolated.</description></item>
/// <item><term><see cref="System.Drawing.Pen"/></term><description>The color, width, color of pens are interpolated. MiterLimit,StartCap,EndCap,LineJoin,DashStyle,DashPattern,DashOffset,DashCap,CompoundArray, and Alignment are switched in the middle of the min/max values.</description></item>
/// <item><term><see cref="System.Drawing.SolidBrush"/></term><description>SolidBrush color are interpolated. Other brushes are not supported.</description></item>
/// <item><term><see cref="Hydra.Framework.Mapping.Styles.VectorStyle"/></term><description>MaxVisible, MinVisible, Line, Outline, Fill and SymbolScale are scaled linearly. Symbol, EnableOutline and Enabled switch in the middle of the min/max values.</description></item>
/// <item><term><see cref="Hydra.Framework.Mapping.Styles.LabelStyle"/></term><description>FontSize, BackColor, ForeColor, MaxVisible, MinVisible, Offset are scaled linearly. All other properties use min-style.</description></item>
/// </list>
/// </para>
/// <example>
/// Creating a rainbow colorblend showing colors from red, through yellow, green and blue depicting
/// the population density of a country.
/// <code lang="C#">
/// //Create two vector styles to interpolate between
/// Hydra.Framework.Mapping.Styles.VectorStyle min = new Hydra.Framework.Mapping.Styles.VectorStyle();
/// Hydra.Framework.Mapping.Styles.VectorStyle max = new Hydra.Framework.Mapping.Styles.VectorStyle();
/// min.Outline.Width = 1f; //Outline width of the minimum value
/// max.Outline.Width = 3f; //Outline width of the maximum value
/// //Create a theme interpolating population density between 0 and 400
/// Hydra.Framework.Mapping.Rendering.Thematics.GradientTheme popdens = new Hydra.Framework.Mapping.Rendering.Thematics.GradientTheme("PopDens", 0, 400, min, max);
/// //Set the fill-style colors to be a rainbow blend from red to blue.
/// popdens.FillColorBlend = Hydra.Framework.Mapping.Rendering.Thematics.ColorBlend.Rainbow5;
/// myVectorLayer.Theme = popdens;
/// </code>
/// </example>
/// </remarks>
// **********************************************************************
//
public GradientTheme(string columnName, double minValue, double maxValue, Hydra.Framework.Mapping.Styles.IStyle minStyle, Hydra.Framework.Mapping.Styles.IStyle maxStyle)
{
m_ColumnName = columnName;
m_Min = minValue;
m_Max = maxValue;
m_MaxStyle = maxStyle;
m_MinStyle = minStyle;
}
#endregion
#region Properties
//
// **********************************************************************
/// <summary>
/// Gets or sets the column name from where to get the attribute value
/// </summary>
/// <value>The name of the column.</value>
// **********************************************************************
//
public string ColumnName
{
get
{
return m_ColumnName;
}
set
{
m_ColumnName = value;
}
}
//
// **********************************************************************
/// <summary>
/// Gets or sets the minimum value of the gradient
/// </summary>
/// <value>The min.</value>
// **********************************************************************
//
public double Min
{
get
{
return m_Min;
}
set
{
m_Min = value;
}
}
//
// **********************************************************************
/// <summary>
/// Gets or sets the maximum value of the gradient
/// </summary>
/// <value>The max.</value>
// **********************************************************************
//
public double Max
{
get
{
return m_Max;
}
set
{
m_Max = value;
}
}
//
// **********************************************************************
/// <summary>
/// Gets or sets the <see cref="Hydra.Framework.Mapping.Styles.IStyle">style</see> for the minimum value
/// </summary>
/// <value>The min style.</value>
// **********************************************************************
//
public Hydra.Framework.Mapping.Styles.IStyle MinStyle
{
get
{
return m_MinStyle;
}
set
{
m_MinStyle = value;
}
}
//
// **********************************************************************
/// <summary>
/// Gets or sets the <see cref="Hydra.Framework.Mapping.Styles.IStyle">style</see> for the maximum value
/// </summary>
/// <value>The max style.</value>
// **********************************************************************
//
public Hydra.Framework.Mapping.Styles.IStyle MaxStyle
{
get
{
return m_MaxStyle;
}
set
{
m_MaxStyle = value;
}
}
//
// **********************************************************************
/// <summary>
/// Gets or sets the <see cref="Hydra.Framework.Mapping.Rendering.Thematics.ColorBlend"/> used on labels
/// </summary>
/// <value>The text color blend.</value>
// **********************************************************************
//
public ColorBlend TextColorBlend
{
get
{
return m_TextColorBlend;
}
set
{
m_TextColorBlend = value;
}
}
//
// **********************************************************************
/// <summary>
/// Gets or sets the <see cref="Hydra.Framework.Mapping.Rendering.Thematics.ColorBlend"/> used on lines
/// </summary>
/// <value>The line color blend.</value>
// **********************************************************************
//
public ColorBlend LineColorBlend
{
get
{
return m_LineColorBlend;
}
set
{
m_LineColorBlend = value;
}
}
//
// **********************************************************************
/// <summary>
/// Gets or sets the <see cref="Hydra.Framework.Mapping.Rendering.Thematics.ColorBlend"/> used as Fill
/// </summary>
/// <value>The fill color blend.</value>
// **********************************************************************
//
public ColorBlend FillColorBlend
{
get
{
return m_FillColorBlend;
}
set
{
m_FillColorBlend = value;
}
}
#endregion
#region ITheme Implementation
//
// **********************************************************************
/// <summary>
/// Returns the style based on a numeric DataColumn, where style
/// properties are linearly interpolated between max and min values.
/// </summary>
/// <param name="row">Feature</param>
/// <returns>
/// <see cref="Hydra.Framework.Mapping.Styles.IStyle">AbstractStyle</see> calculated by a linear interpolation between the min/max styles
/// </returns>
// **********************************************************************
//
public Hydra.Framework.Mapping.Styles.IStyle GetStyle(Hydra.Framework.Mapping.Data.FeatureDataRow row)
{
double attr = 0;
try
{
attr = Convert.ToDouble(row[this.m_ColumnName]);
}
catch
{
throw new ApplicationException("Invalid Attribute type in Gradient Theme - Couldn't parse attribute (must be numerical)");
}
if (m_MinStyle.GetType() != m_MaxStyle.GetType())
throw new ArgumentException("MinStyle and MaxStyle must be of the same type");
switch (MinStyle.GetType().FullName)
{
case "Hydra.Framework.Mapping.Styles.VectorStyle":
return CalculateVectorStyle(MinStyle as VectorStyle, MaxStyle as VectorStyle, attr);
case "Hydra.Framework.Mapping.Styles.LabelStyle":
return CalculateLabelStyle(MinStyle as LabelStyle, MaxStyle as LabelStyle, attr);
default:
throw new ArgumentException("Only Hydra.Framework.Mapping.Styles.VectorStyle and Hydra.Framework.Mapping.Styles.LabelStyle are supported for the gradient theme");
}
}
//
// **********************************************************************
/// <summary>
/// Calculates the vector style.
/// </summary>
/// <param name="min">The min.</param>
/// <param name="max">The max.</param>
/// <param name="value">The value.</param>
/// <returns></returns>
// **********************************************************************
//
private VectorStyle CalculateVectorStyle(Hydra.Framework.Mapping.Styles.VectorStyle min, Hydra.Framework.Mapping.Styles.VectorStyle max, double value)
{
VectorStyle style = new VectorStyle();
double dFrac = Fraction(value);
float fFrac = Convert.ToSingle(dFrac);
style.Enabled = (dFrac > 0.5 ? min.Enabled : max.Enabled);
style.EnableOutline = (dFrac > 0.5 ? min.EnableOutline : max.EnableOutline);
if (m_FillColorBlend != null)
style.Fill = new System.Drawing.SolidBrush(m_FillColorBlend.GetColor(fFrac));
else if (min.Fill != null && max.Fill != null)
style.Fill = InterpolateBrush(min.Fill, max.Fill, value);
if (min.Line != null && max.Line != null)
style.Line = InterpolatePen(min.Line, max.Line, value);
if (m_LineColorBlend != null)
style.Line.Color = m_LineColorBlend.GetColor(fFrac);
if (min.Outline != null && max.Outline != null)
style.Outline = InterpolatePen(min.Outline, max.Outline, value);
style.MinVisible = InterpolateDouble(min.MinVisible, max.MinVisible, value);
style.MaxVisible = InterpolateDouble(min.MaxVisible, max.MaxVisible, value);
style.Symbol = (dFrac > 0.5 ? min.Symbol : max.Symbol);
style.SymbolOffset = (dFrac > 0.5 ? min.SymbolOffset : max.SymbolOffset); // We don't interpolate the offset but let it follow the symbol instead
style.SymbolScale = InterpolateFloat(min.SymbolScale, max.SymbolScale, value);
return style;
}
//
// **********************************************************************
/// <summary>
/// Calculates the label style.
/// </summary>
/// <param name="min">The min.</param>
/// <param name="max">The max.</param>
/// <param name="value">The value.</param>
/// <returns></returns>
// **********************************************************************
//
private LabelStyle CalculateLabelStyle(Hydra.Framework.Mapping.Styles.LabelStyle min, Hydra.Framework.Mapping.Styles.LabelStyle max, double value)
{
LabelStyle style = new LabelStyle();
style.CollisionDetection = min.CollisionDetection;
style.Enabled = InterpolateBool(min.Enabled, max.Enabled, value);
float FontSize = InterpolateFloat(min.Font.Size, max.Font.Size, value);
style.Font = new System.Drawing.Font(min.Font.FontFamily, FontSize, min.Font.Style);
if (min.BackColor != null && max.BackColor != null)
style.BackColor = InterpolateBrush(min.BackColor, max.BackColor, value);
if (m_TextColorBlend != null)
style.ForeColor = m_LineColorBlend.GetColor(Convert.ToSingle(Fraction(value)));
else
style.ForeColor = InterpolateColor(min.ForeColor, max.ForeColor, value);
if (min.Halo != null && max.Halo != null)
style.Halo = InterpolatePen(min.Halo, max.Halo, value);
style.MinVisible = InterpolateDouble(min.MinVisible, max.MinVisible, value);
style.MaxVisible = InterpolateDouble(min.MaxVisible, max.MaxVisible, value);
style.Offset = new System.Drawing.PointF(InterpolateFloat(min.Offset.X, max.Offset.X, value), InterpolateFloat(min.Offset.Y, max.Offset.Y, value));
return style;
}
//
// **********************************************************************
/// <summary>
/// Fractions the specified attr.
/// </summary>
/// <param name="attr">The attr.</param>
/// <returns></returns>
// **********************************************************************
//
private double Fraction(double attr)
{
if (attr < m_Min)
return 0;
if (attr > m_Max)
return 1;
return (attr - m_Min) / (m_Max - m_Min);
}
//
// **********************************************************************
/// <summary>
/// Interpolates the bool.
/// </summary>
/// <param name="min">if set to <c>true</c> [min].</param>
/// <param name="max">if set to <c>true</c> [max].</param>
/// <param name="attr">The attr.</param>
/// <returns></returns>
// **********************************************************************
//
private bool InterpolateBool(bool min, bool max, double attr)
{
double frac = Fraction(attr);
if (frac > 0.5)
return max;
else return min;
}
//
// **********************************************************************
/// <summary>
/// Interpolates the float.
/// </summary>
/// <param name="min">The min.</param>
/// <param name="max">The max.</param>
/// <param name="attr">The attr.</param>
/// <returns></returns>
// **********************************************************************
//
private float InterpolateFloat(float min, float max, double attr)
{
return Convert.ToSingle((max - min) * Fraction(attr) + min);
}
//
// **********************************************************************
/// <summary>
/// Interpolates the double.
/// </summary>
/// <param name="min">The min.</param>
/// <param name="max">The max.</param>
/// <param name="attr">The attr.</param>
/// <returns></returns>
// **********************************************************************
//
private double InterpolateDouble(double min, double max, double attr)
{
return (max - min) * Fraction(attr) + min;
}
//
// **********************************************************************
/// <summary>
/// Interpolates the brush.
/// </summary>
/// <param name="min">The min.</param>
/// <param name="max">The max.</param>
/// <param name="attr">The attr.</param>
/// <returns></returns>
// **********************************************************************
//
private System.Drawing.SolidBrush InterpolateBrush(System.Drawing.Brush min, System.Drawing.Brush max, double attr)
{
if (min.GetType() != typeof(System.Drawing.SolidBrush) ||
max.GetType() != typeof(System.Drawing.SolidBrush))
throw (new ArgumentException("Only SolidBrush brushes are supported in GradientTheme"));
return new System.Drawing.SolidBrush(InterpolateColor((min as System.Drawing.SolidBrush).Color, (max as System.Drawing.SolidBrush).Color, attr));
}
//
// **********************************************************************
/// <summary>
/// Interpolates the pen.
/// </summary>
/// <param name="min">The min.</param>
/// <param name="max">The max.</param>
/// <param name="attr">The attr.</param>
/// <returns></returns>
// **********************************************************************
//
private System.Drawing.Pen InterpolatePen(System.Drawing.Pen min, System.Drawing.Pen max, double attr)
{
if (min.PenType != System.Drawing.Drawing2D.PenType.SolidColor ||
max.PenType != System.Drawing.Drawing2D.PenType.SolidColor)
throw (new ArgumentException("Only SolidColor pens are supported in GradientTheme"));
System.Drawing.Pen pen = new System.Drawing.Pen(InterpolateColor(min.Color, max.Color, attr), InterpolateFloat(min.Width, max.Width, attr));
double frac = Fraction(attr);
pen.MiterLimit = InterpolateFloat(min.MiterLimit, max.MiterLimit, attr);
pen.StartCap = (frac > 0.5 ? max.StartCap : min.StartCap);
pen.EndCap = (frac > 0.5 ? max.EndCap : min.EndCap);
pen.LineJoin = (frac > 0.5 ? max.LineJoin : min.LineJoin);
pen.DashStyle = (frac > 0.5 ? max.DashStyle : min.DashStyle);
if (min.DashStyle == System.Drawing.Drawing2D.DashStyle.Custom &&
max.DashStyle == System.Drawing.Drawing2D.DashStyle.Custom)
pen.DashPattern = (frac > 0.5 ? max.DashPattern : min.DashPattern);
pen.DashOffset = (frac > 0.5 ? max.DashOffset : min.DashOffset);
pen.DashCap = (frac > 0.5 ? max.DashCap : min.DashCap);
if (min.CompoundArray.Length > 0 && max.CompoundArray.Length > 0)
pen.CompoundArray = (frac > 0.5 ? max.CompoundArray : min.CompoundArray);
pen.Alignment = (frac > 0.5 ? max.Alignment : min.Alignment);
return pen;
}
//
// **********************************************************************
/// <summary>
/// Interpolates the color.
/// </summary>
/// <param name="minCol">The min col.</param>
/// <param name="maxCol">The max col.</param>
/// <param name="attr">The attr.</param>
/// <returns></returns>
// **********************************************************************
//
private System.Drawing.Color InterpolateColor(System.Drawing.Color minCol, System.Drawing.Color maxCol, double attr)
{
double frac = Fraction(attr);
if (frac == 1)
return maxCol;
else if (frac == 0)
return minCol;
else
{
double r = (maxCol.R - minCol.R) * frac + minCol.R;
double g = (maxCol.G - minCol.G) * frac + minCol.G;
double b = (maxCol.B - minCol.B) * frac + minCol.B;
double a = (maxCol.A - minCol.A) * frac + minCol.A;
if (r > 255)
r = 255;
if (g > 255)
g = 255;
if (b > 255)
b = 255;
if (a > 255)
a = 255;
return System.Drawing.Color.FromArgb((int)a, (int)r, (int)g, (int)b);
}
}
#endregion
}
}
| |
using System;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.TestUtilities;
using Pomelo.EntityFrameworkCore.MySql.FunctionalTests.TestUtilities;
using Pomelo.EntityFrameworkCore.MySql.Infrastructure;
using Pomelo.EntityFrameworkCore.MySql.Tests.TestUtilities.Attributes;
using Xunit;
#nullable enable
namespace Pomelo.EntityFrameworkCore.MySql.FunctionalTests
{
[SupportedServerVersionCondition(nameof(ServerVersionSupport.RenameColumn))]
public class MigrationsInfrastructureMySqlTest : MigrationsInfrastructureTestBase<MigrationsInfrastructureMySqlTest.MigrationsInfrastructureMySqlFixture>
{
public MigrationsInfrastructureMySqlTest(MigrationsInfrastructureMySqlFixture fixture)
: base(fixture)
{
}
public override void Can_generate_migration_from_initial_database_to_initial()
{
base.Can_generate_migration_from_initial_database_to_initial();
Assert.Equal(
@"CREATE TABLE IF NOT EXISTS `__EFMigrationsHistory` (
`MigrationId` varchar(150) CHARACTER SET utf8mb4 NOT NULL,
`ProductVersion` varchar(32) CHARACTER SET utf8mb4 NOT NULL,
CONSTRAINT `PK___EFMigrationsHistory` PRIMARY KEY (`MigrationId`)
) CHARACTER SET=utf8mb4;
",
Sql,
ignoreLineEndingDifferences: true);
}
public override void Can_generate_no_migration_script()
{
base.Can_generate_no_migration_script();
Assert.Equal(
@"CREATE TABLE IF NOT EXISTS `__EFMigrationsHistory` (
`MigrationId` varchar(150) CHARACTER SET utf8mb4 NOT NULL,
`ProductVersion` varchar(32) CHARACTER SET utf8mb4 NOT NULL,
CONSTRAINT `PK___EFMigrationsHistory` PRIMARY KEY (`MigrationId`)
) CHARACTER SET=utf8mb4;
",
Sql,
ignoreLineEndingDifferences: true);
}
public override void Can_generate_up_scripts()
{
base.Can_generate_up_scripts();
Assert.Equal(
@"CREATE TABLE IF NOT EXISTS `__EFMigrationsHistory` (
`MigrationId` varchar(150) CHARACTER SET utf8mb4 NOT NULL,
`ProductVersion` varchar(32) CHARACTER SET utf8mb4 NOT NULL,
CONSTRAINT `PK___EFMigrationsHistory` PRIMARY KEY (`MigrationId`)
) CHARACTER SET=utf8mb4;
START TRANSACTION;
CREATE TABLE `Table1` (
`Id` int NOT NULL,
`Foo` int NOT NULL,
CONSTRAINT `PK_Table1` PRIMARY KEY (`Id`)
);
INSERT INTO `__EFMigrationsHistory` (`MigrationId`, `ProductVersion`)
VALUES ('00000000000001_Migration1', '7.0.0-test');
COMMIT;
START TRANSACTION;
ALTER TABLE `Table1` RENAME COLUMN `Foo` TO `Bar`;
INSERT INTO `__EFMigrationsHistory` (`MigrationId`, `ProductVersion`)
VALUES ('00000000000002_Migration2', '7.0.0-test');
COMMIT;
START TRANSACTION;
INSERT INTO `__EFMigrationsHistory` (`MigrationId`, `ProductVersion`)
VALUES ('00000000000003_Migration3', '7.0.0-test');
COMMIT;
",
Sql,
ignoreLineEndingDifferences: true);
}
public override void Can_generate_one_up_script()
{
base.Can_generate_one_up_script();
Assert.Equal(
@"START TRANSACTION;
ALTER TABLE `Table1` RENAME COLUMN `Foo` TO `Bar`;
INSERT INTO `__EFMigrationsHistory` (`MigrationId`, `ProductVersion`)
VALUES ('00000000000002_Migration2', '7.0.0-test');
COMMIT;
",
Sql,
ignoreLineEndingDifferences: true);
}
public override void Can_generate_up_script_using_names()
{
base.Can_generate_up_script_using_names();
Assert.Equal(
@"START TRANSACTION;
ALTER TABLE `Table1` RENAME COLUMN `Foo` TO `Bar`;
INSERT INTO `__EFMigrationsHistory` (`MigrationId`, `ProductVersion`)
VALUES ('00000000000002_Migration2', '7.0.0-test');
COMMIT;
",
Sql,
ignoreLineEndingDifferences: true);
}
public override void Can_generate_idempotent_up_scripts()
{
base.Can_generate_idempotent_up_scripts();
Assert.Equal(@"CREATE TABLE IF NOT EXISTS `__EFMigrationsHistory` (
`MigrationId` varchar(150) CHARACTER SET utf8mb4 NOT NULL,
`ProductVersion` varchar(32) CHARACTER SET utf8mb4 NOT NULL,
CONSTRAINT `PK___EFMigrationsHistory` PRIMARY KEY (`MigrationId`)
) CHARACTER SET=utf8mb4;
START TRANSACTION;
DROP PROCEDURE IF EXISTS MigrationsScript;
DELIMITER //
CREATE PROCEDURE MigrationsScript()
BEGIN
IF NOT EXISTS(SELECT 1 FROM `__EFMigrationsHistory` WHERE `MigrationId` = '00000000000001_Migration1') THEN
CREATE TABLE `Table1` (
`Id` int NOT NULL,
`Foo` int NOT NULL,
CONSTRAINT `PK_Table1` PRIMARY KEY (`Id`)
);
END IF;
END //
DELIMITER ;
CALL MigrationsScript();
DROP PROCEDURE MigrationsScript;
DROP PROCEDURE IF EXISTS MigrationsScript;
DELIMITER //
CREATE PROCEDURE MigrationsScript()
BEGIN
IF NOT EXISTS(SELECT 1 FROM `__EFMigrationsHistory` WHERE `MigrationId` = '00000000000001_Migration1') THEN
INSERT INTO `__EFMigrationsHistory` (`MigrationId`, `ProductVersion`)
VALUES ('00000000000001_Migration1', '7.0.0-test');
END IF;
END //
DELIMITER ;
CALL MigrationsScript();
DROP PROCEDURE MigrationsScript;
COMMIT;
START TRANSACTION;
DROP PROCEDURE IF EXISTS MigrationsScript;
DELIMITER //
CREATE PROCEDURE MigrationsScript()
BEGIN
IF NOT EXISTS(SELECT 1 FROM `__EFMigrationsHistory` WHERE `MigrationId` = '00000000000002_Migration2') THEN
ALTER TABLE `Table1` RENAME COLUMN `Foo` TO `Bar`;
END IF;
END //
DELIMITER ;
CALL MigrationsScript();
DROP PROCEDURE MigrationsScript;
DROP PROCEDURE IF EXISTS MigrationsScript;
DELIMITER //
CREATE PROCEDURE MigrationsScript()
BEGIN
IF NOT EXISTS(SELECT 1 FROM `__EFMigrationsHistory` WHERE `MigrationId` = '00000000000002_Migration2') THEN
INSERT INTO `__EFMigrationsHistory` (`MigrationId`, `ProductVersion`)
VALUES ('00000000000002_Migration2', '7.0.0-test');
END IF;
END //
DELIMITER ;
CALL MigrationsScript();
DROP PROCEDURE MigrationsScript;
COMMIT;
START TRANSACTION;
DROP PROCEDURE IF EXISTS MigrationsScript;
DELIMITER //
CREATE PROCEDURE MigrationsScript()
BEGIN
IF NOT EXISTS(SELECT 1 FROM `__EFMigrationsHistory` WHERE `MigrationId` = '00000000000003_Migration3') THEN
INSERT INTO `__EFMigrationsHistory` (`MigrationId`, `ProductVersion`)
VALUES ('00000000000003_Migration3', '7.0.0-test');
END IF;
END //
DELIMITER ;
CALL MigrationsScript();
DROP PROCEDURE MigrationsScript;
COMMIT;
",
Sql,
ignoreLineEndingDifferences: true);
}
public override void Can_generate_down_scripts()
{
base.Can_generate_down_scripts();
Assert.Equal(
@"START TRANSACTION;
ALTER TABLE `Table1` RENAME COLUMN `Bar` TO `Foo`;
DELETE FROM `__EFMigrationsHistory`
WHERE `MigrationId` = '00000000000002_Migration2';
COMMIT;
START TRANSACTION;
DROP TABLE `Table1`;
DELETE FROM `__EFMigrationsHistory`
WHERE `MigrationId` = '00000000000001_Migration1';
COMMIT;
",
Sql,
ignoreLineEndingDifferences: true);
}
public override void Can_generate_one_down_script()
{
base.Can_generate_one_down_script();
Assert.Equal(
@"START TRANSACTION;
ALTER TABLE `Table1` RENAME COLUMN `Bar` TO `Foo`;
DELETE FROM `__EFMigrationsHistory`
WHERE `MigrationId` = '00000000000002_Migration2';
COMMIT;
",
Sql,
ignoreLineEndingDifferences: true);
}
public override void Can_generate_down_script_using_names()
{
base.Can_generate_down_script_using_names();
Assert.Equal(
@"START TRANSACTION;
ALTER TABLE `Table1` RENAME COLUMN `Bar` TO `Foo`;
DELETE FROM `__EFMigrationsHistory`
WHERE `MigrationId` = '00000000000002_Migration2';
COMMIT;
",
Sql,
ignoreLineEndingDifferences: true);
}
public override void Can_generate_idempotent_down_scripts()
{
base.Can_generate_idempotent_down_scripts();
Assert.Equal(
@"START TRANSACTION;
DROP PROCEDURE IF EXISTS MigrationsScript;
DELIMITER //
CREATE PROCEDURE MigrationsScript()
BEGIN
IF EXISTS(SELECT 1 FROM `__EFMigrationsHistory` WHERE `MigrationId` = '00000000000002_Migration2') THEN
ALTER TABLE `Table1` RENAME COLUMN `Bar` TO `Foo`;
END IF;
END //
DELIMITER ;
CALL MigrationsScript();
DROP PROCEDURE MigrationsScript;
DROP PROCEDURE IF EXISTS MigrationsScript;
DELIMITER //
CREATE PROCEDURE MigrationsScript()
BEGIN
IF EXISTS(SELECT 1 FROM `__EFMigrationsHistory` WHERE `MigrationId` = '00000000000002_Migration2') THEN
DELETE FROM `__EFMigrationsHistory`
WHERE `MigrationId` = '00000000000002_Migration2';
END IF;
END //
DELIMITER ;
CALL MigrationsScript();
DROP PROCEDURE MigrationsScript;
COMMIT;
START TRANSACTION;
DROP PROCEDURE IF EXISTS MigrationsScript;
DELIMITER //
CREATE PROCEDURE MigrationsScript()
BEGIN
IF EXISTS(SELECT 1 FROM `__EFMigrationsHistory` WHERE `MigrationId` = '00000000000001_Migration1') THEN
DROP TABLE `Table1`;
END IF;
END //
DELIMITER ;
CALL MigrationsScript();
DROP PROCEDURE MigrationsScript;
DROP PROCEDURE IF EXISTS MigrationsScript;
DELIMITER //
CREATE PROCEDURE MigrationsScript()
BEGIN
IF EXISTS(SELECT 1 FROM `__EFMigrationsHistory` WHERE `MigrationId` = '00000000000001_Migration1') THEN
DELETE FROM `__EFMigrationsHistory`
WHERE `MigrationId` = '00000000000001_Migration1';
END IF;
END //
DELIMITER ;
CALL MigrationsScript();
DROP PROCEDURE MigrationsScript;
COMMIT;
",
Sql,
ignoreLineEndingDifferences: true);
}
public override void Can_get_active_provider()
{
base.Can_get_active_provider();
Assert.Equal("Pomelo.EntityFrameworkCore.MySql", ActiveProvider);
}
public override void Can_generate_up_scripts_noTransactions()
{
base.Can_generate_up_scripts_noTransactions();
Assert.Equal(
@"CREATE TABLE IF NOT EXISTS `__EFMigrationsHistory` (
`MigrationId` varchar(150) CHARACTER SET utf8mb4 NOT NULL,
`ProductVersion` varchar(32) CHARACTER SET utf8mb4 NOT NULL,
CONSTRAINT `PK___EFMigrationsHistory` PRIMARY KEY (`MigrationId`)
) CHARACTER SET=utf8mb4;
CREATE TABLE `Table1` (
`Id` int NOT NULL,
`Foo` int NOT NULL,
CONSTRAINT `PK_Table1` PRIMARY KEY (`Id`)
);
INSERT INTO `__EFMigrationsHistory` (`MigrationId`, `ProductVersion`)
VALUES ('00000000000001_Migration1', '7.0.0-test');
ALTER TABLE `Table1` RENAME COLUMN `Foo` TO `Bar`;
INSERT INTO `__EFMigrationsHistory` (`MigrationId`, `ProductVersion`)
VALUES ('00000000000002_Migration2', '7.0.0-test');
INSERT INTO `__EFMigrationsHistory` (`MigrationId`, `ProductVersion`)
VALUES ('00000000000003_Migration3', '7.0.0-test');
",
Sql,
ignoreLineEndingDifferences: true);
}
public override void Can_generate_idempotent_up_scripts_noTransactions()
{
base.Can_generate_idempotent_up_scripts_noTransactions();
Assert.Equal(
@"CREATE TABLE IF NOT EXISTS `__EFMigrationsHistory` (
`MigrationId` varchar(150) CHARACTER SET utf8mb4 NOT NULL,
`ProductVersion` varchar(32) CHARACTER SET utf8mb4 NOT NULL,
CONSTRAINT `PK___EFMigrationsHistory` PRIMARY KEY (`MigrationId`)
) CHARACTER SET=utf8mb4;
DROP PROCEDURE IF EXISTS MigrationsScript;
DELIMITER //
CREATE PROCEDURE MigrationsScript()
BEGIN
IF NOT EXISTS(SELECT 1 FROM `__EFMigrationsHistory` WHERE `MigrationId` = '00000000000001_Migration1') THEN
CREATE TABLE `Table1` (
`Id` int NOT NULL,
`Foo` int NOT NULL,
CONSTRAINT `PK_Table1` PRIMARY KEY (`Id`)
);
END IF;
END //
DELIMITER ;
CALL MigrationsScript();
DROP PROCEDURE MigrationsScript;
DROP PROCEDURE IF EXISTS MigrationsScript;
DELIMITER //
CREATE PROCEDURE MigrationsScript()
BEGIN
IF NOT EXISTS(SELECT 1 FROM `__EFMigrationsHistory` WHERE `MigrationId` = '00000000000001_Migration1') THEN
INSERT INTO `__EFMigrationsHistory` (`MigrationId`, `ProductVersion`)
VALUES ('00000000000001_Migration1', '7.0.0-test');
END IF;
END //
DELIMITER ;
CALL MigrationsScript();
DROP PROCEDURE MigrationsScript;
DROP PROCEDURE IF EXISTS MigrationsScript;
DELIMITER //
CREATE PROCEDURE MigrationsScript()
BEGIN
IF NOT EXISTS(SELECT 1 FROM `__EFMigrationsHistory` WHERE `MigrationId` = '00000000000002_Migration2') THEN
ALTER TABLE `Table1` RENAME COLUMN `Foo` TO `Bar`;
END IF;
END //
DELIMITER ;
CALL MigrationsScript();
DROP PROCEDURE MigrationsScript;
DROP PROCEDURE IF EXISTS MigrationsScript;
DELIMITER //
CREATE PROCEDURE MigrationsScript()
BEGIN
IF NOT EXISTS(SELECT 1 FROM `__EFMigrationsHistory` WHERE `MigrationId` = '00000000000002_Migration2') THEN
INSERT INTO `__EFMigrationsHistory` (`MigrationId`, `ProductVersion`)
VALUES ('00000000000002_Migration2', '7.0.0-test');
END IF;
END //
DELIMITER ;
CALL MigrationsScript();
DROP PROCEDURE MigrationsScript;
DROP PROCEDURE IF EXISTS MigrationsScript;
DELIMITER //
CREATE PROCEDURE MigrationsScript()
BEGIN
IF NOT EXISTS(SELECT 1 FROM `__EFMigrationsHistory` WHERE `MigrationId` = '00000000000003_Migration3') THEN
INSERT INTO `__EFMigrationsHistory` (`MigrationId`, `ProductVersion`)
VALUES ('00000000000003_Migration3', '7.0.0-test');
END IF;
END //
DELIMITER ;
CALL MigrationsScript();
DROP PROCEDURE MigrationsScript;
",
Sql,
ignoreLineEndingDifferences: true);
}
[ConditionalFact(Skip = "TODO: Implement")]
public override void Can_diff_against_2_2_model()
{
throw new NotImplementedException();
}
[ConditionalFact(Skip = "TODO: Implement")]
public override void Can_diff_against_3_0_ASP_NET_Identity_model()
{
throw new NotImplementedException();
}
[ConditionalFact(Skip = "TODO: Implement")]
public override void Can_diff_against_2_2_ASP_NET_Identity_model()
{
throw new NotImplementedException();
}
[ConditionalFact(Skip = "TODO: Implement")]
public override void Can_diff_against_2_1_ASP_NET_Identity_model()
{
throw new NotImplementedException();
}
public class MigrationsInfrastructureMySqlFixture : MigrationsInfrastructureFixtureBase
{
protected override ITestStoreFactory TestStoreFactory
=> MySqlConnectionStringTestStoreFactory.Instance;
}
}
}
| |
using System;
using System.Globalization;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using Examine;
using Examine.LuceneEngine;
using Lucene.Net.Documents;
using Umbraco.Core;
using Umbraco.Core.Cache;
using Umbraco.Core.Logging;
using Umbraco.Core.Models;
using Umbraco.Core.Sync;
using Umbraco.Web.Cache;
using UmbracoExamine;
using Content = umbraco.cms.businesslogic.Content;
using Document = umbraco.cms.businesslogic.web.Document;
namespace Umbraco.Web.Search
{
/// <summary>
/// Used to wire up events for Examine
/// </summary>
public sealed class ExamineEvents : ApplicationEventHandler
{
/// <summary>
/// Once the application has started we should bind to all events and initialize the providers.
/// </summary>
/// <param name="httpApplication"></param>
/// <param name="applicationContext"></param>
/// <remarks>
/// We need to do this on the Started event as to guarantee that all resolvers are setup properly.
/// </remarks>
protected override void ApplicationStarted(UmbracoApplicationBase httpApplication, ApplicationContext applicationContext)
{
LogHelper.Info<ExamineEvents>("Initializing Examine and binding to business logic events");
var registeredProviders = ExamineManager.Instance.IndexProviderCollection
.OfType<BaseUmbracoIndexer>().Count(x => x.EnableDefaultEventHandler);
LogHelper.Info<ExamineEvents>("Adding examine event handlers for index providers: {0}", () => registeredProviders);
//don't bind event handlers if we're not suppose to listen
if (registeredProviders == 0)
return;
//Bind to distributed cache events - this ensures that this logic occurs on ALL servers that are taking part
// in a load balanced environment.
CacheRefresherBase<UnpublishedPageCacheRefresher>.CacheUpdated += UnpublishedPageCacheRefresherCacheUpdated;
CacheRefresherBase<PageCacheRefresher>.CacheUpdated += PublishedPageCacheRefresherCacheUpdated;
CacheRefresherBase<MediaCacheRefresher>.CacheUpdated += MediaCacheRefresherCacheUpdated;
CacheRefresherBase<MemberCacheRefresher>.CacheUpdated += MemberCacheRefresherCacheUpdated;
CacheRefresherBase<ContentTypeCacheRefresher>.CacheUpdated += ContentTypeCacheRefresherCacheUpdated;
var contentIndexer = ExamineManager.Instance.IndexProviderCollection[Constants.Examine.InternalIndexer] as UmbracoContentIndexer;
if (contentIndexer != null)
{
contentIndexer.DocumentWriting += IndexerDocumentWriting;
}
var memberIndexer = ExamineManager.Instance.IndexProviderCollection[Constants.Examine.InternalMemberIndexer] as UmbracoMemberIndexer;
if (memberIndexer != null)
{
memberIndexer.DocumentWriting += IndexerDocumentWriting;
}
}
/// <summary>
/// This is used to refresh content indexers IndexData based on the DataService whenever a content type is changed since
/// properties may have been added/removed
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
/// <remarks>
/// See: http://issues.umbraco.org/issue/U4-4798
/// </remarks>
static void ContentTypeCacheRefresherCacheUpdated(ContentTypeCacheRefresher sender, CacheRefresherEventArgs e)
{
var indexersToUpdated = ExamineManager.Instance.IndexProviderCollection.OfType<UmbracoContentIndexer>();
foreach (var provider in indexersToUpdated)
{
provider.RefreshIndexerDataFromDataService();
}
}
static void MemberCacheRefresherCacheUpdated(MemberCacheRefresher sender, CacheRefresherEventArgs e)
{
switch (e.MessageType)
{
case MessageType.RefreshById:
var c1 = ApplicationContext.Current.Services.MemberService.GetById((int)e.MessageObject);
if (c1 != null)
{
ReIndexForMember(c1);
}
break;
case MessageType.RemoveById:
// This is triggered when the item is permanently deleted
DeleteIndexForEntity((int)e.MessageObject, false);
break;
case MessageType.RefreshByInstance:
var c3 = e.MessageObject as IMember;
if (c3 != null)
{
ReIndexForMember(c3);
}
break;
case MessageType.RemoveByInstance:
// This is triggered when the item is permanently deleted
var c4 = e.MessageObject as IMember;
if (c4 != null)
{
DeleteIndexForEntity(c4.Id, false);
}
break;
case MessageType.RefreshAll:
case MessageType.RefreshByJson:
default:
//We don't support these, these message types will not fire for unpublished content
break;
}
}
/// <summary>
/// Handles index management for all media events - basically handling saving/copying/trashing/deleting
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
static void MediaCacheRefresherCacheUpdated(MediaCacheRefresher sender, CacheRefresherEventArgs e)
{
switch (e.MessageType)
{
case MessageType.RefreshById:
var c1 = ApplicationContext.Current.Services.MediaService.GetById((int)e.MessageObject);
if (c1 != null)
{
ReIndexForMedia(c1, c1.Trashed == false);
}
break;
case MessageType.RemoveById:
var c2 = ApplicationContext.Current.Services.MediaService.GetById((int)e.MessageObject);
if (c2 != null)
{
//This is triggered when the item has trashed.
// So we need to delete the index from all indexes not supporting unpublished content.
DeleteIndexForEntity(c2.Id, true);
//We then need to re-index this item for all indexes supporting unpublished content
ReIndexForMedia(c2, false);
}
break;
case MessageType.RefreshByJson:
var jsonPayloads = MediaCacheRefresher.DeserializeFromJsonPayload((string)e.MessageObject);
if (jsonPayloads.Any())
{
foreach (var payload in jsonPayloads)
{
switch (payload.Operation)
{
case MediaCacheRefresher.OperationType.Saved:
var media1 = ApplicationContext.Current.Services.MediaService.GetById(payload.Id);
if (media1 != null)
{
ReIndexForMedia(media1, media1.Trashed == false);
}
break;
case MediaCacheRefresher.OperationType.Trashed:
//keep if trashed for indexes supporting unpublished
//(delete the index from all indexes not supporting unpublished content)
DeleteIndexForEntity(payload.Id, true);
//We then need to re-index this item for all indexes supporting unpublished content
var media2 = ApplicationContext.Current.Services.MediaService.GetById(payload.Id);
if (media2 != null)
{
ReIndexForMedia(media2, false);
}
break;
case MediaCacheRefresher.OperationType.Deleted:
//permanently remove from all indexes
DeleteIndexForEntity(payload.Id, false);
break;
default:
throw new ArgumentOutOfRangeException();
}
}
}
break;
case MessageType.RefreshByInstance:
case MessageType.RemoveByInstance:
case MessageType.RefreshAll:
default:
//We don't support these, these message types will not fire for media
break;
}
}
/// <summary>
/// Handles index management for all published content events - basically handling published/unpublished
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
/// <remarks>
/// This will execute on all servers taking part in load balancing
/// </remarks>
static void PublishedPageCacheRefresherCacheUpdated(PageCacheRefresher sender, CacheRefresherEventArgs e)
{
switch (e.MessageType)
{
case MessageType.RefreshById:
var c1 = ApplicationContext.Current.Services.ContentService.GetById((int)e.MessageObject);
if (c1 != null)
{
ReIndexForContent(c1, true);
}
break;
case MessageType.RemoveById:
//This is triggered when the item has been unpublished or trashed (which also performs an unpublish).
var c2 = ApplicationContext.Current.Services.ContentService.GetById((int)e.MessageObject);
if (c2 != null)
{
// So we need to delete the index from all indexes not supporting unpublished content.
DeleteIndexForEntity(c2.Id, true);
// We then need to re-index this item for all indexes supporting unpublished content
ReIndexForContent(c2, false);
}
break;
case MessageType.RefreshByInstance:
var c3 = e.MessageObject as IContent;
if (c3 != null)
{
ReIndexForContent(c3, true);
}
break;
case MessageType.RemoveByInstance:
//This is triggered when the item has been unpublished or trashed (which also performs an unpublish).
var c4 = e.MessageObject as IContent;
if (c4 != null)
{
// So we need to delete the index from all indexes not supporting unpublished content.
DeleteIndexForEntity(c4.Id, true);
// We then need to re-index this item for all indexes supporting unpublished content
ReIndexForContent(c4, false);
}
break;
case MessageType.RefreshAll:
case MessageType.RefreshByJson:
default:
//We don't support these for examine indexing
break;
}
}
/// <summary>
/// Handles index management for all unpublished content events - basically handling saving/copying/deleting
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
/// <remarks>
/// This will execute on all servers taking part in load balancing
/// </remarks>
static void UnpublishedPageCacheRefresherCacheUpdated(UnpublishedPageCacheRefresher sender, CacheRefresherEventArgs e)
{
switch (e.MessageType)
{
case MessageType.RefreshById:
var c1 = ApplicationContext.Current.Services.ContentService.GetById((int) e.MessageObject);
if (c1 != null)
{
ReIndexForContent(c1, false);
}
break;
case MessageType.RemoveById:
// This is triggered when the item is permanently deleted
DeleteIndexForEntity((int)e.MessageObject, false);
break;
case MessageType.RefreshByInstance:
var c3 = e.MessageObject as IContent;
if (c3 != null)
{
ReIndexForContent(c3, false);
}
break;
case MessageType.RemoveByInstance:
// This is triggered when the item is permanently deleted
var c4 = e.MessageObject as IContent;
if (c4 != null)
{
DeleteIndexForEntity(c4.Id, false);
}
break;
case MessageType.RefreshByJson:
var jsonPayloads = UnpublishedPageCacheRefresher.DeserializeFromJsonPayload((string)e.MessageObject);
if (jsonPayloads.Any())
{
foreach (var payload in jsonPayloads)
{
switch (payload.Operation)
{
case UnpublishedPageCacheRefresher.OperationType.Deleted:
//permanently remove from all indexes
DeleteIndexForEntity(payload.Id, false);
break;
default:
throw new ArgumentOutOfRangeException();
}
}
}
break;
case MessageType.RefreshAll:
default:
//We don't support these, these message types will not fire for unpublished content
break;
}
}
private static void ReIndexForMember(IMember member)
{
ExamineManager.Instance.ReIndexNode(
member.ToXml(), IndexTypes.Member,
ExamineManager.Instance.IndexProviderCollection.OfType<BaseUmbracoIndexer>()
//ensure that only the providers are flagged to listen execute
.Where(x => x.EnableDefaultEventHandler));
}
/// <summary>
/// Event handler to create a lower cased version of the node name, this is so we can support case-insensitive searching and still
/// use the Whitespace Analyzer
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void IndexerDocumentWriting(object sender, DocumentWritingEventArgs e)
{
if (e.Fields.Keys.Contains("nodeName"))
{
//TODO: This logic should really be put into the content indexer instead of hidden here!!
//add the lower cased version
e.Document.Add(new Field("__nodeName",
e.Fields["nodeName"].ToLower(),
Field.Store.YES,
Field.Index.ANALYZED,
Field.TermVector.NO
));
}
}
private static void ReIndexForMedia(IMedia sender, bool isMediaPublished)
{
var xml = sender.ToXml();
//add an icon attribute to get indexed
xml.Add(new XAttribute("icon", sender.ContentType.Icon));
ExamineManager.Instance.ReIndexNode(
xml, IndexTypes.Media,
ExamineManager.Instance.IndexProviderCollection.OfType<BaseUmbracoIndexer>()
//Index this item for all indexers if the media is not trashed, otherwise if the item is trashed
// then only index this for indexers supporting unpublished media
.Where(x => isMediaPublished || (x.SupportUnpublishedContent))
.Where(x => x.EnableDefaultEventHandler));
}
/// <summary>
/// Remove items from any index that doesn't support unpublished content
/// </summary>
/// <param name="entityId"></param>
/// <param name="keepIfUnpublished">
/// If true, indicates that we will only delete this item from indexes that don't support unpublished content.
/// If false it will delete this from all indexes regardless.
/// </param>
private static void DeleteIndexForEntity(int entityId, bool keepIfUnpublished)
{
ExamineManager.Instance.DeleteFromIndex(
entityId.ToString(CultureInfo.InvariantCulture),
ExamineManager.Instance.IndexProviderCollection.OfType<BaseUmbracoIndexer>()
//if keepIfUnpublished == true then only delete this item from indexes not supporting unpublished content,
// otherwise if keepIfUnpublished == false then remove from all indexes
.Where(x => keepIfUnpublished == false || x.SupportUnpublishedContent == false)
.Where(x => x.EnableDefaultEventHandler));
}
/// <summary>
/// Re-indexes a content item whether published or not but only indexes them for indexes supporting unpublished content
/// </summary>
/// <param name="sender"></param>
/// <param name="isContentPublished">
/// Value indicating whether the item is published or not
/// </param>
private static void ReIndexForContent(IContent sender, bool isContentPublished)
{
var xml = sender.ToXml();
//add an icon attribute to get indexed
xml.Add(new XAttribute("icon", sender.ContentType.Icon));
ExamineManager.Instance.ReIndexNode(
xml, IndexTypes.Content,
ExamineManager.Instance.IndexProviderCollection.OfType<BaseUmbracoIndexer>()
//Index this item for all indexers if the content is published, otherwise if the item is not published
// then only index this for indexers supporting unpublished content
.Where(x => isContentPublished || (x.SupportUnpublishedContent))
.Where(x => x.EnableDefaultEventHandler));
}
/// <summary>
/// Converts a content node to XDocument
/// </summary>
/// <param name="node"></param>
/// <param name="cacheOnly">true if data is going to be returned from cache</param>
/// <returns></returns>
[Obsolete("This method is no longer used and will be removed from the core in future versions, the cacheOnly parameter has no effect. Use the other ToXDocument overload instead")]
public static XDocument ToXDocument(Content node, bool cacheOnly)
{
return ToXDocument(node);
}
/// <summary>
/// Converts a content node to Xml
/// </summary>
/// <param name="node"></param>
/// <returns></returns>
private static XDocument ToXDocument(Content node)
{
if (TypeHelper.IsTypeAssignableFrom<Document>(node))
{
return new XDocument(((Document) node).ContentEntity.ToXml());
}
if (TypeHelper.IsTypeAssignableFrom<global::umbraco.cms.businesslogic.media.Media>(node))
{
return new XDocument(((global::umbraco.cms.businesslogic.media.Media) node).MediaItem.ToXml());
}
var xDoc = new XmlDocument();
var xNode = xDoc.CreateNode(XmlNodeType.Element, "node", "");
node.XmlPopulate(xDoc, ref xNode, false);
if (xNode.Attributes["nodeTypeAlias"] == null)
{
//we'll add the nodeTypeAlias ourselves
XmlAttribute d = xDoc.CreateAttribute("nodeTypeAlias");
d.Value = node.ContentType.Alias;
xNode.Attributes.Append(d);
}
return new XDocument(ExamineXmlExtensions.ToXElement(xNode));
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Text;
using Internal.Runtime.CompilerServices;
using Internal.Runtime.Augments;
using Internal.Reflection.Augments;
using CorElementType = System.Runtime.RuntimeImports.RhCorElementType;
namespace System
{
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public abstract class Enum : ValueType, IComparable, IFormattable, IConvertible
{
public int CompareTo(object target)
{
if (target == null)
return 1;
if (target == this)
return 0;
if (this.EETypePtr != target.EETypePtr)
{
throw new ArgumentException(SR.Format(SR.Arg_EnumAndObjectMustBeSameType, target.GetType().ToString(), this.GetType().ToString()));
}
ref byte pThisValue = ref this.GetRawData();
ref byte pTargetValue = ref target.GetRawData();
switch (this.EETypePtr.CorElementType)
{
case CorElementType.ELEMENT_TYPE_I1:
return (Unsafe.As<byte, sbyte>(ref pThisValue) == Unsafe.As<byte, sbyte>(ref pTargetValue)) ?
0 : (Unsafe.As<byte, sbyte>(ref pThisValue) < Unsafe.As<byte, sbyte>(ref pTargetValue)) ? -1 : 1;
case CorElementType.ELEMENT_TYPE_U1:
case CorElementType.ELEMENT_TYPE_BOOLEAN:
return (Unsafe.As<byte, byte>(ref pThisValue) == Unsafe.As<byte, byte>(ref pTargetValue)) ?
0 : (Unsafe.As<byte, byte>(ref pThisValue) < Unsafe.As<byte, byte>(ref pTargetValue)) ? -1 : 1;
case CorElementType.ELEMENT_TYPE_I2:
return (Unsafe.As<byte, short>(ref pThisValue) == Unsafe.As<byte, short>(ref pTargetValue)) ?
0 : (Unsafe.As<byte, short>(ref pThisValue) < Unsafe.As<byte, short>(ref pTargetValue)) ? -1 : 1;
case CorElementType.ELEMENT_TYPE_U2:
case CorElementType.ELEMENT_TYPE_CHAR:
return (Unsafe.As<byte, ushort>(ref pThisValue) == Unsafe.As<byte, ushort>(ref pTargetValue)) ?
0 : (Unsafe.As<byte, ushort>(ref pThisValue) < Unsafe.As<byte, ushort>(ref pTargetValue)) ? -1 : 1;
case CorElementType.ELEMENT_TYPE_I4:
return (Unsafe.As<byte, int>(ref pThisValue) == Unsafe.As<byte, int>(ref pTargetValue)) ?
0 : (Unsafe.As<byte, int>(ref pThisValue) < Unsafe.As<byte, int>(ref pTargetValue)) ? -1 : 1;
case CorElementType.ELEMENT_TYPE_U4:
return (Unsafe.As<byte, uint>(ref pThisValue) == Unsafe.As<byte, uint>(ref pTargetValue)) ?
0 : (Unsafe.As<byte, uint>(ref pThisValue) < Unsafe.As<byte, uint>(ref pTargetValue)) ? -1 : 1;
case CorElementType.ELEMENT_TYPE_I8:
return (Unsafe.As<byte, long>(ref pThisValue) == Unsafe.As<byte, long>(ref pTargetValue)) ?
0 : (Unsafe.As<byte, long>(ref pThisValue) < Unsafe.As<byte, long>(ref pTargetValue)) ? -1 : 1;
case CorElementType.ELEMENT_TYPE_U8:
return (Unsafe.As<byte, ulong>(ref pThisValue) == Unsafe.As<byte, ulong>(ref pTargetValue)) ?
0 : (Unsafe.As<byte, ulong>(ref pThisValue) < Unsafe.As<byte, ulong>(ref pTargetValue)) ? -1 : 1;
default:
Environment.FailFast("Unexpected enum underlying type");
return 0;
}
}
public override bool Equals(object obj)
{
if (obj == null)
return false;
EETypePtr eeType = this.EETypePtr;
if (!eeType.FastEquals(obj.EETypePtr))
return false;
ref byte pThisValue = ref this.GetRawData();
ref byte pOtherValue = ref obj.GetRawData();
RuntimeImports.RhCorElementTypeInfo corElementTypeInfo = eeType.CorElementTypeInfo;
switch (corElementTypeInfo.Log2OfSize)
{
case 0:
return Unsafe.As<byte, byte>(ref pThisValue) == Unsafe.As<byte, byte>(ref pOtherValue);
case 1:
return Unsafe.As<byte, ushort>(ref pThisValue) == Unsafe.As<byte, ushort>(ref pOtherValue);
case 2:
return Unsafe.As<byte, uint>(ref pThisValue) == Unsafe.As<byte, uint>(ref pOtherValue);
case 3:
return Unsafe.As<byte, ulong>(ref pThisValue) == Unsafe.As<byte, ulong>(ref pOtherValue);
default:
Environment.FailFast("Unexpected enum underlying type");
return false;
}
}
public override int GetHashCode()
{
ref byte pValue = ref this.GetRawData();
switch (this.EETypePtr.CorElementType)
{
case CorElementType.ELEMENT_TYPE_BOOLEAN:
return Unsafe.As<byte, bool>(ref pValue).GetHashCode();
case CorElementType.ELEMENT_TYPE_CHAR:
return Unsafe.As<byte, char>(ref pValue).GetHashCode();
case CorElementType.ELEMENT_TYPE_I1:
return Unsafe.As<byte, sbyte>(ref pValue).GetHashCode();
case CorElementType.ELEMENT_TYPE_U1:
return Unsafe.As<byte, byte>(ref pValue).GetHashCode();
case CorElementType.ELEMENT_TYPE_I2:
return Unsafe.As<byte, short>(ref pValue).GetHashCode();
case CorElementType.ELEMENT_TYPE_U2:
return Unsafe.As<byte, ushort>(ref pValue).GetHashCode();
case CorElementType.ELEMENT_TYPE_I4:
return Unsafe.As<byte, int>(ref pValue).GetHashCode();
case CorElementType.ELEMENT_TYPE_U4:
return Unsafe.As<byte, uint>(ref pValue).GetHashCode();
case CorElementType.ELEMENT_TYPE_I8:
return Unsafe.As<byte, long>(ref pValue).GetHashCode();
case CorElementType.ELEMENT_TYPE_U8:
return Unsafe.As<byte, ulong>(ref pValue).GetHashCode();
default:
Environment.FailFast("Unexpected enum underlying type");
return 0;
}
}
public static string Format(Type enumType, object value, string format)
{
if (enumType == null)
throw new ArgumentNullException(nameof(enumType));
if (!enumType.IsEnum)
throw new ArgumentException(SR.Arg_MustBeEnum, nameof(enumType));
if (value == null)
throw new ArgumentNullException(nameof(value));
if (format == null)
throw new ArgumentNullException(nameof(format));
if (!enumType.IsRuntimeImplemented())
throw new ArgumentException(SR.Arg_MustBeType, nameof(enumType));
EnumInfo enumInfo = GetEnumInfo(enumType);
if (value is Enum)
{
EETypePtr enumTypeEEType;
if ((!enumType.TryGetEEType(out enumTypeEEType)) || enumTypeEEType != value.EETypePtr)
throw new ArgumentException(SR.Format(SR.Arg_EnumAndObjectMustBeSameType, value.GetType().ToString(), enumType.ToString()));
}
else
{
if (value.EETypePtr != enumInfo.UnderlyingType.TypeHandle.ToEETypePtr())
throw new ArgumentException(SR.Format(SR.Arg_EnumFormatUnderlyingTypeAndObjectMustBeSameType, value.GetType().ToString(), enumInfo.UnderlyingType.ToString()));
}
return Format(enumInfo, value, format);
}
private static string Format(EnumInfo enumInfo, object value, string format)
{
ulong rawValue;
if (!TryGetUnboxedValueOfEnumOrInteger(value, out rawValue))
{
Debug.Fail("Caller was expected to do enough validation to avoid reaching this.");
throw new ArgumentException();
}
if (format.Length == 1)
{
switch (format[0])
{
case 'G':
case 'g':
return DoFormatG(enumInfo, rawValue);
case 'D':
case 'd':
return DoFormatD(rawValue, value.EETypePtr.CorElementType);
case 'X':
case 'x':
return DoFormatX(rawValue, value.EETypePtr.CorElementType);
case 'F':
case 'f':
return DoFormatF(enumInfo, rawValue);
}
}
throw new FormatException(SR.Format_InvalidEnumFormatSpecification);
}
//
// Helper for Enum.Format(,,"d")
//
private static string DoFormatD(ulong rawValue, CorElementType corElementType)
{
switch (corElementType)
{
case CorElementType.ELEMENT_TYPE_I1:
{
sbyte result = (sbyte)rawValue;
return result.ToString();
}
case CorElementType.ELEMENT_TYPE_U1:
{
byte result = (byte)rawValue;
return result.ToString();
}
case CorElementType.ELEMENT_TYPE_BOOLEAN:
{
// direct cast from bool to byte is not allowed
bool b = (rawValue != 0);
return b.ToString();
}
case CorElementType.ELEMENT_TYPE_I2:
{
short result = (short)rawValue;
return result.ToString();
}
case CorElementType.ELEMENT_TYPE_U2:
{
ushort result = (ushort)rawValue;
return result.ToString();
}
case CorElementType.ELEMENT_TYPE_CHAR:
{
char result = (char)rawValue;
return result.ToString();
}
case CorElementType.ELEMENT_TYPE_U4:
{
uint result = (uint)rawValue;
return result.ToString();
}
case CorElementType.ELEMENT_TYPE_I4:
{
int result = (int)rawValue;
return result.ToString();
}
case CorElementType.ELEMENT_TYPE_U8:
{
ulong result = (ulong)rawValue;
return result.ToString();
}
case CorElementType.ELEMENT_TYPE_I8:
{
long result = (long)rawValue;
return result.ToString();
}
default:
Debug.Fail("Invalid Object type in Format");
throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType);
}
}
//
// Helper for Enum.Format(,,"x")
//
private static string DoFormatX(ulong rawValue, CorElementType corElementType)
{
switch (corElementType)
{
case CorElementType.ELEMENT_TYPE_I1:
{
byte result = (byte)(sbyte)rawValue;
return result.ToString("X2", null);
}
case CorElementType.ELEMENT_TYPE_U1:
{
byte result = (byte)rawValue;
return result.ToString("X2", null);
}
case CorElementType.ELEMENT_TYPE_BOOLEAN:
{
// direct cast from bool to byte is not allowed
byte result = (byte)rawValue;
return result.ToString("X2", null);
}
case CorElementType.ELEMENT_TYPE_I2:
{
ushort result = (ushort)(short)rawValue;
return result.ToString("X4", null);
}
case CorElementType.ELEMENT_TYPE_U2:
{
ushort result = (ushort)rawValue;
return result.ToString("X4", null);
}
case CorElementType.ELEMENT_TYPE_CHAR:
{
ushort result = (ushort)(char)rawValue;
return result.ToString("X4", null);
}
case CorElementType.ELEMENT_TYPE_U4:
{
uint result = (uint)rawValue;
return result.ToString("X8", null);
}
case CorElementType.ELEMENT_TYPE_I4:
{
uint result = (uint)(int)rawValue;
return result.ToString("X8", null);
}
case CorElementType.ELEMENT_TYPE_U8:
{
ulong result = (ulong)rawValue;
return result.ToString("X16", null);
}
case CorElementType.ELEMENT_TYPE_I8:
{
ulong result = (ulong)(long)rawValue;
return result.ToString("X16", null);
}
default:
Debug.Fail("Invalid Object type in Format");
throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType);
}
}
//
// Helper for Enum.Format(,,"g")
//
private static string DoFormatG(EnumInfo enumInfo, ulong rawValue)
{
Debug.Assert(enumInfo != null);
if (!enumInfo.HasFlagsAttribute) // Not marked with Flags attribute
{
// Try to see if its one of the enum values, then we return a String back else the value
string name = GetNameIfAny(enumInfo, rawValue);
if (name == null)
return DoFormatD(rawValue, enumInfo.UnderlyingType.TypeHandle.ToEETypePtr().CorElementType);
else
return name;
}
else // These are flags OR'ed together (We treat everything as unsigned types)
{
return DoFormatF(enumInfo, rawValue);
}
}
//
// Helper for Enum.Format(,,"f")
//
private static string DoFormatF(EnumInfo enumInfo, ulong rawValue)
{
Debug.Assert(enumInfo != null);
// These values are sorted by value. Don't change this
KeyValuePair<string, ulong>[] namesAndValues = enumInfo.NamesAndValues;
int index = namesAndValues.Length - 1;
StringBuilder retval = new StringBuilder();
bool firstTime = true;
ulong result = rawValue;
// We will not optimize this code further to keep it maintainable. There are some boundary checks that can be applied
// to minimize the comparsions required. This code works the same for the best/worst case. In general the number of
// items in an enum are sufficiently small and not worth the optimization.
while (index >= 0)
{
if ((index == 0) && (namesAndValues[index].Value == 0))
break;
if ((result & namesAndValues[index].Value) == namesAndValues[index].Value)
{
result -= namesAndValues[index].Value;
if (!firstTime)
retval.Insert(0, ", ");
retval.Insert(0, namesAndValues[index].Key);
firstTime = false;
}
index--;
}
// We were unable to represent this number as a bitwise or of valid flags
if (result != 0)
return DoFormatD(rawValue, enumInfo.UnderlyingType.TypeHandle.ToEETypePtr().CorElementType);
// For the case when we have zero
if (rawValue == 0)
{
if (namesAndValues.Length > 0 && namesAndValues[0].Value == 0)
return namesAndValues[0].Key; // Zero was one of the enum values.
else
return "0";
}
else
return retval.ToString(); // Built a list of matching names. Return it.
}
internal object GetValue()
{
ref byte pValue = ref this.GetRawData();
switch (this.EETypePtr.CorElementType)
{
case CorElementType.ELEMENT_TYPE_BOOLEAN:
return Unsafe.As<byte, bool>(ref pValue);
case CorElementType.ELEMENT_TYPE_CHAR:
return Unsafe.As<byte, char>(ref pValue);
case CorElementType.ELEMENT_TYPE_I1:
return Unsafe.As<byte, sbyte>(ref pValue);
case CorElementType.ELEMENT_TYPE_U1:
return Unsafe.As<byte, byte>(ref pValue);
case CorElementType.ELEMENT_TYPE_I2:
return Unsafe.As<byte, short>(ref pValue);
case CorElementType.ELEMENT_TYPE_U2:
return Unsafe.As<byte, ushort>(ref pValue);
case CorElementType.ELEMENT_TYPE_I4:
return Unsafe.As<byte, int>(ref pValue);
case CorElementType.ELEMENT_TYPE_U4:
return Unsafe.As<byte, uint>(ref pValue);
case CorElementType.ELEMENT_TYPE_I8:
return Unsafe.As<byte, long>(ref pValue);
case CorElementType.ELEMENT_TYPE_U8:
return Unsafe.As<byte, ulong>(ref pValue);
default:
Environment.FailFast("Unexpected enum underlying type");
return 0;
}
}
public static string GetName(Type enumType, object value)
{
if (enumType == null)
throw new ArgumentNullException(nameof(enumType));
if (!enumType.IsRuntimeImplemented())
return enumType.GetEnumName(value);
if (value == null)
throw new ArgumentNullException(nameof(value));
ulong rawValue;
if (!TryGetUnboxedValueOfEnumOrInteger(value, out rawValue))
throw new ArgumentException(SR.Arg_MustBeEnumBaseTypeOrEnum, nameof(value));
// For desktop compatibility, do not bounce an incoming integer that's the wrong size.
// Do a value-preserving cast of both it and the enum values and do a 64-bit compare.
if (!enumType.IsEnum)
throw new ArgumentException(SR.Arg_MustBeEnum);
EnumInfo enumInfo = GetEnumInfo(enumType);
string nameOrNull = GetNameIfAny(enumInfo, rawValue);
return nameOrNull;
}
public static string[] GetNames(Type enumType)
{
if (enumType == null)
throw new ArgumentNullException(nameof(enumType));
if (!enumType.IsRuntimeImplemented())
return enumType.GetEnumNames();
if (!enumType.IsEnum)
throw new ArgumentException(SR.Arg_MustBeEnum);
KeyValuePair<string, ulong>[] namesAndValues = GetEnumInfo(enumType).NamesAndValues;
string[] names = new string[namesAndValues.Length];
for (int i = 0; i < namesAndValues.Length; i++)
names[i] = namesAndValues[i].Key;
return names;
}
public static Type GetUnderlyingType(Type enumType)
{
if (enumType == null)
throw new ArgumentNullException(nameof(enumType));
if (!enumType.IsRuntimeImplemented())
return enumType.GetEnumUnderlyingType();
if (!enumType.IsEnum)
throw new ArgumentException(SR.Arg_MustBeEnum, nameof(enumType));
return GetEnumInfo(enumType).UnderlyingType;
}
public static Array GetValues(Type enumType)
{
if (enumType == null)
throw new ArgumentNullException(nameof(enumType));
if (!enumType.IsRuntimeImplemented())
return enumType.GetEnumValues();
if (!enumType.IsEnum)
throw new ArgumentException(SR.Arg_MustBeEnum);
Array values = GetEnumInfo(enumType).Values;
int count = values.Length;
#if PROJECTN
Array result = Array.CreateInstance(enumType, count);
#else
// Without universal shared generics, chances are slim that we'll have the appropriate
// array type available. Offer an escape hatch that avoids a MissingMetadataException
// at the cost of a small appcompat risk.
Array result;
if (AppContext.TryGetSwitch("Switch.System.Enum.RelaxedGetValues", out bool isRelaxed) && isRelaxed)
result = Array.CreateInstance(Enum.GetUnderlyingType(enumType), count);
else
result = Array.CreateInstance(enumType, count);
#endif
Array.CopyImplValueTypeArrayNoInnerGcRefs(values, 0, result, 0, count);
return result;
}
[Intrinsic]
public bool HasFlag(Enum flag)
{
if (flag == null)
throw new ArgumentNullException(nameof(flag));
if (!(this.EETypePtr == flag.EETypePtr))
throw new ArgumentException(SR.Format(SR.Argument_EnumTypeDoesNotMatch, flag.GetType(), this.GetType()));
ref byte pThisValue = ref this.GetRawData();
ref byte pFlagValue = ref flag.GetRawData();
switch (this.EETypePtr.CorElementTypeInfo.Log2OfSize)
{
case 0:
return (Unsafe.As<byte, byte>(ref pThisValue) & Unsafe.As<byte, byte>(ref pFlagValue)) == Unsafe.As<byte, byte>(ref pFlagValue);
case 1:
return (Unsafe.As<byte, ushort>(ref pThisValue) & Unsafe.As<byte, ushort>(ref pFlagValue)) == Unsafe.As<byte, ushort>(ref pFlagValue);
case 2:
return (Unsafe.As<byte, uint>(ref pThisValue) & Unsafe.As<byte, uint>(ref pFlagValue)) == Unsafe.As<byte, uint>(ref pFlagValue);
case 3:
return (Unsafe.As<byte, ulong>(ref pThisValue) & Unsafe.As<byte, ulong>(ref pFlagValue)) == Unsafe.As<byte, ulong>(ref pFlagValue);
default:
Environment.FailFast("Unexpected enum underlying type");
return false;
}
}
public static bool IsDefined(Type enumType, object value)
{
if (enumType == null)
throw new ArgumentNullException(nameof(enumType));
if (!enumType.IsRuntimeImplemented())
return enumType.IsEnumDefined(value);
if (value == null)
throw new ArgumentNullException(nameof(value));
if (value is string valueAsString)
{
if (!enumType.IsEnum)
throw new ArgumentException(SR.Arg_MustBeEnum);
EnumInfo enumInfo = GetEnumInfo(enumType);
foreach (KeyValuePair<string, ulong> kv in enumInfo.NamesAndValues)
{
if (valueAsString == kv.Key)
return true;
}
return false;
}
else
{
ulong rawValue;
if (!TryGetUnboxedValueOfEnumOrInteger(value, out rawValue))
{
if (Type.IsIntegerType(value.GetType()))
throw new ArgumentException(SR.Format(SR.Arg_EnumUnderlyingTypeAndObjectMustBeSameType, value.GetType(), Enum.GetUnderlyingType(enumType)));
else
throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType);
}
EnumInfo enumInfo = null;
if (value is Enum)
{
if (!ValueTypeMatchesEnumType(enumType, value))
throw new ArgumentException(SR.Format(SR.Arg_EnumAndObjectMustBeSameType, value.GetType(), enumType));
}
else
{
if (!enumType.IsEnum)
throw new ArgumentException(SR.Arg_MustBeEnum);
enumInfo = GetEnumInfo(enumType);
if (!(enumInfo.UnderlyingType.TypeHandle.ToEETypePtr() == value.EETypePtr))
throw new ArgumentException(SR.Format(SR.Arg_EnumUnderlyingTypeAndObjectMustBeSameType, value.GetType(), enumInfo.UnderlyingType));
}
if (enumInfo == null)
{
if (!enumType.IsEnum)
throw new ArgumentException(SR.Arg_MustBeEnum);
enumInfo = GetEnumInfo(enumType);
}
string nameOrNull = GetNameIfAny(enumInfo, rawValue);
return nameOrNull != null;
}
}
public static object Parse(Type enumType, string value) =>
Parse(enumType, value, ignoreCase: false);
public static object Parse(Type enumType, string value, bool ignoreCase)
{
bool success = TryParse(enumType, value, ignoreCase, throwOnFailure: true, out object result);
Debug.Assert(success);
return result;
}
public static TEnum Parse<TEnum>(string value) where TEnum : struct =>
Parse<TEnum>(value, ignoreCase: false);
public static TEnum Parse<TEnum>(string value, bool ignoreCase) where TEnum : struct
{
bool success = TryParse<TEnum>(value, ignoreCase, throwOnFailure: true, out TEnum result);
Debug.Assert(success);
return result;
}
public static bool TryParse(Type enumType, string value, out object result) =>
TryParse(enumType, value, ignoreCase: false, out result);
public static bool TryParse(Type enumType, string value, bool ignoreCase, out object result) =>
TryParse(enumType, value, ignoreCase, throwOnFailure: false, out result);
public static bool TryParse<TEnum>(string value, out TEnum result) where TEnum : struct =>
TryParse<TEnum>(value, ignoreCase: false, out result);
public static bool TryParse<TEnum>(string value, bool ignoreCase, out TEnum result) where TEnum : struct =>
TryParse<TEnum>(value, ignoreCase, throwOnFailure: false, out result);
private static bool TryParse<TEnum>(string value, bool ignoreCase, bool throwOnFailure, out TEnum result) where TEnum : struct
{
object tempResult;
if (!TryParse(typeof(TEnum), value, ignoreCase, throwOnFailure, out tempResult))
{
result = default(TEnum);
return false;
}
result = (TEnum)tempResult;
return true;
}
public override string ToString()
{
try
{
return this.ToString("G");
}
catch (Exception)
{
return this.LastResortToString;
}
}
public string ToString(string format)
{
if (format == null || format.Length == 0)
format = "G";
EnumInfo enumInfo = GetEnumInfo(this.GetType());
// Project N port note: If Reflection info isn't available, fallback to ToString() which will substitute a numeric value for the "correct" output.
// This scenario has been hit frequently when throwing exceptions formatted with error strings containing enum substitations.
// To avoid replacing the masking the actual exception with an uninteresting MissingMetadataException, we choose instead
// to return a base-effort string.
if (enumInfo == null)
return this.LastResortToString;
return Format(enumInfo, this, format);
}
[Obsolete("The provider argument is not used. Please use ToString().")]
public string ToString(string format, IFormatProvider provider)
{
return ToString(format);
}
[Obsolete("The provider argument is not used. Please use ToString().")]
public string ToString(IFormatProvider provider)
{
return ToString();
}
private static EnumInfo GetEnumInfo(Type enumType)
{
Debug.Assert(enumType != null);
Debug.Assert(enumType.IsRuntimeImplemented());
Debug.Assert(enumType.IsEnum);
return ReflectionAugments.ReflectionCoreCallbacks.GetEnumInfo(enumType);
}
//
// Checks if value.GetType() matches enumType exactly.
//
private static bool ValueTypeMatchesEnumType(Type enumType, object value)
{
EETypePtr enumEEType;
if (!enumType.TryGetEEType(out enumEEType))
return false;
if (!(enumEEType == value.EETypePtr))
return false;
return true;
}
// Exported for use by legacy user-defined Type Enum apis.
internal static ulong ToUInt64(object value)
{
ulong result;
if (!TryGetUnboxedValueOfEnumOrInteger(value, out result))
throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType);
return result;
}
//
// Note: This works on both Enum's and underlying integer values.
//
//
// This returns the underlying enum values as "ulong" regardless of the actual underlying type. Signed integral
// types get sign-extended into the 64-bit value, unsigned types get zero-extended.
//
// The return value is "bool" if "value" is not an enum or an "integer type" as defined by the BCL Enum apis.
//
private static bool TryGetUnboxedValueOfEnumOrInteger(object value, out ulong result)
{
EETypePtr eeType = value.EETypePtr;
// For now, this check is required to flush out pointers.
if (!eeType.IsDefType)
{
result = 0;
return false;
}
CorElementType corElementType = eeType.CorElementType;
ref byte pValue = ref value.GetRawData();
switch (corElementType)
{
case CorElementType.ELEMENT_TYPE_BOOLEAN:
result = Unsafe.As<byte, bool>(ref pValue) ? 1UL : 0UL;
return true;
case CorElementType.ELEMENT_TYPE_CHAR:
result = (ulong)(long)Unsafe.As<byte, char>(ref pValue);
return true;
case CorElementType.ELEMENT_TYPE_I1:
result = (ulong)(long)Unsafe.As<byte, sbyte>(ref pValue);
return true;
case CorElementType.ELEMENT_TYPE_U1:
result = (ulong)(long)Unsafe.As<byte, byte>(ref pValue);
return true;
case CorElementType.ELEMENT_TYPE_I2:
result = (ulong)(long)Unsafe.As<byte, short>(ref pValue);
return true;
case CorElementType.ELEMENT_TYPE_U2:
result = (ulong)(long)Unsafe.As<byte, ushort>(ref pValue);
return true;
case CorElementType.ELEMENT_TYPE_I4:
result = (ulong)(long)Unsafe.As<byte, int>(ref pValue);
return true;
case CorElementType.ELEMENT_TYPE_U4:
result = (ulong)(long)Unsafe.As<byte, uint>(ref pValue);
return true;
case CorElementType.ELEMENT_TYPE_I8:
result = (ulong)(long)Unsafe.As<byte, long>(ref pValue);
return true;
case CorElementType.ELEMENT_TYPE_U8:
result = (ulong)(long)Unsafe.As<byte, ulong>(ref pValue);
return true;
default:
result = 0;
return false;
}
}
//
// Look up a name for rawValue if a matching one exists. Returns null if no matching name exists.
//
private static string GetNameIfAny(EnumInfo enumInfo, ulong rawValue)
{
KeyValuePair<string, ulong>[] namesAndValues = enumInfo.NamesAndValues;
KeyValuePair<string, ulong> searchKey = new KeyValuePair<string, ulong>(null, rawValue);
int index = Array.BinarySearch<KeyValuePair<String, ulong>>(namesAndValues, searchKey, s_nameAndValueComparer);
if (index < 0)
return null;
return namesAndValues[index].Key;
}
//
// Common funnel for Enum.Parse methods.
//
private static bool TryParse(Type enumType, string value, bool ignoreCase, bool throwOnFailure, out object result)
{
result = null;
if (enumType == null)
throw new ArgumentNullException(nameof(enumType));
if (!enumType.IsRuntimeImplemented())
throw new ArgumentException(SR.Arg_MustBeType, nameof(enumType));
if (!enumType.IsEnum)
throw new ArgumentException(SR.Arg_MustBeEnum, nameof(enumType));
if (value == null)
{
if (throwOnFailure)
throw new ArgumentNullException(nameof(value));
return false;
}
int firstNonWhitespaceIndex = -1;
for (int i = 0; i < value.Length; i++)
{
if (!char.IsWhiteSpace(value[i]))
{
firstNonWhitespaceIndex = i;
break;
}
}
if (firstNonWhitespaceIndex == -1)
{
if (throwOnFailure)
throw new ArgumentException(SR.Arg_MustContainEnumInfo);
return false;
}
// Check for the unfortunate "typeof(Outer<>).InnerEnum" corner case.
if (enumType.ContainsGenericParameters)
throw new InvalidOperationException(SR.Format(SR.Arg_OpenType, enumType.ToString()));
EETypePtr enumEEType = enumType.TypeHandle.ToEETypePtr();
if (TryParseAsInteger(enumEEType, value, firstNonWhitespaceIndex, out result))
return true;
if (StillLooksLikeInteger(value, firstNonWhitespaceIndex))
{
if (throwOnFailure)
throw new OverflowException();
return false;
}
// Parse as string. Now (and only now) do we look for metadata information.
EnumInfo enumInfo = GetEnumInfo(enumType);
ulong v = 0;
// Port note: The docs are silent on how multiple matches are resolved when doing case-insensitive parses.
// The desktop's ad-hoc behavior is to pick the one with the smallest value after doing a value-preserving cast
// to a ulong, so we'll follow that here.
StringComparison comparison = ignoreCase ?
StringComparison.OrdinalIgnoreCase :
StringComparison.Ordinal;
KeyValuePair<string, ulong>[] actualNamesAndValues = enumInfo.NamesAndValues;
int valueIndex = firstNonWhitespaceIndex;
while (valueIndex <= value.Length) // '=' is to handle invalid case of an ending comma
{
// Find the next separator, if there is one, otherwise the end of the string.
int endIndex = value.IndexOf(',', valueIndex);
if (endIndex == -1)
{
endIndex = value.Length;
}
// Shift the starting and ending indices to eliminate whitespace
int endIndexNoWhitespace = endIndex;
while (valueIndex < endIndex && char.IsWhiteSpace(value[valueIndex])) valueIndex++;
while (endIndexNoWhitespace > valueIndex && char.IsWhiteSpace(value[endIndexNoWhitespace - 1])) endIndexNoWhitespace--;
int valueSubstringLength = endIndexNoWhitespace - valueIndex;
// Try to match this substring against each enum name
bool foundMatch = false;
foreach (KeyValuePair<string, ulong> kv in actualNamesAndValues)
{
string actualName = kv.Key;
if (actualName.Length == valueSubstringLength &&
string.Compare(actualName, 0, value, valueIndex, valueSubstringLength, comparison) == 0)
{
v |= kv.Value;
foundMatch = true;
break;
}
}
if (!foundMatch)
{
if (throwOnFailure)
throw new ArgumentException(SR.Format(SR.Arg_EnumValueNotFound, value));
return false;
}
// Move our pointer to the ending index to go again.
valueIndex = endIndex + 1;
}
unsafe
{
result = RuntimeImports.RhBox(enumEEType, &v); //@todo: Not compatible with big-endian platforms.
}
return true;
}
private static bool TryParseAsInteger(EETypePtr enumEEType, string value, int valueOffset, out object result)
{
Debug.Assert(value != null, "Expected non-null value");
Debug.Assert(value.Length > 0, "Expected non-empty value");
Debug.Assert(valueOffset >= 0 && valueOffset < value.Length, "Expected valueOffset to be within value");
result = null;
char firstNonWhitespaceChar = value[valueOffset];
if (!(char.IsDigit(firstNonWhitespaceChar) || firstNonWhitespaceChar == '+' || firstNonWhitespaceChar == '-'))
return false;
CorElementType corElementType = enumEEType.CorElementType;
value = value.Trim();
unsafe
{
switch (corElementType)
{
case CorElementType.ELEMENT_TYPE_BOOLEAN:
{
bool v;
if (!bool.TryParse(value, out v))
return false;
result = RuntimeImports.RhBox(enumEEType, &v);
return true;
}
case CorElementType.ELEMENT_TYPE_CHAR:
{
char v;
if (!char.TryParse(value, out v))
return false;
result = RuntimeImports.RhBox(enumEEType, &v);
return true;
}
case CorElementType.ELEMENT_TYPE_I1:
{
sbyte v;
if (!sbyte.TryParse(value, out v))
return false;
result = RuntimeImports.RhBox(enumEEType, &v);
return true;
}
case CorElementType.ELEMENT_TYPE_U1:
{
byte v;
if (!byte.TryParse(value, out v))
return false;
result = RuntimeImports.RhBox(enumEEType, &v);
return true;
}
case CorElementType.ELEMENT_TYPE_I2:
{
short v;
if (!short.TryParse(value, out v))
return false;
result = RuntimeImports.RhBox(enumEEType, &v);
return true;
}
case CorElementType.ELEMENT_TYPE_U2:
{
ushort v;
if (!ushort.TryParse(value, out v))
return false;
result = RuntimeImports.RhBox(enumEEType, &v);
return true;
}
case CorElementType.ELEMENT_TYPE_I4:
{
int v;
if (!int.TryParse(value, out v))
return false;
result = RuntimeImports.RhBox(enumEEType, &v);
return true;
}
case CorElementType.ELEMENT_TYPE_U4:
{
uint v;
if (!uint.TryParse(value, out v))
return false;
result = RuntimeImports.RhBox(enumEEType, &v);
return true;
}
case CorElementType.ELEMENT_TYPE_I8:
{
long v;
if (!long.TryParse(value, out v))
return false;
result = RuntimeImports.RhBox(enumEEType, &v);
return true;
}
case CorElementType.ELEMENT_TYPE_U8:
{
ulong v;
if (!ulong.TryParse(value, out v))
return false;
result = RuntimeImports.RhBox(enumEEType, &v);
return true;
}
default:
throw new NotSupportedException();
}
}
}
private static bool StillLooksLikeInteger(string value, int index)
{
if (index != value.Length && (value[index] == '-' || value[index] == '+'))
{
index++;
}
if (index == value.Length || !char.IsDigit(value[index]))
return false;
index++;
while (index != value.Length && char.IsDigit(value[index]))
{
index++;
}
while (index != value.Length && char.IsWhiteSpace(value[index]))
{
index++;
}
return index == value.Length;
}
[Conditional("BIGENDIAN")]
private static unsafe void AdjustForEndianness(ref byte* pValue, EETypePtr enumEEType)
{
// On Debug builds, include the big-endian code to help deter bitrot (the "Conditional("BIGENDIAN")" will prevent it from executing on little-endian).
// On Release builds, exclude code to deter IL bloat and toolchain work.
#if BIGENDIAN || DEBUG
CorElementType corElementType = enumEEType.CorElementType;
switch (corElementType)
{
case CorElementType.ELEMENT_TYPE_I1:
case CorElementType.ELEMENT_TYPE_U1:
pValue += sizeof(long) - sizeof(byte);
break;
case CorElementType.ELEMENT_TYPE_I2:
case CorElementType.ELEMENT_TYPE_U2:
pValue += sizeof(long) - sizeof(short);
break;
case CorElementType.ELEMENT_TYPE_I4:
case CorElementType.ELEMENT_TYPE_U4:
pValue += sizeof(long) - sizeof(int);
break;
case CorElementType.ELEMENT_TYPE_I8:
case CorElementType.ELEMENT_TYPE_U8:
break;
default:
throw new NotSupportedException();
}
#endif //BIGENDIAN || DEBUG
}
//
// Sort comparer for NamesAndValues
//
private class NamesAndValueComparer : IComparer<KeyValuePair<string, ulong>>
{
public int Compare(KeyValuePair<string, ulong> kv1, KeyValuePair<string, ulong> kv2)
{
ulong x = kv1.Value;
ulong y = kv2.Value;
if (x < y)
return -1;
else if (x > y)
return 1;
else
return 0;
}
}
private static NamesAndValueComparer s_nameAndValueComparer = new NamesAndValueComparer();
private string LastResortToString
{
get
{
return string.Format("{0}", GetValue());
}
}
#region IConvertible
public TypeCode GetTypeCode()
{
CorElementType corElementType = this.EETypePtr.CorElementType;
switch (corElementType)
{
case CorElementType.ELEMENT_TYPE_I1:
return TypeCode.SByte;
case CorElementType.ELEMENT_TYPE_U1:
return TypeCode.Byte;
case CorElementType.ELEMENT_TYPE_BOOLEAN:
return TypeCode.Boolean;
case CorElementType.ELEMENT_TYPE_I2:
return TypeCode.Int16;
case CorElementType.ELEMENT_TYPE_U2:
return TypeCode.UInt16;
case CorElementType.ELEMENT_TYPE_CHAR:
return TypeCode.Char;
case CorElementType.ELEMENT_TYPE_I4:
return TypeCode.Int32;
case CorElementType.ELEMENT_TYPE_U4:
return TypeCode.UInt32;
case CorElementType.ELEMENT_TYPE_I8:
return TypeCode.Int64;
case CorElementType.ELEMENT_TYPE_U8:
return TypeCode.UInt64;
default:
Debug.Fail("Unknown underlying type.");
throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType);
}
}
bool IConvertible.ToBoolean(IFormatProvider provider)
{
return Convert.ToBoolean(GetValue(), CultureInfo.CurrentCulture);
}
char IConvertible.ToChar(IFormatProvider provider)
{
return Convert.ToChar(GetValue(), CultureInfo.CurrentCulture);
}
sbyte IConvertible.ToSByte(IFormatProvider provider)
{
return Convert.ToSByte(GetValue(), CultureInfo.CurrentCulture);
}
byte IConvertible.ToByte(IFormatProvider provider)
{
return Convert.ToByte(GetValue(), CultureInfo.CurrentCulture);
}
short IConvertible.ToInt16(IFormatProvider provider)
{
return Convert.ToInt16(GetValue(), CultureInfo.CurrentCulture);
}
ushort IConvertible.ToUInt16(IFormatProvider provider)
{
return Convert.ToUInt16(GetValue(), CultureInfo.CurrentCulture);
}
int IConvertible.ToInt32(IFormatProvider provider)
{
return Convert.ToInt32(GetValue(), CultureInfo.CurrentCulture);
}
uint IConvertible.ToUInt32(IFormatProvider provider)
{
return Convert.ToUInt32(GetValue(), CultureInfo.CurrentCulture);
}
long IConvertible.ToInt64(IFormatProvider provider)
{
return Convert.ToInt64(GetValue(), CultureInfo.CurrentCulture);
}
ulong IConvertible.ToUInt64(IFormatProvider provider)
{
return Convert.ToUInt64(GetValue(), CultureInfo.CurrentCulture);
}
float IConvertible.ToSingle(IFormatProvider provider)
{
return Convert.ToSingle(GetValue(), CultureInfo.CurrentCulture);
}
double IConvertible.ToDouble(IFormatProvider provider)
{
return Convert.ToDouble(GetValue(), CultureInfo.CurrentCulture);
}
decimal IConvertible.ToDecimal(IFormatProvider provider)
{
return Convert.ToDecimal(GetValue(), CultureInfo.CurrentCulture);
}
DateTime IConvertible.ToDateTime(IFormatProvider provider)
{
throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Enum", "DateTime"));
}
object IConvertible.ToType(Type type, IFormatProvider provider)
{
return Convert.DefaultToType((IConvertible)this, type, provider);
}
#endregion
#region ToObject
public static object ToObject(Type enumType, object value)
{
if (value == null)
throw new ArgumentNullException(nameof(value));
// Delegate rest of error checking to the other functions
switch (Convert.GetTypeCode(value))
{
case TypeCode.Int32:
return ToObject(enumType, (int)value);
case TypeCode.SByte:
return ToObject(enumType, (sbyte)value);
case TypeCode.Int16:
return ToObject(enumType, (short)value);
case TypeCode.Int64:
return ToObject(enumType, (long)value);
case TypeCode.UInt32:
return ToObject(enumType, (uint)value);
case TypeCode.Byte:
return ToObject(enumType, (byte)value);
case TypeCode.UInt16:
return ToObject(enumType, (ushort)value);
case TypeCode.UInt64:
return ToObject(enumType, (ulong)value);
case TypeCode.Char:
return ToObject(enumType, (char)value);
case TypeCode.Boolean:
return ToObject(enumType, (bool)value);
default:
throw new ArgumentException(SR.Arg_MustBeEnumBaseTypeOrEnum, nameof(value));
}
}
//
// Non-boxing overloads for Enum.ToObject().
//
// The underlying integer type of the enum does not have to match the type of "value." If
// the enum type is larger, this api does a value-preserving widening if possible (or a 2's complement
// conversion if not.) If the enum type is smaller, the api discards the higher order bits.
// Either way, no exception is thrown upon overflow.
//
[CLSCompliant(false)]
public static object ToObject(Type enumType, sbyte value) => ToObjectWorker(enumType, value);
public static object ToObject(Type enumType, byte value) => ToObjectWorker(enumType, value);
[CLSCompliant(false)]
public static object ToObject(Type enumType, ushort value) => ToObjectWorker(enumType, value);
public static object ToObject(Type enumType, short value) => ToObjectWorker(enumType, value);
[CLSCompliant(false)]
public static object ToObject(Type enumType, uint value) => ToObjectWorker(enumType, value);
public static object ToObject(Type enumType, int value) => ToObjectWorker(enumType, value);
[CLSCompliant(false)]
public static object ToObject(Type enumType, ulong value) => ToObjectWorker(enumType, (long)value);
public static object ToObject(Type enumType, long value) => ToObjectWorker(enumType, value);
// These are needed to service ToObject(Type, Object).
private static object ToObject(Type enumType, char value) => ToObjectWorker(enumType, value);
private static object ToObject(Type enumType, bool value) => ToObjectWorker(enumType, value ? 1 : 0);
// Common helper for the non-boxing Enum.ToObject() overloads.
private static object ToObjectWorker(Type enumType, long value)
{
if (enumType == null)
throw new ArgumentNullException(nameof(enumType));
if (!enumType.IsEnum)
throw new ArgumentException(SR.Arg_MustBeEnum, nameof(enumType));
if (!enumType.IsRuntimeImplemented())
throw new ArgumentException(SR.Arg_MustBeType, nameof(enumType));
// Check for the unfortunate "typeof(Outer<>).InnerEnum" corner case.
if (enumType.ContainsGenericParameters)
throw new InvalidOperationException(SR.Format(SR.Arg_OpenType, enumType.ToString()));
EETypePtr enumEEType = enumType.TypeHandle.ToEETypePtr();
return ToObject(enumEEType, value);
}
internal unsafe static object ToObject(EETypePtr enumEEType, long value)
{
Debug.Assert(enumEEType.IsEnum);
byte* pValue = (byte*)&value;
AdjustForEndianness(ref pValue, enumEEType);
return RuntimeImports.RhBox(enumEEType, pValue);
}
#endregion
}
}
| |
//
// modifiers.cs: Modifiers handling
//
// Authors: Miguel de Icaza (miguel@gnu.org)
// Marek Safar (marek.safar@gmail.com)
//
// Dual licensed under the terms of the MIT X11 or GNU GPL
//
// Copyright 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
// Copyright 2004-2010 Novell, Inc
//
using System;
#if STATIC
using IKVM.Reflection;
#else
using System.Reflection;
#endif
namespace Mono.CSharp
{
[Flags]
public enum Modifiers
{
PROTECTED = 0x0001,
PUBLIC = 0x0002,
PRIVATE = 0x0004,
INTERNAL = 0x0008,
NEW = 0x0010,
ABSTRACT = 0x0020,
SEALED = 0x0040,
STATIC = 0x0080,
READONLY = 0x0100,
VIRTUAL = 0x0200,
OVERRIDE = 0x0400,
EXTERN = 0x0800,
VOLATILE = 0x1000,
UNSAFE = 0x2000,
TOP = 0x4000,
//
// Compiler specific flags
//
PROPERTY_CUSTOM = 0x4000,
ASYNC = 0x10000,
PARTIAL = 0x20000,
DEFAULT_ACCESS_MODIFER = 0x40000,
METHOD_EXTENSION = 0x80000,
COMPILER_GENERATED = 0x100000,
BACKING_FIELD = 0x200000,
DEBUGGER_HIDDEN = 0x400000,
AccessibilityMask = PUBLIC | PROTECTED | INTERNAL | PRIVATE,
AllowedExplicitImplFlags = UNSAFE | EXTERN,
}
static class ModifiersExtensions
{
public static string AccessibilityName (Modifiers mod)
{
switch (mod & Modifiers.AccessibilityMask) {
case Modifiers.PUBLIC:
return "public";
case Modifiers.PROTECTED:
return "protected";
case Modifiers.PROTECTED | Modifiers.INTERNAL:
return "protected internal";
case Modifiers.INTERNAL:
return "internal";
case Modifiers.PRIVATE:
return "private";
default:
throw new NotImplementedException (mod.ToString ());
}
}
static public string Name (Modifiers i)
{
string s = "";
switch (i) {
case Modifiers.NEW:
s = "new"; break;
case Modifiers.PUBLIC:
s = "public"; break;
case Modifiers.PROTECTED:
s = "protected"; break;
case Modifiers.INTERNAL:
s = "internal"; break;
case Modifiers.PRIVATE:
s = "private"; break;
case Modifiers.ABSTRACT:
s = "abstract"; break;
case Modifiers.SEALED:
s = "sealed"; break;
case Modifiers.STATIC:
s = "static"; break;
case Modifiers.READONLY:
s = "readonly"; break;
case Modifiers.VIRTUAL:
s = "virtual"; break;
case Modifiers.OVERRIDE:
s = "override"; break;
case Modifiers.EXTERN:
s = "extern"; break;
case Modifiers.VOLATILE:
s = "volatile"; break;
case Modifiers.UNSAFE:
s = "unsafe"; break;
}
return s;
}
//
// Used by custom property accessors to check whether @modA is more restrictive than @modB
//
public static bool IsRestrictedModifier (Modifiers modA, Modifiers modB)
{
Modifiers flags = 0;
if ((modB & Modifiers.PUBLIC) != 0) {
flags = Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE;
} else if ((modB & Modifiers.PROTECTED) != 0) {
if ((modB & Modifiers.INTERNAL) != 0)
flags = Modifiers.PROTECTED | Modifiers.INTERNAL;
flags |= Modifiers.PRIVATE;
} else if ((modB & Modifiers.INTERNAL) != 0)
flags = Modifiers.PRIVATE;
return modB != modA && (modA & (~flags)) == 0;
}
public static TypeAttributes TypeAttr (Modifiers mod_flags, bool is_toplevel)
{
TypeAttributes t = 0;
if (is_toplevel){
if ((mod_flags & Modifiers.PUBLIC) != 0)
t = TypeAttributes.Public;
else if ((mod_flags & Modifiers.PRIVATE) != 0)
t = TypeAttributes.NotPublic;
} else {
if ((mod_flags & Modifiers.PUBLIC) != 0)
t = TypeAttributes.NestedPublic;
else if ((mod_flags & Modifiers.PRIVATE) != 0)
t = TypeAttributes.NestedPrivate;
else if ((mod_flags & (Modifiers.PROTECTED | Modifiers.INTERNAL)) == (Modifiers.PROTECTED | Modifiers.INTERNAL))
t = TypeAttributes.NestedFamORAssem;
else if ((mod_flags & Modifiers.PROTECTED) != 0)
t = TypeAttributes.NestedFamily;
else if ((mod_flags & Modifiers.INTERNAL) != 0)
t = TypeAttributes.NestedAssembly;
}
if ((mod_flags & Modifiers.SEALED) != 0)
t |= TypeAttributes.Sealed;
if ((mod_flags & Modifiers.ABSTRACT) != 0)
t |= TypeAttributes.Abstract;
return t;
}
public static FieldAttributes FieldAttr (Modifiers mod_flags)
{
FieldAttributes fa = 0;
if ((mod_flags & Modifiers.PUBLIC) != 0)
fa |= FieldAttributes.Public;
if ((mod_flags & Modifiers.PRIVATE) != 0)
fa |= FieldAttributes.Private;
if ((mod_flags & Modifiers.PROTECTED) != 0) {
if ((mod_flags & Modifiers.INTERNAL) != 0)
fa |= FieldAttributes.FamORAssem;
else
fa |= FieldAttributes.Family;
} else {
if ((mod_flags & Modifiers.INTERNAL) != 0)
fa |= FieldAttributes.Assembly;
}
if ((mod_flags & Modifiers.STATIC) != 0)
fa |= FieldAttributes.Static;
if ((mod_flags & Modifiers.READONLY) != 0)
fa |= FieldAttributes.InitOnly;
return fa;
}
public static MethodAttributes MethodAttr (Modifiers mod_flags)
{
MethodAttributes ma = MethodAttributes.HideBySig;
switch (mod_flags & Modifiers.AccessibilityMask) {
case Modifiers.PUBLIC:
ma |= MethodAttributes.Public;
break;
case Modifiers.PRIVATE:
ma |= MethodAttributes.Private;
break;
case Modifiers.PROTECTED | Modifiers.INTERNAL:
ma |= MethodAttributes.FamORAssem;
break;
case Modifiers.PROTECTED:
ma |= MethodAttributes.Family;
break;
case Modifiers.INTERNAL:
ma |= MethodAttributes.Assembly;
break;
default:
throw new NotImplementedException (mod_flags.ToString ());
}
if ((mod_flags & Modifiers.STATIC) != 0)
ma |= MethodAttributes.Static;
if ((mod_flags & Modifiers.ABSTRACT) != 0) {
ma |= MethodAttributes.Abstract | MethodAttributes.Virtual;
}
if ((mod_flags & Modifiers.SEALED) != 0)
ma |= MethodAttributes.Final;
if ((mod_flags & Modifiers.VIRTUAL) != 0)
ma |= MethodAttributes.Virtual;
if ((mod_flags & Modifiers.OVERRIDE) != 0) {
ma |= MethodAttributes.Virtual;
} else {
if ((ma & MethodAttributes.Virtual) != 0)
ma |= MethodAttributes.NewSlot;
}
return ma;
}
// <summary>
// Checks the object @mod modifiers to be in @allowed.
// Returns the new mask. Side effect: reports any
// incorrect attributes.
// </summary>
public static Modifiers Check (Modifiers allowed, Modifiers mod, Modifiers def_access, Location l, Report Report)
{
int invalid_flags = (~(int) allowed) & ((int) mod & ((int) Modifiers.TOP - 1));
int i;
if (invalid_flags == 0){
//
// If no accessibility bits provided
// then provide the defaults.
//
if ((mod & Modifiers.AccessibilityMask) == 0) {
mod |= def_access;
if (def_access != 0)
mod |= Modifiers.DEFAULT_ACCESS_MODIFER;
return mod;
}
return mod;
}
for (i = 1; i <= (int) Modifiers.TOP; i <<= 1) {
if ((i & invalid_flags) == 0)
continue;
Error_InvalidModifier ((Modifiers)i, l, Report);
}
return allowed & mod;
}
static void Error_InvalidModifier (Modifiers mod, Location l, Report Report)
{
Report.Error (106, l, "The modifier `{0}' is not valid for this item",
Name (mod));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
namespace EncompassRest.Loans
{
/// <summary>
/// PreliminaryConditionLog
/// </summary>
public sealed partial class PreliminaryConditionLog : DirtyExtensibleObject, IIdentifiable
{
private DirtyValue<string?>? _addedBy;
private DirtyList<LogAlert>? _alerts;
private DirtyValue<string?>? _alertsXml;
private DirtyValue<string?>? _category;
private DirtyList<LogComment>? _commentList;
private DirtyValue<string?>? _commentListXml;
private DirtyValue<string?>? _comments;
private DirtyValue<DateTime?>? _dateAddedUtc;
private DirtyValue<DateTime?>? _dateExpected;
private DirtyValue<DateTime?>? _dateFulfilled;
private DirtyValue<DateTime?>? _dateReceived;
private DirtyValue<DateTime?>? _dateRequestedUtc;
private DirtyValue<DateTime?>? _dateRerequestedUtc;
private DirtyValue<DateTime?>? _dateUtc;
private DirtyValue<string?>? _description;
private DirtyValue<string?>? _details;
private DirtyValue<bool?>? _expected;
private DirtyValue<bool?>? _fileAttachmentsMigrated;
private DirtyValue<bool?>? _fulfilled;
private DirtyValue<string?>? _fulfilledBy;
private DirtyValue<string?>? _guid;
private DirtyValue<string?>? _id;
private DirtyValue<bool?>? _isMarkedRemoved;
private DirtyValue<bool?>? _isPastDue;
private DirtyValue<bool?>? _isSystemSpecificIndicator;
private DirtyValue<int?>? _logRecordIndex;
private DirtyValue<string?>? _pairId;
private DirtyValue<string?>? _priorTo;
private DirtyValue<bool?>? _received;
private DirtyValue<string?>? _receivedBy;
private DirtyValue<bool?>? _requested;
private DirtyValue<string?>? _requestedBy;
private DirtyValue<bool?>? _rerequested;
private DirtyValue<string?>? _rerequestedBy;
private DirtyValue<string?>? _source;
private DirtyValue<string?>? _status;
private DirtyValue<string?>? _statusDescription;
private DirtyValue<string?>? _systemId;
private DirtyValue<string?>? _title;
private DirtyValue<bool?>? _underwriterAccessIndicator;
private DirtyValue<DateTime?>? _updatedDateUtc;
/// <summary>
/// PreliminaryConditionLog AddedBy
/// </summary>
public string? AddedBy { get => _addedBy; set => SetField(ref _addedBy, value); }
/// <summary>
/// PreliminaryConditionLog Alerts
/// </summary>
[AllowNull]
public IList<LogAlert> Alerts { get => GetField(ref _alerts); set => SetField(ref _alerts, value); }
/// <summary>
/// PreliminaryConditionLog AlertsXml
/// </summary>
public string? AlertsXml { get => _alertsXml; set => SetField(ref _alertsXml, value); }
/// <summary>
/// PreliminaryConditionLog Category
/// </summary>
public string? Category { get => _category; set => SetField(ref _category, value); }
/// <summary>
/// PreliminaryConditionLog CommentList
/// </summary>
[AllowNull]
public IList<LogComment> CommentList { get => GetField(ref _commentList); set => SetField(ref _commentList, value); }
/// <summary>
/// PreliminaryConditionLog CommentListXml
/// </summary>
public string? CommentListXml { get => _commentListXml; set => SetField(ref _commentListXml, value); }
/// <summary>
/// PreliminaryConditionLog Comments
/// </summary>
public string? Comments { get => _comments; set => SetField(ref _comments, value); }
/// <summary>
/// PreliminaryConditionLog DateAddedUtc
/// </summary>
public DateTime? DateAddedUtc { get => _dateAddedUtc; set => SetField(ref _dateAddedUtc, value); }
/// <summary>
/// PreliminaryConditionLog DateExpected
/// </summary>
public DateTime? DateExpected { get => _dateExpected; set => SetField(ref _dateExpected, value); }
/// <summary>
/// PreliminaryConditionLog DateFulfilled
/// </summary>
public DateTime? DateFulfilled { get => _dateFulfilled; set => SetField(ref _dateFulfilled, value); }
/// <summary>
/// PreliminaryConditionLog DateReceived
/// </summary>
public DateTime? DateReceived { get => _dateReceived; set => SetField(ref _dateReceived, value); }
/// <summary>
/// PreliminaryConditionLog DateRequestedUtc
/// </summary>
public DateTime? DateRequestedUtc { get => _dateRequestedUtc; set => SetField(ref _dateRequestedUtc, value); }
/// <summary>
/// PreliminaryConditionLog DateRerequestedUtc
/// </summary>
public DateTime? DateRerequestedUtc { get => _dateRerequestedUtc; set => SetField(ref _dateRerequestedUtc, value); }
/// <summary>
/// PreliminaryConditionLog DateUtc
/// </summary>
public DateTime? DateUtc { get => _dateUtc; set => SetField(ref _dateUtc, value); }
/// <summary>
/// PreliminaryConditionLog Description
/// </summary>
public string? Description { get => _description; set => SetField(ref _description, value); }
/// <summary>
/// PreliminaryConditionLog Details
/// </summary>
public string? Details { get => _details; set => SetField(ref _details, value); }
/// <summary>
/// PreliminaryConditionLog Expected
/// </summary>
public bool? Expected { get => _expected; set => SetField(ref _expected, value); }
/// <summary>
/// PreliminaryConditionLog FileAttachmentsMigrated
/// </summary>
public bool? FileAttachmentsMigrated { get => _fileAttachmentsMigrated; set => SetField(ref _fileAttachmentsMigrated, value); }
/// <summary>
/// PreliminaryConditionLog Fulfilled
/// </summary>
public bool? Fulfilled { get => _fulfilled; set => SetField(ref _fulfilled, value); }
/// <summary>
/// PreliminaryConditionLog FulfilledBy
/// </summary>
public string? FulfilledBy { get => _fulfilledBy; set => SetField(ref _fulfilledBy, value); }
/// <summary>
/// PreliminaryConditionLog Guid
/// </summary>
public string? Guid { get => _guid; set => SetField(ref _guid, value); }
/// <summary>
/// PreliminaryConditionLog Id
/// </summary>
public string? Id { get => _id; set => SetField(ref _id, value); }
/// <summary>
/// PreliminaryConditionLog IsMarkedRemoved
/// </summary>
public bool? IsMarkedRemoved { get => _isMarkedRemoved; set => SetField(ref _isMarkedRemoved, value); }
/// <summary>
/// PreliminaryConditionLog IsPastDue
/// </summary>
public bool? IsPastDue { get => _isPastDue; set => SetField(ref _isPastDue, value); }
/// <summary>
/// PreliminaryConditionLog IsSystemSpecificIndicator
/// </summary>
public bool? IsSystemSpecificIndicator { get => _isSystemSpecificIndicator; set => SetField(ref _isSystemSpecificIndicator, value); }
/// <summary>
/// PreliminaryConditionLog LogRecordIndex
/// </summary>
public int? LogRecordIndex { get => _logRecordIndex; set => SetField(ref _logRecordIndex, value); }
/// <summary>
/// PreliminaryConditionLog PairId
/// </summary>
public string? PairId { get => _pairId; set => SetField(ref _pairId, value); }
/// <summary>
/// PreliminaryConditionLog PriorTo
/// </summary>
public string? PriorTo { get => _priorTo; set => SetField(ref _priorTo, value); }
/// <summary>
/// PreliminaryConditionLog Received
/// </summary>
public bool? Received { get => _received; set => SetField(ref _received, value); }
/// <summary>
/// PreliminaryConditionLog ReceivedBy
/// </summary>
public string? ReceivedBy { get => _receivedBy; set => SetField(ref _receivedBy, value); }
/// <summary>
/// PreliminaryConditionLog Requested
/// </summary>
public bool? Requested { get => _requested; set => SetField(ref _requested, value); }
/// <summary>
/// PreliminaryConditionLog RequestedBy
/// </summary>
public string? RequestedBy { get => _requestedBy; set => SetField(ref _requestedBy, value); }
/// <summary>
/// PreliminaryConditionLog Rerequested
/// </summary>
public bool? Rerequested { get => _rerequested; set => SetField(ref _rerequested, value); }
/// <summary>
/// PreliminaryConditionLog RerequestedBy
/// </summary>
public string? RerequestedBy { get => _rerequestedBy; set => SetField(ref _rerequestedBy, value); }
/// <summary>
/// PreliminaryConditionLog Source
/// </summary>
public string? Source { get => _source; set => SetField(ref _source, value); }
/// <summary>
/// PreliminaryConditionLog Status
/// </summary>
public string? Status { get => _status; set => SetField(ref _status, value); }
/// <summary>
/// PreliminaryConditionLog StatusDescription
/// </summary>
public string? StatusDescription { get => _statusDescription; set => SetField(ref _statusDescription, value); }
/// <summary>
/// PreliminaryConditionLog SystemId
/// </summary>
public string? SystemId { get => _systemId; set => SetField(ref _systemId, value); }
/// <summary>
/// PreliminaryConditionLog Title
/// </summary>
public string? Title { get => _title; set => SetField(ref _title, value); }
/// <summary>
/// PreliminaryConditionLog UnderwriterAccessIndicator
/// </summary>
public bool? UnderwriterAccessIndicator { get => _underwriterAccessIndicator; set => SetField(ref _underwriterAccessIndicator, value); }
/// <summary>
/// PreliminaryConditionLog UpdatedDateUtc
/// </summary>
public DateTime? UpdatedDateUtc { get => _updatedDateUtc; set => SetField(ref _updatedDateUtc, value); }
}
}
| |
// Copyright 2017 Esri.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific
// language governing permissions and limitations under the License.
using Esri.ArcGISRuntime.Data;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using Windows.UI.Popups;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Data;
namespace ArcGISRuntime.WinUI.Samples.StatsQueryGroupAndSort
{
[ArcGISRuntime.Samples.Shared.Attributes.Sample(
name: "Statistical query group and sort",
category: "Data",
description: "Query a feature table for statistics, grouping and sorting by different fields.",
instructions: "The sample will start with some default options selected. You can immediately click the \"Get Statistics\" button to see the results for these options. There are several ways to customize your queries:",
tags: new[] { "correlation", "data", "fields", "filter", "group", "sort", "statistics", "table" })]
public partial class StatsQueryGroupAndSort
{
// URI for the US states map service
private Uri _usStatesServiceUri = new Uri("https://services.arcgis.com/jIL9msH9OI208GCb/arcgis/rest/services/Counties_Obesity_Inactivity_Diabetes_2013/FeatureServer/0");
// US states feature table
private FeatureTable _usStatesTable;
// Collection of (user-defined) statistics to use in the query
private ObservableCollection<StatisticDefinition> _statDefinitions = new ObservableCollection<StatisticDefinition>();
// Selected fields for grouping results
private List<string> _groupByFields = new List<string>();
// Collection to hold fields to order results by
private ObservableCollection<OrderFieldOption> _orderByFields = new ObservableCollection<OrderFieldOption>();
public StatsQueryGroupAndSort()
{
InitializeComponent();
// Initialize the US states feature table and populate UI controls
Initialize();
}
private async void Initialize()
{
// Create the US states feature table
_usStatesTable = new ServiceFeatureTable(_usStatesServiceUri);
try
{
// Load the table
await _usStatesTable.LoadAsync();
// Fill the fields combo and "group by" list with fields from the table
FieldsComboBox.ItemsSource = _usStatesTable.Fields;
GroupFieldsListBox.ItemsSource = _usStatesTable.Fields;
// Set the (initially empty) collection of fields as the "order by" fields list data source
OrderByFieldsListBox.ItemsSource = _orderByFields;
// Fill the statistics type combo with values from the StatisticType enum
StatTypeComboBox.ItemsSource = Enum.GetValues(typeof(StatisticType)).OfType<StatisticType>().Select(e => e.ToString());
// Set the (initially empty) collection of statistic definitions as the statistics list box data source
StatFieldsListBox.ItemsSource = _statDefinitions;
}
catch (Exception e)
{
await new MessageDialog2(e.ToString(), "Error").ShowAsync();
}
}
// Execute a statistical query using the parameters defined by the user and display the results
private async void OnExecuteStatisticsQueryClicked(object sender, RoutedEventArgs e)
{
// Verify that there is at least one statistic definition
if (_statDefinitions.Count == 0)
{
ShowMessage("Please define at least one statistic for the query.", "Statistical Query");
return;
}
// Create the statistics query parameters, pass in the list of statistic definitions
StatisticsQueryParameters statQueryParams = new StatisticsQueryParameters(_statDefinitions);
// Specify the group fields (if any)
foreach (string groupField in _groupByFields)
{
statQueryParams.GroupByFieldNames.Add(groupField);
}
// Specify the fields to order by (if any)
foreach (OrderFieldOption orderBy in _orderByFields)
{
statQueryParams.OrderByFields.Add(orderBy.OrderInfo);
}
// Ignore counties with missing data
statQueryParams.WhereClause = "\"State\" IS NOT NULL";
try
{
// Execute the statistical query with these parameters and await the results
StatisticsQueryResult statQueryResult = await _usStatesTable.QueryStatisticsAsync(statQueryParams);
// Format the output for display of grouped results in the list view
IEnumerable<IGrouping<string,IReadOnlyDictionary<string,object>>> groupedResults = statQueryResult.GroupBy(r => string.Join(", ", r.Group.Values), r => r.Statistics);
// Apply the results to the list view data source
GroupedResultData.Source = groupedResults;
}
catch (Exception ex)
{
await new MessageDialog2(ex.Message, "Error").ShowAsync();
}
}
// Helper function to show a message
private async void ShowMessage(string message, string title)
{
var messageDialog = new MessageDialog2(message, title);
await messageDialog.ShowAsync();
}
// Handle when the check box for a "group by" field is checked on or off by adding or removing the field from the collection
private void GroupFieldCheckChanged(object sender, RoutedEventArgs e)
{
// Get the check box that raised the event (group field)
CheckBox groupFieldCheckBox = (CheckBox)sender;
// Get the field name
string fieldName = groupFieldCheckBox.Content.ToString();
// See if the field is being added or removed from the "group by" list
bool fieldAdded = groupFieldCheckBox.IsChecked == true;
// See if the field already exists in the "group by" list
bool fieldIsInList = _groupByFields.Contains(fieldName);
// If the field is being added, and is NOT in the list, add it ...
if (fieldAdded && !fieldIsInList)
{
_groupByFields.Add(fieldName);
// Also add it to the "order by" list
OrderBy orderBy = new OrderBy(fieldName, SortOrder.Ascending);
OrderFieldOption orderOption = new OrderFieldOption(false, orderBy);
_orderByFields.Add(orderOption);
}
// If the field is being removed and it IS in the list, remove it ...
else if (!fieldAdded && fieldIsInList)
{
_groupByFields.Remove(fieldName);
// Also check for this field in the "order by" list and remove if necessary (only group fields can be used to order results)
OrderFieldOption orderBy = _orderByFields.FirstOrDefault(field => field.OrderInfo.FieldName == fieldName);
if (orderBy != null)
{
// Remove the field from the "order by" list
_orderByFields.Remove(orderBy);
}
}
}
// Create a statistic definition and add it to the collection based on the user selection in the combo boxes
private void AddStatisticClicked(object sender, RoutedEventArgs e)
{
// Verify that a field name and statistic type has been selected
if (FieldsComboBox.SelectedValue == null || StatTypeComboBox.SelectedValue == null) { return; }
// Get the chosen field name and statistic type from the combo boxes
string fieldName = FieldsComboBox.SelectedValue.ToString();
StatisticType statType = Enum.Parse<StatisticType>(StatTypeComboBox.SelectedValue as string);
// Check if this statistic definition has already be created (same field name and statistic type)
StatisticDefinition existingStatDefinition = _statDefinitions.FirstOrDefault(def => def.OnFieldName == fieldName && def.StatisticType == statType);
// If it doesn't exist, create it and add it to the collection (use the field name and statistic type to build the output alias)
if (existingStatDefinition == null)
{
StatisticDefinition statDefinition = new StatisticDefinition(fieldName, statType, fieldName + "_" + statType.ToString());
_statDefinitions.Add(statDefinition);
}
}
// Toggle the sort order (ascending/descending) for the field selected in the sort fields list
private void ChangeFieldSortOrder(object sender, RoutedEventArgs e)
{
// Verify that there is a selected sort field in the list
OrderFieldOption selectedSortField = OrderByFieldsListBox.SelectedItem as OrderFieldOption;
if (selectedSortField == null) { return; }
// Create a new order field info to define the sort for the selected field
OrderBy newOrderBy = new OrderBy(selectedSortField.OrderInfo.FieldName, selectedSortField.OrderInfo.SortOrder);
OrderFieldOption newSortDefinition = new OrderFieldOption(true, newOrderBy);
// Toggle the sort order from the current value
if (newSortDefinition.OrderInfo.SortOrder == SortOrder.Ascending)
{
newSortDefinition.OrderInfo.SortOrder = SortOrder.Descending;
}
else
{
newSortDefinition.OrderInfo.SortOrder = SortOrder.Ascending;
}
// Add the new OrderBy at the same location in the collection and remove the old one
_orderByFields.Insert(_orderByFields.IndexOf(selectedSortField), newSortDefinition);
_orderByFields.Remove(selectedSortField);
}
// Remove the selected statistic definition from the list
private void RemoveStatisticClicked(object sender, RoutedEventArgs e)
{
// Verify that there is a selected statistic definition
if (StatFieldsListBox.SelectedItem == null) { return; }
// Get the selected statistic definition and remove it from the collection
StatisticDefinition selectedStat = StatFieldsListBox.SelectedItem as StatisticDefinition;
_statDefinitions.Remove(selectedStat);
}
// Add the selected field in the "group by" list to the "order by" list
private void AddSortFieldClicked(object sender, RoutedEventArgs e)
{
// Verify that there is a selected field in the "group by" list
if (GroupFieldsListBox.SelectedItem == null) { return; }
// Get the name of the selected field and ensure that it's in the list of selected group fields (checked on in the list, e.g.)
string selectedFieldName = GroupFieldsListBox.SelectedItem.ToString();
if (!_groupByFields.Contains(selectedFieldName))
{
ShowMessage("Only fields used for grouping can be used to order results.", "Order fields");
return;
}
// Verify that the field isn't already in the "order by" list
OrderFieldOption existingOrderBy = _orderByFields.FirstOrDefault(f => f.OrderInfo.FieldName == selectedFieldName);
if (existingOrderBy == null)
{
// Create a new OrderBy for this field and add it to the collection (default to ascending sort order)
OrderBy newOrderBy = new OrderBy(selectedFieldName, SortOrder.Ascending);
OrderFieldOption orderField = new OrderFieldOption(false, newOrderBy);
_orderByFields.Add(orderField);
}
}
// Remove the selected field from the list of "order by" fields
private void RemoveSortFieldClicked(object sender, RoutedEventArgs e)
{
// Verify that there is a selected item in the "order by" list
if (OrderByFieldsListBox.SelectedItem == null) { return; }
// Get the selected OrderFieldOption object and remove it from the collection
OrderFieldOption selectedOrderBy = OrderByFieldsListBox.SelectedItem as OrderFieldOption;
_orderByFields.Remove(selectedOrderBy);
}
}
// Simple class to describe an "order by" option
public class OrderFieldOption
{
// Whether or not to use this field to order results
public bool OrderWith { get; set; }
// The order by info: field name and sort order
public OrderBy OrderInfo { get; set; }
public OrderFieldOption(bool orderWith, OrderBy orderInfo)
{
OrderWith = orderWith;
OrderInfo = orderInfo;
}
}
// Value converter to return strings in a specified format
public class StringFormatConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
// Make sure there's a value
if (value == null)
return null;
// Make sure there's a converter parameter (format string, "{0:0,0}", for example)
if (parameter == null)
return value;
// Return the formatted string
return string.Format((string)parameter, value);
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
}
| |
using System;
using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;
/*
* Copyright 2011-2014 Stefan Thoolen (http://www.netmftoolbox.com/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Toolbox.NETMF.Hardware
{
/// <summary>
/// SPI Helper to make it easier to use multiple SPI-devices on one SPI-bus
/// </summary>
public class MultiSPI
{
/// <summary>Reference to the SPI Device. All MultiSPI devices use the same SPI class from the NETMF, so this reference is static</summary>
private static SPI _SPIDevice;
/// <summary>SPI Configuration. Different for each device, so not a static reference</summary>
private SPI.Configuration _Configuration;
/// <summary>There is a software ChipSelect feature because of a bug. True when enabled</summary>
/// <remarks>see http://netduino.codeplex.com/workitem/3 for more details about the bug.</remarks>
private bool _Use_SoftwareCS;
/// <summary>Reference to the latch-pin when using software chip-select</summary>
private OutputPort _SoftwareCS;
/// <summary>Active state when using software chip-select</summary>
private bool _SoftwareCS_ActiveState;
/// <summary>Returns the SPI Configuration</summary>
public SPI.Configuration Config { get { return this._Configuration; } }
/// <summary>
/// Initializes a new SPI device
/// </summary>
/// <param name="config">The SPI-module configuration</param>
public MultiSPI(SPI.Configuration config)
{
// The timing of the Netduino pin 4, Netduino Plus pin 4 and Netduino Mini pin 13 have a small bug, probably in the IC or NETMF itself.
//
// They all refer to the same pin ID on the AT91SAM7X512: (int)12
// - SecretLabs.NETMF.Hardware.Netduino.Pins.GPIO_PIN_D4
// - SecretLabs.NETMF.Hardware.NetduinoPlus.Pins.GPIO_PIN_D4
// - SecretLabs.NETMF.Hardware.NetduinoMini.Pins.GPIO_PIN_13
//
// To work around this problem we use a software chip select. A bit slower, but it works.
// We will include this work-around until the actual bug is fixed.
bool SoftwareChipSelect = false;
if ((int)config.ChipSelect_Port == 12 && (
Tools.HardwareProvider == "Netduino" || Tools.HardwareProvider == "NetduinoMini" || Tools.HardwareProvider == "NetduinoPlus"
))
{
Debug.Print("MultiSPI: Software ChipSelect enabled to prevent timing issues");
Debug.Print("MultiSPI: See http://netduino.codeplex.com/workitem/3 for more");
SoftwareChipSelect = true;
}
// Sets the configuration in a local value
this._Configuration = config;
// When we use a software chipset we need to record some more details
if (SoftwareChipSelect)
{
this._SoftwareCS = new OutputPort(config.ChipSelect_Port, !config.ChipSelect_ActiveState);
this._SoftwareCS_ActiveState = config.ChipSelect_ActiveState;
this._Use_SoftwareCS = true;
// Copies the Configuration, but without Chip Select pin
this._Configuration = new SPI.Configuration(
Cpu.Pin.GPIO_NONE,
_Configuration.BusyPin_ActiveState,
_Configuration.ChipSelect_SetupTime,
_Configuration.ChipSelect_HoldTime,
_Configuration.Clock_IdleState,
_Configuration.Clock_Edge,
_Configuration.Clock_RateKHz,
_Configuration.SPI_mod,
_Configuration.BusyPin,
_Configuration.BusyPin_ActiveState
);
}
// If no SPI Device exists yet, we create it's first instance
if (_SPIDevice == null)
{
// Creates the SPI Device
_SPIDevice = new SPI(this._Configuration);
}
}
/// <summary>
/// The 8-bit bytes to write to the SPI-buffer
/// </summary>
/// <param name="WriteBuffer">An array of 8-bit bytes</param>
public void Write(byte[] WriteBuffer)
{
if (this._Use_SoftwareCS) this._SoftwareCS.Write(this._SoftwareCS_ActiveState);
_SPIDevice.Config = this._Configuration;
_SPIDevice.Write(WriteBuffer);
if (this._Use_SoftwareCS) this._SoftwareCS.Write(!this._SoftwareCS_ActiveState);
}
/// <summary>
/// The 16-bit bytes to write to the SPI-buffer
/// </summary>
/// <param name="WriteBuffer">An array of 16-bit bytes</param>
public void Write(ushort[] WriteBuffer)
{
if (this._Use_SoftwareCS) this._SoftwareCS.Write(this._SoftwareCS_ActiveState);
_SPIDevice.Config = this._Configuration;
_SPIDevice.Write(WriteBuffer);
if (this._Use_SoftwareCS) this._SoftwareCS.Write(!this._SoftwareCS_ActiveState);
}
/// <summary>
/// Reads 8-bit bytes
/// </summary>
/// <param name="ReadBuffer">An array with 8-bit bytes to read</param>
public void Read(byte[] ReadBuffer)
{
if (this._Use_SoftwareCS) this._SoftwareCS.Write(this._SoftwareCS_ActiveState);
_SPIDevice.Config = this._Configuration;
_SPIDevice.WriteRead(ReadBuffer, ReadBuffer); // First parameter is actually a WriteBuffer
if (this._Use_SoftwareCS) this._SoftwareCS.Write(!this._SoftwareCS_ActiveState);
}
/// <summary>
/// Reads 16-bit bytes
/// </summary>
/// <param name="ReadBuffer">An array with 16-bit bytes to read</param>
public void Read(ushort[] ReadBuffer)
{
if (this._Use_SoftwareCS) this._SoftwareCS.Write(this._SoftwareCS_ActiveState);
_SPIDevice.Config = this._Configuration;
_SPIDevice.WriteRead(ReadBuffer, ReadBuffer); // First parameter is actually a WriteBuffer
if (this._Use_SoftwareCS) this._SoftwareCS.Write(!this._SoftwareCS_ActiveState);
}
/// <summary>
/// Writes an array of 8-bit bytes to the interface, and reads an array of 8-bit bytes from the interface.
/// </summary>
/// <param name="WriteBuffer">An array with 8-bit bytes to write</param>
/// <param name="ReadBuffer">An array with 8-bit bytes to read</param>
public void WriteRead(byte[] WriteBuffer, byte[] ReadBuffer)
{
if (this._Use_SoftwareCS) this._SoftwareCS.Write(this._SoftwareCS_ActiveState);
_SPIDevice.Config = this._Configuration;
_SPIDevice.WriteRead(WriteBuffer, ReadBuffer);
if (this._Use_SoftwareCS) this._SoftwareCS.Write(!this._SoftwareCS_ActiveState);
}
/// <summary>
/// Writes an array of 16-bit bytes to the interface, and reads an array of 16-bit bytes from the interface.
/// </summary>
/// <param name="WriteBuffer">An array with 16-bit bytes to write</param>
/// <param name="ReadBuffer">An array with 16-bit bytes to read</param>
public void WriteRead(ushort[] WriteBuffer, ushort[] ReadBuffer)
{
if (this._Use_SoftwareCS) this._SoftwareCS.Write(this._SoftwareCS_ActiveState);
_SPIDevice.Config = this._Configuration;
_SPIDevice.WriteRead(WriteBuffer, ReadBuffer);
if (this._Use_SoftwareCS) this._SoftwareCS.Write(!this._SoftwareCS_ActiveState);
}
/// <summary>
/// Writes an array of 8-bit bytes to the interface, and reads an array of 8-bit bytes from the interface into a specified location in the read buffer.
/// </summary>
/// <param name="WriteBuffer">An array with 8-bit bytes to write</param>
/// <param name="ReadBuffer">An array with 8-bit bytes to read</param>
/// <param name="StartReadOffset">The offset in time, measured in transacted elements from writeBuffer, when to start reading back data into readBuffer</param>
public void WriteRead(byte[] WriteBuffer, byte[] ReadBuffer, int StartReadOffset)
{
if (this._Use_SoftwareCS) this._SoftwareCS.Write(this._SoftwareCS_ActiveState);
_SPIDevice.Config = this._Configuration;
_SPIDevice.WriteRead(WriteBuffer, ReadBuffer, StartReadOffset);
if (this._Use_SoftwareCS) this._SoftwareCS.Write(!this._SoftwareCS_ActiveState);
}
/// <summary>
/// Writes an array of 16-bit bytes to the interface, and reads an array of 16-bit bytes from the interface into a specified location in the read buffer.
/// </summary>
/// <param name="WriteBuffer">An array with 16-bit bytes to write</param>
/// <param name="ReadBuffer">An array with 16-bit bytes to read</param>
/// <param name="StartReadOffset">The offset in time, measured in transacted elements from writeBuffer, when to start reading back data into readBuffer</param>
public void WriteRead(ushort[] WriteBuffer, ushort[] ReadBuffer, int StartReadOffset)
{
if (this._Use_SoftwareCS) this._SoftwareCS.Write(this._SoftwareCS_ActiveState);
_SPIDevice.Config = this._Configuration;
_SPIDevice.WriteRead(WriteBuffer, ReadBuffer, StartReadOffset);
if (this._Use_SoftwareCS) this._SoftwareCS.Write(!this._SoftwareCS_ActiveState);
}
/// <summary>
/// Writes an array of 16-bit bytes to the interface, and reads an array of 16-bit bytes from the interface into a specified location in the read buffer.
/// </summary>
/// <param name="WriteBuffer">An array with 8-bit bytes to write</param>
/// <param name="ReadBuffer">An array with 8-bit bytes to read</param>
/// <param name="WriteOffset">The offset in writeBuffer to start write data from</param>
/// <param name="WriteCount">The number of elements in writeBuffer to write</param>
/// <param name="ReadOffset">The offset in readBuffer to start read data from</param>
/// <param name="ReadCount">The number of elements in readBuffer to fill</param>
/// <param name="StartReadOffset">The offset in time, measured in transacted elements from writeBuffer, when to start reading back data into readBuffer</param>
public void WriteRead(byte[] WriteBuffer, int WriteOffset, int WriteCount, byte[] ReadBuffer, int ReadOffset, int ReadCount, int StartReadOffset)
{
if (this._Use_SoftwareCS) this._SoftwareCS.Write(this._SoftwareCS_ActiveState);
_SPIDevice.Config = this._Configuration;
_SPIDevice.WriteRead(WriteBuffer, WriteOffset, WriteCount, ReadBuffer, ReadOffset, ReadCount, StartReadOffset);
if (this._Use_SoftwareCS) this._SoftwareCS.Write(!this._SoftwareCS_ActiveState);
}
/// <summary>
/// Writes an array of 16-bit bytes to the interface, and reads an array of 16-bit bytes from the interface into a specified location in the read buffer.
/// </summary>
/// <param name="WriteBuffer">An array with 16-bit bytes to write</param>
/// <param name="ReadBuffer">An array with 16-bit bytes to read</param>
/// <param name="WriteOffset">The offset in writeBuffer to start write data from</param>
/// <param name="WriteCount">The number of elements in writeBuffer to write</param>
/// <param name="ReadOffset">The offset in readBuffer to start read data from</param>
/// <param name="ReadCount">The number of elements in readBuffer to fill</param>
/// <param name="StartReadOffset">The offset in time, measured in transacted elements from writeBuffer, when to start reading back data into readBuffer</param>
public void WriteRead(ushort[] WriteBuffer, int WriteOffset, int WriteCount, ushort[] ReadBuffer, int ReadOffset, int ReadCount, int StartReadOffset)
{
if (this._Use_SoftwareCS) this._SoftwareCS.Write(this._SoftwareCS_ActiveState);
_SPIDevice.Config = this._Configuration;
_SPIDevice.WriteRead(WriteBuffer, WriteOffset, WriteCount, ReadBuffer, ReadOffset, ReadCount, StartReadOffset);
if (this._Use_SoftwareCS) this._SoftwareCS.Write(!this._SoftwareCS_ActiveState);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using NuGet.Frameworks;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Versioning;
using System.Xml.Linq;
namespace Microsoft.DotNet.Build.Tasks.Packaging
{
public class FrameworkSet
{
private const string LastNonSemanticVersionsFileName = "LastNonSemanticVersions.xml";
// avoid parsing the same documents multiple times on a single node.
private static Dictionary<string, FrameworkSet> s_frameworkSetCache = new Dictionary<string, FrameworkSet>();
private static object s_frameworkSetCacheLock = new object();
public FrameworkSet()
{
Frameworks = new Dictionary<string, SortedSet<Framework>>();
LastNonSemanticVersions = new Dictionary<string, Version>();
}
public static FrameworkSet Load(string frameworkListsPath)
{
FrameworkSet result;
if (s_frameworkSetCache.TryGetValue(frameworkListsPath, out result))
return result;
result = new FrameworkSet();
foreach (string fxDir in Directory.EnumerateDirectories(frameworkListsPath))
{
string targetName = Path.GetFileName(fxDir);
Framework framework = new Framework(targetName);
foreach (string frameworkListPath in Directory.EnumerateFiles(fxDir, "*.xml"))
{
AddAssembliesFromFrameworkList(framework.Assemblies, frameworkListPath);
}
SortedSet<Framework> frameworkVersions = null;
string fxId = framework.FrameworkName.Identifier;
if (fxId == FrameworkConstants.FrameworkIdentifiers.Portable)
{
// portable doesn't have version relationships, use the entire TFM
fxId = framework.FrameworkName.ToString();
}
if (!result.Frameworks.TryGetValue(fxId, out frameworkVersions))
{
frameworkVersions = new SortedSet<Framework>();
}
frameworkVersions.Add(framework);
result.Frameworks[fxId] = frameworkVersions;
}
string lastNonSemanticVersionsListPath = Path.Combine(frameworkListsPath, LastNonSemanticVersionsFileName);
AddAssembliesFromFrameworkList(result.LastNonSemanticVersions, lastNonSemanticVersionsListPath);
lock (s_frameworkSetCacheLock)
{
s_frameworkSetCache[frameworkListsPath] = result;
}
return result;
}
private static void AddAssembliesFromFrameworkList(IDictionary<string, Version> assemblies, string frameworkListPath)
{
XDocument frameworkList = XDocument.Load(frameworkListPath);
foreach (var file in frameworkList.Element("FileList").Elements("File"))
{
string assemblyName = file.Attribute("AssemblyName").Value;
var versionAttribute = file.Attribute("Version");
Version supportedVersion = null;
if (versionAttribute != null)
{
supportedVersion = new Version(versionAttribute.Value);
}
// Use a file entry with no version to indicate any version,
// this is how Xamarin wishes us to support them
assemblies.Add(assemblyName,
supportedVersion ??
new Version(int.MaxValue, int.MaxValue, int.MaxValue, int.MaxValue));
}
}
public Dictionary<string, SortedSet<Framework>> Frameworks { get; private set; }
public Dictionary<string, Version> LastNonSemanticVersions { get; private set; }
/// <summary>
/// Determines the significant API version given an assembly version.
/// </summary>
/// <param name="assemblyName">Name of assembly</param>
/// <param name="assemblyVersion">Version of assembly</param>
/// <returns>Lowest version with the same API surface as assemblyVersion</returns>
public Version GetApiVersion(string assemblyName, Version assemblyVersion)
{
if (assemblyVersion == null)
{
return null;
}
if (assemblyVersion.Build == 0 && assemblyVersion.Revision == 0)
{
// fast path for X.Y.0.0
return assemblyVersion;
}
Version latestLegacyVersion = null;
LastNonSemanticVersions.TryGetValue(assemblyName, out latestLegacyVersion);
if (latestLegacyVersion == null)
{
return new Version(assemblyVersion.Major, assemblyVersion.Minor, 0, 0);
}
else if (assemblyVersion.Major <= latestLegacyVersion.Major && assemblyVersion.Minor <= latestLegacyVersion.Minor)
{
// legacy version round build to nearest 10
return new Version(assemblyVersion.Major, assemblyVersion.Minor, assemblyVersion.Build - assemblyVersion.Build % 10, 0);
}
else
{
// new version
return new Version(assemblyVersion.Major, assemblyVersion.Minor, 0, 0);
}
}
}
public class Framework : IComparable<Framework>
{
public Framework(string targetName)
{
Assemblies = new Dictionary<string, Version>();
FrameworkName = new FrameworkName(targetName);
var nugetFramework = new NuGetFramework(FrameworkName.Identifier, FrameworkName.Version, FrameworkName.Profile);
ShortName = nugetFramework.GetShortFolderName();
if (ShortName.EndsWith(nugetFramework.Version.Major.ToString()) && nugetFramework.Version.Minor == 0)
{
// prefer a trailing zero
ShortName += "0";
}
if (ShortName == "win" || ShortName == "netcore45")
{
// prefer the versioned short name
ShortName = "win8";
}
if (ShortName == "netcore451")
{
ShortName = "win81";
}
}
public IDictionary<string, Version> Assemblies { get; private set; }
public FrameworkName FrameworkName { get; private set; }
public string ShortName { get; private set; }
public int CompareTo(Framework other)
{
if (this.FrameworkName.Identifier != other.FrameworkName.Identifier)
{
throw new ArgumentException("Frameworks with different IDs are not comparable.", "other");
}
return this.FrameworkName.Version.CompareTo(other.FrameworkName.Version);
}
}
public class Frameworks
{
private static FrameworkSet s_inboxFrameworks;
private static FrameworkSet GetInboxFrameworks(string frameworkListsPath)
{
if (s_inboxFrameworks == null)
s_inboxFrameworks = FrameworkSet.Load(frameworkListsPath);
return s_inboxFrameworks;
}
public static string[] GetInboxFrameworksList(string frameworkListsPath, string assemblyName, string assemblyVersion, ILog log)
{
// if no version is specified just use 0.0.0.0 to evaluate for any version of the contract
Version version = String.IsNullOrEmpty(assemblyVersion) ? new Version(0, 0, 0, 0) : new Version(assemblyVersion);
FrameworkSet fxs = GetInboxFrameworks(frameworkListsPath);
Version latestLegacyVersion = null;
fxs.LastNonSemanticVersions.TryGetValue(assemblyName, out latestLegacyVersion);
List<string> inboxIds = new List<string>();
foreach (var fxVersions in fxs.Frameworks.Values)
{
// find the first version (if any) that supports this contract
foreach (var fxVersion in fxVersions)
{
Version supportedVersion;
if (fxVersion.Assemblies.TryGetValue(assemblyName, out supportedVersion))
{
if (supportedVersion >= version)
{
if (log != null)
log.LogMessage(LogImportance.Low, "inbox on {0}", fxVersion.ShortName);
inboxIds.Add(fxVersion.ShortName);
break;
}
// new versions represent API surface via major.minor only, so consider
// a contract as supported so long as the latest legacy version is supported
// and this contract's major.minor match the latest legacy version.
if (supportedVersion == latestLegacyVersion &&
version.Major == latestLegacyVersion.Major && version.Minor == latestLegacyVersion.Minor)
{
if (log != null)
log.LogMessage(LogImportance.Low, "Considering {0},Version={1} inbox on {2}, since it only differs in revsion.build from {3}", assemblyName, assemblyVersion, fxVersion.ShortName, latestLegacyVersion);
inboxIds.Add(fxVersion.ShortName);
break;
}
}
}
}
return inboxIds.ToArray();
}
public static bool IsInbox(string frameworkListsPath, string framework, string assemblyName, string assemblyVersion)
{
NuGetFramework fx = NuGetFramework.Parse(framework);
return IsInbox(frameworkListsPath, fx, assemblyName, assemblyVersion);
}
public static bool IsInbox(string frameworkListsPath, NuGetFramework framework, string assemblyName, string assemblyVersion)
{
if (framework.Framework == FrameworkConstants.FrameworkIdentifiers.UAP ||
(framework.Framework == FrameworkConstants.FrameworkIdentifiers.NetCore && framework.Version >= FrameworkConstants.CommonFrameworks.NetCore50.Version))
{
// UAP & netcore50 or higher are completely OOB, despite being compatible with netcore4x which has inbox assemblies
return false;
}
// if no version is specified just use 0.0.0.0 to evaluate for any version of the contract
Version version = FrameworkUtilities.Ensure4PartVersion(String.IsNullOrEmpty(assemblyVersion) ? new Version(0, 0, 0, 0) : new Version(assemblyVersion));
FrameworkSet fxs = GetInboxFrameworks(frameworkListsPath);
Version latestLegacyVersion = null;
fxs.LastNonSemanticVersions.TryGetValue(assemblyName, out latestLegacyVersion);
foreach (var fxVersions in fxs.Frameworks.Values)
{
// Get the nearest compatible framework from this set of frameworks.
var nearest = FrameworkUtilities.GetNearest(framework, fxVersions.Select(fx => NuGetFramework.Parse(fx.ShortName)).ToArray());
// If there are not compatible frameworks in the current framework set, there is not going to be a match.
if (nearest == null)
{
continue;
}
// don't allow PCL to specify inbox for non-PCL framework.
if (nearest.IsPCL != framework.IsPCL)
{
continue;
}
// find the first version (if any) that supports this contract
foreach (var fxVersion in fxVersions)
{
Version supportedVersion;
if (fxVersion.Assemblies.TryGetValue(assemblyName, out supportedVersion))
{
if (supportedVersion >= version)
{
return true;
}
// new versions represent API surface via major.minor only, so consider
// a contract as supported so long as the latest legacy version is supported
// and this contract's major.minor match the latest legacy version.
if (supportedVersion == latestLegacyVersion &&
version.Major == latestLegacyVersion.Major && version.Minor == latestLegacyVersion.Minor)
{
return true;
}
}
}
}
return false;
}
internal static IEnumerable<NuGetFramework> GetAlllInboxFrameworks(string frameworkListsPath)
{
FrameworkSet fxs = FrameworkSet.Load(frameworkListsPath);
return fxs.Frameworks.SelectMany(fxList => fxList.Value).Select(fx => NuGetFramework.Parse(fx.ShortName));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using Cleangorod.Web.Areas.HelpPage.ModelDescriptions;
using Cleangorod.Web.Areas.HelpPage.Models;
namespace Cleangorod.Web.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
using System;
using System.Collections;
#if !SILVERLIGHT
using System.Collections.Concurrent;
#else
using TvdP.Collections;
#endif
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
namespace AutoMapper
{
public delegate object LateBoundMethod(object target, object[] arguments);
public delegate object LateBoundPropertyGet(object target);
public delegate object LateBoundFieldGet(object target);
public delegate void LateBoundFieldSet(object target, object value);
public delegate void LateBoundPropertySet(object target, object value);
public delegate void LateBoundValueTypeFieldSet(ref object target, object value);
public delegate void LateBoundValueTypePropertySet(ref object target, object value);
public delegate object LateBoundCtor();
public delegate object LateBoundParamsCtor(params object[] parameters);
public static class DelegateFactory
{
private static readonly ConcurrentDictionary<Type, LateBoundCtor> _ctorCache = new ConcurrentDictionary<Type, LateBoundCtor>();
public static LateBoundMethod CreateGet(MethodInfo method)
{
ParameterExpression instanceParameter = Expression.Parameter(typeof(object), "target");
ParameterExpression argumentsParameter = Expression.Parameter(typeof(object[]), "arguments");
MethodCallExpression call;
if (!method.IsDefined(typeof(ExtensionAttribute), false))
{
// instance member method
call = Expression.Call(
Expression.Convert(instanceParameter, method.DeclaringType),
method,
CreateParameterExpressions(method, instanceParameter, argumentsParameter));
}
else
{
// static extension method
call = Expression.Call(
method,
CreateParameterExpressions(method, instanceParameter, argumentsParameter));
}
Expression<LateBoundMethod> lambda = Expression.Lambda<LateBoundMethod>(
Expression.Convert(call, typeof(object)),
instanceParameter,
argumentsParameter);
return lambda.Compile();
}
public static LateBoundPropertyGet CreateGet(PropertyInfo property)
{
ParameterExpression instanceParameter = Expression.Parameter(typeof(object), "target");
MemberExpression member = Expression.Property(Expression.Convert(instanceParameter, property.DeclaringType), property);
Expression<LateBoundPropertyGet> lambda = Expression.Lambda<LateBoundPropertyGet>(
Expression.Convert(member, typeof(object)),
instanceParameter
);
return lambda.Compile();
}
public static LateBoundFieldGet CreateGet(FieldInfo field)
{
ParameterExpression instanceParameter = Expression.Parameter(typeof(object), "target");
MemberExpression member = Expression.Field(Expression.Convert(instanceParameter, field.DeclaringType), field);
Expression<LateBoundFieldGet> lambda = Expression.Lambda<LateBoundFieldGet>(
Expression.Convert(member, typeof(object)),
instanceParameter
);
return lambda.Compile();
}
public static LateBoundFieldSet CreateSet(FieldInfo field)
{
var sourceType = field.DeclaringType;
var method = CreateDynamicMethod(field, sourceType);
var gen = method.GetILGenerator();
gen.Emit(OpCodes.Ldarg_0); // Load input to stack
gen.Emit(OpCodes.Castclass, sourceType); // Cast to source type
gen.Emit(OpCodes.Ldarg_1); // Load value to stack
gen.Emit(OpCodes.Unbox_Any, field.FieldType); // Unbox the value to its proper value type
gen.Emit(OpCodes.Stfld, field); // Set the value to the input field
gen.Emit(OpCodes.Ret);
var callback = (LateBoundFieldSet)method.CreateDelegate(typeof(LateBoundFieldSet));
return callback;
}
public static LateBoundPropertySet CreateSet(PropertyInfo property)
{
var sourceType = property.DeclaringType;
var setter = property.GetSetMethod(true);
var method = CreateDynamicMethod(property, sourceType);
var gen = method.GetILGenerator();
gen.Emit(OpCodes.Ldarg_0); // Load input to stack
gen.Emit(OpCodes.Castclass, sourceType); // Cast to source type
gen.Emit(OpCodes.Ldarg_1); // Load value to stack
gen.Emit(OpCodes.Unbox_Any, property.PropertyType); // Unbox the value to its proper value type
gen.Emit(OpCodes.Callvirt, setter); // Call the setter method
gen.Emit(OpCodes.Ret);
var result = (LateBoundPropertySet)method.CreateDelegate(typeof(LateBoundPropertySet));
return result;
}
public static LateBoundValueTypePropertySet CreateValueTypeSet(PropertyInfo property)
{
var sourceType = property.DeclaringType;
var setter = property.GetSetMethod(true);
var method = CreateValueTypeDynamicMethod(property, sourceType);
var gen = method.GetILGenerator();
method.InitLocals = true;
gen.Emit(OpCodes.Ldarg_0); // Load input to stack
gen.Emit(OpCodes.Ldind_Ref);
gen.Emit(OpCodes.Unbox_Any, sourceType); // Unbox the source to its correct type
gen.Emit(OpCodes.Stloc_0); // Store the unboxed input on the stack
gen.Emit(OpCodes.Ldloca_S, 0);
gen.Emit(OpCodes.Ldarg_1); // Load value to stack
gen.Emit(OpCodes.Castclass, property.PropertyType); // Unbox the value to its proper value type
gen.Emit(OpCodes.Call, setter); // Call the setter method
gen.Emit(OpCodes.Ret);
var result = (LateBoundValueTypePropertySet)method.CreateDelegate(typeof(LateBoundValueTypePropertySet));
return result;
}
public static LateBoundCtor CreateCtor(Type type)
{
LateBoundCtor ctor = _ctorCache.GetOrAdd(type, t =>
{
var ctorExpression = Expression.Lambda<LateBoundCtor>(Expression.Convert(Expression.New(type), typeof(object)));
return ctorExpression.Compile();
});
return ctor;
}
private static DynamicMethod CreateValueTypeDynamicMethod(MemberInfo member, Type sourceType)
{
#if !SILVERLIGHT
if (sourceType.IsInterface)
return new DynamicMethod("Set" + member.Name, null, new[] { typeof(object).MakeByRefType(), typeof(object) }, sourceType.Assembly.ManifestModule, true);
return new DynamicMethod("Set" + member.Name, null, new[] { typeof(object).MakeByRefType(), typeof(object) }, sourceType, true);
#else
if (sourceType.IsInterface)
return new DynamicMethod("Set" + member.Name, null, new[] { typeof(object).MakeByRefType(), typeof(object) });
return new DynamicMethod("Set" + member.Name, null, new[] { typeof(object).MakeByRefType(), typeof(object) });
#endif
}
private static DynamicMethod CreateDynamicMethod(MemberInfo member, Type sourceType)
{
#if !SILVERLIGHT
if (sourceType.IsInterface)
return new DynamicMethod("Set" + member.Name, null, new[] { typeof(object), typeof(object) }, sourceType.Assembly.ManifestModule, true);
return new DynamicMethod("Set" + member.Name, null, new[] { typeof(object), typeof(object) }, sourceType, true);
#else
if (sourceType.IsInterface)
return new DynamicMethod("Set" + member.Name, null, new[] { typeof(object), typeof(object) });
return new DynamicMethod("Set" + member.Name, null, new[] { typeof(object), typeof(object) });
#endif
}
private static Expression[] CreateParameterExpressions(MethodInfo method, Expression instanceParameter, Expression argumentsParameter)
{
var expressions = new List<UnaryExpression>();
var realMethodParameters = method.GetParameters();
if (method.IsDefined(typeof(ExtensionAttribute), false))
{
Type extendedType = method.GetParameters()[0].ParameterType;
expressions.Add(Expression.Convert(instanceParameter, extendedType));
realMethodParameters = realMethodParameters.Skip(1).ToArray();
}
expressions.AddRange(realMethodParameters.Select((parameter, index) =>
Expression.Convert(
Expression.ArrayIndex(argumentsParameter, Expression.Constant(index)),
parameter.ParameterType)));
return expressions.ToArray();
}
public static LateBoundParamsCtor CreateCtor(ConstructorInfo constructorInfo, IEnumerable<ConstructorParameterMap> ctorParams)
{
ParameterExpression paramsExpr = Expression.Parameter(typeof(object[]), "parameters");
var convertExprs = ctorParams
.Select((ctorParam, i) => Expression.Convert(
Expression.ArrayIndex(paramsExpr, Expression.Constant(i)),
ctorParam.Parameter.ParameterType))
.ToArray();
NewExpression newExpression = Expression.New(constructorInfo, convertExprs);
var lambda = Expression.Lambda<LateBoundParamsCtor>(newExpression, paramsExpr);
return lambda.Compile();
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gcav = Google.Cloud.AIPlatform.V1;
using sys = System;
namespace Google.Cloud.AIPlatform.V1
{
/// <summary>Resource name for the <c>Index</c> resource.</summary>
public sealed partial class IndexName : gax::IResourceName, sys::IEquatable<IndexName>
{
/// <summary>The possible contents of <see cref="IndexName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>projects/{project}/locations/{location}/indexes/{index}</c>.
/// </summary>
ProjectLocationIndex = 1,
}
private static gax::PathTemplate s_projectLocationIndex = new gax::PathTemplate("projects/{project}/locations/{location}/indexes/{index}");
/// <summary>Creates a <see cref="IndexName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="IndexName"/> containing the provided <paramref name="unparsedResourceName"/>.
/// </returns>
public static IndexName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new IndexName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="IndexName"/> with the pattern
/// <c>projects/{project}/locations/{location}/indexes/{index}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="indexId">The <c>Index</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="IndexName"/> constructed from the provided ids.</returns>
public static IndexName FromProjectLocationIndex(string projectId, string locationId, string indexId) =>
new IndexName(ResourceNameType.ProjectLocationIndex, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), indexId: gax::GaxPreconditions.CheckNotNullOrEmpty(indexId, nameof(indexId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="IndexName"/> with pattern
/// <c>projects/{project}/locations/{location}/indexes/{index}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="indexId">The <c>Index</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="IndexName"/> with pattern
/// <c>projects/{project}/locations/{location}/indexes/{index}</c>.
/// </returns>
public static string Format(string projectId, string locationId, string indexId) =>
FormatProjectLocationIndex(projectId, locationId, indexId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="IndexName"/> with pattern
/// <c>projects/{project}/locations/{location}/indexes/{index}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="indexId">The <c>Index</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="IndexName"/> with pattern
/// <c>projects/{project}/locations/{location}/indexes/{index}</c>.
/// </returns>
public static string FormatProjectLocationIndex(string projectId, string locationId, string indexId) =>
s_projectLocationIndex.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(indexId, nameof(indexId)));
/// <summary>Parses the given resource name string into a new <see cref="IndexName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/locations/{location}/indexes/{index}</c></description></item>
/// </list>
/// </remarks>
/// <param name="indexName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="IndexName"/> if successful.</returns>
public static IndexName Parse(string indexName) => Parse(indexName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="IndexName"/> instance; optionally allowing an
/// unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/locations/{location}/indexes/{index}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="indexName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="IndexName"/> if successful.</returns>
public static IndexName Parse(string indexName, bool allowUnparsed) =>
TryParse(indexName, allowUnparsed, out IndexName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="IndexName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/locations/{location}/indexes/{index}</c></description></item>
/// </list>
/// </remarks>
/// <param name="indexName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="IndexName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string indexName, out IndexName result) => TryParse(indexName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="IndexName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/locations/{location}/indexes/{index}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="indexName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="IndexName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string indexName, bool allowUnparsed, out IndexName result)
{
gax::GaxPreconditions.CheckNotNull(indexName, nameof(indexName));
gax::TemplatedResourceName resourceName;
if (s_projectLocationIndex.TryParseName(indexName, out resourceName))
{
result = FromProjectLocationIndex(resourceName[0], resourceName[1], resourceName[2]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(indexName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private IndexName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string indexId = null, string locationId = null, string projectId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
IndexId = indexId;
LocationId = locationId;
ProjectId = projectId;
}
/// <summary>
/// Constructs a new instance of a <see cref="IndexName"/> class from the component parts of pattern
/// <c>projects/{project}/locations/{location}/indexes/{index}</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="indexId">The <c>Index</c> ID. Must not be <c>null</c> or empty.</param>
public IndexName(string projectId, string locationId, string indexId) : this(ResourceNameType.ProjectLocationIndex, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), indexId: gax::GaxPreconditions.CheckNotNullOrEmpty(indexId, nameof(indexId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Index</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string IndexId { get; }
/// <summary>
/// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string LocationId { get; }
/// <summary>
/// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.ProjectLocationIndex: return s_projectLocationIndex.Expand(ProjectId, LocationId, IndexId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as IndexName);
/// <inheritdoc/>
public bool Equals(IndexName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(IndexName a, IndexName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(IndexName a, IndexName b) => !(a == b);
}
public partial class Index
{
/// <summary>
/// <see cref="gcav::IndexName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcav::IndexName IndexName
{
get => string.IsNullOrEmpty(Name) ? null : gcav::IndexName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
using MeshSplitting.MeshTools;
using MeshSplitting.SplitterMath;
using System;
using UnityEngine;
namespace MeshSplitting.Splitables
{
[AddComponentMenu("Mesh Splitting/Splitable")]
public class Splitable : MonoBehaviour, ISplitable
{
#if UNITY_EDITOR
[NonSerialized]
public bool ShowDebug = false;
#endif
public GameObject OptionalTargetObject;
public bool Convex = false;
public float SplitForce = 0f;
public bool CreateCap = true;
public bool UseCapUV = false;
public bool CustomUV = false;
public Vector2 CapUVMin = Vector2.zero;
public Vector2 CapUVMax = Vector2.one;
public bool ForceNoBatching = false;
private Transform _transform;
private PlaneMath _splitPlane;
private MeshContainer[] _meshContainerStatic;
private IMeshSplitter[] _meshSplitterStatic;
private MeshContainer[] _meshContainerSkinned;
private IMeshSplitter[] _meshSplitterSkinned;
private bool _isSplitting = false;
private bool _splitMesh = false;
private void Awake()
{
_transform = GetComponent<Transform>();
}
private void Update()
{
if (_splitMesh)
{
_splitMesh = false;
bool anySplit = false;
for (int i = 0; i < _meshContainerStatic.Length; i++)
{
_meshContainerStatic[i].MeshInitialize();
_meshContainerStatic[i].CalculateWorldSpace();
// split mesh
_meshSplitterStatic[i].MeshSplit();
if (_meshContainerStatic[i].IsMeshSplit())
{
anySplit = true;
if (CreateCap) _meshSplitterStatic[i].MeshCreateCaps();
}
}
for (int i = 0; i < _meshContainerSkinned.Length; i++)
{
_meshContainerSkinned[i].MeshInitialize();
_meshContainerSkinned[i].CalculateWorldSpace();
// split mesh
_meshSplitterSkinned[i].MeshSplit();
if (_meshContainerSkinned[i].IsMeshSplit())
{
anySplit = true;
if (CreateCap) _meshSplitterSkinned[i].MeshCreateCaps();
}
}
if (anySplit) CreateNewObjects();
_isSplitting = false;
}
}
public void Split(Transform splitTransform)
{
if (!_isSplitting)
{
_isSplitting = _splitMesh = true;
_splitPlane = new PlaneMath(splitTransform);
MeshFilter[] meshFilters = GetComponentsInChildren<MeshFilter>();
SkinnedMeshRenderer[] skinnedRenderes = GetComponentsInChildren<SkinnedMeshRenderer>();
_meshContainerStatic = new MeshContainer[meshFilters.Length];
_meshSplitterStatic = new IMeshSplitter[meshFilters.Length];
for (int i = 0; i < meshFilters.Length; i++)
{
_meshContainerStatic[i] = new MeshContainer(meshFilters[i]);
_meshSplitterStatic[i] = Convex ? (IMeshSplitter)new MeshSplitterConvex(_meshContainerStatic[i], _splitPlane, splitTransform.rotation) :
(IMeshSplitter)new MeshSplitterConcave(_meshContainerStatic[i], _splitPlane, splitTransform.rotation);
if (UseCapUV) _meshSplitterStatic[i].SetCapUV(UseCapUV, CustomUV, CapUVMin, CapUVMax);
#if UNITY_EDITOR
_meshSplitterStatic[i].DebugDraw(ShowDebug);
#endif
}
_meshSplitterSkinned = new IMeshSplitter[skinnedRenderes.Length];
_meshContainerSkinned = new MeshContainer[skinnedRenderes.Length];
for (int i = 0; i < skinnedRenderes.Length; i++)
{
_meshContainerSkinned[i] = new MeshContainer(skinnedRenderes[i]);
_meshSplitterSkinned[i] = Convex ? (IMeshSplitter)new MeshSplitterConvex(_meshContainerSkinned[i], _splitPlane, splitTransform.rotation) :
(IMeshSplitter)new MeshSplitterConcave(_meshContainerSkinned[i], _splitPlane, splitTransform.rotation);
if (UseCapUV) _meshSplitterSkinned[i].SetCapUV(UseCapUV, CustomUV, CapUVMin, CapUVMax);
#if UNITY_EDITOR
_meshSplitterSkinned[i].DebugDraw(ShowDebug);
#endif
}
}
}
private void CreateNewObjects()
{
Transform parent = _transform.parent;
if (parent == null)
{
GameObject go = new GameObject("Parent: " + gameObject.name);
parent = go.transform;
parent.position = Vector3.zero;
parent.rotation = Quaternion.identity;
parent.localScale = Vector3.one;
}
Mesh origMesh = GetMeshOnGameObject(gameObject);
Rigidbody ownBody = null;
float ownMass = 100f;
float ownVolume = 1f;
if (origMesh != null)
{
ownBody = GetComponent<Rigidbody>();
if (ownBody != null) ownMass = ownBody.mass;
Vector3 ownMeshSize = origMesh.bounds.size;
ownVolume = ownMeshSize.x * ownMeshSize.y * ownMeshSize.z;
}
GameObject[] newGOs = new GameObject[2];
if (OptionalTargetObject == null)
{
newGOs[0] = Instantiate(gameObject) as GameObject;
newGOs[0].name = gameObject.name;
newGOs[1] = gameObject;
}
else
{
newGOs[0] = Instantiate(OptionalTargetObject) as GameObject;
newGOs[1] = Instantiate(OptionalTargetObject) as GameObject;
}
Animation[] animSources = newGOs[1].GetComponentsInChildren<Animation>();
Animation[] animDests = newGOs[0].GetComponentsInChildren<Animation>();
for (int i = 0; i < animSources.Length; i++)
{
foreach (AnimationState stateSource in animSources[i])
{
AnimationState stateDest = animDests[i][stateSource.name];
stateDest.enabled = stateSource.enabled;
stateDest.weight = stateSource.weight;
stateDest.time = stateSource.time;
stateDest.speed = stateSource.speed;
stateDest.layer = stateSource.layer;
stateDest.blendMode = stateSource.blendMode;
}
}
for (int i = 0; i < 2; i++)
{
UpdateMeshesInChildren(i, newGOs[i]);
Transform newTransform = newGOs[i].GetComponent<Transform>();
newTransform.parent = parent;
Mesh newMesh = GetMeshOnGameObject(newGOs[i]);
if (newMesh != null)
{
MeshCollider newCollider = newGOs[i].GetComponent<MeshCollider>();
if (newCollider != null)
{
newCollider.sharedMesh = newMesh;
newCollider.convex = Convex;
// if hull has less than 255 polygons set convex, Unity limit!
if (newCollider.convex && newMesh.triangles.Length > 765)
newCollider.convex = false;
}
Rigidbody newBody = newGOs[i].GetComponent<Rigidbody>();
if (ownBody != null && newBody != null)
{
Vector3 newMeshSize = newMesh.bounds.size;
float meshVolume = newMeshSize.x * newMeshSize.y * newMeshSize.z;
float newMass = ownMass * (meshVolume / ownVolume);
newBody.useGravity = ownBody.useGravity;
newBody.mass = newMass;
newBody.velocity = ownBody.velocity;
newBody.angularVelocity = ownBody.angularVelocity;
if (SplitForce > 0f) newBody.AddForce(_splitPlane.Normal * newMass * (i == 0 ? SplitForce : -SplitForce), ForceMode.Impulse);
}
}
PostProcessObject(newGOs[i]);
}
}
private void UpdateMeshesInChildren(int i, GameObject go)
{
if (_meshContainerStatic.Length > 0)
{
MeshFilter[] meshFilters = go.GetComponentsInChildren<MeshFilter>();
for (int j = 0; j < _meshContainerStatic.Length; j++)
{
Renderer renderer = meshFilters[j].GetComponent<Renderer>();
if (ForceNoBatching)
{
renderer.materials = renderer.materials;
}
if (i == 0)
{
if (_meshContainerStatic[j].HasMeshUpper() & _meshContainerStatic[j].HasMeshLower())
{
meshFilters[j].mesh = _meshContainerStatic[j].CreateMeshUpper();
}
else if (!_meshContainerStatic[j].HasMeshUpper())
{
if (renderer != null) Destroy(renderer);
Destroy(meshFilters[j]);
}
}
else
{
if (_meshContainerStatic[j].HasMeshUpper() & _meshContainerStatic[j].HasMeshLower())
{
meshFilters[j].mesh = _meshContainerStatic[j].CreateMeshLower();
}
else if (!_meshContainerStatic[j].HasMeshLower())
{
if (renderer != null) Destroy(renderer);
Destroy(meshFilters[j]);
}
}
}
}
if (_meshContainerSkinned.Length > 0)
{
SkinnedMeshRenderer[] skinnedRenderer = go.GetComponentsInChildren<SkinnedMeshRenderer>();
for (int j = 0; j < _meshContainerSkinned.Length; j++)
{
if (i == 0)
{
if (_meshContainerSkinned[j].HasMeshUpper() & _meshContainerSkinned[j].HasMeshLower())
{
skinnedRenderer[j].sharedMesh = _meshContainerSkinned[j].CreateMeshUpper();
}
else if (!_meshContainerSkinned[j].HasMeshUpper())
{
Destroy(skinnedRenderer[j]);
}
}
else
{
if (_meshContainerSkinned[j].HasMeshUpper() & _meshContainerSkinned[j].HasMeshLower())
{
skinnedRenderer[j].sharedMesh = _meshContainerSkinned[j].CreateMeshLower();
}
else if (!_meshContainerSkinned[j].HasMeshLower())
{
Destroy(skinnedRenderer[j]);
}
}
}
}
}
private Material[] GetSharedMaterials(GameObject go)
{
SkinnedMeshRenderer skinnedMeshRenderer = go.GetComponent<SkinnedMeshRenderer>();
if (skinnedMeshRenderer != null)
{
return skinnedMeshRenderer.sharedMaterials;
}
else
{
Renderer renderer = go.GetComponent<Renderer>();
if (renderer != null)
{
return renderer.sharedMaterials;
}
}
return null;
}
private void SetSharedMaterials(GameObject go, Material[] materials)
{
SkinnedMeshRenderer skinnedMeshRenderer = go.GetComponent<SkinnedMeshRenderer>();
if (skinnedMeshRenderer != null)
{
skinnedMeshRenderer.sharedMaterials = materials;
}
else
{
Renderer renderer = go.GetComponent<Renderer>();
if (renderer != null)
{
renderer.sharedMaterials = materials;
}
}
}
private void SetMeshOnGameObject(GameObject go, Mesh mesh)
{
SkinnedMeshRenderer skinnedMeshRenderer = go.GetComponent<SkinnedMeshRenderer>();
if (skinnedMeshRenderer != null)
{
skinnedMeshRenderer.sharedMesh = mesh;
}
else
{
MeshFilter meshFilter = go.GetComponent<MeshFilter>();
if (meshFilter != null)
{
meshFilter.mesh = mesh;
}
}
}
private Mesh GetMeshOnGameObject(GameObject go)
{
SkinnedMeshRenderer skinnedMeshRenderer = go.GetComponent<SkinnedMeshRenderer>();
if (skinnedMeshRenderer != null)
{
return skinnedMeshRenderer.sharedMesh;
}
else
{
MeshFilter meshFilter = go.GetComponent<MeshFilter>();
if (meshFilter != null)
{
return meshFilter.mesh;
}
}
return null;
}
protected virtual void PostProcessObject(GameObject go) { }
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using EncompassRest.Loans.Enums;
using EncompassRest.Utilities;
using Newtonsoft.Json;
namespace EncompassRest.Loans.RateLocks
{
/// <summary>
/// SellSide
/// </summary>
public sealed partial class SellSide : DirtyExtensibleObject
{
private DirtyValue<string?>? _requestedBy;
private DirtyValue<decimal?>? _srp;
private DirtyValue<Investor?>? _investor;
private DirtyValue<string?>? _servicer;
private DirtyValue<decimal?>? _servicingFee;
private DirtyValue<decimal?>? _guarantyBaseFee;
private DirtyValue<decimal?>? _guaranteeFee;
private DirtyValue<string?>? _poolNumber;
private DirtyValue<string?>? _poolId;
private DirtyValue<string?>? _commitmentContractNumber;
private DirtyValue<string?>? _productName;
private DirtyValue<decimal?>? _msrValue;
private DirtyValue<DateTime?>? _commitmentDate;
private DirtyValue<decimal?>? _actualAmount;
private DirtyValue<decimal?>? _actualPrice;
private DirtyValue<decimal?>? _actualSrp;
private DirtyValue<decimal?>? _diffAmount;
private DirtyValue<decimal?>? _diffPrice;
private DirtyValue<decimal?>? _diffSrp;
private DirtyValue<decimal?>? _netAmount;
private DirtyValue<decimal?>? _paidMiPremium;
private DirtyValue<decimal?>? _correspondentEscrowDisbursementsToBePaid;
private DirtyValue<string?>? _tradeMgmtPrevConfirmedLockGuid;
private DirtyValue<string?>? _tradeId;
private DirtyValue<string?>? _tradeNumber;
private DirtyValue<int?>? _daysToExtend;
private DirtyValue<DateTime?>? _extendedLockExpirationDate;
private DirtyValue<decimal?>? _lockExtendPriceAdjustment;
private DirtyValue<StringEnumValue<ServicingType>>? _servicingType;
private DirtyValue<decimal?>? _discountYsp;
private DirtyValue<string?>? _masterContractNumber;
private DirtyValue<decimal?>? _gainLossPercentage;
private DirtyValue<decimal?>? _gainLossPrice;
private DirtyValue<decimal?>? _gainLossTotalPrice;
private DirtyValue<string?>? _rateSheetId;
private DirtyValue<DateTime?>? _lastRateSetDate;
private DirtyValue<int?>? _lockNumberOfDays;
private DirtyValue<DateTime?>? _lockExpirationDate;
private DirtyValue<DateTime?>? _lockDate;
private DirtyValue<decimal?>? _baseRate;
private DirtyList<LockAdjustment>? _adjustments;
private DirtyValue<decimal?>? _netRate;
private DirtyValue<decimal?>? _totalRateAdjustments;
private DirtyValue<decimal?>? _basePrice;
private DirtyValue<decimal?>? _totalPriceAdjustments;
private DirtyValue<decimal?>? _netPrice;
private DirtyValue<decimal?>? _baseMarginRate;
private DirtyValue<decimal?>? _totalMarginAdjustments;
private DirtyValue<decimal?>? _netMarginRate;
private DirtyValue<string?>? _comments;
private DirtyValue<DateTime?>? _originalLockExpirationDate;
private DirtyValue<decimal?>? _srpPaidOut;
private DirtyValue<string?>? _loanProgram;
/// <summary>
/// The individual who entered the sell side lock and pricing information.
/// </summary>
public string? RequestedBy { get => _requestedBy; set => SetField(ref _requestedBy, value); }
/// <summary>
/// Service release premium percentage (SRP) from investor.
/// </summary>
public decimal? Srp { get => _srp; set => SetField(ref _srp, value); }
/// <summary>
/// Array containing information about the investor.
/// </summary>
public Investor? Investor { get => _investor; set => SetField(ref _investor, value); }
/// <summary>
/// Name of the servicer.
/// </summary>
public string? Servicer { get => _servicer; set => SetField(ref _servicer, value); }
/// <summary>
/// Rate lock sell side servicing fee.
/// </summary>
public decimal? ServicingFee { get => _servicingFee; set => SetField(ref _servicingFee, value); }
/// <summary>
/// Rate lock sell side guarantee base fee.
/// </summary>
public decimal? GuarantyBaseFee { get => _guarantyBaseFee; set => SetField(ref _guarantyBaseFee, value); }
/// <summary>
/// Rate lock sell side guarantee fee.
/// </summary>
public decimal? GuaranteeFee { get => _guaranteeFee; set => SetField(ref _guaranteeFee, value); }
/// <summary>
/// The pool number assigned by the investor.
/// </summary>
public string? PoolNumber { get => _poolNumber; set => SetField(ref _poolNumber, value); }
/// <summary>
/// Unique identifier for a group or pool of loans.
/// </summary>
public string? PoolId { get => _poolId; set => SetField(ref _poolId, value); }
/// <summary>
/// The commitment contract number.
/// </summary>
public string? CommitmentContractNumber { get => _commitmentContractNumber; set => SetField(ref _commitmentContractNumber, value); }
/// <summary>
/// Rate lock sell side product name.
/// </summary>
public string? ProductName { get => _productName; set => SetField(ref _productName, value); }
/// <summary>
/// Mortgage servicing rights (MSR) value.
/// </summary>
public decimal? MsrValue { get => _msrValue; set => SetField(ref _msrValue, value); }
/// <summary>
/// Rate lock sell side commitment date.
/// </summary>
[JsonConverter(typeof(ElliDateJsonConverter))]
public DateTime? CommitmentDate { get => _commitmentDate; set => SetField(ref _commitmentDate, value); }
/// <summary>
/// Rate lock sell side actual amount.
/// </summary>
public decimal? ActualAmount { get => _actualAmount; set => SetField(ref _actualAmount, value); }
/// <summary>
/// Rate lock sell side actual price.
/// </summary>
public decimal? ActualPrice { get => _actualPrice; set => SetField(ref _actualPrice, value); }
/// <summary>
/// The service release premium (SRP) from the Sell Side on the Secondary Registration tool.
/// </summary>
public decimal? ActualSrp { get => _actualSrp; set => SetField(ref _actualSrp, value); }
/// <summary>
/// Rate lock sell side different amount.
/// </summary>
public decimal? DiffAmount { get => _diffAmount; set => SetField(ref _diffAmount, value); }
/// <summary>
/// Rate lock sell side different price.
/// </summary>
public decimal? DiffPrice { get => _diffPrice; set => SetField(ref _diffPrice, value); }
/// <summary>
/// Rate lock sell side different SRP.
/// </summary>
public decimal? DiffSrp { get => _diffSrp; set => SetField(ref _diffSrp, value); }
/// <summary>
/// The Base Sell Price plus the Total Price Adjustments.
/// </summary>
public decimal? NetAmount { get => _netAmount; set => SetField(ref _netAmount, value); }
/// <summary>
/// Rate lock sell side paid MI premium.
/// </summary>
public decimal? PaidMiPremium { get => _paidMiPremium; set => SetField(ref _paidMiPremium, value); }
/// <summary>
/// Correspondent escrow disbursements to be paid by the seller.
/// </summary>
public decimal? CorrespondentEscrowDisbursementsToBePaid { get => _correspondentEscrowDisbursementsToBePaid; set => SetField(ref _correspondentEscrowDisbursementsToBePaid, value); }
/// <summary>
/// TradeMgmtPrevConfirmedLockGuid
/// </summary>
public string? TradeMgmtPrevConfirmedLockGuid { get => _tradeMgmtPrevConfirmedLockGuid; set => SetField(ref _tradeMgmtPrevConfirmedLockGuid, value); }
/// <summary>
/// Rate lock sell side trade ID.
/// </summary>
public string? TradeId { get => _tradeId; set => SetField(ref _tradeId, value); }
/// <summary>
/// Rate lock sell side trade number.
/// </summary>
public string? TradeNumber { get => _tradeNumber; set => SetField(ref _tradeNumber, value); }
/// <summary>
/// Sell side number of additional days for the rate lock extension.
/// </summary>
public int? DaysToExtend { get => _daysToExtend; set => SetField(ref _daysToExtend, value); }
/// <summary>
/// Sell side expiration date for the requested rate lock extension.
/// </summary>
[JsonConverter(typeof(ElliDateJsonConverter))]
public DateTime? ExtendedLockExpirationDate { get => _extendedLockExpirationDate; set => SetField(ref _extendedLockExpirationDate, value); }
/// <summary>
/// Sell side price adjustment for the requested rate lock extension.
/// </summary>
public decimal? LockExtendPriceAdjustment { get => _lockExtendPriceAdjustment; set => SetField(ref _lockExtendPriceAdjustment, value); }
/// <summary>
/// Rate lock sell side servicing type.
/// </summary>
public StringEnumValue<ServicingType> ServicingType { get => _servicingType; set => SetField(ref _servicingType, value); }
/// <summary>
/// The discount yield spread premium
/// </summary>
public decimal? DiscountYsp { get => _discountYsp; set => SetField(ref _discountYsp, value); }
/// <summary>
/// The master contract number.
/// </summary>
public string? MasterContractNumber { get => _masterContractNumber; set => SetField(ref _masterContractNumber, value); }
/// <summary>
/// Rate lock sell side gain loss percentage.
/// </summary>
public decimal? GainLossPercentage { get => _gainLossPercentage; set => SetField(ref _gainLossPercentage, value); }
/// <summary>
/// Rate lock sell side gain loss price.
/// </summary>
public decimal? GainLossPrice { get => _gainLossPrice; set => SetField(ref _gainLossPrice, value); }
/// <summary>
/// Rate lock sell side gain loss total price.
/// </summary>
public decimal? GainLossTotalPrice { get => _gainLossTotalPrice; set => SetField(ref _gainLossTotalPrice, value); }
/// <summary>
/// The ID from the investor's rate sheet.
/// </summary>
public string? RateSheetId { get => _rateSheetId; set => SetField(ref _rateSheetId, value); }
/// <summary>
/// Date when the interest rate for the loan was last locked.
/// </summary>
[JsonConverter(typeof(ElliDateJsonConverter))]
public DateTime? LastRateSetDate { get => _lastRateSetDate; set => SetField(ref _lastRateSetDate, value); }
/// <summary>
/// The number of days for the sell side lock.
/// </summary>
public int? LockNumberOfDays { get => _lockNumberOfDays; set => SetField(ref _lockNumberOfDays, value); }
/// <summary>
/// The date the sell side rate lock expires, calculated by adding the value in the # of Days field to the date in the Lock Date field on the Secondary Lock Tool.
/// </summary>
[JsonConverter(typeof(ElliDateJsonConverter))]
public DateTime? LockExpirationDate { get => _lockExpirationDate; set => SetField(ref _lockExpirationDate, value); }
/// <summary>
/// The sell side lock date.
/// </summary>
[JsonConverter(typeof(ElliDateJsonConverter))]
public DateTime? LockDate { get => _lockDate; set => SetField(ref _lockDate, value); }
/// <summary>
/// The base sell side rate (as a percentage) for the lock. The rate is populated from the Sell Side Lock and Pricing column on the Secondary Lock Tool.
/// </summary>
public decimal? BaseRate { get => _baseRate; set => SetField(ref _baseRate, value); }
/// <summary>
/// Object containing attributes that describe sell side rate lock adjustments.
/// </summary>
[AllowNull]
public IList<LockAdjustment> Adjustments { get => GetField(ref _adjustments); set => SetField(ref _adjustments, value); }
/// <summary>
/// The total value of the sell side rate adjustments.
/// </summary>
public decimal? TotalRateAdjustments { get => _totalRateAdjustments; set => SetField(ref _totalRateAdjustments, value); }
/// <summary>
/// The base sell side rate plus the total rate adjustments.
/// </summary>
public decimal? NetRate { get => _netRate; set => SetField(ref _netRate, value); }
/// <summary>
/// The base sell side price for the lock. Enter pricing using 100 as par. Example 1: If the base price is .25 above par, enter 100.25. A loan amount of $100,000 with pricing of 100.25 would result in $100,250 being received. Example 2: If the base price is .25 below par, enter 99.75. A loan amount of $100,000 with pricing of 99.75 would result in $99,750 being received.
/// </summary>
public decimal? BasePrice { get => _basePrice; set => SetField(ref _basePrice, value); }
/// <summary>
/// The total value of the sell side price adjustments.
/// </summary>
public decimal? TotalPriceAdjustments { get => _totalPriceAdjustments; set => SetField(ref _totalPriceAdjustments, value); }
/// <summary>
/// The base sell side price plus the total rate adjustments.
/// </summary>
public decimal? NetPrice { get => _netPrice; set => SetField(ref _netPrice, value); }
/// <summary>
/// The sell side base margin rate.
/// </summary>
public decimal? BaseMarginRate { get => _baseMarginRate; set => SetField(ref _baseMarginRate, value); }
/// <summary>
/// The sell side total margin adjustment.
/// </summary>
public decimal? TotalMarginAdjustments { get => _totalMarginAdjustments; set => SetField(ref _totalMarginAdjustments, value); }
/// <summary>
/// The base sell side net margin rate.
/// </summary>
public decimal? NetMarginRate { get => _netMarginRate; set => SetField(ref _netMarginRate, value); }
/// <summary>
/// Additional notes and comments.
/// </summary>
public string? Comments { get => _comments; set => SetField(ref _comments, value); }
/// <summary>
/// Original lock expiration date.
/// </summary>
[JsonConverter(typeof(ElliDateJsonConverter))]
public DateTime? OriginalLockExpirationDate { get => _originalLockExpirationDate; set => SetField(ref _originalLockExpirationDate, value); }
/// <summary>
/// Service release premium percentage (SRP) paid out.
/// </summary>
public decimal? SrpPaidOut { get => _srpPaidOut; set => SetField(ref _srpPaidOut, value); }
/// <summary>
/// Sell side loan program.
/// </summary>
public string? LoanProgram { get => _loanProgram; set => SetField(ref _loanProgram, value); }
}
}
| |
using Xunit;
namespace Jint.Tests.Ecma
{
public class Test_15_12_3 : EcmaTest
{
[Fact]
[Trait("Category", "15.12.3")]
public void TheNameJsonMustBeBoundToAnObjectSection15SaysThatEveryBuiltInFunctionObjectDescribedInThisSectionWhetherAsAConstructorAnOrdinaryFunctionOrBothHasALengthPropertyWhoseValueIsAnIntegerUnlessOtherwiseSpecifiedThisValueIsEqualToTheLargestNumberOfNamedArgumentsShownInTheSectionHeadingsForTheFunctionDescriptionIncludingOptionalParametersThisDefaultAppliesToJsonStringifyAndItMustExistAsAFunctionTaking3Parameters()
{
RunTest(@"TestCases/ch15/15.12/15.12.3/15.12.3-0-1.js", false);
}
[Fact]
[Trait("Category", "15.12.3")]
public void TheNameJsonMustBeBoundToAnObjectSection15SaysThatEveryBuiltInFunctionObjectDescribedInThisSectionWhetherAsAConstructorAnOrdinaryFunctionOrBothHasALengthPropertyWhoseValueIsAnIntegerUnlessOtherwiseSpecifiedThisValueIsEqualToTheLargestNumberOfNamedArgumentsShownInTheSectionHeadingsForTheFunctionDescriptionIncludingOptionalParametersThisDefaultAppliesToJsonStringifyAndItMustExistAsAFunctionTaking3Parameters2()
{
RunTest(@"TestCases/ch15/15.12/15.12.3/15.12.3-0-2.js", false);
}
[Fact]
[Trait("Category", "15.12.3")]
public void ThisTestShouldBeRunWithoutAnyBuiltInsBeingAddedAugmentedTheInitialValueOfConfigurableOnJsonIsTrueThisMeansWeShouldBeAbleToDelete8625TheStringifyAndParseProperties()
{
RunTest(@"TestCases/ch15/15.12/15.12.3/15.12.3-0-3.js", false);
}
[Fact]
[Trait("Category", "15.12.3")]
public void JsonStringifyUndefinedReturnsUndefined()
{
RunTest(@"TestCases/ch15/15.12/15.12.3/15.12.3-11-1.js", false);
}
[Fact]
[Trait("Category", "15.12.3")]
public void AJsonStringifyReplacerFunctionAppliedToATopLevelScalarValueCanReturnUndefined()
{
RunTest(@"TestCases/ch15/15.12/15.12.3/15.12.3-11-10.js", false);
}
[Fact]
[Trait("Category", "15.12.3")]
public void AJsonStringifyReplacerFunctionAppliedToATopLevelObjectCanReturnUndefined()
{
RunTest(@"TestCases/ch15/15.12/15.12.3/15.12.3-11-11.js", false);
}
[Fact]
[Trait("Category", "15.12.3")]
public void AJsonStringifyReplacerFunctionAppliedToATopLevelScalarCanReturnAnArray()
{
RunTest(@"TestCases/ch15/15.12/15.12.3/15.12.3-11-12.js", false);
}
[Fact]
[Trait("Category", "15.12.3")]
public void AJsonStringifyReplacerFunctionAppliedToATopLevelScalarCanReturnAnObject()
{
RunTest(@"TestCases/ch15/15.12/15.12.3/15.12.3-11-13.js", false);
}
[Fact]
[Trait("Category", "15.12.3")]
public void ApplyingJsonStringifyToAFunctionReturnsUndefined()
{
RunTest(@"TestCases/ch15/15.12/15.12.3/15.12.3-11-14.js", false);
}
[Fact]
[Trait("Category", "15.12.3")]
public void ApplyingJsonStringifyWithAReplacerFunctionToAFunctionReturnsTheReplacerValue()
{
RunTest(@"TestCases/ch15/15.12/15.12.3/15.12.3-11-15.js", false);
}
[Fact]
[Trait("Category", "15.12.3")]
public void JsonStringifyStringifyingAnObjectWherePropertyNameIsTheUnionOfAllNullCharacterTheAbstractOperationQuoteValueStep2C()
{
RunTest(@"TestCases/ch15/15.12/15.12.3/15.12.3-11-16.js", false);
}
[Fact]
[Trait("Category", "15.12.3")]
public void JsonStringifyStringifyingAnObjectWherePropertyNameStartsWithTheUnionOfAllNullCharacterTheAbstractOperationQuoteValueStep2C()
{
RunTest(@"TestCases/ch15/15.12/15.12.3/15.12.3-11-17.js", false);
}
[Fact]
[Trait("Category", "15.12.3")]
public void JsonStringifyStringifyingAnObjectWherePropertyNameEndsWithTheUnionOfAllNullCharacterTheAbstractOperationQuoteValueStep2C()
{
RunTest(@"TestCases/ch15/15.12/15.12.3/15.12.3-11-18.js", false);
}
[Fact]
[Trait("Category", "15.12.3")]
public void JsonStringifyStringifyingAnObjectWherePropertyNameStartsAndEndsWithTheUnionOfAllNullCharacterTheAbstractOperationQuoteValueStep2C()
{
RunTest(@"TestCases/ch15/15.12/15.12.3/15.12.3-11-19.js", false);
}
[Fact]
[Trait("Category", "15.12.3")]
public void AJsonStringifyReplacerFunctionWorksIsAppliedToATopLevelUndefinedValue()
{
RunTest(@"TestCases/ch15/15.12/15.12.3/15.12.3-11-2.js", false);
}
[Fact]
[Trait("Category", "15.12.3")]
public void JsonStringifyStringifyingAnObjectWherePropertyNameMiddlesWithTheUnionOfAllNullCharacterTheAbstractOperationQuoteValueStep2C()
{
RunTest(@"TestCases/ch15/15.12/15.12.3/15.12.3-11-20.js", false);
}
[Fact]
[Trait("Category", "15.12.3")]
public void JsonStringifyStringifyingAnObjectWherePropertyValueIsTheUnionOfAllNullCharacterTheAbstractOperationQuoteValueStep2C()
{
RunTest(@"TestCases/ch15/15.12/15.12.3/15.12.3-11-21.js", false);
}
[Fact]
[Trait("Category", "15.12.3")]
public void JsonStringifyStringifyingAnObjectWherePropertyValueStartsWithTheUnionOfAllNullCharacterTheAbstractOperationQuoteValueStep2C()
{
RunTest(@"TestCases/ch15/15.12/15.12.3/15.12.3-11-22.js", false);
}
[Fact]
[Trait("Category", "15.12.3")]
public void JsonStringifyStringifyingAnObjectWherePropertyValueEndsWithTheUnionOfAllNullCharacterTheAbstractOperationQuoteValueStep2C()
{
RunTest(@"TestCases/ch15/15.12/15.12.3/15.12.3-11-23.js", false);
}
[Fact]
[Trait("Category", "15.12.3")]
public void JsonStringifyStringifyingAnObjectWherePropertyValueStartsAndEndsWithTheUnionOfAllNullCharacterTheAbstractOperationQuoteValueStep2C()
{
RunTest(@"TestCases/ch15/15.12/15.12.3/15.12.3-11-24.js", false);
}
[Fact]
[Trait("Category", "15.12.3")]
public void JsonStringifyStringifyingAnObjectWherePropertyValueMiddlesWithTheUnionOfAllNullCharacterTheAbstractOperationQuoteValueStep2C()
{
RunTest(@"TestCases/ch15/15.12/15.12.3/15.12.3-11-25.js", false);
}
[Fact]
[Trait("Category", "15.12.3")]
public void JsonStringifyTheLastElementOfTheConcatenationIsTheAbstractOperationJaValueStep10BIii()
{
RunTest(@"TestCases/ch15/15.12/15.12.3/15.12.3-11-26.js", false);
}
[Fact]
[Trait("Category", "15.12.3")]
public void AJsonStringifyCorrectlyWorksOnTopLevelStringValues()
{
RunTest(@"TestCases/ch15/15.12/15.12.3/15.12.3-11-3.js", false);
}
[Fact]
[Trait("Category", "15.12.3")]
public void JsonStringifyCorrectlyWorksOnTopLevelNumberValues()
{
RunTest(@"TestCases/ch15/15.12/15.12.3/15.12.3-11-4.js", false);
}
[Fact]
[Trait("Category", "15.12.3")]
public void JsonStringifyCorrectlyWorksOnTopLevelBooleanValues()
{
RunTest(@"TestCases/ch15/15.12/15.12.3/15.12.3-11-5.js", false);
}
[Fact]
[Trait("Category", "15.12.3")]
public void JsonStringifyCorrectlyWorksOnTopLevelNullValues()
{
RunTest(@"TestCases/ch15/15.12/15.12.3/15.12.3-11-6.js", false);
}
[Fact]
[Trait("Category", "15.12.3")]
public void JsonStringifyCorrectlyWorksOnTopLevelNumberObjects()
{
RunTest(@"TestCases/ch15/15.12/15.12.3/15.12.3-11-7.js", false);
}
[Fact]
[Trait("Category", "15.12.3")]
public void JsonStringifyCorrectlyWorksOnTopLevelStringObjects()
{
RunTest(@"TestCases/ch15/15.12/15.12.3/15.12.3-11-8.js", false);
}
[Fact]
[Trait("Category", "15.12.3")]
public void JsonStringifyCorrectlyWorksOnTopLevelBooleanObjects()
{
RunTest(@"TestCases/ch15/15.12/15.12.3/15.12.3-11-9.js", false);
}
[Fact]
[Trait("Category", "15.12.3")]
public void JsonStringifyIgnoresReplacerArugumentsThatAreNotFunctionsOrArrays()
{
RunTest(@"TestCases/ch15/15.12/15.12.3/15.12.3-4-1.js", false);
}
[Fact]
[Trait("Category", "15.12.3")]
public void JsonStringifyConvertsNumberWrapperObjectSpaceArugumentsToNumberValues()
{
RunTest(@"TestCases/ch15/15.12/15.12.3/15.12.3-5-a-i-1.js", false);
}
[Fact]
[Trait("Category", "15.12.3")]
public void JsonStringifyConvertsStringWrapperObjectSpaceArugumentsToStringValues()
{
RunTest(@"TestCases/ch15/15.12/15.12.3/15.12.3-5-b-i-1.js", false);
}
[Fact]
[Trait("Category", "15.12.3")]
public void JsonStringifyTreatsNumericSpaceArgumentsGreaterThan10TheSameAsASpaceArgumentOf10()
{
RunTest(@"TestCases/ch15/15.12/15.12.3/15.12.3-6-a-1.js", false);
}
[Fact]
[Trait("Category", "15.12.3")]
public void JsonStringifyTruccatesNonIntegerNumericSpaceArgumentsToTheirIntegerPart()
{
RunTest(@"TestCases/ch15/15.12/15.12.3/15.12.3-6-a-2.js", false);
}
[Fact]
[Trait("Category", "15.12.3")]
public void JsonStringifyTreatsNumericSpaceArgumentsLessThan10999999TheSameAsEmptryStringSpaceArgument()
{
RunTest(@"TestCases/ch15/15.12/15.12.3/15.12.3-6-b-1.js", false);
}
[Fact]
[Trait("Category", "15.12.3")]
public void JsonStringifyTreatsNumericSpaceArgumentsLessThan10TheSameAsEmptryStringSpaceArgument()
{
RunTest(@"TestCases/ch15/15.12/15.12.3/15.12.3-6-b-2.js", false);
}
[Fact]
[Trait("Category", "15.12.3")]
public void JsonStringifyTreatsNumericSpaceArgumentsLessThan15TheSameAsEmptryStringSpaceArgument()
{
RunTest(@"TestCases/ch15/15.12/15.12.3/15.12.3-6-b-3.js", false);
}
[Fact]
[Trait("Category", "15.12.3")]
public void JsonStringifyTreatsNumericSpaceArgumentsInTheRange110IsEquivalentToAStringOfSpacesOfThatLength()
{
RunTest(@"TestCases/ch15/15.12/15.12.3/15.12.3-6-b-4.js", false);
}
[Fact]
[Trait("Category", "15.12.3")]
public void JsonStringifyOnlyUsesTheFirst10CharactersOfAStringSpaceArguments()
{
RunTest(@"TestCases/ch15/15.12/15.12.3/15.12.3-7-a-1.js", false);
}
[Fact]
[Trait("Category", "15.12.3")]
public void JsonStringifyTreatsAnEmptyStringSpaceArgumentTheSameAsAMissingSpaceArgument()
{
RunTest(@"TestCases/ch15/15.12/15.12.3/15.12.3-8-a-1.js", false);
}
[Fact]
[Trait("Category", "15.12.3")]
public void JsonStringifyTreatsAnBooleanSpaceArgumentTheSameAsAMissingSpaceArgument()
{
RunTest(@"TestCases/ch15/15.12/15.12.3/15.12.3-8-a-2.js", false);
}
[Fact]
[Trait("Category", "15.12.3")]
public void JsonStringifyTreatsAnNullSpaceArgumentTheSameAsAMissingSpaceArgument()
{
RunTest(@"TestCases/ch15/15.12/15.12.3/15.12.3-8-a-3.js", false);
}
[Fact]
[Trait("Category", "15.12.3")]
public void JsonStringifyTreatsAnBooleanWrapperSpaceArgumentTheSameAsAMissingSpaceArgument()
{
RunTest(@"TestCases/ch15/15.12/15.12.3/15.12.3-8-a-4.js", false);
}
[Fact]
[Trait("Category", "15.12.3")]
public void JsonStringifyTreatsNonNumberOrStringObjectSpaceArgumentsTheSameAsAMissingSpaceArgument()
{
RunTest(@"TestCases/ch15/15.12/15.12.3/15.12.3-8-a-5.js", false);
}
[Fact]
[Trait("Category", "15.12.3")]
public void JsonStringifyConvertsStringWrapperObjectsReturnedFromATojsonCallToLiteralStrings()
{
RunTest(@"TestCases/ch15/15.12/15.12.3/15.12.3_2-2-b-i-1.js", false);
}
[Fact]
[Trait("Category", "15.12.3")]
public void JsonStringifyConvertsNumberWrapperObjectsReturnedFromATojsonCallToLiteralNumber()
{
RunTest(@"TestCases/ch15/15.12/15.12.3/15.12.3_2-2-b-i-2.js", false);
}
[Fact]
[Trait("Category", "15.12.3")]
public void JsonStringifyConvertsBooleanWrapperObjectsReturnedFromATojsonCallToLiteralBooleanValues()
{
RunTest(@"TestCases/ch15/15.12/15.12.3/15.12.3_2-2-b-i-3.js", false);
}
[Fact]
[Trait("Category", "15.12.3")]
public void JsonStringifyConvertsStringWrapperObjectsReturnedFromReplacerFunctionsToLiteralStrings()
{
RunTest(@"TestCases/ch15/15.12/15.12.3/15.12.3_2-3-a-1.js", false);
}
[Fact]
[Trait("Category", "15.12.3")]
public void JsonStringifyConvertsNumberWrapperObjectsReturnedFromReplacerFunctionsToLiteralNumbers()
{
RunTest(@"TestCases/ch15/15.12/15.12.3/15.12.3_2-3-a-2.js", false);
}
[Fact]
[Trait("Category", "15.12.3")]
public void JsonStringifyConvertsBooleanWrapperObjectsReturnedFromReplacerFunctionsToLiteralNumbers()
{
RunTest(@"TestCases/ch15/15.12/15.12.3/15.12.3_2-3-a-3.js", false);
}
[Fact]
[Trait("Category", "15.12.3")]
public void JsonStringifyACircularObjectThrowsAError()
{
RunTest(@"TestCases/ch15/15.12/15.12.3/15.12.3_4-1-1.js", false);
}
[Fact]
[Trait("Category", "15.12.3")]
public void JsonStringifyACircularObjectThrowsATypeerror()
{
RunTest(@"TestCases/ch15/15.12/15.12.3/15.12.3_4-1-2.js", false);
}
[Fact]
[Trait("Category", "15.12.3")]
public void JsonStringifyAIndirectlyCircularObjectThrowsAError()
{
RunTest(@"TestCases/ch15/15.12/15.12.3/15.12.3_4-1-3.js", false);
}
}
}
| |
/* Generated SBE (Simple Binary Encoding) message codec */
using System;
using System.Text;
using System.Collections.Generic;
using Adaptive.Agrona;
namespace Adaptive.Archiver.Codecs {
public class RecordingPositionRequestDecoder
{
public const ushort BLOCK_LENGTH = 24;
public const ushort TEMPLATE_ID = 12;
public const ushort SCHEMA_ID = 101;
public const ushort SCHEMA_VERSION = 6;
private RecordingPositionRequestDecoder _parentMessage;
private IDirectBuffer _buffer;
protected int _offset;
protected int _limit;
protected int _actingBlockLength;
protected int _actingVersion;
public RecordingPositionRequestDecoder()
{
_parentMessage = this;
}
public ushort SbeBlockLength()
{
return BLOCK_LENGTH;
}
public ushort SbeTemplateId()
{
return TEMPLATE_ID;
}
public ushort SbeSchemaId()
{
return SCHEMA_ID;
}
public ushort SbeSchemaVersion()
{
return SCHEMA_VERSION;
}
public string SbeSemanticType()
{
return "";
}
public IDirectBuffer Buffer()
{
return _buffer;
}
public int Offset()
{
return _offset;
}
public RecordingPositionRequestDecoder Wrap(
IDirectBuffer buffer, int offset, int actingBlockLength, int actingVersion)
{
this._buffer = buffer;
this._offset = offset;
this._actingBlockLength = actingBlockLength;
this._actingVersion = actingVersion;
Limit(offset + actingBlockLength);
return this;
}
public int EncodedLength()
{
return _limit - _offset;
}
public int Limit()
{
return _limit;
}
public void Limit(int limit)
{
this._limit = limit;
}
public static int ControlSessionIdId()
{
return 1;
}
public static int ControlSessionIdSinceVersion()
{
return 0;
}
public static int ControlSessionIdEncodingOffset()
{
return 0;
}
public static int ControlSessionIdEncodingLength()
{
return 8;
}
public static string ControlSessionIdMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static long ControlSessionIdNullValue()
{
return -9223372036854775808L;
}
public static long ControlSessionIdMinValue()
{
return -9223372036854775807L;
}
public static long ControlSessionIdMaxValue()
{
return 9223372036854775807L;
}
public long ControlSessionId()
{
return _buffer.GetLong(_offset + 0, ByteOrder.LittleEndian);
}
public static int CorrelationIdId()
{
return 2;
}
public static int CorrelationIdSinceVersion()
{
return 0;
}
public static int CorrelationIdEncodingOffset()
{
return 8;
}
public static int CorrelationIdEncodingLength()
{
return 8;
}
public static string CorrelationIdMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static long CorrelationIdNullValue()
{
return -9223372036854775808L;
}
public static long CorrelationIdMinValue()
{
return -9223372036854775807L;
}
public static long CorrelationIdMaxValue()
{
return 9223372036854775807L;
}
public long CorrelationId()
{
return _buffer.GetLong(_offset + 8, ByteOrder.LittleEndian);
}
public static int RecordingIdId()
{
return 3;
}
public static int RecordingIdSinceVersion()
{
return 0;
}
public static int RecordingIdEncodingOffset()
{
return 16;
}
public static int RecordingIdEncodingLength()
{
return 8;
}
public static string RecordingIdMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static long RecordingIdNullValue()
{
return -9223372036854775808L;
}
public static long RecordingIdMinValue()
{
return -9223372036854775807L;
}
public static long RecordingIdMaxValue()
{
return 9223372036854775807L;
}
public long RecordingId()
{
return _buffer.GetLong(_offset + 16, ByteOrder.LittleEndian);
}
public override string ToString()
{
return AppendTo(new StringBuilder(100)).ToString();
}
public StringBuilder AppendTo(StringBuilder builder)
{
int originalLimit = Limit();
Limit(_offset + _actingBlockLength);
builder.Append("[RecordingPositionRequest](sbeTemplateId=");
builder.Append(TEMPLATE_ID);
builder.Append("|sbeSchemaId=");
builder.Append(SCHEMA_ID);
builder.Append("|sbeSchemaVersion=");
if (_parentMessage._actingVersion != SCHEMA_VERSION)
{
builder.Append(_parentMessage._actingVersion);
builder.Append('/');
}
builder.Append(SCHEMA_VERSION);
builder.Append("|sbeBlockLength=");
if (_actingBlockLength != BLOCK_LENGTH)
{
builder.Append(_actingBlockLength);
builder.Append('/');
}
builder.Append(BLOCK_LENGTH);
builder.Append("):");
//Token{signal=BEGIN_FIELD, name='controlSessionId', referencedName='null', description='null', id=1, version=0, deprecated=0, encodedLength=0, offset=0, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=0, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("ControlSessionId=");
builder.Append(ControlSessionId());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='correlationId', referencedName='null', description='null', id=2, version=0, deprecated=0, encodedLength=0, offset=8, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=8, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("CorrelationId=");
builder.Append(CorrelationId());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='recordingId', referencedName='null', description='null', id=3, version=0, deprecated=0, encodedLength=0, offset=16, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=16, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("RecordingId=");
builder.Append(RecordingId());
Limit(originalLimit);
return builder;
}
}
}
| |
using System.Globalization;
using System.Collections.Generic;
using NServiceKit.Common;
using NServiceKit.Common.Web;
using NServiceKit.ServiceHost;
using NServiceKit.Configuration;
using NServiceKit.FluentValidation;
namespace NServiceKit.ServiceInterface.Auth
{
/// <summary>The credentials authentication provider.</summary>
public class CredentialsAuthProvider : AuthProvider
{
class CredentialsAuthValidator : AbstractValidator<Auth>
{
/// <summary>Initializes a new instance of the NServiceKit.ServiceInterface.Auth.CredentialsAuthProvider.CredentialsAuthValidator class.</summary>
public CredentialsAuthValidator()
{
RuleFor(x => x.UserName).NotEmpty();
RuleFor(x => x.Password).NotEmpty();
}
}
/// <summary>The name.</summary>
public static string Name = AuthService.CredentialsProvider;
/// <summary>The realm.</summary>
public static string Realm = "/auth/" + AuthService.CredentialsProvider;
/// <summary>Initializes a new instance of the NServiceKit.ServiceInterface.Auth.CredentialsAuthProvider class.</summary>
public CredentialsAuthProvider()
{
this.Provider = Name;
this.AuthRealm = Realm;
}
/// <summary>Initializes a new instance of the NServiceKit.ServiceInterface.Auth.CredentialsAuthProvider class.</summary>
///
/// <param name="appSettings"> The application settings.</param>
/// <param name="authRealm"> The authentication realm.</param>
/// <param name="oAuthProvider">The authentication provider.</param>
public CredentialsAuthProvider(IResourceManager appSettings, string authRealm, string oAuthProvider)
: base(appSettings, authRealm, oAuthProvider) { }
/// <summary>Initializes a new instance of the NServiceKit.ServiceInterface.Auth.CredentialsAuthProvider class.</summary>
///
/// <param name="appSettings">The application settings.</param>
public CredentialsAuthProvider(IResourceManager appSettings)
: base(appSettings, Realm, Name) { }
/// <summary>Attempts to authenticate from the given data.</summary>
///
/// <param name="authService">The authentication service.</param>
/// <param name="userName"> Name of the user.</param>
/// <param name="password"> The password.</param>
///
/// <returns>true if it succeeds, false if it fails.</returns>
public virtual bool TryAuthenticate(IServiceBase authService, string userName, string password)
{
var authRepo = authService.TryResolve<IUserAuthRepository>();
if (authRepo == null)
{
Log.WarnFormat("Tried to authenticate without a registered IUserAuthRepository");
return false;
}
var session = authService.GetSession();
UserAuth userAuth = null;
if (authRepo.TryAuthenticate(userName, password, out userAuth))
{
session.PopulateWith(userAuth);
session.IsAuthenticated = true;
session.UserAuthId = userAuth.Id.ToString(CultureInfo.InvariantCulture);
session.ProviderOAuthAccess = authRepo.GetUserOAuthProviders(session.UserAuthId)
.ConvertAll(x => (IOAuthTokens)x);
return true;
}
return false;
}
/// <summary>Determine if the current session is already authenticated with this AuthProvider.</summary>
///
/// <param name="session">The session.</param>
/// <param name="tokens"> The tokens.</param>
/// <param name="request">The request.</param>
///
/// <returns>true if authorized, false if not.</returns>
public override bool IsAuthorized(IAuthSession session, IOAuthTokens tokens, Auth request=null)
{
if (request != null)
{
if (!LoginMatchesSession(session, request.UserName)) return false;
}
return !session.UserAuthName.IsNullOrEmpty();
}
/// <summary>The entry point for all AuthProvider providers. Runs inside the AuthService so exceptions are treated normally. Overridable so you can provide your own Auth implementation.</summary>
///
/// <param name="authService">The authentication service.</param>
/// <param name="session"> The session.</param>
/// <param name="request"> The request.</param>
///
/// <returns>An object.</returns>
public override object Authenticate(IServiceBase authService, IAuthSession session, Auth request)
{
new CredentialsAuthValidator().ValidateAndThrow(request);
return Authenticate(authService, session, request.UserName, request.Password, request.Continue);
}
/// <summary>Authenticates.</summary>
///
/// <param name="authService">The authentication service.</param>
/// <param name="session"> The session.</param>
/// <param name="userName"> Name of the user.</param>
/// <param name="password"> The password.</param>
///
/// <returns>An object.</returns>
protected object Authenticate(IServiceBase authService, IAuthSession session, string userName, string password)
{
return Authenticate(authService, session, userName, password, string.Empty);
}
/// <summary>Authenticates.</summary>
///
/// <exception cref="Unauthorized">Thrown when an unauthorized error condition occurs.</exception>
///
/// <param name="authService">The authentication service.</param>
/// <param name="session"> The session.</param>
/// <param name="userName"> Name of the user.</param>
/// <param name="password"> The password.</param>
/// <param name="referrerUrl">URL of the referrer.</param>
///
/// <returns>An object.</returns>
protected object Authenticate(IServiceBase authService, IAuthSession session, string userName, string password, string referrerUrl)
{
if (!LoginMatchesSession(session, userName))
{
authService.RemoveSession();
session = authService.GetSession();
}
if (TryAuthenticate(authService, userName, password))
{
if (session.UserAuthName == null)
session.UserAuthName = userName;
OnAuthenticated(authService, session, null, null);
return new AuthResponse {
UserName = userName,
SessionId = session.Id,
ReferrerUrl = referrerUrl
};
}
throw HttpError.Unauthorized("Invalid UserName or Password");
}
/// <summary>Executes the authenticated action.</summary>
///
/// <param name="authService">The authentication service.</param>
/// <param name="session"> The session.</param>
/// <param name="tokens"> The tokens.</param>
/// <param name="authInfo"> Information describing the authentication.</param>
public override void OnAuthenticated(IServiceBase authService, IAuthSession session, IOAuthTokens tokens, Dictionary<string, string> authInfo)
{
var userSession = session as AuthUserSession;
if (userSession != null)
{
LoadUserAuthInfo(userSession, tokens, authInfo);
}
var authRepo = authService.TryResolve<IUserAuthRepository>();
if (authRepo != null)
{
if (tokens != null)
{
authInfo.ForEach((x, y) => tokens.Items[x] = y);
session.UserAuthId = authRepo.CreateOrMergeAuthSession(session, tokens);
}
foreach (var oAuthToken in session.ProviderOAuthAccess)
{
var authProvider = AuthService.GetAuthProvider(oAuthToken.Provider);
if (authProvider == null) continue;
var userAuthProvider = authProvider as OAuthProvider;
if (userAuthProvider != null)
{
userAuthProvider.LoadUserOAuthProvider(session, oAuthToken);
}
}
var httpRes = authService.RequestContext.Get<IHttpResponse>();
if (httpRes != null)
{
httpRes.Cookies.AddPermanentCookie(HttpHeaders.XUserAuthId, session.UserAuthId);
}
}
authService.SaveSession(session, SessionExpiry);
session.OnAuthenticated(authService, session, tokens, authInfo);
}
}
}
| |
// This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
// It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
using UnityEngine;
namespace Fungus
{
/// <summary>
/// Supported display operations for Stage.
/// </summary>
public enum StageDisplayType
{
/// <summary> No operation </summary>
None,
/// <summary> Show the stage and all portraits. </summary>
Show,
/// <summary> Hide the stage and all portraits. </summary>
Hide,
/// <summary> Swap the stage and all portraits with another stage. </summary>
Swap,
/// <summary> Move stage to the front. </summary>
MoveToFront,
/// <summary> Undim all portraits on the stage. </summary>
UndimAllPortraits,
/// <summary> Dim all non-speaking portraits on the stage. </summary>
DimNonSpeakingPortraits
}
/// <summary>
/// Controls the stage on which character portraits are displayed.
/// </summary>
[CommandInfo("Narrative",
"Control Stage",
"Controls the stage on which character portraits are displayed.")]
public class ControlStage : ControlWithDisplay<StageDisplayType>
{
[Tooltip("Stage to display characters on")]
[SerializeField] protected Stage stage;
public virtual Stage _Stage { get { return stage; } }
[Tooltip("Stage to swap with")]
[SerializeField] protected Stage replacedStage;
[Tooltip("Use Default Settings")]
[SerializeField] protected bool useDefaultSettings = true;
public virtual bool UseDefaultSettings { get { return useDefaultSettings; } }
[Tooltip("Fade Duration")]
[SerializeField] protected float fadeDuration;
[Tooltip("Wait until the tween has finished before executing the next command")]
[SerializeField] protected bool waitUntilFinished = false;
protected virtual void Show(Stage stage, bool visible)
{
float duration = (fadeDuration == 0) ? float.Epsilon : fadeDuration;
float targetAlpha = visible ? 1f : 0f;
CanvasGroup canvasGroup = stage.GetComponentInChildren<CanvasGroup>();
if (canvasGroup == null)
{
Continue();
return;
}
LeanTween.value(canvasGroup.gameObject, canvasGroup.alpha, targetAlpha, duration).setOnUpdate( (float alpha) => {
canvasGroup.alpha = alpha;
}).setOnComplete( () => {
OnComplete();
});
}
protected virtual void MoveToFront(Stage stage)
{
var activeStages = Stage.ActiveStages;
for (int i = 0; i < activeStages.Count; i++)
{
var s = activeStages[i];
if (s == stage)
{
s.PortraitCanvas.sortingOrder = 1;
}
else
{
s.PortraitCanvas.sortingOrder = 0;
}
}
}
protected virtual void UndimAllPortraits(Stage stage)
{
stage.DimPortraits = false;
var charactersOnStage = stage.CharactersOnStage;
for (int i = 0; i < charactersOnStage.Count; i++)
{
var character = charactersOnStage[i];
stage.SetDimmed(character, false);
}
}
protected virtual void DimNonSpeakingPortraits(Stage stage)
{
stage.DimPortraits = true;
}
protected virtual void OnComplete()
{
if (waitUntilFinished)
{
Continue();
}
}
#region Public members
public override void OnEnter()
{
// If no display specified, do nothing
if (IsDisplayNone(display))
{
Continue();
return;
}
// Selected "use default Portrait Stage"
if (stage == null)
{
// If no default specified, try to get any portrait stage in the scene
stage = FindObjectOfType<Stage>();
// If portrait stage does not exist, do nothing
if (stage == null)
{
Continue();
return;
}
}
// Selected "use default Portrait Stage"
if (display == StageDisplayType.Swap) // Default portrait stage selected
{
if (replacedStage == null) // If no default specified, try to get any portrait stage in the scene
{
replacedStage = GameObject.FindObjectOfType<Stage>();
}
// If portrait stage does not exist, do nothing
if (replacedStage == null)
{
Continue();
return;
}
}
// Use default settings
if (useDefaultSettings)
{
fadeDuration = stage.FadeDuration;
}
switch(display)
{
case (StageDisplayType.Show):
Show(stage, true);
break;
case (StageDisplayType.Hide):
Show(stage, false);
break;
case (StageDisplayType.Swap):
Show(stage, true);
Show(replacedStage, false);
break;
case (StageDisplayType.MoveToFront):
MoveToFront(stage);
break;
case (StageDisplayType.UndimAllPortraits):
UndimAllPortraits(stage);
break;
case (StageDisplayType.DimNonSpeakingPortraits):
DimNonSpeakingPortraits(stage);
break;
}
if (!waitUntilFinished)
{
Continue();
}
}
public override string GetSummary()
{
string displaySummary = "";
if (display != StageDisplayType.None)
{
displaySummary = StringFormatter.SplitCamelCase(display.ToString());
}
else
{
return "Error: No display selected";
}
string stageSummary = "";
if (stage != null)
{
stageSummary = " \"" + stage.name + "\"";
}
return displaySummary + stageSummary;
}
public override Color GetButtonColor()
{
return new Color32(230, 200, 250, 255);
}
public override void OnCommandAdded(Block parentBlock)
{
//Default to display type: show
display = StageDisplayType.Show;
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// DistinctQueryOperator.cs
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
namespace System.Linq.Parallel
{
/// <summary>
/// This operator yields all of the distinct elements in a single data set. It works quite
/// like the above set operations, with the obvious difference being that it only accepts
/// a single data source as input.
/// </summary>
/// <typeparam name="TInputOutput"></typeparam>
internal sealed class DistinctQueryOperator<TInputOutput> : UnaryQueryOperator<TInputOutput, TInputOutput>
{
private readonly IEqualityComparer<TInputOutput> _comparer; // An (optional) equality comparer.
//---------------------------------------------------------------------------------------
// Constructs a new distinction operator.
//
internal DistinctQueryOperator(IEnumerable<TInputOutput> source, IEqualityComparer<TInputOutput> comparer)
: base(source)
{
Debug.Assert(source != null, "child data source cannot be null");
_comparer = comparer;
SetOrdinalIndexState(OrdinalIndexState.Shuffled);
}
//---------------------------------------------------------------------------------------
// Just opens the current operator, including opening the child and wrapping it with
// partitions as needed.
//
internal override QueryResults<TInputOutput> Open(QuerySettings settings, bool preferStriping)
{
// We just open our child operator. Do not propagate the preferStriping value, but
// instead explicitly set it to false. Regardless of whether the parent prefers striping or range
// partitioning, the output will be hash-partitioned.
QueryResults<TInputOutput> childResults = Child.Open(settings, false);
return new UnaryQueryOperatorResults(childResults, this, settings, false);
}
internal override void WrapPartitionedStream<TKey>(
PartitionedStream<TInputOutput, TKey> inputStream, IPartitionedStreamRecipient<TInputOutput> recipient, bool preferStriping, QuerySettings settings)
{
// Hash-repartition the source stream
if (OutputOrdered)
{
WrapPartitionedStreamHelper<TKey>(
ExchangeUtilities.HashRepartitionOrdered<TInputOutput, NoKeyMemoizationRequired, TKey>(
inputStream, null, null, _comparer, settings.CancellationState.MergedCancellationToken),
recipient, settings.CancellationState.MergedCancellationToken);
}
else
{
WrapPartitionedStreamHelper<int>(
ExchangeUtilities.HashRepartition<TInputOutput, NoKeyMemoizationRequired, TKey>(
inputStream, null, null, _comparer, settings.CancellationState.MergedCancellationToken),
recipient, settings.CancellationState.MergedCancellationToken);
}
}
//---------------------------------------------------------------------------------------
// This is a helper method. WrapPartitionedStream decides what type TKey is going
// to be, and then call this method with that key as a generic parameter.
//
private void WrapPartitionedStreamHelper<TKey>(
PartitionedStream<Pair, TKey> hashStream,
IPartitionedStreamRecipient<TInputOutput> recipient, CancellationToken cancellationToken)
{
int partitionCount = hashStream.PartitionCount;
PartitionedStream<TInputOutput, TKey> outputStream =
new PartitionedStream<TInputOutput, TKey>(partitionCount, hashStream.KeyComparer, OrdinalIndexState.Shuffled);
for (int i = 0; i < partitionCount; i++)
{
if (OutputOrdered)
{
outputStream[i] =
new OrderedDistinctQueryOperatorEnumerator<TKey>(hashStream[i], _comparer, hashStream.KeyComparer, cancellationToken);
}
else
{
outputStream[i] = (QueryOperatorEnumerator<TInputOutput, TKey>)(object)
new DistinctQueryOperatorEnumerator<TKey>(hashStream[i], _comparer, cancellationToken);
}
}
recipient.Receive(outputStream);
}
//---------------------------------------------------------------------------------------
// Whether this operator performs a premature merge that would not be performed in
// a similar sequential operation (i.e., in LINQ to Objects).
//
internal override bool LimitsParallelism
{
get { return false; }
}
//---------------------------------------------------------------------------------------
// This enumerator performs the distinct operation incrementally. It does this by
// maintaining a history -- in the form of a set -- of all data already seen. It simply
// then doesn't return elements it has already seen before.
//
class DistinctQueryOperatorEnumerator<TKey> : QueryOperatorEnumerator<TInputOutput, int>
{
private QueryOperatorEnumerator<Pair, TKey> _source; // The data source.
private Set<TInputOutput> _hashLookup; // The hash lookup, used to produce the distinct set.
private CancellationToken _cancellationToken;
private Shared<int> _outputLoopCount; // Allocated in MoveNext to avoid false sharing.
//---------------------------------------------------------------------------------------
// Instantiates a new distinction operator.
//
internal DistinctQueryOperatorEnumerator(
QueryOperatorEnumerator<Pair, TKey> source, IEqualityComparer<TInputOutput> comparer,
CancellationToken cancellationToken)
{
Debug.Assert(source != null);
_source = source;
_hashLookup = new Set<TInputOutput>(comparer);
_cancellationToken = cancellationToken;
}
//---------------------------------------------------------------------------------------
// Walks the single data source, skipping elements it has already seen.
//
internal override bool MoveNext(ref TInputOutput currentElement, ref int currentKey)
{
Debug.Assert(_source != null);
Debug.Assert(_hashLookup != null);
// Iterate over this set's elements until we find a unique element.
TKey keyUnused = default(TKey);
Pair current = new Pair(default(TInputOutput), default(NoKeyMemoizationRequired));
if (_outputLoopCount == null)
_outputLoopCount = new Shared<int>(0);
while (_source.MoveNext(ref current, ref keyUnused))
{
if ((_outputLoopCount.Value++ & CancellationState.POLL_INTERVAL) == 0)
CancellationState.ThrowIfCanceled(_cancellationToken);
// We ensure we never return duplicates by tracking them in our set.
if (_hashLookup.Add((TInputOutput)current.First))
{
#if DEBUG
currentKey = unchecked((int)0xdeadbeef);
#endif
currentElement = (TInputOutput)current.First;
return true;
}
}
return false;
}
protected override void Dispose(bool disposing)
{
Debug.Assert(_source != null);
_source.Dispose();
}
}
//---------------------------------------------------------------------------------------
// Returns an enumerable that represents the query executing sequentially.
//
internal override IEnumerable<TInputOutput> AsSequentialQuery(CancellationToken token)
{
IEnumerable<TInputOutput> wrappedChild = CancellableEnumerable.Wrap(Child.AsSequentialQuery(token), token);
return wrappedChild.Distinct(_comparer);
}
class OrderedDistinctQueryOperatorEnumerator<TKey> : QueryOperatorEnumerator<TInputOutput, TKey>
{
private QueryOperatorEnumerator<Pair, TKey> _source; // The data source.
private Dictionary<Wrapper<TInputOutput>, TKey> _hashLookup; // The hash lookup, used to produce the distinct set.
private IComparer<TKey> _keyComparer; // Comparer to decide the key order.
private IEnumerator<KeyValuePair<Wrapper<TInputOutput>, TKey>> _hashLookupEnumerator; // Enumerates over _hashLookup.
private CancellationToken _cancellationToken;
//---------------------------------------------------------------------------------------
// Instantiates a new distinction operator.
//
internal OrderedDistinctQueryOperatorEnumerator(
QueryOperatorEnumerator<Pair, TKey> source,
IEqualityComparer<TInputOutput> comparer, IComparer<TKey> keyComparer,
CancellationToken cancellationToken)
{
Debug.Assert(source != null);
_source = source;
_keyComparer = keyComparer;
_hashLookup = new Dictionary<Wrapper<TInputOutput>, TKey>(
new WrapperEqualityComparer<TInputOutput>(comparer));
_cancellationToken = cancellationToken;
}
//---------------------------------------------------------------------------------------
// Walks the single data source, skipping elements it has already seen.
//
internal override bool MoveNext(ref TInputOutput currentElement, ref TKey currentKey)
{
Debug.Assert(_source != null);
Debug.Assert(_hashLookup != null);
if (_hashLookupEnumerator == null)
{
Pair elem = new Pair(default(TInputOutput), default(NoKeyMemoizationRequired));
TKey orderKey = default(TKey);
int i = 0;
while (_source.MoveNext(ref elem, ref orderKey))
{
if ((i++ & CancellationState.POLL_INTERVAL) == 0)
CancellationState.ThrowIfCanceled(_cancellationToken);
// For each element, we track the smallest order key for that element that we saw so far
TKey oldEntry;
Wrapper<TInputOutput> wrappedElem = new Wrapper<TInputOutput>((TInputOutput)elem.First);
// If this is the first occurrence of this element, or the order key is lower than all keys we saw previously,
// update the order key for this element.
if (!_hashLookup.TryGetValue(wrappedElem, out oldEntry) || _keyComparer.Compare(orderKey, oldEntry) < 0)
{
// For each "elem" value, we store the smallest key, and the element value that had that key.
// Note that even though two element values are "equal" according to the EqualityComparer,
// we still cannot choose arbitrarily which of the two to yield.
_hashLookup[wrappedElem] = orderKey;
}
}
_hashLookupEnumerator = _hashLookup.GetEnumerator();
}
if (_hashLookupEnumerator.MoveNext())
{
KeyValuePair<Wrapper<TInputOutput>, TKey> currentPair = _hashLookupEnumerator.Current;
currentElement = currentPair.Key.Value;
currentKey = currentPair.Value;
return true;
}
return false;
}
protected override void Dispose(bool disposing)
{
Debug.Assert(_source != null);
_source.Dispose();
if (_hashLookupEnumerator != null)
{
_hashLookupEnumerator.Dispose();
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
namespace Aardvark.Base
{
/// <summary>
/// Conversion routines.
/// </summary>
public static partial class Conversion
{
#region Spherical <-> Cartesian
/// <summary>
/// Returns unit vector in direction (phi, theta).
/// Phi is rotation in xy-plane (x-axis is 0, y-axis is pi/2, ...).
/// Positive theta rotates towards positive z-axis.
/// </summary>
public static V3d CartesianFromSpherical(double phi, double theta)
{
var s = theta.Cos();
return new V3d(phi.Cos() * s, phi.Sin() * s, theta.Sin());
}
/// <summary>
/// Returns unit vector in direction (phi, theta).
/// Phi is rotation in xy-plane (x-axis is 0, y-axis is pi/2, ...).
/// Positive theta rotates towards positive z-axis.
/// </summary>
public static V3d CartesianFromSpherical(this V2d phiAndTheta)
{
return CartesianFromSpherical(phiAndTheta.X, phiAndTheta.Y);
}
/// <summary>
/// Returns unit vector in direction phi.
/// Phi is rotation in xy-plane (x-axis is 0, y-axis is pi/2, ...).
/// </summary>
public static V2d CartesianFromSpherical(this double phi)
{
return new V2d(phi.Cos(), phi.Sin());
}
/// <summary>
/// Returns spherical direction (phi, theta) from Cartesian direction.
/// </summary>
public static V2d SphericalFromCartesian(this V3d v)
{
return new V2d(
Fun.Atan2(v.Y, v.X), // phi
Fun.Atan2(v.Z, v.XY.Length) // theta
);
}
/// <summary>
/// Returns spherical direction (phi) from Cartesian direction.
/// </summary>
public static double SphericalFromCartesian(this V2d v)
{
return Fun.Atan2(v.Y, v.X);
}
#endregion
#region Angles (Radians, Degrees, Gons)
/// <summary>
/// Converts an angle given in radians to degrees.
/// </summary>
public static float DegreesFromRadians(this float radians)
{
return radians * ConstantF.DegreesPerRadian;
}
/// <summary>
/// Converts an angle given in radians to degrees.
/// </summary>
public static double DegreesFromRadians(this double radians)
{
return radians * Constant.DegreesPerRadian;
}
/// <summary>
/// Converts an angle given in degrees to radians.
/// </summary>
public static float RadiansFromDegrees(this float degrees)
{
return degrees * ConstantF.RadiansPerDegree;
}
/// <summary>
/// Converts an angle given in degrees to radians.
/// </summary>
public static double RadiansFromDegrees(this double degrees)
{
return degrees * Constant.RadiansPerDegree;
}
/// <summary>
/// Converts an angle given in gons to degrees.
/// </summary>
public static float DegreesFromGons(this float gons)
{
return gons * ConstantF.DegreesPerGon;
}
/// <summary>
/// Converts an angle given in gons to degrees.
/// </summary>
public static double DegreesFromGons(this double gons)
{
return gons * Constant.DegreesPerGon;
}
/// <summary>
/// Converts an angle given in gons to radians.
/// </summary>
public static float RadiansFromGons(this float gons)
{
return gons * ConstantF.RadiansPerGon;
}
/// <summary>
/// Converts an angle given in gons to radians.
/// </summary>
public static double RadiansFromGons(this double gons)
{
return gons * Constant.RadiansPerGon;
}
/// <summary>
/// Converts an angle given in degrees to gons.
/// </summary>
public static float GonsFromDegrees(this float degrees)
{
return degrees * ConstantF.GonsPerDegree;
}
/// <summary>
/// Converts an angle given in degrees to gons.
/// </summary>
public static double GonsFromDegrees(this double degrees)
{
return degrees * Constant.GonsPerDegree;
}
/// <summary>
/// Converts an angle given in radians to gons.
/// </summary>
public static float GonsFromRadians(this float radians)
{
return radians * ConstantF.GonsPerRadian;
}
/// <summary>
/// Converts an angle given in radians to gons.
/// </summary>
public static double GonsFromRadians(this double radians)
{
return radians * Constant.GonsPerRadian;
}
#endregion
#region Temperature
/// <summary>
/// Converts a temperature given in Fahrenheit to Celsius.
/// </summary>
public static float CelsiusFromFahrenheit(this float fahrenheit)
{
return (fahrenheit - 32.0f) / 1.8f;
}
/// <summary>
/// Converts a temperature given in Fahrenheit to Celsius.
/// </summary>
public static double CelsiusFromFahrenheit(this double fahrenheit)
{
return (fahrenheit - 32.0) / 1.8;
}
/// <summary>
/// Converts a temperature given in Celsius to Fahrenheit.
/// </summary>
public static float FahrenheitFromCelsius(this float celsius)
{
return (celsius * 1.8f) + 32.0f;
}
/// <summary>
/// Converts a temperature given in Celsius to Fahrenheit.
/// </summary>
public static double FahrenheitFromCelsius(this double celsius)
{
return (celsius * 1.8) + 32.0;
}
/// <summary>
/// Converts a temperature given in Fahrenheit to Kelvin.
/// </summary>
public static float KelvinFromFahrenheit(this float fahrenheit)
{
return (fahrenheit + 459.67f) / 1.8f;
}
/// <summary>
/// Converts a temperature given in Fahrenheit to Kelvin.
/// </summary>
public static double KelvinFromFahrenheit(this double fahrenheit)
{
return (fahrenheit + 459.67) / 1.8;
}
/// <summary>
/// Converts a temperature given in Kelvin to Fahrenheit.
/// </summary>
public static float FahrenheitFromKelvin(this float kelvin)
{
return (kelvin * 1.8f) - 459.67f;
}
/// <summary>
/// Converts a temperature given in Kelvin to Fahrenheit.
/// </summary>
public static double FahrenheitFromKelvin(this double kelvin)
{
return (kelvin * 1.8) - 459.67;
}
/// <summary>
/// Converts a temperature given in Kelvin to Celsius.
/// </summary>
public static float CelsiusFromKelvin(this float kelvin)
{
return kelvin - 273.15f;
}
/// <summary>
/// Converts a temperature given in Kelvin to Celsius.
/// </summary>
public static double CelsiusFromKelvin(this double kelvin)
{
return kelvin - 273.15;
}
/// <summary>
/// Converts a temperature given in Celsius to Kelvin.
/// </summary>
public static float KelvinFromCelsius(this float celsius)
{
return celsius + 273.15f;
}
/// <summary>
/// Converts a temperature given in Celsius to Kelvin.
/// </summary>
public static double KelvinFromCelsius(this double celsius)
{
return celsius + 273.15;
}
#endregion
#region Byte order (little endian / big endian)
#region HostToNetworkOrder
public static byte[] HostToNetworkOrder(short x)
{
byte[] data = BitConverter.GetBytes(x);
if (BitConverter.IsLittleEndian) ReverseBytes(data);
return data;
}
public static byte[] HostToNetworkOrder(ushort x)
{
byte[] data = BitConverter.GetBytes(x);
if (BitConverter.IsLittleEndian) ReverseBytes(data);
return data;
}
public static byte[] HostToNetworkOrder(int x)
{
byte[] data = BitConverter.GetBytes(x);
if (BitConverter.IsLittleEndian) ReverseBytes(data);
return data;
}
public static byte[] HostToNetworkOrder(uint x)
{
byte[] data = BitConverter.GetBytes(x);
if (BitConverter.IsLittleEndian) ReverseBytes(data);
return data;
}
public static byte[] HostToNetworkOrder(long x)
{
byte[] data = BitConverter.GetBytes(x);
if (BitConverter.IsLittleEndian) ReverseBytes(data);
return data;
}
public static byte[] HostToNetworkOrder(ulong x)
{
byte[] data = BitConverter.GetBytes(x);
if (BitConverter.IsLittleEndian) ReverseBytes(data);
return data;
}
public static byte[] HostToNetworkOrder(float x)
{
byte[] data = BitConverter.GetBytes(x);
if (BitConverter.IsLittleEndian) ReverseBytes(data);
return data;
}
public static byte[] HostToNetworkOrder(double x)
{
byte[] data = BitConverter.GetBytes(x);
if (BitConverter.IsLittleEndian) ReverseBytes(data);
return data;
}
#endregion
#region NetworkToHostOrder
public static short NetworkToHostOrderInt16(byte[] data)
{
byte[] copy = (byte[])data.Clone();
if (BitConverter.IsLittleEndian) ReverseBytes(copy);
return BitConverter.ToInt16(copy, 0);
}
public static short NetworkToHostOrderInt16InPlace(byte[] data)
{
if (BitConverter.IsLittleEndian) ReverseBytes(data);
return BitConverter.ToInt16(data, 0);
}
public static ushort NetworkToHostOrderUInt16(byte[] data)
{
byte[] copy = (byte[])data.Clone();
if (BitConverter.IsLittleEndian) ReverseBytes(copy);
return BitConverter.ToUInt16(copy, 0);
}
public static ushort NetworkToHostOrderUInt16InPlace(byte[] data)
{
if (BitConverter.IsLittleEndian) ReverseBytes(data);
return BitConverter.ToUInt16(data, 0);
}
public static int NetworkToHostOrderInt32(byte[] data)
{
byte[] copy = (byte[])data.Clone();
if (BitConverter.IsLittleEndian) ReverseBytes(copy);
return BitConverter.ToInt32(copy, 0);
}
public static int NetworkToHostOrderInt32InPlace(byte[] data)
{
if (BitConverter.IsLittleEndian) ReverseBytes(data);
return BitConverter.ToInt32(data, 0);
}
public static uint NetworkToHostOrderUInt32(byte[] data)
{
byte[] copy = (byte[])data.Clone();
if (BitConverter.IsLittleEndian) ReverseBytes(copy);
return BitConverter.ToUInt32(copy, 0);
}
public static uint NetworkToHostOrderUInt32InPlace(byte[] data)
{
if (BitConverter.IsLittleEndian) ReverseBytes(data);
return BitConverter.ToUInt32(data, 0);
}
public static long NetworkToHostOrderInt64(byte[] data)
{
byte[] copy = (byte[])data.Clone();
if (BitConverter.IsLittleEndian) ReverseBytes(copy);
return BitConverter.ToInt64(copy, 0);
}
public static long NetworkToHostOrderInt64InPlace(byte[] data)
{
if (BitConverter.IsLittleEndian) ReverseBytes(data);
return BitConverter.ToInt64(data, 0);
}
public static ulong NetworkToHostOrderUInt64(byte[] data)
{
byte[] copy = (byte[])data.Clone();
if (BitConverter.IsLittleEndian) ReverseBytes(copy);
return BitConverter.ToUInt64(copy, 0);
}
public static ulong NetworkToHostOrderUInt64InPlace(byte[] data)
{
if (BitConverter.IsLittleEndian) ReverseBytes(data);
return BitConverter.ToUInt64(data, 0);
}
public static float NetworkToHostOrderSingle(byte[] data)
{
byte[] copy = (byte[])data.Clone();
if (BitConverter.IsLittleEndian) ReverseBytes(copy);
return BitConverter.ToSingle(copy, 0);
}
public static float NetworkToHostOrderSingleInPlace(byte[] data)
{
if (BitConverter.IsLittleEndian) ReverseBytes(data);
return BitConverter.ToSingle(data, 0);
}
public static double NetworkToHostOrderDouble(byte[] data)
{
byte[] copy = (byte[])data.Clone();
if (BitConverter.IsLittleEndian) ReverseBytes(copy);
return BitConverter.ToDouble(copy, 0);
}
public static double NetworkToHostOrderDoubleInPlace(byte[] data)
{
if (BitConverter.IsLittleEndian) ReverseBytes(data);
return BitConverter.ToDouble(data, 0);
}
#endregion
/// <summary>
/// Reverses elements of given byte array.
/// </summary>
public static void ReverseBytes(byte[] data)
{
int length = data.Length;
int maxIndex = length - 1;
for (int i = 0; i < length / 2; i++)
{
int j = maxIndex - i;
byte tmp = data[i]; data[i] = data[j]; data[j] = tmp;
}
}
#endregion
#region Color
/// <summary>
/// Converts XYZ-color to Lab-color
/// </summary>
/// <param name="xyz"></param>
/// <returns></returns>
public static C3f XYZToLab(this C3f xyz)
{
var X = xyz.R / XREF;
var Y = xyz.G / YREF;
var Z = xyz.B / ZREF;
var fx = f(X);
var fy = f(Y);
var fz = f(Z);
var L = (116 * fy) - 16;
var a = 500 * (fx - fy);
var b = 200 * (fy - fz);
return new C3f(L, a, b);
}
/// <summary>
/// converts Lab-color to XYZ-color
/// </summary>
/// <param name="lab">L=[0,100], a=[-150,150], b=[-150,150]</param>
/// <returns></returns>
public static C3f LabToXYZ(this C3f lab)
{
var L = lab.R;
var a = lab.G;
var b = lab.B;
var d = (1.0f / 116.0f) * (L + 16);
var Y = YREF * fInv(d);
var X = XREF * fInv(d + a / 500.0f);
var Z = ZREF * fInv(d - b / 200.0f);
return new C3f(X, Y, Z);
}
private static float f(float t)
{
if (t > 0.008856)
return t.Pow(1.0f / 3.0f);
return (903.3f * t + 16f) / 116f; //(1.0f / 3.0f) * (float)(29.0f / 6.0f).Square() * t + (4.0f / 29.0f);
}
private static float fInv(float t)
{
if (t > 0.20689)
return t.Pow(3);
return (t * 116f - 16) / 903.3f; //3 * (float)(6.0f / 29.0f).Square() * (t - 4.0f / 29.0f);
}
private const float XREF = 0.95f; // Illuminant= D65
private const float YREF = 1f;
private const float ZREF = 1.09f;
#endregion
}
public static class ColorConversion
{
public static C3f FromYuvToYxy(this C3f Yuv)
{
var Y = Yuv.R;
var u = Yuv.G;
var v = Yuv.B;
return new C3f(Y,
3 * u / (2 * u - 8 * v + 4),
2 * v / (2 * u - 8 * v + 4));
}
public static C3f FromYxyToXYZ(this C3f Yxy)
{
double Y = Yxy.R;
double x = Yxy.G;
double y = Yxy.B;
//AZ: check for y == 0 needed - szabo: DONE
if (y == 0) y = double.Epsilon;
return new C3f((x * (Y / y)), Y, ((1 - x - y) * (Y / y)));
}
public static C3f FromXYZToYxy(this C3f XYZ)
{
double Y = XYZ.G;
double x = XYZ.R / (XYZ.R + XYZ.G + XYZ.B);
double y = XYZ.G / (XYZ.R + XYZ.G + XYZ.B);
return new C3f(Y, x, y);
}
/// <summary>
/// Returns the GamutMap represantion of the supplied C3f.
/// </summary>
public static C3f ToGamutMap(this C3f self)
{
return self.Clamped(0.0f, 1.0f);
}
/// <summary>
/// Returns the int representation of the supplied C3f color.
/// </summary>
public static int FromRgbToInt(this C3f self)
{
return Col.ByteFromDouble(self.R) << 16 |
Col.ByteFromDouble(self.G) << 8 |
Col.ByteFromDouble(self.B);
}
}
}
| |
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Stream.Rest;
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Threading.Tasks;
namespace Stream
{
using ReactionFilter = FeedFilter;
public class ReactionsWithActivity
{
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "results")]
public IEnumerable<Reaction> Reactions { get; internal set; }
public EnrichedActivity Activity { get; internal set; }
}
public class Reaction
{
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "id")]
public string ID { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "kind")]
public string Kind { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "created_at")]
public DateTime? CreatedAt { get; internal set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "updated_at")]
public DateTime? UpdatedAt { get; internal set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "activity_id")]
public string ActivityID { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "user_id")]
public string UserID { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "user"), JsonConverter(typeof(EnrichableFieldConverter))]
public EnrichableField User { get; internal set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "data")]
public IDictionary<string, object> Data { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "target_feeds")]
public IEnumerable<string> TargetFeeds { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "parent")]
public string ParentID { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "latest_children")]
public Dictionary<string, Reaction[]> LatestChildren { get; internal set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "children_counts")]
public Dictionary<string, int> ChildrenCounters { get; internal set; }
}
public class ReactionFiltering
{
const int DefaultLimit = 10;
int _limit = DefaultLimit;
ReactionFilter _filter = null;
public ReactionFiltering WithLimit(int limit)
{
_limit = limit;
return this;
}
public ReactionFiltering WithFilter(ReactionFilter filter)
{
_filter = filter;
return this;
}
internal ReactionFiltering WithActivityData()
{
_filter = (_filter == null) ? ReactionFilter.Where().WithActivityData() : _filter.WithActivityData();
return this;
}
internal void Apply(RestRequest request)
{
request.AddQueryParameter("limit", _limit.ToString());
// filter if needed
if (_filter != null)
_filter.Apply(request);
}
internal bool IncludesActivityData
{
get
{
return _filter.IncludesActivityData;
}
}
public static ReactionFiltering Default
{
get
{
return new ReactionFiltering()
{
_limit = DefaultLimit
};
}
}
}
public class ReactionPagination
{
string _kind = null;
string _lookup_attr;
string _lookup_value;
private ReactionPagination() { }
public ReactionPagination ActivityID(string activityID)
{
_lookup_attr = "activity_id";
_lookup_value = activityID;
return this;
}
public ReactionPagination ReactionID(string reactionID)
{
_lookup_attr = "reaction_id";
_lookup_value = reactionID;
return this;
}
public ReactionPagination UserID(string userID)
{
_lookup_attr = "user_id";
_lookup_value = userID;
return this;
}
public ReactionPagination Kind(string kind)
{
_kind = kind;
return this;
}
public static ReactionPagination By
{
get { return new ReactionPagination(); }
}
public string GetPath()
{
if (_kind != null)
return $"{_lookup_attr}/{_lookup_value}/{_kind}/";
return $"{_lookup_attr}/{_lookup_value}/";
}
}
public class Reactions
{
readonly StreamClient _client;
private class ReactionsFilterResponse
{
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "results")]
public IEnumerable<Reaction> Reactions { get; internal set; }
internal static EnrichedActivity GetActivity(string json)
{
JObject obj = JObject.Parse(json);
foreach (var prop in obj.Properties())
{
if (prop.Name == "activity")
{
return EnrichedActivity.FromJson((JObject)prop.Value);
}
}
return null;
}
}
internal Reactions(StreamClient client)
{
_client = client;
}
public async Task<Reaction> Add(string kind, string activityID, string userID,
IDictionary<string, object> data = null, IEnumerable<string> targetFeeds = null)
{
var r = new Reaction()
{
Kind = kind,
ActivityID = activityID,
UserID = userID,
Data = data,
TargetFeeds = targetFeeds
};
return await this.Add(r);
}
public async Task<Reaction> AddChild(Reaction parent, string kind, string userID,
IDictionary<string, object> data = null, IEnumerable<string> targetFeeds = null)
{
var r = new Reaction()
{
Kind = kind,
UserID = userID,
Data = data,
ParentID = parent.ID,
TargetFeeds = targetFeeds
};
return await this.Add(r);
}
public async Task<Reaction> Get(string reactionID)
{
var request = this._client.BuildAppRequest($"reaction/{reactionID}/", HttpMethod.GET);
var response = await this._client.MakeRequest(request);
if (response.StatusCode == System.Net.HttpStatusCode.OK)
return JsonConvert.DeserializeObject<Reaction>(response.Content);
throw StreamException.FromResponse(response);
}
public async Task<IEnumerable<Reaction>> Filter(ReactionFiltering filtering, ReactionPagination pagination)
{
var response = await FilterHelper(filtering, pagination);
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
return JsonConvert.DeserializeObject<ReactionsFilterResponse>(response.Content).Reactions;
}
throw StreamException.FromResponse(response);
}
public async Task<ReactionsWithActivity> FilterWithActivityData(ReactionFiltering filtering, ReactionPagination pagination)
{
var response = await FilterHelper(filtering.WithActivityData(), pagination);
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
var reactions = JsonConvert.DeserializeObject<ReactionsFilterResponse>(response.Content).Reactions;
var activity = ReactionsFilterResponse.GetActivity(response.Content);
return new ReactionsWithActivity
{
Reactions = reactions,
Activity = activity
};
}
throw StreamException.FromResponse(response);
}
private async Task<RestResponse> FilterHelper(ReactionFiltering filtering, ReactionPagination pagination)
{
var urlPath = pagination.GetPath();
var request = this._client.BuildAppRequest($"reaction/{urlPath}", HttpMethod.GET);
filtering.Apply(request);
var response = await this._client.MakeRequest(request);
return response;
}
public async Task<Reaction> Update(string reactionID, IDictionary<string, object> data = null, IEnumerable<string> targetFeeds = null)
{
var r = new Reaction()
{
ID = reactionID,
Data = data,
TargetFeeds = targetFeeds
};
var request = this._client.BuildAppRequest($"reaction/{reactionID}/", HttpMethod.PUT);
request.SetJsonBody(JsonConvert.SerializeObject(r));
var response = await this._client.MakeRequest(request);
if (response.StatusCode == System.Net.HttpStatusCode.Created)
return JsonConvert.DeserializeObject<Reaction>(response.Content);
throw StreamException.FromResponse(response);
}
public async Task Delete(string reactionID)
{
var request = this._client.BuildAppRequest($"reaction/{reactionID}/", HttpMethod.DELETE);
var response = await this._client.MakeRequest(request);
if (response.StatusCode != System.Net.HttpStatusCode.OK)
throw StreamException.FromResponse(response);
}
private async Task<Reaction> Add(Reaction r)
{
var request = this._client.BuildAppRequest("reaction/", HttpMethod.POST);
request.SetJsonBody(JsonConvert.SerializeObject(r));
var response = await this._client.MakeRequest(request);
if (response.StatusCode == System.Net.HttpStatusCode.Created)
return JsonConvert.DeserializeObject<Reaction>(response.Content);
throw StreamException.FromResponse(response);
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations
{
public class UnsafeKeywordRecommenderTests : KeywordRecommenderTests
{
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AtRoot_Interactive()
{
VerifyKeyword(SourceCodeKind.Script,
@"$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterClass_Interactive()
{
VerifyKeyword(SourceCodeKind.Script,
@"class C { }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterGlobalStatement_Interactive()
{
VerifyKeyword(SourceCodeKind.Script,
@"System.Console.WriteLine();
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterGlobalVariableDeclaration_Interactive()
{
VerifyKeyword(SourceCodeKind.Script,
@"int i = 0;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotInUsingAlias()
{
VerifyAbsence(
@"using Foo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InEmptyStatement()
{
VerifyKeyword(AddInsideMethod(
@"$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InCompilationUnit()
{
VerifyKeyword(
@"$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterExtern()
{
VerifyKeyword(
@"extern alias Foo;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterUsing()
{
VerifyKeyword(
@"using Foo;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterNamespace()
{
VerifyKeyword(
@"namespace N {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterTypeDeclaration()
{
VerifyKeyword(
@"class C {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterDelegateDeclaration()
{
VerifyKeyword(
@"delegate void Foo();
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterMethod()
{
VerifyKeyword(
@"class C {
void Foo() {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterField()
{
VerifyKeyword(
@"class C {
int i;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterProperty()
{
VerifyKeyword(
@"class C {
int i { get; }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotBeforeUsing()
{
VerifyAbsence(SourceCodeKind.Regular,
@"$$
using Foo;");
}
[WpfFact(Skip = "528041"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotBeforeUsing_Interactive()
{
VerifyAbsence(SourceCodeKind.Script,
@"$$
using Foo;");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterAssemblyAttribute()
{
VerifyKeyword(
@"[assembly: foo]
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterRootAttribute()
{
VerifyKeyword(
@"[foo]
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterNestedAttribute()
{
VerifyKeyword(
@"class C {
[foo]
$$");
}
// This will be fixed once we have accessibility for members
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InsideStruct()
{
VerifyKeyword(
@"struct S {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InsideInterface()
{
VerifyKeyword(
@"interface I {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InsideClass()
{
VerifyKeyword(
@"class C {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterPartial()
{
VerifyAbsence(@"partial $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterAbstract()
{
VerifyKeyword(
@"abstract $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterInternal()
{
VerifyKeyword(
@"internal $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterUnsafe()
{
VerifyAbsence(@"unsafe $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterStaticUnsafe()
{
VerifyAbsence(@"static unsafe $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterUnsafeStatic()
{
VerifyAbsence(@"unsafe static $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterPrivate()
{
VerifyKeyword(
@"private $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterProtected()
{
VerifyKeyword(
@"protected $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterSealed()
{
VerifyKeyword(
@"sealed $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterStatic()
{
VerifyKeyword(
@"static $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterStaticInUsingDirective()
{
VerifyAbsence(
@"using static $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterClass()
{
VerifyAbsence(@"class $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterDelegate()
{
VerifyAbsence(@"delegate $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterNestedAbstract()
{
VerifyKeyword(
@"class C {
abstract $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterNestedVirtual()
{
VerifyKeyword(
@"class C {
virtual $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterNestedOverride()
{
VerifyKeyword(
@"class C {
override $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterNestedSealed()
{
VerifyKeyword(
@"class C {
sealed $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void BeforeStatement()
{
VerifyKeyword(AddInsideMethod(
@"$$
return true;"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterStatement()
{
VerifyKeyword(AddInsideMethod(
@"return true;
$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterBlock()
{
VerifyKeyword(AddInsideMethod(
@"if (true) {
}
$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void InsideSwitchBlock()
{
VerifyKeyword(AddInsideMethod(
@"switch (E) {
case 0:
$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void NotAfterUnsafe_InMethod()
{
VerifyAbsence(AddInsideMethod(
@"unsafe $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public void AfterInterfaceModifiers()
{
VerifyKeyword(
@"public $$ interface IBinaryDocumentMemoryBlock {");
}
}
}
| |
using System;
using System.IO;
using System.Xml;
using System.Collections;
using System.Windows.Forms;
namespace BinxEd
{
/// <summary>
/// The model class for the BinX document as a container to hold all its elements, and it also provides
/// basic operations such as loading, saving for access by the controller.
/// </summary>
public class Document
{
private DataTypes dataTypes_;
private string filePath_;
private const string sXMLHeader = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
private const string sBinXHeader = "<binx xmlns=\"http://www.edikt.org/binx/2003/06/binx\">";
private DefinitionsNode definitions_;
private DatasetNode dataset_;
private bool modified_;
public Document()
{
dataTypes_ = new DataTypes();
definitions_ = new DefinitionsNode();
dataset_ = new DatasetNode();
}
public Document(string sFilePath)
{
this.filePath_ = sFilePath;
dataTypes_ = new DataTypes();
definitions_ = new DefinitionsNode();
dataset_ = new DatasetNode();
}
/// <summary>
/// Property to get or set DataTypes object for primitive/complex types
/// </summary>
public DataTypes getDataTypes()
{
return this.dataTypes_;
}
public bool isTypeDefined(string typeName)
{
return definitions_.contains(typeName);
}
public string[] getPrimitiveTypeNames()
{
return dataTypes_.getPrimitiveTypes();
}
public string[] getUserDefinedTypeNames()
{
string[] defs = new string[definitions_.count()];
int i = 0;
foreach (DefineTypeNode tp in definitions_.getDefinitions())
{
defs[i++] = tp.getTypeName();
}
return defs; //userTypes_.getUserTypeNames();
}
/// <summary>
/// Get all primitive and user-defined type names
/// </summary>
/// <returns></returns>
public string[] getTypeNames()
{
string[] allTypes = dataTypes_.getAllTypes();
int n = allTypes.Length + definitions_.count();
string[] sa = new string[n];
int i = 0;
while (i < allTypes.Length)
{
sa[i] = allTypes[i];
i ++;
}
foreach (DefineTypeNode tp in definitions_.getDefinitions())
{
sa[i++] = tp.getTypeName();
}
return sa;
}
public DefinitionsNode getDefinitions()
{
return definitions_;
}
public ArrayList getDefinitionsList()
{
return definitions_.getDefinitions();
}
public void addDefinition(DefineTypeNode node)
{
definitions_.addChild(node);
}
public void removeDefinition(int index)
{
definitions_.removeChild(index);
}
public DatasetNode getDataset()
{
return dataset_;
}
public ArrayList getDatasetList()
{
return dataset_.getDataset();
}
public void addDataset(AbstractNode node)
{
dataset_.addChild(node);
}
public void removeDataset(int index)
{
dataset_.removeChild(index);
}
/// <summary>
/// Property to get or set modified flag
/// </summary>
public bool isModified()
{
return modified_;
}
public void setModified()
{
modified_ = true;
}
/// <summary>
/// Property to get or set big endian
/// </summary>
public bool isBigEndian()
{
return dataset_.isBigEndian();
}
public void setBigEndian(bool big)
{
dataset_.setBigEndian(big);
}
/// <summary>
/// Property to get filePath
/// </summary>
public string getFilePath()
{
return filePath_;
}
public void setFilePath(string filePath)
{
filePath_ = filePath;
}
/// <summary>
/// Save BinX into file.
/// </summary>
public void save()
{
StreamWriter sr = File.CreateText(filePath_);
sr.WriteLine(sXMLHeader);
sr.WriteLine(sBinXHeader);
if (definitions_.count() > 0)
{
definitions_.save(sr);
}
dataset_.save(sr);
sr.WriteLine("</binx>");
sr.Close();
modified_ = false;
}
/// <summary>
/// Save BinX definitions and dataset into a specified file.
/// </summary>
/// <param name="sFilename"></param>
public void save(string sFilename)
{
this.filePath_ = sFilename;
dataset_.setBinaryFileName(filePath_);
save();
}
/// <summary>
/// Clear document content
/// </summary>
public void clear()
{
modified_ = false;
definitions_.clear();
dataset_.clear();
this.filePath_ = null;
}
/// <summary>
/// Load a BinX document from specified file.
/// </summary>
/// <param name="filepath"></param>
/// <returns></returns>
public bool load(string filepath)
{
clear();
this.filePath_ = filepath;
return Parser.load(filePath_, ref definitions_, ref dataset_);;
}
/// <summary>
/// Make a string for the dataset text.
/// </summary>
/// <returns></returns>
public string getDatasetNodeText()
{
return dataset_.toNodeText();
}
/// <summary>
/// Whether doc contains nothing
/// </summary>
public bool isEmpty()
{
return (definitions_.count() <= 0) && (dataset_.count() <= 0);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Msagl.Core;
using Microsoft.Msagl.Core.Geometry;
using Microsoft.Msagl.Core.Layout;
using Microsoft.Msagl.Core.Layout.ProximityOverlapRemoval;
using Microsoft.Msagl.Core.Layout.ProximityOverlapRemoval.MinimumSpanningTree;
using System.Threading.Tasks;
namespace Microsoft.Msagl.Layout.MDS {
/// <summary>
/// Class for graph layout with multidimensional scaling.
/// </summary>
public class MdsGraphLayout : AlgorithmBase {
readonly GeometryGraph graph;
readonly MdsLayoutSettings settings;
/// <summary>
/// Constructs the multidimensional scaling algorithm.
/// </summary>
public MdsGraphLayout(MdsLayoutSettings settings, GeometryGraph geometryGraph)
{
this.settings = settings;
graph = geometryGraph;
}
/// <summary>
/// Executes the algorithm
/// </summary>
protected override void RunInternal() {
LayoutConnectedComponents();
SetGraphBoundingBox();
}
///// <summary>
///// needed a comment
///// </summary>
///// <param name="geometryGraph"></param>
///// <param name="group"></param>
//public void GroupSpread(GeometryGraph geometryGraph, Set<Node> group) {
// this.graph = geometryGraph;
// double[][] d = new double[group.Count][];
// double[] x, y;
// System.Console.WriteLine(group.Count);
// LayoutConnectedComponents(geometryGraph, out x, out y);
// int c = 0;
// foreach (Node node in group) {
// d[c] = Distances.SingleSourceUniformDistances(geometryGraph, node, false);
// c++;
// }
// double[][] w = MultidimensionalScaling.ExponentialWeightMatrix(d, -2);
// MultidimensionalScaling.DistanceScalingSubset(d, x, y, w, 5);
// double scaleX = ((MdsLayoutSettings)geometryGraph.LayoutAlgorithmSettings).ScaleX;
// double scaleY = ((MdsLayoutSettings)geometryGraph.LayoutAlgorithmSettings).ScaleY;
// double rotate = ((MdsLayoutSettings)geometryGraph.LayoutAlgorithmSettings).Rotate;
// Transformation.Rotate(x, y, rotate);
// int index = 0;
// foreach (Node node in geometryGraph.Nodes) {
// node.Center = new Point((int)(x[index] * scaleX), (int)(y[index] * scaleY));
// node.BoundaryCurve = node.BoundaryCurve.Move(node.Center);
// index++;
// }
// RankingLayout.SetEdgeCurves(geometryGraph);
// SetGraphBoundingBox();
//}
void SetGraphBoundingBox() {
graph.BoundingBox = graph.PumpTheBoxToTheGraphWithMargins();
}
/// <summary>
/// Scales a configuration such that the average edge length in the drawing
/// equals the average of the given edge lengths.
/// </summary>
/// <param name="g">A graph.</param>
/// <param name="x">Coordinates.</param>
/// <param name="y">Coordinates.</param>
static void ScaleToAverageEdgeLength(GeometryGraph g, double[] x, double[] y) {
var index = new Dictionary<Node, int>();
int c=0;
foreach(Node node in g.Nodes) {
index.Add(node, c);
c++;
}
double avgSum = 0, avgLength = 0;
foreach(Edge edge in g.Edges) {
int i=index[edge.Source];
int j=index[edge.Target];
avgSum += Math.Sqrt(Math.Pow(x[i] - x[j], 2) + Math.Pow(y[i] - y[j], 2));
avgLength += edge.Length;
}
if(avgLength>0) avgSum /= avgLength;
if(avgSum>0)
for (int i = 0; i < x.Length; i++) {
x[i] /= avgSum;
y[i] /= avgSum;
}
}
/// <summary>
/// Layouts a connected graph with Multidimensional Scaling, using
/// shortest-path distances as Euclidean target distances.
/// </summary>
/// <param name="geometryGraph">A graph.</param>
/// <param name="settings">The settings for the algorithm.</param>
/// <param name="x">Coordinate vector.</param>
/// <param name="y">Coordinate vector.</param>
internal static void LayoutGraphWithMds(GeometryGraph geometryGraph, MdsLayoutSettings settings, out double[] x, out double[] y) {
x = new double[geometryGraph.Nodes.Count];
y = new double[geometryGraph.Nodes.Count];
if (geometryGraph.Nodes.Count == 0) return;
if (geometryGraph.Nodes.Count == 1)
{
x[0] = y[0] = 0;
return;
}
int k = Math.Min(settings.PivotNumber, geometryGraph.Nodes.Count);
int iter = settings.GetNumberOfIterationsWithMajorization(geometryGraph.Nodes.Count);
double exponent = settings.Exponent;
var pivotArray = new int[k];
PivotDistances pivotDistances = new PivotDistances(geometryGraph, false, pivotArray);
pivotDistances.Run();
double[][] c = pivotDistances.Result;
MultidimensionalScaling.LandmarkClassicalScaling(c, out x, out y, pivotArray);
ScaleToAverageEdgeLength(geometryGraph, x, y);
if (iter > 0) {
AllPairsDistances apd = new AllPairsDistances(geometryGraph, false);
apd.Run();
double[][] d = apd.Result;
double[][] w = MultidimensionalScaling.ExponentialWeightMatrix(d, exponent);
// MultidimensionalScaling.DistanceScaling(d, x, y, w, iter);
MultidimensionalScaling.DistanceScalingSubset(d, x, y, w, iter);
}
}
// class GeometryGraphComparer : IComparer<GeometryGraph> {
// public int Compare(GeometryGraph g1, GeometryGraph g2) {
// return g2.Nodes.Count.CompareTo(g1.Nodes.Count);
// }
//}
/// <summary>
/// Computes layout for possibly disconnected graphs by putting
/// the layouts for connected components together.
/// </summary>
internal void LayoutConnectedComponents() {
GeometryGraph[] graphs = GraphConnectedComponents.CreateComponents(graph.Nodes, graph.Edges).ToArray();
// layout components, compute bounding boxes
if (settings.RunInParallel) {
ParallelOptions options = new ParallelOptions();
#if PPC
if (this.CancelToken != null)
options.CancellationToken = this.CancelToken.CancellationToken;
#endif
System.Threading.Tasks.Parallel.ForEach(graphs, options, LayoutConnectedGraphWithMds);
}
else
for (int i = 0; i < graphs.Length; i++) {
Console.WriteLine("laying out {0} connected component", i);
LayoutConnectedGraphWithMds(graphs[i]);
}
if (graphs.Length > 1) {
Console.WriteLine("packing");
PackGraphs(graphs, settings);
Console.WriteLine("done packing");
//restore the parents
foreach (var node in graphs.SelectMany(g => g.Nodes))
node.GeometryParent = graph;
}
Console.WriteLine("done with LayoutConnectedComponents");
}
void LayoutConnectedGraphWithMds(GeometryGraph compGraph)
{
Console.WriteLine("LayoutConnectedGraphWithMds: nodes {0} edges {1}", compGraph.Nodes.Count(), compGraph.Edges.Count());
double[] x, y;
LayoutGraphWithMds(compGraph, settings, out x, out y);
if (settings.RotationAngle != 0)
Transform.Rotate(x, y, settings.RotationAngle);
double scaleX = settings.ScaleX;
double scaleY = settings.ScaleY;
int index = 0;
foreach (Node node in compGraph.Nodes)
{
node.Center = new Point(x[index] * scaleX, y[index] * scaleY);
index++;
if ((index % 100) == 0)
{
ProgressStep();
}
}
if (settings.AdjustScale)
AdjustScale(compGraph.Nodes);
if (settings.RemoveOverlaps)
{
switch (settings.OverlapRemovalMethod)
{
case OverlapRemovalMethod.Prism:
ProximityOverlapRemoval.RemoveOverlaps(compGraph, settings.NodeSeparation);
break;
case OverlapRemovalMethod.MinimalSpanningTree:
OverlapRemoval.RemoveOverlaps(compGraph.Nodes.ToArray(), settings.NodeSeparation);
break;
default:
throw new ArgumentOutOfRangeException();
}
}
compGraph.BoundingBox = compGraph.PumpTheBoxToTheGraphWithMargins();
}
void AdjustScale(IList<Node> nodes) {
if (nodes.Count <= 5)
return; //we can have only a little bit of white space with a layout with only few nodes
int repetitions = 10;
var scale = 1.0;
var delta = 0.5;
var tree = BuildNodeTree(nodes);
var random = new Random(1);
do
{
const int minNumberOfHits = 6;
const int maxNumberOfHits = 15;
const int numberOfChecks = 100;
int hits = NumberOfHits(numberOfChecks, random, tree, maxNumberOfHits);
if (hits < minNumberOfHits)
scale /= 1+delta;
else if (hits > maxNumberOfHits)
scale *= 1+delta;
else {
// if ( maxRepetitions> repetitions )
// Console.WriteLine("reps={0} scale={1}, hits={2}", maxRepetitions-repetitions , scale, hits);
return;
}
delta /= 2;
//adjust the scale the graph
ScaleNodes(nodes, scale);
if (repetitions-- == 0)
return;
UpdateTree(tree);
} while (true);
}
void ScaleNodes(IList<Node> nodes, double scale) {
int i = 0;
foreach (Node node in nodes) {
node.Center *= scale;
i++;
if ((i%100) == 0)
ProgressStep();
}
}
static void UpdateTree(RectangleNode<Node> tree) {
if (tree.IsLeaf)
tree.Rectangle = tree.UserData.BoundingBox;
else {
UpdateTree(tree.Left);
UpdateTree(tree.Right);
tree.rectangle = tree.Left.rectangle;
tree.rectangle.Add(tree.Right.rectangle);
}
}
static int NumberOfHits(int numberOfChecks, Random random, RectangleNode<Node> tree, int maxNumberOfHits) {
// var l = new List<Point>();
int numberOfHits = 0;
for (int i = 0; i < numberOfChecks; i++) {
Point point = RandomPointFromBox(random, ref tree.rectangle);
// l.Add(point);
if ((tree.FirstHitNode(point, (p, t) => HitTestBehavior.Stop)) != null)
numberOfHits++;
if (numberOfHits == maxNumberOfHits)
return maxNumberOfHits;
}
//LayoutAlgorithmSettings.ShowDebugCurvesEnumeration(Getdc(tree, l));
return numberOfHits;
}
/*
static IEnumerable<DebugCurve> Getdc(RectangleNode<Node> tree, List<Point> points) {
foreach (var point in points)
yield return new DebugCurve("red", new Ellipse(5, 5, point));
foreach (var rn in tree.GetAllLeafNodes()) {
yield return new DebugCurve("blue", rn.Rectangle.Perimeter());
yield return new DebugCurve("green", rn.UserData.BoundaryCurve);
}
}
*/
static RectangleNode<Node> BuildNodeTree(IList<Node> nodes) {
return RectangleNode<Node>.CreateRectangleNodeOnEnumeration(
nodes.Select(n => new RectangleNode<Node>(n, n.BoundingBox)));
}
static Point RandomPointFromBox(Random random, ref Rectangle boundingBox) {
var x=random.NextDouble();
var y=random.NextDouble();
var p= new Point(boundingBox.Left + boundingBox.Width * x, boundingBox.Bottom + boundingBox.Height * y);
return p;
}
/// <summary>
/// Pack the given graph components to the specified aspect ratio
/// </summary>
/// <param name="components">set of graphs to pack</param>
/// <param name="settings">settings for packing method and desired aspect ratio</param>
/// <returns>Bounding box of the packed components</returns>
public static Rectangle PackGraphs(IEnumerable<GeometryGraph> components, LayoutAlgorithmSettings settings) {
List<RectangleToPack<GeometryGraph>> rectangles =
(from c in components select new RectangleToPack<GeometryGraph>(c.BoundingBox, c)).ToList();
if (rectangles.Count > 1) {
OptimalPacking<GeometryGraph> packing = settings.PackingMethod == PackingMethod.Compact
? new OptimalRectanglePacking<GeometryGraph>(rectangles, settings.PackingAspectRatio)
: (OptimalPacking<GeometryGraph>)
new OptimalColumnPacking<GeometryGraph>(rectangles, settings.PackingAspectRatio);
packing.Run();
foreach (var r in rectangles) {
GeometryGraph component = r.Data;
var delta = r.Rectangle.LeftBottom - component.boundingBox.LeftBottom;
component.Translate(delta);
}
return new Rectangle(0, 0, packing.PackedWidth, packing.PackedHeight);
}
if (rectangles.Count == 1)
return rectangles[0].Rectangle;
return Rectangle.CreateAnEmptyBox();
}
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Management.Automation.Internal;
using System.Reflection;
using System.Management.Automation.Language;
using Dbg = System.Management.Automation.Diagnostics;
namespace System.Management.Automation
{
/// <summary>
/// A common base class for code shared between an interpreted (old) script block and a compiled (new) script block.
/// </summary>
internal abstract class ScriptCommandProcessorBase : CommandProcessorBase
{
protected ScriptCommandProcessorBase(ScriptBlock scriptBlock, ExecutionContext context, bool useLocalScope, CommandOrigin origin, SessionStateInternal sessionState)
{
this._dontUseScopeCommandOrigin = false;
this.CommandInfo = new ScriptInfo(String.Empty, scriptBlock, context);
this._fromScriptFile = false;
CommonInitialization(scriptBlock, context, useLocalScope, origin, sessionState);
}
protected ScriptCommandProcessorBase(IScriptCommandInfo commandInfo, ExecutionContext context, bool useLocalScope, SessionStateInternal sessionState)
: base((CommandInfo)commandInfo)
{
Diagnostics.Assert(commandInfo != null, "commandInfo cannot be null");
Diagnostics.Assert(commandInfo.ScriptBlock != null, "scriptblock cannot be null");
this._fromScriptFile = (this.CommandInfo is ExternalScriptInfo || this.CommandInfo is ScriptInfo);
this._dontUseScopeCommandOrigin = true;
CommonInitialization(commandInfo.ScriptBlock, context, useLocalScope, CommandOrigin.Internal, sessionState);
}
/// <summary>
/// When executing a scriptblock, the command origin needs to be set for the current scope.
/// If this true, then the scope origin will be set to the command origin. If it's false,
/// then the scope origin will be set to Internal. This allows public functions to call
/// private functions but still see $MyInvocation.CommandOrigin as $true.
/// </summary>
protected bool _dontUseScopeCommandOrigin;
/// <summary>
/// If true, then an exit exception will be rethrown to instead of caught and processed...
/// </summary>
protected bool _rethrowExitException;
/// <summary>
/// This indicates whether exit is called during the execution of
/// script block.
/// </summary>
/// <remarks>
/// Exit command can be executed in any of begin/process/end blocks.
///
/// If exit is called in one block (for example, begin), any subsequent
/// blocks (for example, process and end) should not be executed.
/// </remarks>
protected bool _exitWasCalled;
protected ScriptBlock _scriptBlock;
private ScriptParameterBinderController _scriptParameterBinderController;
internal ScriptParameterBinderController ScriptParameterBinderController
{
get
{
if (_scriptParameterBinderController == null)
{
// Set up the hashtable that will be used to hold all of the bound parameters...
_scriptParameterBinderController =
new ScriptParameterBinderController(((IScriptCommandInfo)CommandInfo).ScriptBlock,
Command.MyInvocation, Context, Command, CommandScope);
_scriptParameterBinderController.CommandLineParameters.UpdateInvocationInfo(this.Command.MyInvocation);
this.Command.MyInvocation.UnboundArguments = _scriptParameterBinderController.DollarArgs;
}
return _scriptParameterBinderController;
}
}
/// <summary>
/// Helper function for setting up command object and commandRuntime object
/// for script command processor.
/// </summary>
protected void CommonInitialization(ScriptBlock scriptBlock, ExecutionContext context, bool useLocalScope, CommandOrigin origin, SessionStateInternal sessionState)
{
Diagnostics.Assert(context != null, "execution context cannot be null");
Diagnostics.Assert(context.Engine != null, "context.engine cannot be null");
this.CommandSessionState = sessionState;
this._context = context;
this._rethrowExitException = this.Context.ScriptCommandProcessorShouldRethrowExit;
this._context.ScriptCommandProcessorShouldRethrowExit = false;
ScriptCommand scriptCommand = new ScriptCommand { CommandInfo = this.CommandInfo };
this.Command = scriptCommand;
// WinBlue: 219115
// Set the command origin for the new ScriptCommand object since we're not
// going through command discovery here where it's usually set.
this.Command.CommandOriginInternal = origin;
this.Command.commandRuntime = this.commandRuntime = new MshCommandRuntime(this.Context, this.CommandInfo, scriptCommand);
this.CommandScope = useLocalScope
? CommandSessionState.NewScope(this.FromScriptFile)
: CommandSessionState.CurrentScope;
this.UseLocalScope = useLocalScope;
_scriptBlock = scriptBlock;
// If the script has been dotted, throw an error if it's from a different language mode.
// Unless it was a script loaded through -File, in which case the danger of dotting other
// language modes (getting internal functions in the user's state) isn't a danger
if ((!this.UseLocalScope) && (!this._rethrowExitException))
{
ValidateCompatibleLanguageMode(_scriptBlock, context.LanguageMode, Command.MyInvocation);
}
}
/// <summary>
/// Checks if user has requested help (for example passing "-?" parameter for a cmdlet)
/// and if yes, then returns the help target to display.
/// </summary>
/// <param name="helpTarget">help target to request</param>
/// <param name="helpCategory">help category to request</param>
/// <returns><c>true</c> if user requested help; <c>false</c> otherwise</returns>
internal override bool IsHelpRequested(out string helpTarget, out HelpCategory helpCategory)
{
if (arguments != null && CommandInfo != null && !string.IsNullOrEmpty(CommandInfo.Name) && _scriptBlock != null)
{
foreach (CommandParameterInternal parameter in this.arguments)
{
Dbg.Assert(parameter != null, "CommandProcessor.arguments shouldn't have any null arguments");
if (parameter.IsDashQuestion())
{
Dictionary<Ast, Token[]> scriptBlockTokenCache = new Dictionary<Ast, Token[]>();
string unused;
HelpInfo helpInfo = _scriptBlock.GetHelpInfo(context: Context, commandInfo: CommandInfo,
dontSearchOnRemoteComputer: false, scriptBlockTokenCache: scriptBlockTokenCache, helpFile: out unused, helpUriFromDotLink: out unused);
if (helpInfo == null)
{
break;
}
helpTarget = helpInfo.Name;
helpCategory = helpInfo.HelpCategory;
return true;
}
}
}
return base.IsHelpRequested(out helpTarget, out helpCategory);
}
}
/// <summary>
/// This class implements a command processor for script related commands.
/// </summary>
/// <remarks>
///
/// 1. Usage scenarios
///
/// ScriptCommandProcessor is used for four kinds of commands.
///
/// a. Functions and filters
///
/// For example,
///
/// function foo($a) {$a}
/// foo "my text"
///
/// Second command is an example of a function invocation.
///
/// In this case, a FunctionInfo object is provided while constructing
/// command processor.
///
/// b. Script File
///
/// For example,
///
/// . .\my.ps1
///
/// In this case, a ExternalScriptInfo or ScriptInfo object is provided
/// while constructing command processor.
///
/// c. ScriptBlock
///
/// For example,
///
/// . {$a = 5}
///
/// In this case, a ScriptBlock object is provided while constructing command
/// processor.
///
/// d. Script Text
///
/// This is used internally for directly running a text stream of script.
///
/// 2. Design
///
/// a. Script block
///
/// No matter how a script command processor is created, core piece of information
/// is always a ScriptBlock object, which can come from either a FunctionInfo object,
/// a ScriptInfo object, or directly parsed from script text.
///
/// b. Script scope
///
/// A script block can be executed either in current scope or in a new scope.
///
/// New scope created should be a scope supporting $script: in case the command
/// processor is created from a script file.
///
/// c. Begin/Process/End blocks
///
/// Each script block can have one block of script for begin/process/end. These map
/// to BeginProcessing, ProcessingRecord, and EndProcessing of cmdlet api.
///
/// d. ExitException handling
///
/// If the command processor is created based on a script file, its exit exception
/// handling is different in the sense that it indicates an exitcode instead of killing
/// current powershell session.
///
/// </remarks>
internal sealed class DlrScriptCommandProcessor : ScriptCommandProcessorBase
{
private new ScriptBlock _scriptBlock;
private readonly ArrayList _input = new ArrayList();
private MutableTuple _localsTuple;
private bool _runOptimizedCode;
private bool _argsBound;
private FunctionContext _functionContext;
internal DlrScriptCommandProcessor(ScriptBlock scriptBlock, ExecutionContext context, bool useNewScope, CommandOrigin origin, SessionStateInternal sessionState)
: base(scriptBlock, context, useNewScope, origin, sessionState)
{
Init();
}
internal DlrScriptCommandProcessor(FunctionInfo functionInfo, ExecutionContext context, bool useNewScope, SessionStateInternal sessionState)
: base(functionInfo, context, useNewScope, sessionState)
{
Init();
}
internal DlrScriptCommandProcessor(ScriptInfo scriptInfo, ExecutionContext context, bool useNewScope, SessionStateInternal sessionState)
: base(scriptInfo, context, useNewScope, sessionState)
{
Init();
}
internal DlrScriptCommandProcessor(ExternalScriptInfo scriptInfo, ExecutionContext context, bool useNewScope, SessionStateInternal sessionState)
: base(scriptInfo, context, useNewScope, sessionState)
{
Init();
}
private void Init()
{
_scriptBlock = base._scriptBlock;
_obsoleteAttribute = _scriptBlock.ObsoleteAttribute;
_runOptimizedCode = _scriptBlock.Compile(optimized: _context._debuggingMode > 0 ? false : UseLocalScope);
_localsTuple = _scriptBlock.MakeLocalsTuple(_runOptimizedCode);
}
/// <summary>
/// Get the ObsoleteAttribute of the current command
/// </summary>
internal override ObsoleteAttribute ObsoleteAttribute
{
get { return _obsoleteAttribute; }
}
private ObsoleteAttribute _obsoleteAttribute;
internal override void Prepare(IDictionary psDefaultParameterValues)
{
if (UseLocalScope)
{
Diagnostics.Assert(CommandScope.LocalsTuple == null, "a newly created scope shouldn't have it's tuple set.");
CommandScope.LocalsTuple = _localsTuple;
}
_localsTuple.SetAutomaticVariable(AutomaticVariable.MyInvocation, this.Command.MyInvocation, _context);
_scriptBlock.SetPSScriptRootAndPSCommandPath(_localsTuple, _context);
_functionContext = new FunctionContext
{
_executionContext = _context,
_outputPipe = commandRuntime.OutputPipe,
_localsTuple = _localsTuple,
_scriptBlock = _scriptBlock,
_file = _scriptBlock.File,
_debuggerHidden = _scriptBlock.DebuggerHidden,
_debuggerStepThrough = _scriptBlock.DebuggerStepThrough,
_sequencePoints = _scriptBlock.SequencePoints,
};
}
/// <summary>
/// Execute BeginProcessing part of command. It sets up the overall scope
/// object for this command and runs the begin clause of the script block if
/// it isn't empty.
/// </summary>
/// <exception cref="PipelineStoppedException">
/// a terminating error occurred, or the pipeline was otherwise stopped
/// </exception>
internal override void DoBegin()
{
if (!RanBeginAlready)
{
RanBeginAlready = true;
ScriptBlock.LogScriptBlockStart(_scriptBlock, Context.CurrentRunspace.InstanceId);
// Even if there is no begin, we need to set up the execution scope for this
// script...
SetCurrentScopeToExecutionScope();
CommandProcessorBase oldCurrentCommandProcessor = Context.CurrentCommandProcessor;
try
{
Context.CurrentCommandProcessor = this;
if (_scriptBlock.HasBeginBlock)
{
RunClause(_runOptimizedCode ? _scriptBlock.BeginBlock : _scriptBlock.UnoptimizedBeginBlock,
AutomationNull.Value, _input);
}
}
finally
{
Context.CurrentCommandProcessor = oldCurrentCommandProcessor;
RestorePreviousScope();
}
}
}
internal override void ProcessRecord()
{
if (_exitWasCalled)
{
return;
}
if (!this.RanBeginAlready)
{
RanBeginAlready = true;
if (_scriptBlock.HasBeginBlock)
{
RunClause(_runOptimizedCode ? _scriptBlock.BeginBlock : _scriptBlock.UnoptimizedBeginBlock, AutomationNull.Value, _input);
}
}
if (_scriptBlock.HasProcessBlock)
{
if (!IsPipelineInputExpected())
{
RunClause(_runOptimizedCode ? _scriptBlock.ProcessBlock : _scriptBlock.UnoptimizedProcessBlock, null, _input);
}
else
{
DoProcessRecordWithInput();
}
}
else if (IsPipelineInputExpected())
{
// accumulate the input when working in "synchronous" mode
Debug.Assert(this.Command.MyInvocation.PipelineIterationInfo != null); // this should have been allocated when the pipe was started
if (this.CommandRuntime.InputPipe.ExternalReader == null)
{
while (Read())
{
// accumulate all of the objects and execute at the end.
_input.Add(Command.CurrentPipelineObject);
}
}
}
}
internal override void Complete()
{
try
{
if (_exitWasCalled)
{
return;
}
// process any items that may still be in the input pipeline
if (_scriptBlock.HasProcessBlock && IsPipelineInputExpected())
{
DoProcessRecordWithInput();
}
if (_scriptBlock.HasEndBlock)
{
var endBlock = _runOptimizedCode ? _scriptBlock.EndBlock : _scriptBlock.UnoptimizedEndBlock;
if (this.CommandRuntime.InputPipe.ExternalReader == null)
{
if (IsPipelineInputExpected())
{
// read any items that may still be in the input pipe
while (Read())
{
_input.Add(Command.CurrentPipelineObject);
}
}
// run with accumulated input
RunClause(endBlock, AutomationNull.Value, _input);
}
else
{
// run with asynchronously updated $input enumerator
RunClause(endBlock, AutomationNull.Value, this.CommandRuntime.InputPipe.ExternalReader.GetReadEnumerator());
}
}
}
finally
{
ScriptBlock.LogScriptBlockEnd(_scriptBlock, Context.CurrentRunspace.InstanceId);
}
}
private void DoProcessRecordWithInput()
{
// block for input and execute "process" block for all input objects
Debug.Assert(this.Command.MyInvocation.PipelineIterationInfo != null); // this should have been allocated when the pipe was started
var processBlock = _runOptimizedCode ? _scriptBlock.ProcessBlock : _scriptBlock.UnoptimizedProcessBlock;
while (Read())
{
_input.Add(Command.CurrentPipelineObject);
this.Command.MyInvocation.PipelineIterationInfo[this.Command.MyInvocation.PipelinePosition]++;
RunClause(processBlock, Command.CurrentPipelineObject, _input);
// now clear input for next iteration; also makes it clear for the end clause.
_input.Clear();
}
}
private void RunClause(Action<FunctionContext> clause, object dollarUnderbar, object inputToProcess)
{
ExecutionContext.CheckStackDepth();
Pipe oldErrorOutputPipe = this.Context.ShellFunctionErrorOutputPipe;
// If the script block has a different language mode than the current,
// change the language mode.
PSLanguageMode? oldLanguageMode = null;
PSLanguageMode? newLanguageMode = null;
if ((_scriptBlock.LanguageMode.HasValue) &&
(_scriptBlock.LanguageMode != Context.LanguageMode))
{
oldLanguageMode = Context.LanguageMode;
newLanguageMode = _scriptBlock.LanguageMode;
}
try
{
var oldScopeOrigin = this.Context.EngineSessionState.CurrentScope.ScopeOrigin;
try
{
this.Context.EngineSessionState.CurrentScope.ScopeOrigin =
this._dontUseScopeCommandOrigin ? CommandOrigin.Internal : this.Command.CommandOrigin;
// Set the language mode. We do this before EnterScope(), so that the language
// mode is appropriately applied for evaluation parameter defaults.
if (newLanguageMode.HasValue)
{
Context.LanguageMode = newLanguageMode.Value;
}
EnterScope();
if (commandRuntime.ErrorMergeTo == MshCommandRuntime.MergeDataStream.Output)
{
Context.RedirectErrorPipe(commandRuntime.OutputPipe);
}
else if (commandRuntime.ErrorOutputPipe.IsRedirected)
{
Context.RedirectErrorPipe(commandRuntime.ErrorOutputPipe);
}
if (dollarUnderbar != AutomationNull.Value)
{
_localsTuple.SetAutomaticVariable(AutomaticVariable.Underbar, dollarUnderbar, _context);
}
if (inputToProcess != AutomationNull.Value)
{
if (inputToProcess == null)
{
inputToProcess = MshCommandRuntime.StaticEmptyArray.GetEnumerator();
}
else
{
IList list = inputToProcess as IList;
inputToProcess = (list != null)
? list.GetEnumerator()
: LanguagePrimitives.GetEnumerator(inputToProcess);
}
_localsTuple.SetAutomaticVariable(AutomaticVariable.Input, inputToProcess, _context);
}
clause(_functionContext);
}
catch (TargetInvocationException tie)
{
// DynamicInvoke wraps exceptions, unwrap them here.
throw tie.InnerException;
}
finally
{
this.Context.RestoreErrorPipe(oldErrorOutputPipe);
if (oldLanguageMode.HasValue)
{
Context.LanguageMode = oldLanguageMode.Value;
}
Context.EngineSessionState.CurrentScope.ScopeOrigin = oldScopeOrigin;
}
}
catch (ExitException ee)
{
if (!this.FromScriptFile || _rethrowExitException)
{
throw;
}
this._exitWasCalled = true;
int exitCode = (int)ee.Argument;
this.Command.Context.SetVariable(SpecialVariables.LastExitCodeVarPath, exitCode);
if (exitCode != 0)
this.commandRuntime.PipelineProcessor.ExecutionFailed = true;
}
catch (FlowControlException)
{
throw;
}
catch (RuntimeException e)
{
ManageScriptException(e); // always throws
// This quiets the compiler which wants to see a return value
// in all codepaths.
throw;
}
catch (Exception e)
{
CommandProcessorBase.CheckForSevereException(e);
// This cmdlet threw an exception, so
// wrap it and bubble it up.
throw ManageInvocationException(e);
}
}
private void EnterScope()
{
if (!_argsBound)
{
_argsBound = true;
// Parameter binder may need to write warning messages for obsolete parameters
using (commandRuntime.AllowThisCommandToWrite(false))
{
this.ScriptParameterBinderController.BindCommandLineParameters(arguments);
}
_localsTuple.SetAutomaticVariable(AutomaticVariable.PSBoundParameters,
this.ScriptParameterBinderController.CommandLineParameters.GetValueToBindToPSBoundParameters(), _context);
}
}
protected override void OnSetCurrentScope()
{
if (!UseLocalScope)
{
CommandSessionState.CurrentScope.DottedScopes.Push(_localsTuple);
}
}
protected override void OnRestorePreviousScope()
{
if (!UseLocalScope)
{
CommandSessionState.CurrentScope.DottedScopes.Pop();
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Runtime.Intrinsics;
namespace System.Runtime.Intrinsics.X86
{
/// <summary>
/// This class provides access to Intel SSE4.2 hardware instructions via intrinsics
/// </summary>
[CLSCompliant(false)]
public static class Sse42
{
public static bool IsSupported { get { return false; } }
/// <summary>
/// int _mm_cmpistra (__m128i a, __m128i b, const int imm8)
/// int _mm_cmpistrc (__m128i a, __m128i b, const int imm8)
/// int _mm_cmpistro (__m128i a, __m128i b, const int imm8)
/// int _mm_cmpistrs (__m128i a, __m128i b, const int imm8)
/// int _mm_cmpistrz (__m128i a, __m128i b, const int imm8)
/// </summary>
public static bool CompareImplicitLength(Vector128<sbyte> left, Vector128<sbyte> right, ResultsFlag flag, StringComparisonMode mode) { throw new NotImplementedException(); }
/// <summary>
/// int _mm_cmpistra (__m128i a, __m128i b, const int imm8)
/// int _mm_cmpistrc (__m128i a, __m128i b, const int imm8)
/// int _mm_cmpistro (__m128i a, __m128i b, const int imm8)
/// int _mm_cmpistrs (__m128i a, __m128i b, const int imm8)
/// int _mm_cmpistrz (__m128i a, __m128i b, const int imm8)
/// </summary>
public static bool CompareImplicitLength(Vector128<byte> left, Vector128<byte> right, ResultsFlag flag, StringComparisonMode mode) { throw new NotImplementedException(); }
/// <summary>
/// int _mm_cmpistra (__m128i a, __m128i b, const int imm8)
/// int _mm_cmpistrc (__m128i a, __m128i b, const int imm8)
/// int _mm_cmpistro (__m128i a, __m128i b, const int imm8)
/// int _mm_cmpistrs (__m128i a, __m128i b, const int imm8)
/// int _mm_cmpistrz (__m128i a, __m128i b, const int imm8)
/// </summary>
public static bool CompareImplicitLength(Vector128<short> left, Vector128<short> right, ResultsFlag flag, StringComparisonMode mode) { throw new NotImplementedException(); }
/// <summary>
/// int _mm_cmpistra (__m128i a, __m128i b, const int imm8)
/// int _mm_cmpistrc (__m128i a, __m128i b, const int imm8)
/// int _mm_cmpistro (__m128i a, __m128i b, const int imm8)
/// int _mm_cmpistrs (__m128i a, __m128i b, const int imm8)
/// int _mm_cmpistrz (__m128i a, __m128i b, const int imm8)
/// </summary>
public static bool CompareImplicitLength(Vector128<ushort> left, Vector128<ushort> right, ResultsFlag flag, StringComparisonMode mode) { throw new NotImplementedException(); }
/// <summary>
/// int _mm_cmpestra (__m128i a, int la, __m128i b, int lb, const int imm8)
/// int _mm_cmpestrc (__m128i a, int la, __m128i b, int lb, const int imm8)
/// int _mm_cmpestro (__m128i a, int la, __m128i b, int lb, const int imm8)
/// int _mm_cmpestrs (__m128i a, int la, __m128i b, int lb, const int imm8)
/// int _mm_cmpestrz (__m128i a, int la, __m128i b, int lb, const int imm8)
/// </summary>
public static bool CompareExplicitLength(Vector128<sbyte> left, byte leftLength, Vector128<sbyte> right, byte rightLength, ResultsFlag flag, StringComparisonMode mode) { throw new NotImplementedException(); }
/// <summary>
/// int _mm_cmpestra (__m128i a, int la, __m128i b, int lb, const int imm8)
/// int _mm_cmpestrc (__m128i a, int la, __m128i b, int lb, const int imm8)
/// int _mm_cmpestro (__m128i a, int la, __m128i b, int lb, const int imm8)
/// int _mm_cmpestrs (__m128i a, int la, __m128i b, int lb, const int imm8)
/// int _mm_cmpestrz (__m128i a, int la, __m128i b, int lb, const int imm8)
/// </summary>
public static bool CompareExplicitLength(Vector128<byte> left, byte leftLength, Vector128<byte> right, byte rightLength, ResultsFlag flag, StringComparisonMode mode) { throw new NotImplementedException(); }
/// <summary>
/// int _mm_cmpestra (__m128i a, int la, __m128i b, int lb, const int imm8)
/// int _mm_cmpestrc (__m128i a, int la, __m128i b, int lb, const int imm8)
/// int _mm_cmpestro (__m128i a, int la, __m128i b, int lb, const int imm8)
/// int _mm_cmpestrs (__m128i a, int la, __m128i b, int lb, const int imm8)
/// int _mm_cmpestrz (__m128i a, int la, __m128i b, int lb, const int imm8)
/// </summary>
public static bool CompareExplicitLength(Vector128<short> left, byte leftLength, Vector128<short> right, byte rightLength, ResultsFlag flag, StringComparisonMode mode) { throw new NotImplementedException(); }
/// <summary>
/// int _mm_cmpestra (__m128i a, int la, __m128i b, int lb, const int imm8)
/// int _mm_cmpestrc (__m128i a, int la, __m128i b, int lb, const int imm8)
/// int _mm_cmpestro (__m128i a, int la, __m128i b, int lb, const int imm8)
/// int _mm_cmpestrs (__m128i a, int la, __m128i b, int lb, const int imm8)
/// int _mm_cmpestrz (__m128i a, int la, __m128i b, int lb, const int imm8)
/// </summary>
public static bool CompareExplicitLength(Vector128<ushort> left, byte leftLength, Vector128<ushort> right, byte rightLength, ResultsFlag flag, StringComparisonMode mode) { throw new NotImplementedException(); }
/// <summary>
/// int _mm_cmpistri (__m128i a, __m128i b, const int imm8)
/// </summary>
public static int CompareImplicitLengthIndex(Vector128<sbyte> left, Vector128<sbyte> right, StringComparisonMode mode) { throw new NotImplementedException(); }
/// <summary>
/// int _mm_cmpistri (__m128i a, __m128i b, const int imm8)
/// </summary>
public static int CompareImplicitLengthIndex(Vector128<byte> left, Vector128<byte> right, StringComparisonMode mode) { throw new NotImplementedException(); }
/// <summary>
/// int _mm_cmpistri (__m128i a, __m128i b, const int imm8)
/// </summary>
public static int CompareImplicitLengthIndex(Vector128<short> left, Vector128<short> right, StringComparisonMode mode) { throw new NotImplementedException(); }
/// <summary>
/// int _mm_cmpistri (__m128i a, __m128i b, const int imm8)
/// </summary>
public static int CompareImplicitLengthIndex(Vector128<ushort> left, Vector128<ushort> right, StringComparisonMode mode) { throw new NotImplementedException(); }
/// <summary>
/// int _mm_cmpestri (__m128i a, int la, __m128i b, int lb, const int imm8)
/// </summary>
public static int CompareExplicitLengthIndex(Vector128<sbyte> left, byte leftLength, Vector128<sbyte> right, byte rightLength, StringComparisonMode mode) { throw new NotImplementedException(); }
/// <summary>
/// int _mm_cmpestri (__m128i a, int la, __m128i b, int lb, const int imm8)
/// </summary>
public static int CompareExplicitLengthIndex(Vector128<byte> left, byte leftLength, Vector128<byte> right, byte rightLength, StringComparisonMode mode) { throw new NotImplementedException(); }
/// <summary>
/// int _mm_cmpestri (__m128i a, int la, __m128i b, int lb, const int imm8)
/// </summary>
public static int CompareExplicitLengthIndex(Vector128<short> left, byte leftLength, Vector128<short> right, byte rightLength, StringComparisonMode mode) { throw new NotImplementedException(); }
/// <summary>
/// int _mm_cmpestri (__m128i a, int la, __m128i b, int lb, const int imm8)
/// </summary>
public static int CompareExplicitLengthIndex(Vector128<ushort> left, byte leftLength, Vector128<ushort> right, byte rightLength, StringComparisonMode mode) { throw new NotImplementedException(); }
/// <summary>
/// __m128i _mm_cmpistrm (__m128i a, __m128i b, const int imm8)
/// </summary>
public static Vector128<ushort> CompareImplicitLengthBitMask(Vector128<sbyte> left, Vector128<sbyte> right, StringComparisonMode mode) { throw new NotImplementedException(); }
/// <summary>
/// __m128i _mm_cmpistrm (__m128i a, __m128i b, const int imm8)
/// </summary>
public static Vector128<ushort> CompareImplicitLengthBitMask(Vector128<byte> left, Vector128<byte> right, StringComparisonMode mode) { throw new NotImplementedException(); }
/// <summary>
/// __m128i _mm_cmpistrm (__m128i a, __m128i b, const int imm8)
/// </summary>
public static Vector128<byte> CompareImplicitLengthBitMask(Vector128<short> left, Vector128<short> right, StringComparisonMode mode) { throw new NotImplementedException(); }
/// <summary>
/// __m128i _mm_cmpistrm (__m128i a, __m128i b, const int imm8)
/// </summary>
public static Vector128<byte> CompareImplicitLengthBitMask(Vector128<ushort> left, Vector128<ushort> right, StringComparisonMode mode) { throw new NotImplementedException(); }
/// <summary>
/// __m128i _mm_cmpistrm (__m128i a, __m128i b, const int imm8)
/// </summary>
public static Vector128<byte> CompareImplicitLengthUnitMask(Vector128<sbyte> left, Vector128<sbyte> right, StringComparisonMode mode) { throw new NotImplementedException(); }
/// <summary>
/// __m128i _mm_cmpistrm (__m128i a, __m128i b, const int imm8)
/// </summary>
public static Vector128<byte> CompareImplicitLengthUnitMask(Vector128<byte> left, Vector128<byte> right, StringComparisonMode mode) { throw new NotImplementedException(); }
/// <summary>
/// __m128i _mm_cmpistrm (__m128i a, __m128i b, const int imm8)
/// </summary>
public static Vector128<ushort> CompareImplicitLengthUnitMask(Vector128<short> left, Vector128<short> right, StringComparisonMode mode) { throw new NotImplementedException(); }
/// <summary>
/// __m128i _mm_cmpistrm (__m128i a, __m128i b, const int imm8)
/// </summary>
public static Vector128<ushort> CompareImplicitLengthUnitMask(Vector128<ushort> left, Vector128<ushort> right, StringComparisonMode mode) { throw new NotImplementedException(); }
/// <summary>
/// __m128i _mm_cmpestrm (__m128i a, int la, __m128i b, int lb, const int imm8)
/// </summary>
public static Vector128<ushort> CompareExplicitLengthBitMask(Vector128<sbyte> left, byte leftLength, Vector128<sbyte> right, byte rightLength, StringComparisonMode mode) { throw new NotImplementedException(); }
/// <summary>
/// __m128i _mm_cmpestrm (__m128i a, int la, __m128i b, int lb, const int imm8)
/// </summary>
public static Vector128<ushort> CompareExplicitLengthBitMask(Vector128<byte> left, byte leftLength, Vector128<byte> right, byte rightLength, StringComparisonMode mode) { throw new NotImplementedException(); }
/// <summary>
/// __m128i _mm_cmpestrm (__m128i a, int la, __m128i b, int lb, const int imm8)
/// </summary>
public static Vector128<byte> CompareExplicitLengthBitMask(Vector128<short> left, byte leftLength, Vector128<short> right, byte rightLength, StringComparisonMode mode) { throw new NotImplementedException(); }
/// <summary>
/// __m128i _mm_cmpestrm (__m128i a, int la, __m128i b, int lb, const int imm8)
/// </summary>
public static Vector128<byte> CompareExplicitLengthBitMask(Vector128<ushort> left, byte leftLength, Vector128<ushort> right, byte rightLength, StringComparisonMode mode) { throw new NotImplementedException(); }
/// <summary>
/// __m128i _mm_cmpestrm (__m128i a, int la, __m128i b, int lb, const int imm8)
/// </summary>
public static Vector128<byte> CompareExplicitLengthUnitMask(Vector128<sbyte> left, byte leftLength, Vector128<sbyte> right, byte rightLength, StringComparisonMode mode) { throw new NotImplementedException(); }
/// <summary>
/// __m128i _mm_cmpestrm (__m128i a, int la, __m128i b, int lb, const int imm8)
/// </summary>
public static Vector128<byte> CompareExplicitLengthUnitMask(Vector128<byte> left, byte leftLength, Vector128<byte> right, byte rightLength, StringComparisonMode mode) { throw new NotImplementedException(); }
/// <summary>
/// __m128i _mm_cmpestrm (__m128i a, int la, __m128i b, int lb, const int imm8)
/// </summary>
public static Vector128<ushort> CompareExplicitLengthUnitMask(Vector128<short> left, byte leftLength, Vector128<short> right, byte rightLength, StringComparisonMode mode) { throw new NotImplementedException(); }
/// <summary>
/// __m128i _mm_cmpestrm (__m128i a, int la, __m128i b, int lb, const int imm8)
/// </summary>
public static Vector128<ushort> CompareExplicitLengthUnitMask(Vector128<ushort> left, byte leftLength, Vector128<ushort> right, byte rightLength, StringComparisonMode mode) { throw new NotImplementedException(); }
/// <summary>
/// __m128i _mm_cmpgt_epi64 (__m128i a, __m128i b)
/// </summary>
public static Vector128<long> CompareGreaterThan(Vector128<long> left, Vector128<long> right) { throw new NotImplementedException(); }
/// <summary>
/// unsigned int _mm_crc32_u8 (unsigned int crc, unsigned char v)
/// </summary>
public static uint Crc32(uint crc, byte data) { throw new NotImplementedException(); }
/// <summary>
/// unsigned int _mm_crc32_u16 (unsigned int crc, unsigned short v)
/// </summary>
public static uint Crc32(uint crc, ushort data) { throw new NotImplementedException(); }
/// <summary>
/// unsigned int _mm_crc32_u32 (unsigned int crc, unsigned int v)
/// </summary>
public static uint Crc32(uint crc, uint data) { throw new NotImplementedException(); }
/// <summary>
/// unsigned __int64 _mm_crc32_u64 (unsigned __int64 crc, unsigned __int64 v)
/// </summary>
public static ulong Crc32(ulong crc, ulong data) { throw new NotImplementedException(); }
}
}
| |
namespace Genesis.Ensure.UnitTests
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Genesis.Ensure;
using Xunit;
public sealed class EnsureFixture
{
[Fact]
public void argument_not_null_does_not_throw_for_non_null_values()
{
Ensure.ArgumentNotNull("", "whatever");
Ensure.ArgumentNotNull(new object(), "whatever");
Ensure.ArgumentNotNull((int?)5, "whatever");
}
[Fact]
public void argument_not_null_throws_for_null_values()
{
Assert.Throws<ArgumentNullException>(() => Ensure.ArgumentNotNull((string)null, "whatever"));
Assert.Throws<ArgumentNullException>(() => Ensure.ArgumentNotNull((object)null, "whatever"));
Assert.Throws<ArgumentNullException>(() => Ensure.ArgumentNotNull((int?)null, "whatever"));
}
[Fact]
public void argument_not_null_does_not_throw_for_non_null_enumerations()
{
Ensure.ArgumentNotNull(new List<string>(), "whatever", true);
Ensure.ArgumentNotNull(new string[] { "one", "two" }, "whatever", true);
}
[Fact]
public void argument_not_null_throws_for_null_enumerations()
{
Assert.Throws<ArgumentNullException>(() => Ensure.ArgumentNotNull((List<string>)null, "whatever", true));
Assert.Throws<ArgumentNullException>(() => Ensure.ArgumentNotNull((string[])null, "whatever", true));
}
[Fact]
public void argument_not_null_does_not_throw_for_null_items_in_enumeration_if_assert_contents_is_false()
{
Ensure.ArgumentNotNull(new string[] { "foo", null }, "whatever", false);
}
[Fact]
public void argument_not_null_throws_if_item_is_null_and_assert_contents_is_true()
{
Assert.Throws<ArgumentException>(() => Ensure.ArgumentNotNull(new string[] { "foo", null }, "whatever", true));
}
[Fact]
public void generic_argument_not_null_does_not_throw_for_non_null_reference_arguments()
{
Ensure.GenericArgumentNotNull(new object(), "whatever");
Ensure.GenericArgumentNotNull("foo", "whatever");
Ensure.GenericArgumentNotNull(new Uri("http://www.example.com"), "whatever");
}
[Fact]
public void generic_argument_not_null_throws_for_null_reference_arguments()
{
Assert.Throws<ArgumentNullException>(() => Ensure.GenericArgumentNotNull<object>(null, "whatever"));
Assert.Throws<ArgumentNullException>(() => Ensure.GenericArgumentNotNull<string>(null, "whatever"));
Assert.Throws<ArgumentNullException>(() => Ensure.GenericArgumentNotNull<Uri>(null, "whatever"));
}
[Fact]
public void generic_argument_not_null_does_not_throw_for_non_null_nullable_arguments()
{
Ensure.GenericArgumentNotNull<int?>(42, "whatever");
Ensure.GenericArgumentNotNull<float?>(3f, "whatever");
Ensure.GenericArgumentNotNull<DateTime?>(DateTime.UtcNow, "whatever");
}
[Fact]
public void generic_argument_not_null_throws_for_null_nullable_arguments()
{
Assert.Throws<ArgumentNullException>(() => Ensure.GenericArgumentNotNull<int?>(null, "whatever"));
Assert.Throws<ArgumentNullException>(() => Ensure.GenericArgumentNotNull<float?>(null, "whatever"));
Assert.Throws<ArgumentNullException>(() => Ensure.GenericArgumentNotNull<DateTime?>(null, "whatever"));
}
[Fact]
public void argument_not_null_or_empty_does_not_throw_for_non_null_and_non_empty_values()
{
Ensure.ArgumentNotNullOrEmpty("foo", "whatever");
Ensure.ArgumentNotNullOrEmpty("bar", "whatever");
Ensure.ArgumentNotNullOrEmpty((IEnumerable<string>)new string[] { "foo" }, "whatever");
Ensure.ArgumentNotNullOrEmpty(new string[] { "foo" }, "whatever");
}
[Fact]
public void argument_not_null_or_empty_throws_if_argument_is_null()
{
Assert.Throws<ArgumentNullException>(() => Ensure.ArgumentNotNullOrEmpty((string)null, "whatever"));
Assert.Throws<ArgumentNullException>(() => Ensure.ArgumentNotNullOrEmpty((IEnumerable<string>)null, "whatever"));
Assert.Throws<ArgumentNullException>(() => Ensure.ArgumentNotNullOrEmpty((string[])null, "whatever"));
}
[Fact]
public void argument_not_null_or_empty_throws_if_argument_is_empty()
{
Assert.Throws<ArgumentException>(() => Ensure.ArgumentNotNullOrEmpty("", "whatever"));
Assert.Throws<ArgumentException>(() => Ensure.ArgumentNotNullOrEmpty(Enumerable.Empty<string>(), "whatever"));
Assert.Throws<ArgumentException>(() => Ensure.ArgumentNotNullOrEmpty(new string[0], "whatever"));
}
[Fact]
public void argument_not_null_or_whitespace_does_not_throw_for_non_null_and_non_whitespace_values()
{
Ensure.ArgumentNotNullOrWhiteSpace("foo", "whatever");
Ensure.ArgumentNotNullOrWhiteSpace("bar", "whatever");
}
[Fact]
public void argument_not_null_or_whitespace_throws_if_argument_is_null()
{
Assert.Throws<ArgumentNullException>(() => Ensure.ArgumentNotNullOrWhiteSpace(null, "whatever"));
}
[Theory]
[InlineData("")]
[InlineData(" ")]
[InlineData(" \t \r\n ")]
public void argument_not_null_or_whitespace_throws_if_argument_is_invalid(string invalidValue)
{
Assert.Throws<ArgumentException>(() => Ensure.ArgumentNotNullOrWhiteSpace(invalidValue, "whatever"));
}
[Fact]
public void argument_condition_does_not_throw_if_condition_holds()
{
Ensure.ArgumentCondition(true, "message", "whatever");
}
[Theory]
[InlineData("message", "argumentName")]
[InlineData("foo", "bar")]
public void argument_condition_throws_if_condition_does_not_hold(string message, string argumentName)
{
var ex = Assert.Throws<ArgumentException>(() => Ensure.ArgumentCondition(false, message, argumentName));
Assert.StartsWith(message, ex.Message);
Assert.Equal(argumentName, ex.ParamName);
}
[Fact]
public void argument_is_valid_enum_throws_if_given_invalid_flag_enumeration_value()
{
var ex = Assert.Throws<ArgumentException>(() => Ensure.ArgumentIsValidEnum((FlagsEnum)68, "test"));
Assert.Equal(string.Format(CultureInfo.InvariantCulture, "Enum value '68' is not valid for flags enumeration 'Genesis.Ensure.UnitTests.EnsureFixture+FlagsEnum'.{0}Parameter name: test", Environment.NewLine), ex.Message);
}
[Fact]
public void argument_is_valid_enum_throws_if_given_invalid_zero_flag_enumeration_value()
{
var ex = Assert.Throws<ArgumentException>(() => Ensure.ArgumentIsValidEnum((FlagsEnumNoNone)0, "test"));
Assert.Equal(string.Format(CultureInfo.InvariantCulture, "Enum value '0' is not valid for flags enumeration 'Genesis.Ensure.UnitTests.EnsureFixture+FlagsEnumNoNone'.{0}Parameter name: test", Environment.NewLine), ex.Message);
}
[Fact]
public void argument_is_valid_enum_does_not_throw_if_enumeration_flags_are_valid()
{
Ensure.ArgumentIsValidEnum(FlagsEnum.None, "test");
Ensure.ArgumentIsValidEnum(FlagsEnum.One, "test");
Ensure.ArgumentIsValidEnum(FlagsEnum.Two, "test");
Ensure.ArgumentIsValidEnum(FlagsEnum.Three, "test");
Ensure.ArgumentIsValidEnum(FlagsEnum.Four, "test");
Ensure.ArgumentIsValidEnum(FlagsEnum.One | FlagsEnum.Two, "test");
Ensure.ArgumentIsValidEnum(FlagsEnum.Two | FlagsEnum.Four, "test");
Ensure.ArgumentIsValidEnum(FlagsEnum.One | FlagsEnum.Two | FlagsEnum.Three, "test");
Ensure.ArgumentIsValidEnum(FlagsEnum.One | FlagsEnum.Two | FlagsEnum.Three | FlagsEnum.Four, "test");
}
[Fact]
public void argument_is_valid_enum_throws_if_enumeration_value_is_invalid()
{
var ex = Assert.Throws<ArgumentException>(() => Ensure.ArgumentIsValidEnum((DayOfWeek)69, "test"));
Assert.Equal(string.Format(CultureInfo.InvariantCulture, "Enum value '69' is not defined for enumeration 'System.DayOfWeek'.{0}Parameter name: test", Environment.NewLine), ex.Message);
}
[Fact]
public void argument_is_valid_enum_does_not_throw_if_enumeration_values_are_valid()
{
Ensure.ArgumentIsValidEnum(DayOfWeek.Monday, "test");
Ensure.ArgumentIsValidEnum((DayOfWeek)3, "test");
}
[Fact]
public void argument_is_valid_enum_works_for_byte_flags_enumeration()
{
Ensure.ArgumentIsValidEnum(ByteFlagsEnum.One | ByteFlagsEnum.Three, "test");
Ensure.ArgumentIsValidEnum(ByteFlagsEnum.None, "test");
Ensure.ArgumentIsValidEnum(ByteFlagsEnum.One | ByteFlagsEnum.Two | ByteFlagsEnum.Three, "test");
var ex = Assert.Throws<ArgumentException>(() => Ensure.ArgumentIsValidEnum((ByteFlagsEnum)80, "test"));
Assert.Equal(string.Format(CultureInfo.InvariantCulture, "Enum value '80' is not valid for flags enumeration 'Genesis.Ensure.UnitTests.EnsureFixture+ByteFlagsEnum'.{0}Parameter name: test", Environment.NewLine), ex.Message);
}
[Fact]
public void argument_is_valid_enum_works_for_byte_enumeration()
{
Ensure.ArgumentIsValidEnum(ByteEnum.One, "test");
Ensure.ArgumentIsValidEnum(ByteEnum.Two, "test");
Ensure.ArgumentIsValidEnum(ByteEnum.Three, "test");
var ex = Assert.Throws<ArgumentException>(() => Ensure.ArgumentIsValidEnum((ByteEnum)10, "test"));
Assert.Equal(string.Format(CultureInfo.InvariantCulture, "Enum value '10' is not defined for enumeration 'Genesis.Ensure.UnitTests.EnsureFixture+ByteEnum'.{0}Parameter name: test", Environment.NewLine), ex.Message);
}
[Fact]
public void argument_is_valid_enum_throws_if_no_valid_values_are_provided()
{
Assert.Throws<ArgumentNullException>(() => Ensure.ArgumentIsValidEnum(DayOfWeek.Monday, "test", null));
}
[Fact]
public void argument_is_valid_enum_throws_if_flag_value_is_not_a_valid_value()
{
var ex = Assert.Throws<ArgumentException>(() => Ensure.ArgumentIsValidEnum(FlagsEnum.Three, "test", FlagsEnum.One, FlagsEnum.Two, FlagsEnum.Four));
Assert.Equal(string.Format(CultureInfo.InvariantCulture, "Enum value 'Three' is not valid for flags enumeration 'Genesis.Ensure.UnitTests.EnsureFixture+FlagsEnum'.{0}Parameter name: test", Environment.NewLine), ex.Message);
}
[Fact]
public void argument_is_valid_enum_throws_if_valid_flag_values_are_provided_but_the_enumeration_value_is_not_a_valid_flag_enumeration_value()
{
var ex = Assert.Throws<ArgumentException>(() => Ensure.ArgumentIsValidEnum((FlagsEnum)68, "test", FlagsEnum.One, FlagsEnum.Two, FlagsEnum.Four));
Assert.Equal(string.Format(CultureInfo.InvariantCulture, "Enum value '68' is not valid for flags enumeration 'Genesis.Ensure.UnitTests.EnsureFixture+FlagsEnum'.{0}Parameter name: test", Environment.NewLine), ex.Message);
}
[Fact]
public void argument_is_valid_enum_throws_if_invalid_zero_flag_enumeration_value_is_passed_in_but_it_is_not_a_valid_value()
{
var ex = Assert.Throws<ArgumentException>(() => Ensure.ArgumentIsValidEnum((FlagsEnumNoNone)0, "test", FlagsEnumNoNone.One));
Assert.Equal(string.Format(CultureInfo.InvariantCulture, "Enum value '0' is not valid for flags enumeration 'Genesis.Ensure.UnitTests.EnsureFixture+FlagsEnumNoNone'.{0}Parameter name: test", Environment.NewLine), ex.Message);
}
[Fact]
public void argument_is_valid_enum_throws_if_zero_flag_enumeration_value_is_passed_in_but_it_is_not_a_valid_value()
{
var ex = Assert.Throws<ArgumentException>(() => Ensure.ArgumentIsValidEnum(FlagsEnum.None, "test", FlagsEnum.One));
Assert.Equal(string.Format(CultureInfo.InvariantCulture, "Enum value 'None' is not valid for flags enumeration 'Genesis.Ensure.UnitTests.EnsureFixture+FlagsEnum'.{0}Parameter name: test", Environment.NewLine), ex.Message);
}
[Fact]
public void argument_is_valid_enum_does_not_throw_if_flag_enumeration_values_are_valid()
{
var validValues = new FlagsEnum[] { FlagsEnum.One, FlagsEnum.Two, FlagsEnum.Four, FlagsEnum.None };
Ensure.ArgumentIsValidEnum(FlagsEnum.None, "test", validValues);
Ensure.ArgumentIsValidEnum(FlagsEnum.One, "test", validValues);
Ensure.ArgumentIsValidEnum(FlagsEnum.Two, "test", validValues);
Ensure.ArgumentIsValidEnum(FlagsEnum.Four, "test", validValues);
Ensure.ArgumentIsValidEnum(FlagsEnum.One | FlagsEnum.Two, "test", validValues);
Ensure.ArgumentIsValidEnum(FlagsEnum.One | FlagsEnum.Four, "test", validValues);
Ensure.ArgumentIsValidEnum(FlagsEnum.One | FlagsEnum.Two | FlagsEnum.Four, "test", validValues);
}
[Fact]
public void argument_is_valid_enum_throws_if_value_is_not_a_valid_value()
{
var ex = Assert.Throws<ArgumentException>(() => Ensure.ArgumentIsValidEnum(DayOfWeek.Monday, "test", DayOfWeek.Friday, DayOfWeek.Sunday));
Assert.Equal(string.Format(CultureInfo.InvariantCulture, "Enum value 'Monday' is defined for enumeration 'System.DayOfWeek' but it is not permitted in this context.{0}Parameter name: test", Environment.NewLine), ex.Message);
}
[Fact]
public void argument_is_valid_enum_throws_if_valid_values_are_provided_but_the_enumeration_value_is_not_a_valid_enumeration_value()
{
var ex = Assert.Throws<ArgumentException>(() => Ensure.ArgumentIsValidEnum((DayOfWeek)69, "test", DayOfWeek.Friday, DayOfWeek.Sunday));
Assert.Equal(string.Format(CultureInfo.InvariantCulture, "Enum value '69' is not defined for enumeration 'System.DayOfWeek'.{0}Parameter name: test", Environment.NewLine), ex.Message);
}
[Fact]
public void argument_is_valid_enum_does_not_throw_if_valid_values_are_specified_and_enumeration_values_are_valid()
{
var validValues = new DayOfWeek[] { DayOfWeek.Friday, DayOfWeek.Sunday, DayOfWeek.Saturday };
Ensure.ArgumentIsValidEnum(DayOfWeek.Friday, "test", validValues);
Ensure.ArgumentIsValidEnum(DayOfWeek.Sunday, "test", validValues);
Ensure.ArgumentIsValidEnum(DayOfWeek.Saturday, "test", validValues);
}
[Fact]
public void condition_does_not_throw_if_condition_holds()
{
Ensure.Condition(true, () => new Exception());
}
[Fact]
public void condition_throws_if_condition_does_not_hold()
{
Assert.Throws<InvalidOperationException>(() => Ensure.Condition(false, () => new InvalidOperationException()));
}
#region Supporting Types
[Flags]
private enum FlagsEnum
{
None = 0,
One = 1,
Two = 2,
Three = 4,
Four = 8
}
[Flags]
private enum FlagsEnumNoNone
{
One = 1,
}
private enum ByteEnum : byte
{
One,
Two,
Three
}
[Flags]
private enum ByteFlagsEnum : byte
{
None = 0,
One = 1,
Two = 2,
Three = 4
}
#endregion
}
}
| |
using System;
using System.IO;
using System.Collections;
//(COMMA^ IDENT ("="! expr)? )*
namespace GrillScript
{
public class Environment
{
private Environment Parent;
private SortedList TypingEnv;
private int AutoVariable;
public ArrayList ServiceFunctions;
public bool IsServiceFunc(string x)
{
return ServiceFunctions.Contains(x);
}
public int GetAutoVariable()
{
if(Parent==null)
{
int v = AutoVariable;
AutoVariable++;
return v;
}
return Parent.GetAutoVariable();
}
public Environment()
{
AutoVariable = 0;
TypingEnv = new SortedList();
Parent = null;
}
public Environment(Environment P)
{
AutoVariable = 0;
TypingEnv = new SortedList();
ServiceFunctions = P.ServiceFunctions;
Parent = P;
}
public void Map(string x, object o)
{
if(TypingEnv.Contains(x))
TypingEnv[x] = o;
else
TypingEnv.Add(x,o);
}
public object Get(string x)
{
if(TypingEnv.Contains(x))
return TypingEnv[x];
if(Parent!=null)
return Parent.Get(x);
return null;
}
}
public class Compiler
{
public static ArrayList AnonymousFunctions = new ArrayList();
class AnonyFunction
{
public string name;
// global declaration
public string gDECL;
};
public static string CompileReturnType(LispNode N)
{
return N.node;
}
public static string CompileInlineFunction(LispNode N, Environment E)
{
AnonyFunction F = new AnonyFunction();
F.name = "anony_fun_" + AnonymousFunctions.Count;
AnonymousFunctions.Add(F);
ArrayList L2 = FreeVariables.GetFreeVariables(N);
ArrayList L = new ArrayList();
foreach(string x in L2)
{
if(ExpressionTyping.IsMathFunctionTrueImpliesArity(x) < 0 && ! E.IsServiceFunc(x))
{
L.Add(x);
}
}
string cRef = "(closure " + F.name + " ";
string cImp = "";
string pTyps = "";
int e = 0;
foreach(string x in L)
{
string typx = (string) E.Get(x);
if(ExpressionTyping.IsFunctional(typx))
throw new Exception("Super Error: Anonymous Closure has reference to a closure.. bad");
if(typx.IndexOf("*")>=0)
typx = "array";
else
typx = GetMachineType2(typx);
cRef += "(m "+typx+" " + x + ")";
if(typx.Equals("array"))
{
cImp += "(" + typx+" " + x + ")";
cImp += "(set " + x + " (cl " + typx + pTyps+"))";
}
else
{
cImp += "(" + typx+" " + x + " (cl " + typx + pTyps+"))";
}
pTyps += " " + typx;
e++;
}
cRef += ")";
Environment eN = new Environment(E);
F.gDECL = "(func " + CompileReturnType(N.children[0]) + " " + F.name + " ";
if(N.children[1].children != null)
{
for(uint i = 0; i < N.children[1].children.Length; i++)
{
LispNode C = N.children[1].children[i];
if( ExpressionTyping.IsSpecialRealType(C.children[0]))
{
string SSS = "real*";
eN.Map(C.children[1].node, SSS);
F.gDECL += "(array " + C.children[1].node + ")";
}
else
{
string SSS = GetMachineType(C.children[0]);
string ptr = "";
for(int x = 2; x < C.children.Length; x++)
{
ptr += "*";
}
eN.Map(C.children[1].node, C.children[0].node + ptr);
if(ptr.Length > 0) SSS = "array";
F.gDECL += "(" + SSS + " " + C.children[1].node + ")";
}
}
}
string body = CompileStatement(N.children[2],eN);
F.gDECL += "(seq " + cImp + body + "))";
return cRef;
/*
LispNode Body = N.children[3];
func += CompileStatement(Body,eN);
return func + ")";;
*/
/*
Environment eN = new Environment(E);
string func = "(func " + CompileReturnType(N.children[0]) + " " + N.children[1].node+" ";
if(N.children[2].children != null)
{
for(uint i = 0; i < N.children[2].children.Length; i++)
{
LispNode C = N.children[2].children[i];
if( ExpressionTyping.IsSpecialRealType(C.children[0]))
{
string SSS = "real*";
eN.Map(C.children[1].node, SSS);
func += "(array " + C.children[1].node + ")";
}
else
{
string SSS = GetMachineType(C.children[0]);
string ptr = "";
for(int x = 2; x < C.children.Length; x++)
{
ptr += "*";
}
eN.Map(C.children[1].node, C.children[0].node + ptr);
if(ptr.Length > 0) SSS = "array";
func += "(" + SSS + " " + C.children[1].node + ")";
}
}
}
LispNode Body = N.children[3];
func += CompileStatement(Body,eN);
return func + ")";;
*/
// return "";
}
public static string CompileConstant(LispNode N)
{
if(N.node.Equals("null")) return "(int 0)";
if(N.node.Equals("nil")) return "(int 0)";
if(N.node.Equals("true")) return "(int 1)";
if(N.node.Equals("false")) return "(int 0)";
if(N.node.Equals("dom")) return "(dom)";
if(N.node.Equals("document")) return "(dom)";
if(N.node.Equals("random")) return "(random)";
if(N.node.Equals("pi")) return "(real 3.1415926535897932384626433832795)";
if(N.node.Equals("euler")) return "(real 2.7182818284590452353602874713527)";
if(N.node.Equals("real")) return "(real " + N.children[0].node + "." + N.children[1].node + ")";
if(N.node.Equals("integer")) return "(int " + N.children[0].node + ")";
if(N.node.Equals("string"))
{
string o = "(iarray ";
string str = N.children[0].node;
// Console.WriteLine(":" + str);
int cnt = str.Length;
o += "" + cnt + " 1 char ";
for(int k = 0; k < cnt; k++)
{
o += "(char "+(int)str[k] + ")";
}
o += ")";
//Console.WriteLine("input:" + str);
//Console.WriteLine("output:" + o);
//return "(iarray " + sz + " " + pit + " " + GetMachineType2(typ) + " " + items + ")";
//Console.WriteLine("GOT
//string xyz = "(iarray " + N
return o;
}
throw new Exception("not supported");
}
public static string CompileExpression(LispNode N, Environment E)
{
if(N.node.Equals("|"))
{
return "(math abs " + CompileExpression(N.children[0],E) + ")";
}
if(N.node.Equals("inline_function"))
{
return CompileInlineFunction(N,E);
}
if(N.node.Equals("inline_array"))
{
int pit = N.children[0].children.Length;
int sz = pit * N.children.Length;
string typ = ExpressionTyping.TypeExpression(N.children[0].children[0],E);
string items = "";
for(int k = 0; k < N.children.Length; k++)
{
if(N.children[k].children.Length != pit)
{
throw new Exception("alignment on inline array");
}
for(int j = 0; j < pit; j++)
{
string ltyp = ExpressionTyping.TypeExpression(N.children[k].children[j], E);
if(ltyp.Equals(typ))
{
// everything is good
}
else
{
if(ltyp.Equals("int") && typ.Equals("real"))
{
}
else if(ltyp.Equals("real") && typ.Equals("int"))
{
typ = "real";
}
else
{
throw new Exception("type mismatch! " + ltyp + ":" + typ);
}
}
items += CompileExpression(N.children[k].children[j], E);
}
}
return "(iarray " + sz + " " + pit + " " + GetMachineType2(typ) + " " + items + ")";
}
if(ExpressionTyping.IsConstant(N))
return CompileConstant(N);
if(ExpressionTyping.IsArithmeticOperator(N)
|| ExpressionTyping.IsComparionOperator(N)
|| ExpressionTyping.IsBooleanOperator(N)
|| N.node.Equals("len")
|| N.node.Equals("?")
|| N.node.Equals("once")
)
{
string arith = "(" + N.node + " ";
if(N.node.Equals("fun_app")) arith = "(apply ";
for(uint k = 0; k < N.children.Length; k++)
arith += CompileExpression(N.children[k],E);
return arith + ")";
}
if(N.node.Equals("request"))
{
string arith = "(request " + N.children[0].node + " ";
for(uint k = 1; k < N.children.Length; k++)
arith += CompileExpression(N.children[k],E);
return arith + ")";
}
if(N.node.Equals("fun_app") )
{
bool isMath = false;
if(N.children[0].node.Equals("var"))
{
int mTy = ExpressionTyping.IsMathFunctionTrueImpliesArity(N.children[0].children[0].node);
if(mTy > 0)
{
isMath = true;
string math = "(math " + N.children[0].children[0].node.ToLower() + " ";
if(mTy < 100)
if(N.children.Length-1!=mTy)
throw new Exception("Math Function:" + N.children[0].children[0].node + "invalid arity");
for(uint k = 1; k < N.children.Length; k++)
math += CompileExpression(N.children[k],E);
return math + ")";
}
}
if(!isMath)
{
string app = "(apply ";
for(uint k = 0; k < N.children.Length; k++)
app += CompileExpression(N.children[k],E);
return app + ")";
}
}
if(N.node.Equals("as"))
{
return CompileExpression(N.children[0],E);
}
if(N.node.Equals("var"))
return " " + N.children[0].node + " ";
if(N.node.Equals("."))
{
LispNode PtrObj = N.children[0];
string Field = N.children[1].node;
string TypClass = ExpressionTyping.TypeExpression(PtrObj,E);
if(ExpressionTyping.IsContract(TypClass))
{
return "(fcon " + TypClass + " " + Field + " " + CompileExpression(PtrObj,E) + ")";
}
else
{
return "(fref " + TypClass + " " + Field + " " + CompileExpression(PtrObj,E) + ")";
}
}
if(N.node.Equals("["))
{
string exr = CompileExpression(N.children[0],E);
string xzz = CompileExpression(N.children[1],E);
if(N.children.Length > 2)
return "(eref2 " + exr + xzz + CompileExpression(N.children[2],E) + ")";
else
return "(eref " + exr + xzz + ")";
}
throw new Exception("unk-Node:"+N.node + "\n::" + N.str() );
}
public static string GetMachineType(LispNode N)
{
string ty = "";
if(ExpressionTyping.IsIntegralType(N.node) || N.node.Equals("void"))
ty += "int";
else if(ExpressionTyping.IsCharacterType(N.node))
ty += "char";
else if(ExpressionTyping.IsRealType(N.node))
ty += "real";
else if(ExpressionTyping.IsFunctional(N.node))
ty += "fun";
else if(N.node.Equals("string") || N.str().IndexOf("[") >= 0 || N.node.Equals("array") )
ty += "array";
else
ty += "ptr";
return ty;
}
public static string GetMachineType2(string s)
{
string ty = "";
if(ExpressionTyping.IsIntegralType(s) || s.Equals("void"))
ty += "int";
else if(ExpressionTyping.IsCharacterType(s))
ty += "char";
else if(ExpressionTyping.IsRealType(s))
ty += "real";
else if(ExpressionTyping.IsFunctional(s))
ty += "fun";
else if(s.Equals("string") || s.Equals("array") )
ty += "array";
else
ty += "ptr";
return ty;
}
public static string CompileAssignment(LispNode N, Environment E)
{
// (set var expr)
LispNode A = N.children[0];
if(N.node.Equals("="))
{
LispNode B = N.children[1];
if(A.node.Equals("."))
{
LispNode D = A.children[0];
string Field = A.children[1].node;
string TypClass = ExpressionTyping.TypeExpression(D,E);
if(TypClass.Equals("?"))
throw new Exception("couldn't type expression:" + N.str());
if(ExpressionTyping.IsContract(TypClass))
{
string PTR = CompileExpression(D,E);
string VAL = CompileExpression(B,E);
return "(scon "+TypClass+" "+Field+" " + PTR + " " + VAL + " )";
}
else
{
string PTR = CompileExpression(D,E);
string VAL = CompileExpression(B,E);
return "(sref "+TypClass+" "+Field+" " + PTR + " " + VAL + " )";
}
}
else if(A.node.Equals("["))
{
if(A.children.Length == 2)
{
string PTR = CompileExpression(A.children[0],E);
string IDX = CompileExpression(A.children[1],E);
string XPR = CompileExpression(B,E);
return "(eset " + PTR + IDX + XPR + ")";
}
else if(A.children.Length == 3)
{
string PTR = CompileExpression(A.children[0],E);
string IDX = CompileExpression(A.children[1],E);
string IDX2 = CompileExpression(A.children[2],E);
string XPR = CompileExpression(B,E);
return "(eset2 " + PTR + IDX + IDX2 + XPR + ")";
}
}
else
{
return "(set " + A.children[0].node + " " + CompileExpression(B,E) + ")";
}
}
else
{
if(N.node.Equals("++"))
{
LispNode Comp = new LispNode("+",new ArrayList());
Comp.children = new LispNode[2];
Comp.children[0] = A;
Comp.children[1] = new LispNode("integer",new ArrayList());
Comp.children[1].children = new LispNode[1];
Comp.children[1].children[0] = new LispNode("1",new ArrayList());
LispNode Next = new LispNode("=",new ArrayList());
Next.children = new LispNode[2];
Next.children[0] = A;
Next.children[1] = Comp;
return CompileAssignment(Next,E);
}
if(N.node.Equals("--"))
{
LispNode Comp = new LispNode("-",new ArrayList());
Comp.children = new LispNode[2];
Comp.children[0] = A;
Comp.children[1] = new LispNode("integer",new ArrayList());
Comp.children[1].children = new LispNode[1];
Comp.children[1].children[0] = new LispNode("1",new ArrayList());
LispNode Next = new LispNode("=",new ArrayList());
Next.children = new LispNode[2];
Next.children[0] = A;
Next.children[1] = Comp;
return CompileAssignment(Next,E);
}
//Console.WriteLine("UNKNOWN ASSIGNMENT:" + N.node + " => " + N.str());
//Console.WriteLine("LEFT:"+A.str());
if(N.children.Length>1)
{
LispNode B = N.children[1];
//Console.WriteLine("RIGHT:"+B.str());
string op = "OPP";
if(N.node.Equals("+=")) op = "+";
if(N.node.Equals("-=")) op = "-";
if(N.node.Equals("*=")) op = "*";
if(N.node.Equals("/=")) op = "/";
if(N.node.Equals("%=")) op = "%";
if(N.node.Equals("|=")) op = "||";
if(N.node.Equals("&=")) op = "&&";
if(N.node.Equals("^=")) op = "^^";
LispNode Comp = new LispNode(op,new ArrayList());
Comp.children = new LispNode[2];
Comp.children[0] = A;
Comp.children[1] = B;
LispNode Next = new LispNode("=",new ArrayList());
Next.children = new LispNode[2];
Next.children[0] = A;
Next.children[1] = Comp;
return CompileAssignment(Next,E);
}
}
return "";
// return CompileAssignment(N,E);
}
public static string CompileStatement(LispNode N, Environment E)
{
// Blocks
if(N.node.Equals("block"))
{
if(N.children != null)
{
Environment eN = new Environment(E);
// Push Environments
string seq = "";
for(uint i = 0; i < N.children.Length; i++)
seq += CompileStatement(N.children[i],eN);
return "(seq " + seq + ")";
}
return "(seq )";
}
// Declarations
if(N.node.Equals("decl"))
{
string decl = "(";
if( ExpressionTyping.IsSpecialRealType(N.children[0]))
{
string Nae = N.children[1].node;
E.Map(Nae,"real*");
// define it and specialize
int wid = ExpressionTyping.GetSpecialRealTypeWidth(N.children[0]);
int pit = ExpressionTyping.GetSpecialRealTypePitch(N.children[0]);
decl += "array " + Nae + " real (int "+wid+"))";
decl += "(setarrpit " + Nae + " (int " + pit + "))";
// return "(set " + A.children[0].node + " " + CompileExpression(B,E) + ")";
if(N.children.Length > 2)
{
decl += "(set " + Nae + " " + CompileExpression(N.children[2],E) + ")";
}
//E.Map(Nae,N.children[0].node + "*");
return decl;
}
else if(N.children[0].node.Equals("string"))
{
string Nae = N.children[1].node;
E.Map(Nae,"string");
// define it and specialize
decl += "array " + Nae + ")";
// return "(set " + A.children[0].node + " " + CompileExpression(B,E) + ")";
if(N.children.Length > 2)
{
decl += "(set " + Nae + " " + CompileExpression(N.children[2],E) + ")";
}
//E.Map(Nae,N.children[0].node + "*");
return decl;
}
else
{
if( ExpressionTyping.IsFunctional(N.children[0].node))
{
E.Map(N.children[1].node,"fun");
}
else
{
E.Map(N.children[1].node,N.children[0].node);
}
decl += GetMachineType(N.children[0]);
decl += " ";
decl += N.children[1].node;
if(N.children.Length > 2)
{
decl += " " + CompileExpression(N.children[2],E);
}
return decl + ")";
}
}
if(N.node.Equals("declarr"))
{
string Sz = "";
string Prep = "";
string App = "";
string Nae = N.children[1].node;
if(N.children.Length>2)
{
Sz = CompileExpression(N.children[2],E);
if(N.children.Length > 3)
{
string tref = "_pit_" + E.GetAutoVariable();
Prep = "(int " + tref + " " + CompileExpression(N.children[3],E) + ")";
Sz = "(* " + tref + " " + Sz + ")";
App = "(setarrpit " + Nae + " " + tref + ")";
}
}
E.Map(Nae,N.children[0].node + "*");
return Prep + "(array " + Nae +" " + GetMachineType(N.children[0]) + " " + Sz + ")" + App;
}
// assignment (do more later)
if(ExpressionTyping.IsAssignment(N))
{
return CompileAssignment(N,E);
}
// while Loop
if(N.node.Equals("while"))
{
string loop = "(while ";
loop += CompileExpression(N.children[0],E);
loop += CompileStatement(N.children[1],E);
loop += ")";
return loop;
}
if(N.node.Equals("if"))
{
string Guard = CompileExpression(N.children[0],E);
string TruePart = "(seq "+CompileStatement(N.children[1], E)+")";
string FalsePart = "(seq)";
if(N.children.Length > 2)
FalsePart = "(seq "+ CompileStatement(N.children[2],E) + ")";
return "(if " + Guard + TruePart + FalsePart + ")";
}
/*
| "ascend"^ LPAREN! IDENT COMMA! expr COMMA! expr RPAREN! statement
| "descend"^ LPAREN! IDENT COMMA! expr COMMA! expr RPAREN! statement
*/
if(N.node.Equals("ascend"))
{
string ret = "(int " + N.children[0].node + " " + CompileExpression(N.children[1],E) + ")";
string ubound = "_max_" + E.GetAutoVariable();
ret += "(seq (int " + ubound + " " + CompileExpression(N.children[2],E) + ")";
ret += "(while (< " + N.children[0].node + " " + ubound + ")(seq ";
Environment E2 = new Environment(E);
E2.Map(N.children[0].node,"int");
ret += CompileStatement(N.children[3],E2);
ret += "(set " + N.children[0].node + " (+ " + N.children[0].node + " (int 1)))";
ret += ")))";
return ret;
}
if(N.node.Equals("descend"))
{
string ret = "(int " + N.children[0].node + " " + CompileExpression(N.children[1],E) + ")";
string lbound = "_max_" + E.GetAutoVariable();
ret += "(seq (int " + lbound + " " + CompileExpression(N.children[2],E) + ")";
ret += "(while (>= " + N.children[0].node + " " + lbound + ")(seq ";
Environment E2 = new Environment(E);
E2.Map(N.children[0].node,"int");
ret += CompileStatement(N.children[3],E2);
ret += "(set " + N.children[0].node + " (- " + N.children[0].node + " (int 1)))";
ret += ")))";
return ret;
}
if(N.node.Equals("foreach"))
{
string ret = "";
string varName = N.children[0].node;
string Typ = ExpressionTyping.TypeExpression(N.children[1],E);
if(Typ[Typ.Length-1]!='*')
{
throw new Exception("Bad Typing:" + N.children[1].str() + ": needs to be an array");
}
string sTyp = Typ.Substring(0,Typ.Length-1);
//Console.WriteLine("Typed:" + varName + ":" + sTyp);
string mTyp = GetMachineType2(sTyp);
Environment E2 = new Environment(E);
E2.Map(varName,sTyp);
string v_idx = "_idx_" + E.GetAutoVariable();
string v_arr = "_arr_" + E.GetAutoVariable();
string v_max = "_max_" + E.GetAutoVariable();
ret += "(" + mTyp + " " + varName + ")";
ret += "(int " + v_idx + " (int 0))";
ret += "(array " + v_arr + ")";
ret += "(set " + v_arr + " " + CompileExpression(N.children[1],E) + ")";
ret += "(int " + v_max + " (len " + v_arr + "))";
ret += "(while (< " + v_idx + " " + v_max + ")(seq ";
ret += "(set " + varName+" (eref " + v_arr + " " + v_idx + "))";
ret += CompileStatement(N.children[2],E2);
// return "(eref " + exr + CompileExpression(N.children[1],E) + ")";
ret += "(set " + v_idx + " (+ " + v_idx + " (int 1)))";
ret += "))";
/*
string ret = "(int " + N.children[0].node + " " + CompileExpression(N.children[1],E) + ")";
string lbound = "_max_" + E.GetAutoVariable();
ret += "(seq (int " + lbound + " " + CompileExpression(N.children[2],E) + ")";
ret += "(while (> " + N.children[0].node + " " + lbound + ")(seq ";
ret += CompileStatement(N.children[3],E);
ret += "(set " + N.children[0].node + " (- " + N.children[0].node + " (int 1)))";
ret += ")))";
*/
return ret;
}
// return
if(N.node.Equals("return"))
{
string ret = "(return ";
if(N.children != null)
{
if(N.children.Length > 0)
{
ret += CompileExpression(N.children[0],E);
}
}
ret += ")";
return ret;
}
// return
if(N.node.Equals("print"))
{
string ret = "(echo ";
for(int k = 0; k < N.children.Length; k++)
ret += CompileExpression(N.children[k],E);
ret += ")";
return ret;
}
if(N.node.Equals("dumpxml"))
{
return "(dumpxml)";
}
// unit evaluation
if(N.node.Equals("unit"))
{
string ret = "(unit ";
for(uint k = 0; k < N.children.Length; k++)
ret += CompileExpression(N.children[k],E);
ret += ")";
return ret;
}
return "(unit " + CompileExpression(N,E) + ")";
// Console.WriteLine("Unknown Statement:" + N.node);
// return "[]";
}
public static string CompileGlobal(LispNode N, Environment E)
{
Environment eN = new Environment(E);
string func = "(func " + CompileReturnType(N.children[0]) + " " + N.children[1].node+" ";
if(N.children[2].children != null)
{
for(uint i = 0; i < N.children[2].children.Length; i++)
{
LispNode C = N.children[2].children[i];
// Console.WriteLine(":" + C.str());
if( ExpressionTyping.IsSpecialRealType(C.children[0]))
{
string SSS = "real*";
eN.Map(C.children[1].node, SSS);
func += "(array " + C.children[1].node + ")";
}
else
{
string SSS = GetMachineType(C.children[0]);
string ptr = "";
for(int x = 2; x < C.children.Length; x++)
{
ptr += "*";
}
eN.Map(C.children[1].node, C.children[0].node + ptr);
if(ptr.Length > 0) SSS = "array";
func += "(" + SSS + " " + C.children[1].node + ")";
}
}
}
LispNode Body = N.children[3];
func += CompileStatement(Body,eN);
return func + ")";;
}
public static string CompileContract(LispNode NP)
{
string cContract = "(c " + NP.children[0].node + " ";
LispNode N = NP.children[1];
for(int k = 0; k < N.children.Length; k++)
{
string vType = N.children[k].children[0].node;
string vName = N.children[k].children[1].node;
if(ExpressionTyping.IsSpecialRealType2(vType) || N.children[k].children.Length > 2 || vType.Equals("string") || vType.Equals("array"))
{
vType = "array";
}
else if(vType.Equals("int")||vType.Equals("real")||vType.Equals("char"))
{
}
else if(ExpressionTyping.IsFunctional(vType))
{
vType = "fun";
}
else
{
vType = "ptr";
}
cContract += vType + " " + vName + " ";
//Console.WriteLine(N.children[k].str());
}
/*
if( ExpressionTyping.IsSpecialRealType(C.children[0]))
{
string SSS = "real*";
eN.Map(C.children[1].node, SSS);
F.gDECL += "(array " + C.children[1].node + ")";
}
else
{
string SSS = GetMachineType(C.children[0]);
string ptr = "";
for(int x = 2; x < C.children.Length; x++)
{
ptr += "*";
}
eN.Map(C.children[1].node, C.children[0].node + ptr);
if(ptr.Length > 0) SSS = "array";
F.gDECL += "(" + SSS + " " + C.children[1].node + ")";
}
*/
return cContract + ")";
}
public static string Compile(LispNode N, Environment E)
{
Compiler.AnonymousFunctions = new ArrayList();
ExpressionTyping.FunctionTypes.Clear();
ExpressionTyping.Contracts.Clear();
E.ServiceFunctions = new ArrayList();
StreamReader sr = new StreamReader("ServiceTyping.txt");
string ln = sr.ReadLine();
while(ln != null)
{
LispNode S = LispNode.Parse(new LispLexer(ln));
E.ServiceFunctions.Add(S.node);
ln = sr.ReadLine();
}
string contracts = "(gc ";
string final = "(gs ";
for(uint i = 0; i < N.children.Length; i++)
{
if(!N.children[i].node.Equals("contract"))
{
string xyz = N.children[i].children[1].node;
ExpressionTyping.FunctionTypes.Add( xyz );
}
else
{
ExpressionTyping.Contracts.Add(N.children[i].children[0].node);
}
}
for(uint i = 0; i < N.children.Length; i++)
{
if(!N.children[i].node.Equals("contract"))
{
final += CompileGlobal(N.children[i],E);
}
else
{
contracts += CompileContract(N.children[i]);
}
}
foreach(AnonyFunction A in Compiler.AnonymousFunctions)
{
final += A.gDECL;
}
return "(nm " + contracts + ")" + final + "))";
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using log4net;
using Mono.Addins;
using Nini.Config;
using System;
using System.Collections.Generic;
using System.Reflection;
using OpenSim.Framework;
using OpenSim.Framework.Console;
using OpenSim.Server.Base;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
using OpenMetaverse;
namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Grid
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "LocalGridServicesConnector")]
public class LocalGridServicesConnector : ISharedRegionModule, IGridService
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
private IGridService m_GridService;
private Dictionary<UUID, RegionCache> m_LocalCache = new Dictionary<UUID, RegionCache>();
private bool m_Enabled;
public LocalGridServicesConnector()
{
}
public LocalGridServicesConnector(IConfigSource source)
{
m_log.Debug("[LOCAL GRID SERVICE CONNECTOR]: LocalGridServicesConnector instantiated directly.");
InitialiseService(source);
}
#region ISharedRegionModule
public Type ReplaceableInterface
{
get { return null; }
}
public string Name
{
get { return "LocalGridServicesConnector"; }
}
public void Initialise(IConfigSource source)
{
IConfig moduleConfig = source.Configs["Modules"];
if (moduleConfig != null)
{
string name = moduleConfig.GetString("GridServices", "");
if (name == Name)
{
InitialiseService(source);
m_log.Info("[LOCAL GRID SERVICE CONNECTOR]: Local grid connector enabled");
}
}
}
private void InitialiseService(IConfigSource source)
{
IConfig assetConfig = source.Configs["GridService"];
if (assetConfig == null)
{
m_log.Error("[LOCAL GRID SERVICE CONNECTOR]: GridService missing from OpenSim.ini");
return;
}
string serviceDll = assetConfig.GetString("LocalServiceModule",
String.Empty);
if (serviceDll == String.Empty)
{
m_log.Error("[LOCAL GRID SERVICE CONNECTOR]: No LocalServiceModule named in section GridService");
return;
}
Object[] args = new Object[] { source };
m_GridService =
ServerUtils.LoadPlugin<IGridService>(serviceDll,
args);
if (m_GridService == null)
{
m_log.Error("[LOCAL GRID SERVICE CONNECTOR]: Can't load grid service");
return;
}
m_Enabled = true;
}
public void PostInitialise()
{
// FIXME: We will still add this command even if we aren't enabled since RemoteGridServiceConnector
// will have instantiated us directly.
MainConsole.Instance.Commands.AddCommand("Regions", false, "show neighbours",
"show neighbours",
"Shows the local regions' neighbours", HandleShowNeighboursCommand);
}
public void Close()
{
}
public void AddRegion(Scene scene)
{
if (!m_Enabled)
return;
scene.RegisterModuleInterface<IGridService>(this);
if (m_LocalCache.ContainsKey(scene.RegionInfo.RegionID))
m_log.ErrorFormat("[LOCAL GRID SERVICE CONNECTOR]: simulator seems to have more than one region with the same UUID. Please correct this!");
else
m_LocalCache.Add(scene.RegionInfo.RegionID, new RegionCache(scene));
}
public void RemoveRegion(Scene scene)
{
if (!m_Enabled)
return;
m_LocalCache[scene.RegionInfo.RegionID].Clear();
m_LocalCache.Remove(scene.RegionInfo.RegionID);
}
public void RegionLoaded(Scene scene)
{
}
#endregion
#region IGridService
public string RegisterRegion(UUID scopeID, GridRegion regionInfo)
{
return m_GridService.RegisterRegion(scopeID, regionInfo);
}
public bool DeregisterRegion(UUID regionID)
{
return m_GridService.DeregisterRegion(regionID);
}
public List<GridRegion> GetNeighbours(UUID scopeID, UUID regionID)
{
return m_GridService.GetNeighbours(scopeID, regionID);
}
public GridRegion GetRegionByUUID(UUID scopeID, UUID regionID)
{
return m_GridService.GetRegionByUUID(scopeID, regionID);
}
public GridRegion GetRegionByPosition(UUID scopeID, int x, int y)
{
GridRegion region = null;
// First see if it's a neighbour, even if it isn't on this sim.
// Neighbour data is cached in memory, so this is fast
foreach (RegionCache rcache in m_LocalCache.Values)
{
region = rcache.GetRegionByPosition(x, y);
if (region != null)
{
return region;
}
}
// Then try on this sim (may be a lookup in DB if this is using MySql).
return m_GridService.GetRegionByPosition(scopeID, x, y);
}
public GridRegion GetRegionByName(UUID scopeID, string regionName)
{
return m_GridService.GetRegionByName(scopeID, regionName);
}
public List<GridRegion> GetRegionsByName(UUID scopeID, string name, int maxNumber)
{
return m_GridService.GetRegionsByName(scopeID, name, maxNumber);
}
public List<GridRegion> GetRegionRange(UUID scopeID, int xmin, int xmax, int ymin, int ymax)
{
return m_GridService.GetRegionRange(scopeID, xmin, xmax, ymin, ymax);
}
public List<GridRegion> GetDefaultRegions(UUID scopeID)
{
return m_GridService.GetDefaultRegions(scopeID);
}
public List<GridRegion> GetFallbackRegions(UUID scopeID, int x, int y)
{
return m_GridService.GetFallbackRegions(scopeID, x, y);
}
public List<GridRegion> GetHyperlinks(UUID scopeID)
{
return m_GridService.GetHyperlinks(scopeID);
}
public int GetRegionFlags(UUID scopeID, UUID regionID)
{
return m_GridService.GetRegionFlags(scopeID, regionID);
}
#endregion
public void HandleShowNeighboursCommand(string module, string[] cmdparams)
{
System.Text.StringBuilder caps = new System.Text.StringBuilder();
foreach (KeyValuePair<UUID, RegionCache> kvp in m_LocalCache)
{
caps.AppendFormat("*** Neighbours of {0} ({1}) ***\n", kvp.Value.RegionName, kvp.Key);
List<GridRegion> regions = kvp.Value.GetNeighbours();
foreach (GridRegion r in regions)
caps.AppendFormat(" {0} @ {1}-{2}\n", r.RegionName, r.RegionLocX / Constants.RegionSize, r.RegionLocY / Constants.RegionSize);
}
MainConsole.Instance.Output(caps.ToString());
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using Server.ContextMenus;
using Server.Engines.Craft;
using Server.Network;
using Server.Targeting;
namespace Server.Items
{
public class SalvageBag : Bag
{
private bool m_Failure;
public override int LabelNumber { get { return 1079931; } } // Salvage Bag
[Constructable]
public SalvageBag()
: this( Utility.RandomBlueHue() )
{
}
[Constructable]
public SalvageBag( int hue )
{
Weight = 2.0;
Hue = hue;
m_Failure = false;
}
public override void GetContextMenuEntries( Mobile from, List<ContextMenuEntry> list )
{
base.GetContextMenuEntries( from, list );
if( from.Alive )
{
list.Add( new SalvageIngotsEntry( this, IsChildOf( from.Backpack ) && Resmeltables() ) );
list.Add( new SalvageClothEntry( this, IsChildOf( from.Backpack ) && Scissorables() ) );
list.Add( new SalvageAllEntry( this, IsChildOf( from.Backpack ) && Resmeltables() && Scissorables() ) );
}
}
#region Checks
private bool Resmeltables() //Where context menu checks for metal items and dragon barding deeds
{
foreach( Item i in Items )
{
if( i != null && !i.Deleted )
{
if( i is BaseWeapon )
{
if( CraftResources.GetType( ( (BaseWeapon)i ).Resource ) == CraftResourceType.Metal )
return true;
}
if( i is BaseArmor )
{
if( CraftResources.GetType( ( (BaseArmor)i ).Resource ) == CraftResourceType.Metal )
return true;
}
if( i is DragonBardingDeed )
return true;
}
}
return false;
}
private bool Scissorables() //Where context menu checks for Leather items and cloth items
{
foreach( Item i in Items )
{
if( i != null && !i.Deleted )
{
if( i is IScissorable )
{
if( i is BaseClothing )
return true;
if( i is BaseArmor )
{
if( CraftResources.GetType( ( (BaseArmor)i ).Resource ) == CraftResourceType.Leather )
return true;
}
if( ( i is Cloth ) || ( i is BoltOfCloth ) || ( i is Hides ) || ( i is BonePile ) )
return true;
}
}
}
return false;
}
#endregion
#region Resmelt.cs
private bool Resmelt( Mobile from, Item item, CraftResource resource )
{
try
{
if( CraftResources.GetType( resource ) != CraftResourceType.Metal )
return false;
CraftResourceInfo info = CraftResources.GetInfo( resource );
if( info == null || info.ResourceTypes.Length == 0 )
return false;
CraftItem craftItem = DefBlacksmithy.CraftSystem.CraftItems.SearchFor( item.GetType() );
if( craftItem == null || craftItem.Resources.Count == 0 )
return false;
CraftRes craftResource = craftItem.Resources.GetAt( 0 );
if( craftResource.Amount < 2 )
return false; // Not enough metal to resmelt
double difficulty = 0.0;
switch ( resource )
{
case CraftResource.MRusty: difficulty = 50.0; break;
case CraftResource.MOldcopper: difficulty = 60.0; break;
case CraftResource.MDullcopper: difficulty = 65.0; break;
case CraftResource.MShadow: difficulty = 70.0; break;
case CraftResource.MCopper: difficulty = 75.0; break;
case CraftResource.MBronze: difficulty = 80.0; break;
case CraftResource.MGold: difficulty = 85.0; break;
case CraftResource.MRose: difficulty = 87.0; break;
case CraftResource.MAgapite: difficulty = 90.0; break;
case CraftResource.MValorite: difficulty = 90.0; break;
case CraftResource.MBloodrock: difficulty = 93.0; break;
case CraftResource.MVerite: difficulty = 95.0; break;
case CraftResource.MSilver: difficulty = 95.0; break;
case CraftResource.MDragon: difficulty = 95.0; break;
case CraftResource.MTitan: difficulty = 95.0; break;
case CraftResource.MCrystaline: difficulty = 95.0; break;
case CraftResource.MKrynite: difficulty = 95.0; break;
case CraftResource.MVulcan: difficulty = 95.0; break;
case CraftResource.MBloodcrest: difficulty = 95.0; break;
case CraftResource.MElvin: difficulty = 95.0; break;
case CraftResource.MAcid: difficulty = 95.0; break;
case CraftResource.MAqua: difficulty = 95.0; break;
case CraftResource.MEldar: difficulty = 95.0; break;
case CraftResource.MGlowing: difficulty = 95.0; break;
case CraftResource.MGorgan: difficulty = 95.0; break;
case CraftResource.MSteel: difficulty = 95.5; break;
case CraftResource.MSandrock: difficulty = 95.0; break;
case CraftResource.MMytheril: difficulty = 97.5; break;
case CraftResource.MBlackrock: difficulty = 98.0; break;
}
Type resourceType = info.ResourceTypes[ 0 ];
Item ingot = (Item)Activator.CreateInstance( resourceType );
if( item is DragonBardingDeed || ( item is BaseArmor && ( (BaseArmor)item ).PlayerConstructed ) || ( item is BaseWeapon && ( (BaseWeapon)item ).PlayerConstructed ) || ( item is BaseClothing && ( (BaseClothing)item ).PlayerConstructed ) )
{
double mining = from.Skills[ SkillName.Mining ].Value;
if( mining > 100.0 )
mining = 100.0;
double amount = ( ( ( 4 + mining ) * craftResource.Amount - 4 ) * 0.0068 );
if( amount < 2 )
ingot.Amount = 2;
else
ingot.Amount = (int)amount;
}
else
{
ingot.Amount = 2;
}
if ( difficulty > from.Skills[ SkillName.Mining ].Value )
{
m_Failure = true;
ingot.Delete();
}
else
item.Delete();
from.AddToBackpack( ingot );
from.PlaySound( 0x2A );
from.PlaySound( 0x240 );
return true;
}
catch( Exception ex )
{
Console.WriteLine( ex.ToString() );
}
return false;
}
#endregion
#region Salvaging
private void SalvageIngots( Mobile from )
{
Item[] tools = from.Backpack.FindItemsByType( typeof( BaseTool ) );
bool ToolFound = false;
foreach( Item tool in tools )
{
if( tool is BaseTool && ( (BaseTool)tool ).CraftSystem == DefBlacksmithy.CraftSystem )
ToolFound = true;
}
if( !ToolFound )
{
from.SendLocalizedMessage( 1079822 ); // You need a blacksmithing tool in order to salvage ingots.
return;
}
bool anvil, forge;
DefBlacksmithy.CheckAnvilAndForge( from, 2, out anvil, out forge );
if( !forge )
{
from.SendLocalizedMessage( 1044265 ); // You must be near a forge.
return;
}
int salvaged = 0;
int notSalvaged = 0;
Container sBag = this;
List<Item> Smeltables = sBag.FindItemsByType<Item>();
for(int i = Smeltables.Count - 1; i >= 0; i--)
{
Item item = Smeltables[ i ];
if( item is BaseArmor )
{
if( Resmelt( from, item, ( (BaseArmor)item ).Resource ) )
salvaged++;
else
notSalvaged++;
}
else if( item is BaseWeapon )
{
if( Resmelt( from, item, ( (BaseWeapon)item ).Resource ) )
salvaged++;
else
notSalvaged++;
}
else if( item is DragonBardingDeed )
{
if( Resmelt( from, item, ( (DragonBardingDeed)item ).Resource ) )
salvaged++;
else
notSalvaged++;
}
}
if( m_Failure )
{
from.SendLocalizedMessage( 1079975 ); // You failed to smelt some metal for lack of skill.
m_Failure = false;
}
else
from.SendLocalizedMessage( 1079973, String.Format( "{0}\t{1}", salvaged, salvaged + notSalvaged ) ); // Salvaged: ~1_COUNT~/~2_NUM~ blacksmithed items
}
private void SalvageCloth( Mobile from )
{
Scissors scissors = from.Backpack.FindItemByType( typeof( Scissors ) ) as Scissors;
if( scissors == null )
{
from.SendLocalizedMessage( 1079823 ); // You need scissors in order to salvage cloth.
return;
}
int salvaged = 0;
int notSalvaged = 0;
Container sBag = this;
List<Item> scissorables = sBag.FindItemsByType<Item>();
for (int i = scissorables.Count - 1; i >= 0; --i)
{
Item item = scissorables[i];
if (item is IScissorable)
{
IScissorable scissorable = (IScissorable)item;
if (Scissors.CanScissor(from, scissorable) && scissorable.Scissor(from, scissors))
++salvaged;
else
++notSalvaged;
}
}
from.SendLocalizedMessage( 1079974, String.Format( "{0}\t{1}", salvaged, salvaged + notSalvaged ) ); // Salvaged: ~1_COUNT~/~2_NUM~ tailored items
Container pack = from.Backpack;
foreach (Item i in ((Container)this).FindItemsByType(typeof(Item), true))
{
if ((i is Leather) || (i is Cloth) || (i is SpinedLeather) || (i is HornedLeather) || (i is BarbedLeather) || (i is DaemonLeather) || (i is Bandage) || (i is Bone))
{
from.AddToBackpack( i );
}
}
}
private void SalvageAll( Mobile from )
{
SalvageIngots( from );
SalvageCloth( from );
}
#endregion
#region ContextMenuEntries
private class SalvageAllEntry : ContextMenuEntry
{
private SalvageBag m_Bag;
public SalvageAllEntry( SalvageBag bag, bool enabled )
: base( 6276 )
{
m_Bag = bag;
if( !enabled )
Flags |= CMEFlags.Disabled;
}
public override void OnClick()
{
if( m_Bag.Deleted )
return;
Mobile from = Owner.From;
if( from.CheckAlive() )
m_Bag.SalvageAll( from );
}
}
private class SalvageIngotsEntry : ContextMenuEntry
{
private SalvageBag m_Bag;
public SalvageIngotsEntry( SalvageBag bag, bool enabled )
: base( 6277 )
{
m_Bag = bag;
if( !enabled )
Flags |= CMEFlags.Disabled;
}
public override void OnClick()
{
if( m_Bag.Deleted )
return;
Mobile from = Owner.From;
if( from.CheckAlive() )
m_Bag.SalvageIngots( from );
}
}
private class SalvageClothEntry : ContextMenuEntry
{
private SalvageBag m_Bag;
public SalvageClothEntry( SalvageBag bag, bool enabled )
: base( 6278 )
{
m_Bag = bag;
if( !enabled )
Flags |= CMEFlags.Disabled;
}
public override void OnClick()
{
if( m_Bag.Deleted )
return;
Mobile from = Owner.From;
if( from.CheckAlive() )
m_Bag.SalvageCloth( from );
}
}
#endregion
#region Serialization
public SalvageBag( Serial serial )
: base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.WriteEncodedInt( (int)0 ); // version
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadEncodedInt();
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Core.Pipeline;
namespace Azure.IoT.TimeSeriesInsights
{
/// <summary>
/// Perform operations such as creating, listing, replacing and deleting Time Series hierarchies.
/// </summary>
public class TimeSeriesInsightsHierarchies
{
private readonly TimeSeriesHierarchiesRestClient _hierarchiesRestClient;
private readonly ClientDiagnostics _clientDiagnostics;
/// <summary>
/// Initializes a new instance of TimeSeriesInsightsHierarchies. This constructor should only be used for mocking purposes.
/// </summary>
protected TimeSeriesInsightsHierarchies()
{
}
internal TimeSeriesInsightsHierarchies(TimeSeriesHierarchiesRestClient hierarchiesRestClient, ClientDiagnostics clientDiagnostics)
{
Argument.AssertNotNull(hierarchiesRestClient, nameof(hierarchiesRestClient));
Argument.AssertNotNull(clientDiagnostics, nameof(clientDiagnostics));
_hierarchiesRestClient = hierarchiesRestClient;
_clientDiagnostics = clientDiagnostics;
}
/// <summary>
/// Gets Time Series Insights hierarchies in pages asynchronously.
/// </summary>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The pageable list <see cref="AsyncPageable{TimeSeriesHierarchy}"/> of Time Series hierarchies with the http response.</returns>
/// <example>
/// <code snippet="Snippet:TimeSeriesInsightsSampleGetAllHierarchies">
/// // Get all Time Series hierarchies in the environment
/// AsyncPageable<TimeSeriesHierarchy> getAllHierarchies = client.Hierarchies.GetAsync();
/// await foreach (TimeSeriesHierarchy hierarchy in getAllHierarchies)
/// {
/// Console.WriteLine($"Retrieved Time Series Insights hierarchy with Id: '{hierarchy.Id}' and Name: '{hierarchy.Name}'.");
/// }
/// </code>
/// </example>
public virtual AsyncPageable<TimeSeriesHierarchy> GetAsync(
CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(TimeSeriesInsightsClient)}.{nameof(Get)}");
scope.Start();
try
{
async Task<Page<TimeSeriesHierarchy>> FirstPageFunc(int? pageSizeHint)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(TimeSeriesInsightsClient)}.{nameof(Get)}");
scope.Start();
try
{
Response<GetHierarchiesPage> getHierarchiesResponse = await _hierarchiesRestClient
.ListAsync(null, null, cancellationToken)
.ConfigureAwait(false);
return Page.FromValues(getHierarchiesResponse.Value.Hierarchies, getHierarchiesResponse.Value.ContinuationToken, getHierarchiesResponse.GetRawResponse());
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
async Task<Page<TimeSeriesHierarchy>> NextPageFunc(string nextLink, int? pageSizeHint)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(TimeSeriesInsightsClient)}.{nameof(Get)}");
scope.Start();
try
{
Response<GetHierarchiesPage> getHierarchiesResponse = await _hierarchiesRestClient
.ListAsync(nextLink, null, cancellationToken)
.ConfigureAwait(false);
return Page.FromValues(getHierarchiesResponse.Value.Hierarchies, getHierarchiesResponse.Value.ContinuationToken, getHierarchiesResponse.GetRawResponse());
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, NextPageFunc);
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary>
/// Gets Time Series Insights hierarchies in pages synchronously.
/// </summary>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The pageable list <see cref="Pageable{TimeSeriesHierarchy}"/> of Time Series hierarchies with the http response.</returns>
/// <seealso cref="GetAsync(CancellationToken)">
/// See the asynchronous version of this method for examples.
/// </seealso>
public virtual Pageable<TimeSeriesHierarchy> Get(CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(TimeSeriesInsightsClient)}.{nameof(Get)}");
scope.Start();
try
{
Page<TimeSeriesHierarchy> FirstPageFunc(int? pageSizeHint)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(TimeSeriesInsightsClient)}.{nameof(Get)}");
scope.Start();
try
{
Response<GetHierarchiesPage> getHierarchiesResponse = _hierarchiesRestClient.List(null, null, cancellationToken);
return Page.FromValues(getHierarchiesResponse.Value.Hierarchies, getHierarchiesResponse.Value.ContinuationToken, getHierarchiesResponse.GetRawResponse());
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
Page<TimeSeriesHierarchy> NextPageFunc(string nextLink, int? pageSizeHint)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(TimeSeriesInsightsClient)}.{nameof(Get)}");
scope.Start();
try
{
Response<GetHierarchiesPage> getHierarchiesResponse = _hierarchiesRestClient.List(nextLink, null, cancellationToken);
return Page.FromValues(getHierarchiesResponse.Value.Hierarchies, getHierarchiesResponse.Value.ContinuationToken, getHierarchiesResponse.GetRawResponse());
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
return PageableHelpers.CreateEnumerable(FirstPageFunc, NextPageFunc);
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary>
/// Gets Time Series Insights hierarchies by hierarchy names asynchronously.
/// </summary>
/// <param name="timeSeriesHierarchyNames">List of names of the Time Series hierarchies to return.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>
/// List of hierarchy or error objects corresponding by position to the array in the request.
/// Hierarchy object is set when operation is successful and error object is set when operation is unsuccessful.
/// </returns>
/// <remarks>
/// For more samples, see <see href="https://github.com/Azure/azure-sdk-for-net/tree/master/sdk/timeseriesinsights/Azure.IoT.TimeSeriesInsights/samples">our repo samples</see>.
/// </remarks>
/// <exception cref="ArgumentNullException">
/// The exception is thrown when <paramref name="timeSeriesHierarchyNames"/> is <c>null</c>.
/// </exception>
/// <exception cref="ArgumentException">
/// The exception is thrown when <paramref name="timeSeriesHierarchyNames"/> is empty.
/// </exception>
public virtual async Task<Response<TimeSeriesHierarchyOperationResult[]>> GetByNameAsync(
IEnumerable<string> timeSeriesHierarchyNames,
CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(TimeSeriesInsightsClient)}.{nameof(GetByName)}");
scope.Start();
try
{
Argument.AssertNotNullOrEmpty(timeSeriesHierarchyNames, nameof(timeSeriesHierarchyNames));
var batchRequest = new HierarchiesBatchRequest()
{
Get = new HierarchiesRequestBatchGetDelete()
};
foreach (string timeSeriesName in timeSeriesHierarchyNames)
{
batchRequest.Get.Names.Add(timeSeriesName);
}
Response<HierarchiesBatchResponse> executeBatchResponse = await _hierarchiesRestClient
.ExecuteBatchAsync(batchRequest, null, cancellationToken)
.ConfigureAwait(false);
return Response.FromValue(executeBatchResponse.Value.Get.ToArray(), executeBatchResponse.GetRawResponse());
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary>
/// Gets Time Series Insights hierarchies by hierarchy names synchronously.
/// </summary>
/// <param name="timeSeriesHierarchyNames">List of names of the Time Series hierarchies to return.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>
/// List of hierarchy or error objects corresponding by position to the array in the request.
/// Hierarchy object is set when operation is successful and error object is set when operation is unsuccessful.
/// </returns>
/// <seealso cref="GetByNameAsync(IEnumerable{string}, CancellationToken)">
/// See the asynchronous version of this method for examples.
/// </seealso>
/// <exception cref="ArgumentNullException">
/// The exception is thrown when <paramref name="timeSeriesHierarchyNames"/> is <c>null</c>.
/// </exception>
/// <exception cref="ArgumentException">
/// The exception is thrown when <paramref name="timeSeriesHierarchyNames"/> is empty.
/// </exception>
public virtual Response<TimeSeriesHierarchyOperationResult[]> GetByName(
IEnumerable<string> timeSeriesHierarchyNames,
CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(TimeSeriesInsightsClient)}.{nameof(GetByName)}");
scope.Start();
try
{
Argument.AssertNotNullOrEmpty(timeSeriesHierarchyNames, nameof(timeSeriesHierarchyNames));
var batchRequest = new HierarchiesBatchRequest()
{
Get = new HierarchiesRequestBatchGetDelete()
};
foreach (string timeSeriesName in timeSeriesHierarchyNames)
{
batchRequest.Get.Names.Add(timeSeriesName);
}
Response<HierarchiesBatchResponse> executeBatchResponse = _hierarchiesRestClient
.ExecuteBatch(batchRequest, null, cancellationToken);
return Response.FromValue(executeBatchResponse.Value.Get.ToArray(), executeBatchResponse.GetRawResponse());
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary>
/// Gets Time Series Insights hierarchies by hierarchy Ids asynchronously.
/// </summary>
/// <param name="timeSeriesHierarchyIds">List of Time Series hierarchy Ids of the Time Series hierarchies to return.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>
/// List of hierarchy or error objects corresponding by position to the array in the request.
/// Hierarchy object is set when operation is successful and error object is set when operation is unsuccessful.
/// </returns>
/// <remarks>
/// For more samples, see <see href="https://github.com/Azure/azure-sdk-for-net/tree/master/sdk/timeseriesinsights/Azure.IoT.TimeSeriesInsights/samples">our repo samples</see>.
/// </remarks>
/// <exception cref="ArgumentNullException">
/// The exception is thrown when <paramref name="timeSeriesHierarchyIds"/> is <c>null</c>.
/// </exception>
/// <exception cref="ArgumentException">
/// The exception is thrown when <paramref name="timeSeriesHierarchyIds"/> is empty.
/// </exception>
/// <example>
/// <code snippet="Snippet:TimeSeriesInsightsSampleGetHierarchiesById">
/// var tsiHierarchyIds = new List<string>
/// {
/// "sampleHierarchyId"
/// };
///
/// Response<TimeSeriesHierarchyOperationResult[]> getHierarchiesByIdsResult = await client
/// .Hierarchies
/// .GetByIdAsync(tsiHierarchyIds);
///
/// // The response of calling the API contains a list of hieararchy or error objects corresponding by position to the input parameter array in the request.
/// // If the error object is set to null, this means the operation was a success.
/// for (int i = 0; i < getHierarchiesByIdsResult.Value.Length; i++)
/// {
/// if (getHierarchiesByIdsResult.Value[i].Error == null)
/// {
/// Console.WriteLine($"Retrieved Time Series hieararchy with Id: '{getHierarchiesByIdsResult.Value[i].Hierarchy.Id}'.");
/// }
/// else
/// {
/// Console.WriteLine($"Failed to retrieve a Time Series hieararchy due to '{getHierarchiesByIdsResult.Value[i].Error.Message}'.");
/// }
/// }
/// </code>
/// </example>
public virtual async Task<Response<TimeSeriesHierarchyOperationResult[]>> GetByIdAsync(
IEnumerable<string> timeSeriesHierarchyIds,
CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(TimeSeriesInsightsClient)}.{nameof(GetById)}");
scope.Start();
try
{
Argument.AssertNotNullOrEmpty(timeSeriesHierarchyIds, nameof(timeSeriesHierarchyIds));
var batchRequest = new HierarchiesBatchRequest()
{
Get = new HierarchiesRequestBatchGetDelete()
};
foreach (string hierarchyId in timeSeriesHierarchyIds)
{
batchRequest.Get.HierarchyIds.Add(hierarchyId);
}
Response<HierarchiesBatchResponse> executeBatchResponse = await _hierarchiesRestClient
.ExecuteBatchAsync(batchRequest, null, cancellationToken)
.ConfigureAwait(false);
return Response.FromValue(executeBatchResponse.Value.Get.ToArray(), executeBatchResponse.GetRawResponse());
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary>
/// Gets Time Series Insights hierarchies by hierarchy Ids synchronously.
/// </summary>
/// <param name="timeSeriesHierarchyIds">List of Time Series hierarchy Ids of the Time Series hierarchies to return.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>
/// List of hierarchy or error objects corresponding by position to the array in the request.
/// Hierarchy object is set when operation is successful and error object is set when operation is unsuccessful.
/// </returns>
/// <seealso cref="GetByIdAsync(IEnumerable{string}, CancellationToken)">
/// See the asynchronous version of this method for examples.
/// </seealso>
/// <exception cref="ArgumentNullException">
/// The exception is thrown when <paramref name="timeSeriesHierarchyIds"/> is <c>null</c>.
/// </exception>
/// <exception cref="ArgumentException">
/// The exception is thrown when <paramref name="timeSeriesHierarchyIds"/> is empty.
/// </exception>
public virtual Response<TimeSeriesHierarchyOperationResult[]> GetById(
IEnumerable<string> timeSeriesHierarchyIds,
CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(TimeSeriesInsightsClient)}.{nameof(GetById)}");
scope.Start();
try
{
Argument.AssertNotNullOrEmpty(timeSeriesHierarchyIds, nameof(timeSeriesHierarchyIds));
var batchRequest = new HierarchiesBatchRequest()
{
Get = new HierarchiesRequestBatchGetDelete()
};
foreach (string hierarchyId in timeSeriesHierarchyIds)
{
batchRequest.Get.HierarchyIds.Add(hierarchyId);
}
Response<HierarchiesBatchResponse> executeBatchResponse = _hierarchiesRestClient
.ExecuteBatch(batchRequest, null, cancellationToken);
return Response.FromValue(executeBatchResponse.Value.Get.ToArray(), executeBatchResponse.GetRawResponse());
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary>
/// Creates Time Series Insights hierarchies asynchronously. If a provided hierarchy is already in use, then this will attempt to replace the existing hierarchy with the provided Time Series hierarchy.
/// </summary>
/// <param name="timeSeriesHierarchies">The Time Series Insights hierarchies to be created or replaced.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>
/// List of error objects corresponding by position to the <paramref name="timeSeriesHierarchies"/> array in the request.
/// An error object will be set when operation is unsuccessful.
/// </returns>
/// <remarks>
/// For more samples, see <see href="https://github.com/Azure/azure-sdk-for-net/tree/master/sdk/timeseriesinsights/Azure.IoT.TimeSeriesInsights/samples">our repo samples</see>.
/// </remarks>
/// <exception cref="ArgumentNullException">
/// The exception is thrown when <paramref name="timeSeriesHierarchies"/> is <c>null</c>.
/// </exception>
/// <exception cref="ArgumentException">
/// The exception is thrown when <paramref name="timeSeriesHierarchies"/> is empty.
/// </exception>
/// <example>
/// <code snippet="Snippet:TimeSeriesInsightsSampleCreateHierarchies">
/// var hierarchySource = new TimeSeriesHierarchySource();
/// hierarchySource.InstanceFieldNames.Add("hierarchyLevel1");
///
/// var tsiHierarchy = new TimeSeriesHierarchy("sampleHierarchy", hierarchySource)
/// {
/// Id = "sampleHierarchyId"
/// };
///
/// var timeSeriesHierarchies = new List<TimeSeriesHierarchy>
/// {
/// tsiHierarchy
/// };
///
/// // Create Time Series hierarchies
/// Response<TimeSeriesHierarchyOperationResult[]> createHierarchiesResult = await client
/// .Hierarchies
/// .CreateOrReplaceAsync(timeSeriesHierarchies);
///
/// // The response of calling the API contains a list of error objects corresponding by position to the input parameter array in the request.
/// // If the error object is set to null, this means the operation was a success.
/// for (int i = 0; i < createHierarchiesResult.Value.Length; i++)
/// {
/// if (createHierarchiesResult.Value[i].Error == null)
/// {
/// Console.WriteLine($"Created Time Series hierarchy successfully.");
/// }
/// else
/// {
/// Console.WriteLine($"Failed to create a Time Series hierarchy: {createHierarchiesResult.Value[i].Error.Message}.");
/// }
/// }
/// </code>
/// </example>
public virtual async Task<Response<TimeSeriesHierarchyOperationResult[]>> CreateOrReplaceAsync(
IEnumerable<TimeSeriesHierarchy> timeSeriesHierarchies,
CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _clientDiagnostics
.CreateScope($"{nameof(TimeSeriesInsightsClient)}.{nameof(CreateOrReplace)}");
scope.Start();
try
{
Argument.AssertNotNullOrEmpty(timeSeriesHierarchies, nameof(timeSeriesHierarchies));
var batchRequest = new HierarchiesBatchRequest();
foreach (TimeSeriesHierarchy hierarchy in timeSeriesHierarchies)
{
batchRequest.Put.Add(hierarchy);
}
Response<HierarchiesBatchResponse> executeBatchResponse = await _hierarchiesRestClient
.ExecuteBatchAsync(batchRequest, null, cancellationToken)
.ConfigureAwait(false);
IEnumerable<TimeSeriesOperationError> errorResults = executeBatchResponse.Value.Put.Select((result) => result.Error);
return Response.FromValue(executeBatchResponse.Value.Put.ToArray(), executeBatchResponse.GetRawResponse());
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary>
/// Creates Time Series Insights hierarchies synchronously. If a provided hierarchy is already in use, then this will attempt to replace the existing hierarchy with the provided Time Series hierarchy.
/// </summary>
/// <param name="timeSeriesHierarchies">The Time Series Insights hierarchies to be created or replaced.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>
/// List of hierarchies or error objects corresponding by position to the <paramref name="timeSeriesHierarchies"/> array in the request.
/// Hierarchy object is set when operation is successful and error object is set when operation is unsuccessful.
/// </returns>
/// <seealso cref="CreateOrReplaceAsync(IEnumerable{TimeSeriesHierarchy}, CancellationToken)">
/// See the asynchronous version of this method for examples.
/// </seealso>
/// <exception cref="ArgumentNullException">
/// The exception is thrown when <paramref name="timeSeriesHierarchies"/> is <c>null</c>.
/// </exception>
/// <exception cref="ArgumentException">
/// The exception is thrown when <paramref name="timeSeriesHierarchies"/> is empty.
/// </exception>
public virtual Response<TimeSeriesHierarchyOperationResult[]> CreateOrReplace(
IEnumerable<TimeSeriesHierarchy> timeSeriesHierarchies,
CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(TimeSeriesInsightsClient)}.{nameof(CreateOrReplace)}");
scope.Start();
try
{
Argument.AssertNotNullOrEmpty(timeSeriesHierarchies, nameof(timeSeriesHierarchies));
var batchRequest = new HierarchiesBatchRequest();
foreach (TimeSeriesHierarchy hierarchy in timeSeriesHierarchies)
{
batchRequest.Put.Add(hierarchy);
}
Response<HierarchiesBatchResponse> executeBatchResponse = _hierarchiesRestClient
.ExecuteBatch(batchRequest, null, cancellationToken);
IEnumerable<TimeSeriesOperationError> errorResults = executeBatchResponse.Value.Put.Select((result) => result.Error);
return Response.FromValue(executeBatchResponse.Value.Put.ToArray(), executeBatchResponse.GetRawResponse());
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary>
/// Deletes Time Series Insights hierarchies by hierarchy names asynchronously.
/// </summary>
/// <param name="timeSeriesHierarchyNames">List of names of the Time Series hierarchies to delete.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>
/// List of error objects corresponding by position to the input array in the request. null when the operation is successful.
/// </returns>
/// <remarks>
/// For more samples, see <see href="https://github.com/Azure/azure-sdk-for-net/tree/master/sdk/timeseriesinsights/Azure.IoT.TimeSeriesInsights/samples">our repo samples</see>.
/// </remarks>
/// <exception cref="ArgumentNullException">
/// The exception is thrown when <paramref name="timeSeriesHierarchyNames"/> is <c>null</c>.
/// </exception>
/// <exception cref="ArgumentException">
/// The exception is thrown when <paramref name="timeSeriesHierarchyNames"/> is empty.
/// </exception>
public virtual async Task<Response<TimeSeriesOperationError[]>> DeleteByNameAsync(
IEnumerable<string> timeSeriesHierarchyNames,
CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(TimeSeriesInsightsClient)}.{nameof(DeleteByName)}");
scope.Start();
try
{
Argument.AssertNotNullOrEmpty(timeSeriesHierarchyNames, nameof(timeSeriesHierarchyNames));
var batchRequest = new HierarchiesBatchRequest
{
Delete = new HierarchiesRequestBatchGetDelete()
};
foreach (string timeSeriesName in timeSeriesHierarchyNames)
{
batchRequest.Delete.Names.Add(timeSeriesName);
}
Response<HierarchiesBatchResponse> executeBatchResponse = await _hierarchiesRestClient
.ExecuteBatchAsync(batchRequest, null, cancellationToken)
.ConfigureAwait(false);
return Response.FromValue(executeBatchResponse.Value.Delete.ToArray(), executeBatchResponse.GetRawResponse());
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary>
/// Deletes Time Series Insights hierarchies by hierarchy names synchronously.
/// </summary>
/// <param name="timeSeriesHierarchyNames">List of names of the Time Series hierarchies to delete.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>
/// List of error objects corresponding by position to the input array in the request. null when the operation is successful.
/// </returns>
/// <seealso cref="DeleteByNameAsync(IEnumerable{string}, CancellationToken)">
/// See the asynchronous version of this method for examples.
/// </seealso>
/// <exception cref="ArgumentNullException">
/// The exception is thrown when <paramref name="timeSeriesHierarchyNames"/> is <c>null</c>.
/// </exception>
/// <exception cref="ArgumentException">
/// The exception is thrown when <paramref name="timeSeriesHierarchyNames"/> is empty.
/// </exception>
public virtual Response<TimeSeriesOperationError[]> DeleteByName(
IEnumerable<string> timeSeriesHierarchyNames,
CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(TimeSeriesInsightsClient)}.{nameof(DeleteByName)}");
scope.Start();
try
{
Argument.AssertNotNullOrEmpty(timeSeriesHierarchyNames, nameof(timeSeriesHierarchyNames));
var batchRequest = new HierarchiesBatchRequest
{
Delete = new HierarchiesRequestBatchGetDelete()
};
foreach (string timeSeriesName in timeSeriesHierarchyNames)
{
batchRequest.Delete.Names.Add(timeSeriesName);
}
Response<HierarchiesBatchResponse> executeBatchResponse = _hierarchiesRestClient
.ExecuteBatch(batchRequest, null, cancellationToken);
return Response.FromValue(executeBatchResponse.Value.Delete.ToArray(), executeBatchResponse.GetRawResponse());
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary>
/// Deletes Time Series Insights hierarchies by hierarchy Ids asynchronously.
/// </summary>
/// <param name="timeSeriesHierarchyIds">List of Time Series hierarchy Ids of the Time Series hierarchies to delete.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>
/// List of error objects corresponding by position to the input array in the request. null when the operation is successful.
/// </returns>
/// <remarks>
/// For more samples, see <see href="https://github.com/Azure/azure-sdk-for-net/tree/master/sdk/timeseriesinsights/Azure.IoT.TimeSeriesInsights/samples">our repo samples</see>.
/// </remarks>
/// <exception cref="ArgumentNullException">
/// The exception is thrown when <paramref name="timeSeriesHierarchyIds"/> is <c>null</c>.
/// </exception>
/// <exception cref="ArgumentException">
/// The exception is thrown when <paramref name="timeSeriesHierarchyIds"/> is empty.
/// </exception>
/// <example>
/// <code snippet="Snippet:TimeSeriesInsightsSampleDeleteHierarchiesById">
/// // Delete Time Series hierarchies with Ids
/// var tsiHierarchyIdsToDelete = new List<string>
/// {
/// "sampleHiearchyId"
/// };
///
/// Response<TimeSeriesOperationError[]> deleteHierarchiesResponse = await client
/// .Hierarchies
/// .DeleteByIdAsync(tsiHierarchyIdsToDelete);
///
/// // The response of calling the API contains a list of error objects corresponding by position to the input parameter
/// // array in the request. If the error object is set to null, this means the operation was a success.
/// foreach (TimeSeriesOperationError result in deleteHierarchiesResponse.Value)
/// {
/// if (result != null)
/// {
/// Console.WriteLine($"Failed to delete a Time Series Insights hierarchy: {result.Message}.");
/// }
/// else
/// {
/// Console.WriteLine($"Deleted a Time Series Insights hierarchy successfully.");
/// }
/// }
/// </code>
/// </example>
public virtual async Task<Response<TimeSeriesOperationError[]>> DeleteByIdAsync(
IEnumerable<string> timeSeriesHierarchyIds,
CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(TimeSeriesInsightsClient)}.{nameof(DeleteById)}");
scope.Start();
try
{
Argument.AssertNotNullOrEmpty(timeSeriesHierarchyIds, nameof(timeSeriesHierarchyIds));
var batchRequest = new HierarchiesBatchRequest
{
Delete = new HierarchiesRequestBatchGetDelete()
};
foreach (string hierarchyId in timeSeriesHierarchyIds)
{
batchRequest.Delete.HierarchyIds.Add(hierarchyId);
}
Response<HierarchiesBatchResponse> executeBatchResponse = await _hierarchiesRestClient
.ExecuteBatchAsync(batchRequest, null, cancellationToken)
.ConfigureAwait(false);
return Response.FromValue(executeBatchResponse.Value.Delete.ToArray(), executeBatchResponse.GetRawResponse());
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary>
/// Deletes Time Series instances from the environment by Time Series Ids synchronously.
/// </summary>
/// <param name="timeSeriesHierarchyIds">List of Ids of the Time Series instances to delete.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>
/// List of error objects corresponding by position to the input array in the request. null when the operation is successful.
/// </returns>
/// <seealso cref="DeleteByIdAsync(IEnumerable{string}, CancellationToken)">
/// See the asynchronous version of this method for examples.
/// </seealso>
/// <exception cref="ArgumentNullException">
/// The exception is thrown when <paramref name="timeSeriesHierarchyIds"/> is <c>null</c>.
/// </exception>
/// <exception cref="ArgumentException">
/// The exception is thrown when <paramref name="timeSeriesHierarchyIds"/> is empty.
/// </exception>
public virtual Response<TimeSeriesOperationError[]> DeleteById(
IEnumerable<string> timeSeriesHierarchyIds,
CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(TimeSeriesInsightsClient)}.{nameof(DeleteById)}");
scope.Start();
try
{
Argument.AssertNotNullOrEmpty(timeSeriesHierarchyIds, nameof(timeSeriesHierarchyIds));
var batchRequest = new HierarchiesBatchRequest
{
Delete = new HierarchiesRequestBatchGetDelete()
};
foreach (string hierarchyId in timeSeriesHierarchyIds ?? Enumerable.Empty<string>())
{
batchRequest.Delete.HierarchyIds.Add(hierarchyId);
}
Response<HierarchiesBatchResponse> executeBatchResponse = _hierarchiesRestClient
.ExecuteBatch(batchRequest, null, cancellationToken);
return Response.FromValue(executeBatchResponse.Value.Delete.ToArray(), executeBatchResponse.GetRawResponse());
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using IndexReader = Lucene.Net.Index.IndexReader;
using TermDocs = Lucene.Net.Index.TermDocs;
using OpenBitSet = Lucene.Net.Util.OpenBitSet;
namespace Lucene.Net.Search
{
/// <summary> A <see cref="Filter" /> that only accepts documents whose single
/// term value in the specified field is contained in the
/// provided set of allowed terms.
///
/// <p/>
///
/// This is the same functionality as TermsFilter (from
/// contrib/queries), except this filter requires that the
/// field contains only a single term for all documents.
/// Because of drastically different implementations, they
/// also have different performance characteristics, as
/// described below.
///
/// <p/>
///
/// The first invocation of this filter on a given field will
/// be slower, since a <see cref="StringIndex" /> must be
/// created. Subsequent invocations using the same field
/// will re-use this cache. However, as with all
/// functionality based on <see cref="FieldCache" />, persistent RAM
/// is consumed to hold the cache, and is not freed until the
/// <see cref="IndexReader" /> is closed. In contrast, TermsFilter
/// has no persistent RAM consumption.
///
///
/// <p/>
///
/// With each search, this filter translates the specified
/// set of Terms into a private <see cref="OpenBitSet" /> keyed by
/// term number per unique <see cref="IndexReader" /> (normally one
/// reader per segment). Then, during matching, the term
/// number for each docID is retrieved from the cache and
/// then checked for inclusion using the <see cref="OpenBitSet" />.
/// Since all testing is done using RAM resident data
/// structures, performance should be very fast, most likely
/// fast enough to not require further caching of the
/// DocIdSet for each possible combination of terms.
/// However, because docIDs are simply scanned linearly, an
/// index with a great many small documents may find this
/// linear scan too costly.
///
/// <p/>
///
/// In contrast, TermsFilter builds up an <see cref="OpenBitSet" />,
/// keyed by docID, every time it's created, by enumerating
/// through all matching docs using <see cref="TermDocs" /> to seek
/// and scan through each term's docID list. While there is
/// no linear scan of all docIDs, besides the allocation of
/// the underlying array in the <see cref="OpenBitSet" />, this
/// approach requires a number of "disk seeks" in proportion
/// to the number of terms, which can be exceptionally costly
/// when there are cache misses in the OS's IO cache.
///
/// <p/>
///
/// Generally, this filter will be slower on the first
/// invocation for a given field, but subsequent invocations,
/// even if you change the allowed set of Terms, should be
/// faster than TermsFilter, especially as the number of
/// Terms being matched increases. If you are matching only
/// a very small number of terms, and those terms in turn
/// match a very small number of documents, TermsFilter may
/// perform faster.
///
/// <p/>
///
/// Which filter is best is very application dependent.
/// </summary>
//[Serializable] //Disabled for https://github.com/dotnet/standard/issues/300
public class FieldCacheTermsFilter:Filter
{
private readonly string field;
private readonly string[] terms;
public FieldCacheTermsFilter(string field, params string[] terms)
{
this.field = field;
this.terms = terms;
}
public virtual FieldCache FieldCache
{
get { return FieldCache_Fields.DEFAULT; }
}
public override DocIdSet GetDocIdSet(IndexReader reader)
{
return new FieldCacheTermsFilterDocIdSet(this, FieldCache.GetStringIndex(reader, field));
}
protected internal class FieldCacheTermsFilterDocIdSet:DocIdSet
{
private void InitBlock(FieldCacheTermsFilter enclosingInstance)
{
this.enclosingInstance = enclosingInstance;
}
private FieldCacheTermsFilter enclosingInstance;
public FieldCacheTermsFilter Enclosing_Instance
{
get
{
return enclosingInstance;
}
}
private readonly Lucene.Net.Search.StringIndex fcsi;
private readonly OpenBitSet openBitSet;
public FieldCacheTermsFilterDocIdSet(FieldCacheTermsFilter enclosingInstance, StringIndex fcsi)
{
InitBlock(enclosingInstance);
this.fcsi = fcsi;
openBitSet = new OpenBitSet(this.fcsi.lookup.Length);
foreach (string t in Enclosing_Instance.terms)
{
int termNumber = this.fcsi.BinarySearchLookup(t);
if (termNumber > 0)
{
openBitSet.FastSet(termNumber);
}
}
}
public override DocIdSetIterator Iterator()
{
return new FieldCacheTermsFilterDocIdSetIterator(this);
}
/// <summary>This DocIdSet implementation is cacheable. </summary>
public override bool IsCacheable
{
get { return true; }
}
protected internal class FieldCacheTermsFilterDocIdSetIterator:DocIdSetIterator
{
public FieldCacheTermsFilterDocIdSetIterator(FieldCacheTermsFilterDocIdSet enclosingInstance)
{
InitBlock(enclosingInstance);
}
private void InitBlock(FieldCacheTermsFilterDocIdSet enclosingInstance)
{
this.enclosingInstance = enclosingInstance;
}
private FieldCacheTermsFilterDocIdSet enclosingInstance;
public FieldCacheTermsFilterDocIdSet Enclosing_Instance
{
get
{
return enclosingInstance;
}
}
private int doc = - 1;
public override int DocID()
{
return doc;
}
public override int NextDoc()
{
try
{
while (!Enclosing_Instance.openBitSet.FastGet(Enclosing_Instance.fcsi.order[++doc]))
{
}
}
catch (IndexOutOfRangeException)
{
doc = NO_MORE_DOCS;
}
return doc;
}
public override int Advance(int target)
{
try
{
doc = target;
while (!Enclosing_Instance.openBitSet.FastGet(Enclosing_Instance.fcsi.order[doc]))
{
doc++;
}
}
catch (IndexOutOfRangeException)
{
doc = NO_MORE_DOCS;
}
return doc;
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Orleans;
using Orleans.Runtime;
using Orleans.Runtime.Scheduler;
using UnitTests.GrainInterfaces;
using UnitTests.Grains;
namespace UnitTestGrains
{
public class TimerGrain : Grain, ITimerGrain
{
private bool deactivating;
int counter = 0;
Dictionary<string, IDisposable> allTimers;
IDisposable defaultTimer;
private static readonly TimeSpan period = TimeSpan.FromMilliseconds(100);
string DefaultTimerName = "DEFAULT TIMER";
ISchedulingContext context;
private ILogger logger;
public TimerGrain(ILoggerFactory loggerFactory)
{
this.logger = loggerFactory.CreateLogger($"{this.GetType().Name}-{this.IdentityString}");
}
public override Task OnActivateAsync()
{
ThrowIfDeactivating();
context = RuntimeContext.Current.ActivationContext;
defaultTimer = this.RegisterTimer(Tick, DefaultTimerName, period, period);
allTimers = new Dictionary<string, IDisposable>();
return Task.CompletedTask;
}
public Task StopDefaultTimer()
{
ThrowIfDeactivating();
defaultTimer.Dispose();
return Task.CompletedTask;
}
private Task Tick(object data)
{
counter++;
logger.Info(data.ToString() + " Tick # " + counter + " RuntimeContext = " + RuntimeContext.Current.ActivationContext.ToString());
// make sure we run in the right activation context.
if(!Equals(context, RuntimeContext.Current.ActivationContext))
logger.Error((int)ErrorCode.Runtime_Error_100146, "grain not running in the right activation context");
string name = (string)data;
IDisposable timer = null;
if (name == DefaultTimerName)
{
timer = defaultTimer;
}
else
{
timer = allTimers[(string)data];
}
if(timer == null)
logger.Error((int)ErrorCode.Runtime_Error_100146, "Timer is null");
if (timer != null && counter > 10000)
{
// do not let orphan timers ticking for long periods
timer.Dispose();
}
return Task.CompletedTask;
}
public Task<TimeSpan> GetTimerPeriod()
{
return Task.FromResult(period);
}
public Task<int> GetCounter()
{
ThrowIfDeactivating();
return Task.FromResult(counter);
}
public Task SetCounter(int value)
{
ThrowIfDeactivating();
lock (this)
{
counter = value;
}
return Task.CompletedTask;
}
public Task StartTimer(string timerName)
{
ThrowIfDeactivating();
IDisposable timer = this.RegisterTimer(Tick, timerName, TimeSpan.Zero, period);
allTimers.Add(timerName, timer);
return Task.CompletedTask;
}
public Task StopTimer(string timerName)
{
ThrowIfDeactivating();
IDisposable timer = allTimers[timerName];
timer.Dispose();
return Task.CompletedTask;
}
public Task LongWait(TimeSpan time)
{
ThrowIfDeactivating();
Thread.Sleep(time);
return Task.CompletedTask;
}
public Task Deactivate()
{
deactivating = true;
DeactivateOnIdle();
return Task.CompletedTask;
}
private void ThrowIfDeactivating()
{
if (deactivating) throw new InvalidOperationException("This activation is deactivating");
}
}
public class TimerCallGrain : Grain, ITimerCallGrain
{
private int tickCount;
private Exception tickException;
private IDisposable timer;
private string timerName;
private ISchedulingContext context;
private TaskScheduler activationTaskScheduler;
private ILogger logger;
public TimerCallGrain(ILoggerFactory loggerFactory)
{
this.logger = loggerFactory.CreateLogger($"{this.GetType().Name}-{this.IdentityString}");
}
public Task<int> GetTickCount() { return Task.FromResult(tickCount); }
public Task<Exception> GetException() { return Task.FromResult(tickException); }
public override Task OnActivateAsync()
{
context = RuntimeContext.Current.ActivationContext;
activationTaskScheduler = TaskScheduler.Current;
return Task.CompletedTask;
}
public Task StartTimer(string name, TimeSpan delay)
{
logger.Info("StartTimer Name={0} Delay={1}", name, delay);
this.timerName = name;
this.timer = base.RegisterTimer(TimerTick, name, delay, Constants.INFINITE_TIMESPAN); // One shot timer
return Task.CompletedTask;
}
public Task StopTimer(string name)
{
logger.Info("StopTimer Name={0}", name);
if (name != this.timerName)
{
throw new ArgumentException(string.Format("Wrong timer name: Expected={0} Actual={1}", this.timerName, name));
}
timer.Dispose();
return Task.CompletedTask;
}
private async Task TimerTick(object data)
{
try
{
await ProcessTimerTick(data);
}
catch (Exception exc)
{
this.tickException = exc;
throw;
}
}
private async Task ProcessTimerTick(object data)
{
string step = "TimerTick";
LogStatus(step);
// make sure we run in the right activation context.
CheckRuntimeContext(step);
string name = (string)data;
if (name != this.timerName)
{
throw new ArgumentException(string.Format("Wrong timer name: Expected={0} Actual={1}", this.timerName, name));
}
ISimpleGrain grain = GrainFactory.GetGrain<ISimpleGrain>(0, SimpleGrain.SimpleGrainNamePrefix);
LogStatus("Before grain call #1");
await grain.SetA(tickCount);
step = "After grain call #1";
LogStatus(step);
CheckRuntimeContext(step);
LogStatus("Before Delay");
await Task.Delay(TimeSpan.FromSeconds(1));
step = "After Delay";
LogStatus(step);
CheckRuntimeContext(step);
LogStatus("Before grain call #2");
await grain.SetB(tickCount);
step = "After grain call #2";
LogStatus(step);
CheckRuntimeContext(step);
LogStatus("Before grain call #3");
int res = await grain.GetAxB();
step = "After grain call #3 - Result = " + res;
LogStatus(step);
CheckRuntimeContext(step);
tickCount++;
}
private void CheckRuntimeContext(string what)
{
if (RuntimeContext.Current.ActivationContext == null
|| !RuntimeContext.Current.ActivationContext.Equals(context))
{
throw new InvalidOperationException(
string.Format("{0} in timer callback with unexpected activation context: Expected={1} Actual={2}",
what, context, RuntimeContext.Current.ActivationContext));
}
if (TaskScheduler.Current.Equals(activationTaskScheduler) && TaskScheduler.Current is ActivationTaskScheduler)
{
// Everything is as expected
}
else
{
throw new InvalidOperationException(
string.Format("{0} in timer callback with unexpected TaskScheduler.Current context: Expected={1} Actual={2}",
what, activationTaskScheduler, TaskScheduler.Current));
}
}
private void LogStatus(string what)
{
logger.Info("{0} Tick # {1} - {2} - RuntimeContext.Current={3} TaskScheduler.Current={4} CurrentWorkerThread={5}",
timerName, tickCount, what, RuntimeContext.Current, TaskScheduler.Current,
Thread.CurrentThread.Name);
}
}
public class TimerRequestGrain : Grain, ITimerRequestGrain
{
private TaskCompletionSource<int> completionSource;
public Task<string> GetRuntimeInstanceId()
{
return Task.FromResult(this.RuntimeIdentity);
}
public async Task StartAndWaitTimerTick(TimeSpan dueTime)
{
this.completionSource = new TaskCompletionSource<int>();
var timer = this.RegisterTimer(TimerTick, null, dueTime, TimeSpan.FromMilliseconds(-1));
await this.completionSource.Task;
}
public Task StartStuckTimer(TimeSpan dueTime)
{
this.completionSource = new TaskCompletionSource<int>();
var timer = this.RegisterTimer(StuckTimerTick, null, dueTime, TimeSpan.FromSeconds(1));
return Task.CompletedTask;
}
private Task TimerTick(object state)
{
this.completionSource.SetResult(1);
return Task.CompletedTask;
}
private async Task StuckTimerTick(object state)
{
await completionSource.Task;
}
}
}
| |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Shouldly;
using Spect.Net.SpectrumEmu.Cpu;
using Spect.Net.SpectrumEmu.Test.Helpers;
namespace Spect.Net.SpectrumEmu.Test.Cpu.IndexedBitOps
{
[TestClass]
public class IyBitOpTests0X30
{
/// <summary>
/// SLL (IY+D),B: 0xFD 0xCB 0x30
/// </summary>
[TestMethod]
public void XSLL_B_WorksAsExpected()
{
// --- Arrange
const byte OFFS = 0x32;
var m = new Z80TestMachine(RunMode.OneInstruction);
m.InitCode(new byte[]
{
0xFD, 0xCB, OFFS, 0x30 // SLL (IY+32H),B
});
var regs = m.Cpu.Registers;
regs.IY = 0x1000;
regs.F |= FlagsSetMask.C;
m.Memory[regs.IY + OFFS] = 0x08;
// --- Act
m.Run();
// --- Assert
regs.B.ShouldBe(m.Memory[regs.IY + OFFS]);
regs.B.ShouldBe((byte)0x11);
regs.SFlag.ShouldBeFalse();
regs.ZFlag.ShouldBeFalse();
regs.CFlag.ShouldBeFalse();
regs.PFlag.ShouldBeTrue();
regs.HFlag.ShouldBeFalse();
regs.NFlag.ShouldBeFalse();
m.ShouldKeepRegisters(except: "F, B");
m.ShouldKeepMemory(except: "1032");
regs.PC.ShouldBe((ushort)0x0004);
m.Cpu.Tacts.ShouldBe(23L);
}
/// <summary>
/// SLL (IY+D),C: 0xFD 0xCB 0x31
/// </summary>
[TestMethod]
public void XSLL_C_WorksAsExpected()
{
// --- Arrange
const byte OFFS = 0x32;
var m = new Z80TestMachine(RunMode.OneInstruction);
m.InitCode(new byte[]
{
0xFD, 0xCB, OFFS, 0x31 // SLL (IY+32H),C
});
var regs = m.Cpu.Registers;
regs.IY = 0x1000;
regs.F |= FlagsSetMask.C;
m.Memory[regs.IY + OFFS] = 0x08;
// --- Act
m.Run();
// --- Assert
regs.C.ShouldBe(m.Memory[regs.IY + OFFS]);
regs.C.ShouldBe((byte)0x11);
regs.SFlag.ShouldBeFalse();
regs.ZFlag.ShouldBeFalse();
regs.CFlag.ShouldBeFalse();
regs.PFlag.ShouldBeTrue();
regs.HFlag.ShouldBeFalse();
regs.NFlag.ShouldBeFalse();
m.ShouldKeepRegisters(except: "F, C");
m.ShouldKeepMemory(except: "1032");
regs.PC.ShouldBe((ushort)0x0004);
m.Cpu.Tacts.ShouldBe(23L);
}
/// <summary>
/// SLL (IY+D),D: 0xFD 0xCB 0x32
/// </summary>
[TestMethod]
public void XSLL_D_WorksAsExpected()
{
// --- Arrange
const byte OFFS = 0x32;
var m = new Z80TestMachine(RunMode.OneInstruction);
m.InitCode(new byte[]
{
0xFD, 0xCB, OFFS, 0x32 // SLL (IY+32H),D
});
var regs = m.Cpu.Registers;
regs.IY = 0x1000;
regs.F |= FlagsSetMask.C;
m.Memory[regs.IY + OFFS] = 0x08;
// --- Act
m.Run();
// --- Assert
regs.D.ShouldBe(m.Memory[regs.IY + OFFS]);
regs.D.ShouldBe((byte)0x11);
regs.SFlag.ShouldBeFalse();
regs.ZFlag.ShouldBeFalse();
regs.CFlag.ShouldBeFalse();
regs.PFlag.ShouldBeTrue();
regs.HFlag.ShouldBeFalse();
regs.NFlag.ShouldBeFalse();
m.ShouldKeepRegisters(except: "F, D");
m.ShouldKeepMemory(except: "1032");
regs.PC.ShouldBe((ushort)0x0004);
m.Cpu.Tacts.ShouldBe(23L);
}
/// <summary>
/// SLL (IY+D),E: 0xFD 0xCB 0x33
/// </summary>
[TestMethod]
public void XSLL_E_WorksAsExpected()
{
// --- Arrange
const byte OFFS = 0x32;
var m = new Z80TestMachine(RunMode.OneInstruction);
m.InitCode(new byte[]
{
0xFD, 0xCB, OFFS, 0x33 // SLL (IY+32H),E
});
var regs = m.Cpu.Registers;
regs.IY = 0x1000;
regs.F |= FlagsSetMask.C;
m.Memory[regs.IY + OFFS] = 0x08;
// --- Act
m.Run();
// --- Assert
regs.E.ShouldBe(m.Memory[regs.IY + OFFS]);
regs.E.ShouldBe((byte)0x11);
regs.SFlag.ShouldBeFalse();
regs.ZFlag.ShouldBeFalse();
regs.CFlag.ShouldBeFalse();
regs.PFlag.ShouldBeTrue();
regs.HFlag.ShouldBeFalse();
regs.NFlag.ShouldBeFalse();
m.ShouldKeepRegisters(except: "F, E");
m.ShouldKeepMemory(except: "1032");
regs.PC.ShouldBe((ushort)0x0004);
m.Cpu.Tacts.ShouldBe(23L);
}
/// <summary>
/// SLL (IY+D),H: 0xFD 0xCB 0x34
/// </summary>
[TestMethod]
public void XSLL_H_WorksAsExpected()
{
// --- Arrange
const byte OFFS = 0x32;
var m = new Z80TestMachine(RunMode.OneInstruction);
m.InitCode(new byte[]
{
0xFD, 0xCB, OFFS, 0x34 // SLL (IY+32H),H
});
var regs = m.Cpu.Registers;
regs.IY = 0x1000;
regs.F |= FlagsSetMask.C;
m.Memory[regs.IY + OFFS] = 0x08;
// --- Act
m.Run();
// --- Assert
regs.H.ShouldBe(m.Memory[regs.IY + OFFS]);
regs.H.ShouldBe((byte)0x11);
regs.SFlag.ShouldBeFalse();
regs.ZFlag.ShouldBeFalse();
regs.CFlag.ShouldBeFalse();
regs.PFlag.ShouldBeTrue();
regs.HFlag.ShouldBeFalse();
regs.NFlag.ShouldBeFalse();
m.ShouldKeepRegisters(except: "F, H");
m.ShouldKeepMemory(except: "1032");
regs.PC.ShouldBe((ushort)0x0004);
m.Cpu.Tacts.ShouldBe(23L);
}
/// <summary>
/// SLL (IY+D),L: 0xFD 0xCB 0x35
/// </summary>
[TestMethod]
public void XSLL_L_WorksAsExpected()
{
// --- Arrange
const byte OFFS = 0x32;
var m = new Z80TestMachine(RunMode.OneInstruction);
m.InitCode(new byte[]
{
0xFD, 0xCB, OFFS, 0x35 // SLL (IY+32H),L
});
var regs = m.Cpu.Registers;
regs.IY = 0x1000;
regs.F |= FlagsSetMask.C;
m.Memory[regs.IY + OFFS] = 0x08;
// --- Act
m.Run();
// --- Assert
regs.L.ShouldBe(m.Memory[regs.IY + OFFS]);
regs.L.ShouldBe((byte)0x11);
regs.SFlag.ShouldBeFalse();
regs.ZFlag.ShouldBeFalse();
regs.CFlag.ShouldBeFalse();
regs.PFlag.ShouldBeTrue();
regs.HFlag.ShouldBeFalse();
regs.NFlag.ShouldBeFalse();
m.ShouldKeepRegisters(except: "F, L");
m.ShouldKeepMemory(except: "1032");
regs.PC.ShouldBe((ushort)0x0004);
m.Cpu.Tacts.ShouldBe(23L);
}
/// <summary>
/// SLL (IY+D): 0xFD 0xCB 0x36
/// </summary>
[TestMethod]
public void XSLL_WorksAsExpected()
{
// --- Arrange
const byte OFFS = 0x32;
var m = new Z80TestMachine(RunMode.OneInstruction);
m.InitCode(new byte[]
{
0xFD, 0xCB, OFFS, 0x36 // SLL (IY+32H)
});
var regs = m.Cpu.Registers;
regs.IY = 0x1000;
regs.F |= FlagsSetMask.C;
m.Memory[regs.IY + OFFS] = 0x08;
// --- Act
m.Run();
// --- Assert
m.Memory[regs.IY + OFFS].ShouldBe((byte)0x11);
regs.SFlag.ShouldBeFalse();
regs.ZFlag.ShouldBeFalse();
regs.CFlag.ShouldBeFalse();
regs.PFlag.ShouldBeTrue();
regs.HFlag.ShouldBeFalse();
regs.NFlag.ShouldBeFalse();
m.ShouldKeepRegisters(except: "F");
m.ShouldKeepMemory(except: "1032");
regs.PC.ShouldBe((ushort)0x0004);
m.Cpu.Tacts.ShouldBe(23L);
}
/// <summary>
/// SLL (IY+D),A: 0xFD 0xCB 0x37
/// </summary>
[TestMethod]
public void XSLL_A_WorksAsExpected()
{
// --- Arrange
const byte OFFS = 0x32;
var m = new Z80TestMachine(RunMode.OneInstruction);
m.InitCode(new byte[]
{
0xFD, 0xCB, OFFS, 0x37 // SLL (IY+32H),A
});
var regs = m.Cpu.Registers;
regs.IY = 0x1000;
regs.F |= FlagsSetMask.C;
m.Memory[regs.IY + OFFS] = 0x08;
// --- Act
m.Run();
// --- Assert
regs.A.ShouldBe(m.Memory[regs.IY + OFFS]);
regs.A.ShouldBe((byte)0x11);
regs.SFlag.ShouldBeFalse();
regs.ZFlag.ShouldBeFalse();
regs.CFlag.ShouldBeFalse();
regs.PFlag.ShouldBeTrue();
regs.HFlag.ShouldBeFalse();
regs.NFlag.ShouldBeFalse();
m.ShouldKeepRegisters(except: "F, A");
m.ShouldKeepMemory(except: "1032");
regs.PC.ShouldBe((ushort)0x0004);
m.Cpu.Tacts.ShouldBe(23L);
}
/// <summary>
/// SRL (IY+D),B: 0xFD 0xCB 0x38
/// </summary>
[TestMethod]
public void XSRL_B_WorksAsExpected()
{
// --- Arrange
const byte OFFS = 0x32;
var m = new Z80TestMachine(RunMode.OneInstruction);
m.InitCode(new byte[]
{
0xFD, 0xCB, OFFS, 0x38 // SRL (IY+32H),B
});
var regs = m.Cpu.Registers;
regs.IY = 0x1000;
regs.F |= FlagsSetMask.C;
m.Memory[regs.IY + OFFS] = 0x10;
// --- Act
m.Run();
// --- Assert
regs.B.ShouldBe(m.Memory[regs.IY + OFFS]);
regs.B.ShouldBe((byte)0x08);
regs.SFlag.ShouldBeFalse();
regs.ZFlag.ShouldBeFalse();
regs.CFlag.ShouldBeFalse();
regs.PFlag.ShouldBeFalse();
regs.HFlag.ShouldBeFalse();
regs.NFlag.ShouldBeFalse();
m.ShouldKeepRegisters(except: "F, B");
m.ShouldKeepMemory(except: "1032");
regs.PC.ShouldBe((ushort)0x0004);
m.Cpu.Tacts.ShouldBe(23L);
}
/// <summary>
/// SRL (IY+D),C: 0xFD 0xCB 0x39
/// </summary>
[TestMethod]
public void XSRL_C_WorksAsExpected()
{
// --- Arrange
const byte OFFS = 0x32;
var m = new Z80TestMachine(RunMode.OneInstruction);
m.InitCode(new byte[]
{
0xFD, 0xCB, OFFS, 0x39 // SRL (IY+32H),C
});
var regs = m.Cpu.Registers;
regs.IY = 0x1000;
regs.F |= FlagsSetMask.C;
m.Memory[regs.IY + OFFS] = 0x10;
// --- Act
m.Run();
// --- Assert
regs.C.ShouldBe(m.Memory[regs.IY + OFFS]);
regs.C.ShouldBe((byte)0x08);
regs.SFlag.ShouldBeFalse();
regs.ZFlag.ShouldBeFalse();
regs.CFlag.ShouldBeFalse();
regs.PFlag.ShouldBeFalse();
regs.HFlag.ShouldBeFalse();
regs.NFlag.ShouldBeFalse();
m.ShouldKeepRegisters(except: "F, C");
m.ShouldKeepMemory(except: "1032");
regs.PC.ShouldBe((ushort)0x0004);
m.Cpu.Tacts.ShouldBe(23L);
}
/// <summary>
/// SRL (IY+D),D: 0xFD 0xCB 0x3A
/// </summary>
[TestMethod]
public void XSRL_D_WorksAsExpected()
{
// --- Arrange
const byte OFFS = 0x32;
var m = new Z80TestMachine(RunMode.OneInstruction);
m.InitCode(new byte[]
{
0xFD, 0xCB, OFFS, 0x3A // SRL (IY+32H),D
});
var regs = m.Cpu.Registers;
regs.IY = 0x1000;
regs.F |= FlagsSetMask.C;
m.Memory[regs.IY + OFFS] = 0x10;
// --- Act
m.Run();
// --- Assert
regs.D.ShouldBe(m.Memory[regs.IY + OFFS]);
regs.D.ShouldBe((byte)0x08);
regs.SFlag.ShouldBeFalse();
regs.ZFlag.ShouldBeFalse();
regs.CFlag.ShouldBeFalse();
regs.PFlag.ShouldBeFalse();
regs.HFlag.ShouldBeFalse();
regs.NFlag.ShouldBeFalse();
m.ShouldKeepRegisters(except: "F, D");
m.ShouldKeepMemory(except: "1032");
regs.PC.ShouldBe((ushort)0x0004);
m.Cpu.Tacts.ShouldBe(23L);
}
/// <summary>
/// SRL (IY+D),E: 0xFD 0xCB 0x3B
/// </summary>
[TestMethod]
public void XSRL_E_WorksAsExpected()
{
// --- Arrange
const byte OFFS = 0x32;
var m = new Z80TestMachine(RunMode.OneInstruction);
m.InitCode(new byte[]
{
0xFD, 0xCB, OFFS, 0x3B // SRL (IY+32H),E
});
var regs = m.Cpu.Registers;
regs.IY = 0x1000;
regs.F |= FlagsSetMask.C;
m.Memory[regs.IY + OFFS] = 0x10;
// --- Act
m.Run();
// --- Assert
regs.E.ShouldBe(m.Memory[regs.IY + OFFS]);
regs.E.ShouldBe((byte)0x08);
regs.SFlag.ShouldBeFalse();
regs.ZFlag.ShouldBeFalse();
regs.CFlag.ShouldBeFalse();
regs.PFlag.ShouldBeFalse();
regs.HFlag.ShouldBeFalse();
regs.NFlag.ShouldBeFalse();
m.ShouldKeepRegisters(except: "F, E");
m.ShouldKeepMemory(except: "1032");
regs.PC.ShouldBe((ushort)0x0004);
m.Cpu.Tacts.ShouldBe(23L);
}
/// <summary>
/// SRL (IY+D),H: 0xFD 0xCB 0x3C
/// </summary>
[TestMethod]
public void XSRL_H_WorksAsExpected()
{
// --- Arrange
const byte OFFS = 0x32;
var m = new Z80TestMachine(RunMode.OneInstruction);
m.InitCode(new byte[]
{
0xFD, 0xCB, OFFS, 0x3C // SRL (IY+32H),H
});
var regs = m.Cpu.Registers;
regs.IY = 0x1000;
regs.F |= FlagsSetMask.C;
m.Memory[regs.IY + OFFS] = 0x10;
// --- Act
m.Run();
// --- Assert
regs.H.ShouldBe(m.Memory[regs.IY + OFFS]);
regs.H.ShouldBe((byte)0x08);
regs.SFlag.ShouldBeFalse();
regs.ZFlag.ShouldBeFalse();
regs.CFlag.ShouldBeFalse();
regs.PFlag.ShouldBeFalse();
regs.HFlag.ShouldBeFalse();
regs.NFlag.ShouldBeFalse();
m.ShouldKeepRegisters(except: "F, H");
m.ShouldKeepMemory(except: "1032");
regs.PC.ShouldBe((ushort)0x0004);
m.Cpu.Tacts.ShouldBe(23L);
}
/// <summary>
/// SRL (IY+D),L: 0xFD 0xCB 0x3D
/// </summary>
[TestMethod]
public void XSRL_L_WorksAsExpected()
{
// --- Arrange
const byte OFFS = 0x32;
var m = new Z80TestMachine(RunMode.OneInstruction);
m.InitCode(new byte[]
{
0xFD, 0xCB, OFFS, 0x3D // SRL (IY+32H),L
});
var regs = m.Cpu.Registers;
regs.IY = 0x1000;
regs.F |= FlagsSetMask.C;
m.Memory[regs.IY + OFFS] = 0x10;
// --- Act
m.Run();
// --- Assert
regs.L.ShouldBe(m.Memory[regs.IY + OFFS]);
regs.L.ShouldBe((byte)0x08);
regs.SFlag.ShouldBeFalse();
regs.ZFlag.ShouldBeFalse();
regs.CFlag.ShouldBeFalse();
regs.PFlag.ShouldBeFalse();
regs.HFlag.ShouldBeFalse();
regs.NFlag.ShouldBeFalse();
m.ShouldKeepRegisters(except: "F, L");
m.ShouldKeepMemory(except: "1032");
regs.PC.ShouldBe((ushort)0x0004);
m.Cpu.Tacts.ShouldBe(23L);
}
/// <summary>
/// SRL (IY+D): 0xFD 0xCB 0x3E
/// </summary>
[TestMethod]
public void XSRL_WorksAsExpected()
{
// --- Arrange
const byte OFFS = 0x32;
var m = new Z80TestMachine(RunMode.OneInstruction);
m.InitCode(new byte[]
{
0xFD, 0xCB, OFFS, 0x3E // SRL (IY+32H)
});
var regs = m.Cpu.Registers;
regs.IY = 0x1000;
regs.F |= FlagsSetMask.C;
m.Memory[regs.IY + OFFS] = 0x10;
// --- Act
m.Run();
// --- Assert
m.Memory[regs.IY + OFFS].ShouldBe((byte)0x08);
regs.SFlag.ShouldBeFalse();
regs.ZFlag.ShouldBeFalse();
regs.CFlag.ShouldBeFalse();
regs.PFlag.ShouldBeFalse();
regs.HFlag.ShouldBeFalse();
regs.NFlag.ShouldBeFalse();
m.ShouldKeepRegisters(except: "F, A");
m.ShouldKeepMemory(except: "1032");
regs.PC.ShouldBe((ushort)0x0004);
m.Cpu.Tacts.ShouldBe(23L);
}
/// <summary>
/// SRL (IY+D),A: 0xFD 0xCB 0x3F
/// </summary>
[TestMethod]
public void XSRL_A_WorksAsExpected()
{
// --- Arrange
const byte OFFS = 0x32;
var m = new Z80TestMachine(RunMode.OneInstruction);
m.InitCode(new byte[]
{
0xFD, 0xCB, OFFS, 0x3F // SRL (IY+32H),A
});
var regs = m.Cpu.Registers;
regs.IY = 0x1000;
regs.F |= FlagsSetMask.C;
m.Memory[regs.IY + OFFS] = 0x10;
// --- Act
m.Run();
// --- Assert
regs.A.ShouldBe(m.Memory[regs.IY + OFFS]);
regs.A.ShouldBe((byte)0x08);
regs.SFlag.ShouldBeFalse();
regs.ZFlag.ShouldBeFalse();
regs.CFlag.ShouldBeFalse();
regs.PFlag.ShouldBeFalse();
regs.HFlag.ShouldBeFalse();
regs.NFlag.ShouldBeFalse();
m.ShouldKeepRegisters(except: "F, A");
m.ShouldKeepMemory(except: "1032");
regs.PC.ShouldBe((ushort)0x0004);
m.Cpu.Tacts.ShouldBe(23L);
}
}
}
| |
using System;
using UIKit;
using System.Linq;
using System.Threading.Tasks;
using System.Collections.Generic;
using static zsquared.C_MessageBox;
using zsquared;
namespace vitavol
{
public partial class VC_AdminUser : UIViewController
{
C_Global Global;
C_VitaUser LoggedInUser;
C_VitaUser SelectedUser;
C_ItemPicker<E_Certification> CertificationPicker;
C_ItemPicker<E_VitaUserRoles> RolePicker;
public VC_AdminUser (IntPtr handle) : base (handle)
{
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
AppDelegate myAppDelegate = (AppDelegate)UIApplication.SharedApplication.Delegate;
Global = myAppDelegate.Global;
LoggedInUser = Global.GetUserFromCacheNoFetch(Global.LoggedInUserId);
SelectedUser = Global.SelectedUser ?? new C_VitaUser();
UITapGestureRecognizer labelTap = new UITapGestureRecognizer(() =>
{
C_Common.DropFirstResponder(View);
});
L_Title.UserInteractionEnabled = true;
L_Title.AddGestureRecognizer(labelTap);
B_Back.TouchUpInside += async (sender, e) =>
{
if (!GetDirty() || !ValidUser())
{
GoBack();
return;
}
E_MessageBoxResults mbres = await MessageBox(this,
"Changes made",
"Changes have been made. Save the changes?",
E_MessageBoxButtons.YesNoCancel);
if (mbres == E_MessageBoxResults.Cancel)
return;
if (mbres == E_MessageBoxResults.No)
{
GoBack();
return;
}
// (introduced after the push of 2.0)
if (!ValidUser())
{
E_MessageBoxResults mbres2 = await MessageBox(this,
"Error",
"Invalid user (must have name, email, and phone).",
E_MessageBoxButtons.Ok);
return;
}
// (introduced after the push of 2.0)
if (Global.SelectedUser == null)
{
C_VitaUser u = Global.GetUserFromCacheNoFetch(TB_Email.Text);
if (u != null)
{
E_MessageBoxResults mbres3 = await MessageBox(this,
"Error",
"That email is already in use.",
E_MessageBoxButtons.Ok);
return;
}
}
PullValuesFromForm();
AI_Busy.StartAnimating();
EnableUI(false);
await Task.Run(async () =>
{
C_JsonBuilder jb = null;
if (Global.SelectedUser != null)
jb = CapturePrivateFields();
bool ok = await SaveUser(jb);
async void p()
{
AI_Busy.StopAnimating();
EnableUI(true);
if (ok)
{
GoBack();
return;
}
E_MessageBoxResults mbres3 = await MessageBox(this,
"Error",
"Unable to update the user details.",
E_MessageBoxButtons.Ok);
}
UIApplication.SharedApplication.InvokeOnMainThread(p);
});
};
B_SitesCoordinated.TouchUpInside += (sender, e) =>
{
if (Global.SelectedUserTemp == null)
Global.SelectedUserTemp = SelectedUser;
PerformSegue("Segue_AdminUserToAdminUserSites", this);
};
B_Save.TouchUpInside += async (sender, e) =>
{
if (!ValidUser())
{
E_MessageBoxResults mbres = await MessageBox(this,
"Error",
"Invalid user (must have name, email, and phone).",
E_MessageBoxButtons.Ok);
return;
}
// (introduced after the push of 2.0)
if (Global.SelectedUser == null)
{
C_VitaUser u = Global.GetUserFromCacheNoFetch(TB_Email.Text);
if (u != null)
{
E_MessageBoxResults mbres = await MessageBox(this,
"Error",
"That email is already in use.",
E_MessageBoxButtons.Ok);
return;
}
}
PullValuesFromForm();
AI_Busy.StartAnimating();
EnableUI(false);
await Task.Run(async () =>
{
C_JsonBuilder jb = null;
if (Global.SelectedUser != null)
jb = CapturePrivateFields();
bool ok = await SaveUser(jb);
async void p()
{
AI_Busy.StopAnimating();
EnableUI(true);
if (ok)
{
GoBack();
return;
}
E_MessageBoxResults mbres = await MessageBox(this,
"Error",
"Unable to update the user details.",
E_MessageBoxButtons.Ok);
}
UIApplication.SharedApplication.InvokeOnMainThread(p);
});
};
TB_Name.AddTarget((sender, e) => { SelectedUser.Dirty = true; CheckEnableSaveButton(); }, UIControlEvent.AllEditingEvents);
TB_Email.AddTarget((sender, e) => { SelectedUser.Dirty = true; CheckEnableSaveButton(); }, UIControlEvent.AllEditingEvents);
TB_Phone.AddTarget((sender, e) => { SelectedUser.Dirty = true; CheckEnableSaveButton(); }, UIControlEvent.AllEditingEvents);
TB_Role.AddTarget((sender, e) =>
{
B_SitesCoordinated.Enabled = RolePicker.Selection == E_VitaUserRoles.SiteCoordinator;
SelectedUser.Dirty = true;
CheckEnableSaveButton();
}, UIControlEvent.AllEditingEvents);
TB_Cert.AddTarget((sender, e) => { SelectedUser.Dirty = true; CheckEnableSaveButton(); }, UIControlEvent.AllEditingEvents);
SW_Mobile.ValueChanged += (sender, e) => { SelectedUser.Dirty = true; };
TB_Password.AddTarget((sender, e) =>
{
SelectedUser.Dirty = true;
CheckEnableSaveButton();
if (Global.SelectedUser == null)
{
CheckEnableSaveButton();
B_Save.Enabled &= TB_Password.Text.Length > 5;
}
}, UIControlEvent.AllEditingEvents);
B_DeleteUser.TouchUpInside += async (sender, e) =>
{
if (!ValidUser() || (Global.SelectedUser == null))
{
GoBack();
return;
}
E_MessageBoxResults mbres = await MessageBox(this,
"Are you sure?",
"Do you really want to delete [" + SelectedUser.Name + "]? There is no undo.",
E_MessageBoxButtons.YesNo);
if (mbres == E_MessageBoxResults.No)
return;
AI_Busy.StartAnimating();
EnableUI(false);
await Task.Run(async () =>
{
C_IOResult ior = await Global.RemoveUser(SelectedUser.id, LoggedInUser.Token);
async void p()
{
AI_Busy.StopAnimating();
EnableUI(true);
if (!ior.Success)
{
E_MessageBoxResults mbresx = await MessageBox(this,
"Error",
"Unable to delete the user.",
E_MessageBoxButtons.Ok);
return;
}
GoBack();
}
UIApplication.SharedApplication.InvokeOnMainThread(p);
});
};
}
public override void ViewDidAppear(bool animated)
{
base.ViewDidAppear(animated);
C_Common.SetUIColors(View);
TB_Name.Text = SelectedUser.Name;
TB_Email.Text = SelectedUser.Email;
TB_Phone.Text = SelectedUser.Phone;
SW_Mobile.On = SelectedUser.HasMobile;
List<E_Certification> certifications = new List<E_Certification>
{
E_Certification.None,
E_Certification.Greeter,
E_Certification.Basic,
E_Certification.Advanced
};
CertificationPicker = new C_ItemPicker<E_Certification>(TB_Cert, certifications);
CertificationPicker.SetSelection(SelectedUser.Certification);
List<E_VitaUserRoles> roles = new List<E_VitaUserRoles>
{
E_VitaUserRoles.Volunteer,
E_VitaUserRoles.SiteCoordinator,
E_VitaUserRoles.Admin
};
RolePicker = new C_ItemPicker<E_VitaUserRoles>(TB_Role, roles);
if (SelectedUser.HasAdmin)
RolePicker.SetSelection(E_VitaUserRoles.Admin);
else if (SelectedUser.HasSiteCoordinator)
RolePicker.SetSelection(E_VitaUserRoles.SiteCoordinator);
else
RolePicker.SetSelection(E_VitaUserRoles.Volunteer);
EnableUI(true);
}
private void EnableUI(bool en)
{
C_Common.EnableUI(View, en);
CheckEnableSaveButton();
B_Save.Enabled &= en;
B_DeleteUser.Enabled = en && (LoggedInUser.id != SelectedUser.id);
B_SitesCoordinated.Enabled = en && SelectedUser.HasSiteCoordinator;
}
private void GoBack()
{
Global.SelectedUserTemp = null;
PerformSegue("Segue_AdminUserToAdminUsers", this);
}
private bool GetDirty()
{
bool nameDirty = (TB_Name.Text != SelectedUser.Name)
&& !string.IsNullOrWhiteSpace(TB_Name.Text) && !string.IsNullOrWhiteSpace(SelectedUser.Name);
bool emailDirty = TB_Email.Text != SelectedUser.Email
&& !string.IsNullOrWhiteSpace(TB_Email.Text) && !string.IsNullOrWhiteSpace(SelectedUser.Email);
bool phoneDirty = TB_Phone.Text != SelectedUser.Phone
&& !string.IsNullOrWhiteSpace(TB_Phone.Text) && !string.IsNullOrWhiteSpace(SelectedUser.Phone);
bool mobileDirty = SW_Mobile.On != SelectedUser.HasMobile;
bool certDirty = CertificationPicker.Selection != SelectedUser.Certification;
bool roleDirty = !SelectedUser.Roles.Contains(RolePicker.Selection);
bool sitesCoordinatedDirty = (Global.SelectedUserTemp != null) && Global.SelectedUserTemp.Dirty;
bool passwordChanged = !string.IsNullOrWhiteSpace(TB_Password.Text) || !string.IsNullOrWhiteSpace(TB_PasswordConfirm.Text);
//bool passwordOK = (TB_Password.Text == TB_PasswordConfirm.Text) && (TB_Password.Text.Length > 7);
return nameDirty || emailDirty || phoneDirty || mobileDirty || certDirty || roleDirty || sitesCoordinatedDirty || passwordChanged;
}
private void PullValuesFromForm()
{
SelectedUser.Name = TB_Name.Text;
SelectedUser.Email = TB_Email.Text;
SelectedUser.Password = TB_Password.Text;
SelectedUser.Phone = TB_Phone.Text;
SelectedUser.Roles = new List<E_VitaUserRoles>();
if (SW_Mobile.On)
SelectedUser.Roles.Add(E_VitaUserRoles.Mobile);
E_VitaUserRoles r = Tools.StringToEnum<E_VitaUserRoles>(TB_Role.Text);
SelectedUser.Roles.Add(r);
SelectedUser.Certification = CertificationPicker.Selection;
}
private void CheckEnableSaveButton()
{
bool nameok = TB_Name.Text.Length > 3;
bool emailok = Tools.EmailAddressIsValid(TB_Email.Text);
bool phoneok = TB_Phone.Text.Length > 10;
bool certok = TB_Cert.Text.Length > 0;
bool roleok = TB_Role.Text.Length > 0;
bool pwok = true;
if (!string.IsNullOrWhiteSpace(TB_Password.Text) || !string.IsNullOrWhiteSpace(TB_PasswordConfirm.Text))
pwok = (TB_Password.Text.Length > 7) && (TB_Password.Text == TB_PasswordConfirm.Text);
bool valuesOk = nameok && emailok && phoneok && certok && roleok && pwok;
bool sitesCoordinatedDirty = (Global.SelectedUserTemp != null) && Global.SelectedUserTemp.Dirty;
B_Save.Enabled = valuesOk || sitesCoordinatedDirty;
}
private bool ValidUser()
{
bool okName = !string.IsNullOrWhiteSpace(TB_Name.Text) && (TB_Name.Text.Length > 3);
bool okEmail = !string.IsNullOrWhiteSpace(TB_Email.Text) && Tools.EmailAddressIsValid(TB_Email.Text);
bool okPhone = !string.IsNullOrWhiteSpace(TB_Phone.Text) && (TB_Phone.Text.Length > 7);
return okName || okEmail || okPhone;
}
private C_JsonBuilder CapturePrivateFields()
{
C_JsonBuilder jb = SelectedUser.ToJsonAsJsonBuilder();
if (Global.SelectedUserTemp == null)
{
jb.StartArray(C_VitaUser.N_SitesCoordinated);
foreach (C_SiteCoordinated sc in SelectedUser.SitesCoordinated)
jb.AddArrayObject(sc.ToJson());
jb.EndArray();
}
else
{
jb.StartArray(C_VitaUser.N_SitesCoordinated);
foreach (C_SiteCoordinated sc in Global.SelectedUserTemp.SitesCoordinated)
jb.AddArrayObject(sc.ToJson());
jb.EndArray();
}
return jb;
}
private async Task<bool> SaveUser(C_JsonBuilder jb)
{
C_IOResult ior = null;
try
{
if (Global.SelectedUser == null)
{
// new user
if (Global.SelectedUserTemp != null)
{
SelectedUser.SitesCoordinated = Global.SelectedUserTemp.SitesCoordinated;
await AdjustSiteCoordinators();
}
ior = await Global.CreateUser(SelectedUser, LoggedInUser.Token);
}
else
{
await AdjustSiteCoordinators();
ior = await Global.UpdateUserFields(jb, SelectedUser, LoggedInUser.Token);
}
}
catch
{
ior = new C_IOResult();
ior.Success = false;
}
return (ior != null) && ior.Success;
}
private async Task<bool> AdjustSiteCoordinators()
{
foreach (C_VitaSite site in Global.SiteCache)
{
var ou = SelectedUser.SitesCoordinated.Where(sc => sc.SiteId == site.id);
if (ou.Any())
{
// make sure this user is listed in the site
var ou1 = site.SiteCoordinators.Where(sc => sc.UserId == SelectedUser.id);
if (!ou1.Any())
{
C_SiteCoordinator sc = new C_SiteCoordinator(SelectedUser);
site.SiteCoordinators.Add(sc);
await Global.UpdateSite(site, LoggedInUser.Token);
}
}
else
{
// make sure this user is not listed in the site
var ou1 = site.SiteCoordinators.Where(sc => sc.UserId == SelectedUser.id);
if (ou1.Any())
{
C_SiteCoordinator sc = ou1.First();
int ix = site.SiteCoordinators.IndexOf(sc);
site.SiteCoordinators.RemoveAt(ix);
await Global.UpdateSite(site, LoggedInUser.Token);
}
}
}
return true;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Common.Logging;
using Rhino.PersistentHashTable;
using Rhino.ServiceBus.DataStructures;
using Rhino.ServiceBus.Exceptions;
using Rhino.ServiceBus.Impl;
using Rhino.ServiceBus.Internal;
using Rhino.ServiceBus.MessageModules;
using Rhino.ServiceBus.Messages;
using Rhino.ServiceBus.Transport;
namespace Rhino.ServiceBus.RhinoQueues
{
public class PhtSubscriptionStorage : ISubscriptionStorage, IDisposable, IMessageModule
{
private const string SubscriptionsKey = "subscriptions";
private readonly Hashtable<string, List<WeakReference>> localInstanceSubscriptions =
new Hashtable<string, List<WeakReference>>();
private readonly ILog logger = LogManager.GetLogger(typeof (PhtSubscriptionStorage));
private readonly IMessageSerializer messageSerializer;
private PersistentHashTable.PersistentHashTable pht;
private readonly IReflection reflection;
private readonly MultiValueIndexHashtable<Guid, string, Uri, int> remoteInstanceSubscriptions =
new MultiValueIndexHashtable<Guid, string, Uri, int>();
private readonly Hashtable<TypeAndUriKey, IList<int>> subscriptionMessageIds =
new Hashtable<TypeAndUriKey, IList<int>>();
private readonly string subscriptionPath;
private readonly Hashtable<string, HashSet<Uri>> subscriptions = new Hashtable<string, HashSet<Uri>>();
private bool currentlyLoadingPersistentData;
public PhtSubscriptionStorage(
string subscriptionPath,
IMessageSerializer messageSerializer,
IReflection reflection)
{
this.subscriptionPath = subscriptionPath;
this.messageSerializer = messageSerializer;
this.reflection = reflection;
pht = new PersistentHashTable.PersistentHashTable(subscriptionPath);
}
#region IDisposable Members
public void Dispose()
{
if (pht != null)
{
pht.Dispose();
pht = null;
}
}
#endregion
#region IMessageModule Members
void IMessageModule.Init(ITransport transport, IServiceBus bus)
{
transport.AdministrativeMessageArrived += HandleAdministrativeMessage;
}
void IMessageModule.Stop(ITransport transport, IServiceBus bus)
{
transport.AdministrativeMessageArrived -= HandleAdministrativeMessage;
}
#endregion
#region ISubscriptionStorage Members
public void Initialize()
{
logger.DebugFormat("Initializing msmq subscription storage on: {0}", subscriptionPath);
pht.Initialize();
pht.Batch(actions =>
{
var items = actions.GetItems(new GetItemsRequest
{
Key = SubscriptionsKey
});
foreach (var item in items)
{
object[] msgs;
try
{
msgs = messageSerializer.Deserialize(new MemoryStream(item.Value));
}
catch (Exception e)
{
throw new SubscriptionException("Could not deserialize message from subscription queue", e);
}
try
{
currentlyLoadingPersistentData = true;
foreach (var msg in msgs)
{
HandleAdministrativeMessage(new CurrentMessageInformation
{
AllMessages = msgs,
Message = msg,
});
}
}
catch (Exception e)
{
throw new SubscriptionException("Failed to process subscription records", e);
}
finally
{
currentlyLoadingPersistentData = false;
}
}
actions.Commit();
});
}
public IEnumerable<Uri> GetSubscriptionsFor(Type type)
{
HashSet<Uri> subscriptionForType = null;
subscriptions.Read(reader => reader.TryGetValue(type.FullName, out subscriptionForType));
var subscriptionsFor = subscriptionForType ?? new HashSet<Uri>();
List<Uri> instanceSubscriptions;
remoteInstanceSubscriptions.TryGet(type.FullName, out instanceSubscriptions);
subscriptionsFor.UnionWith(instanceSubscriptions);
return subscriptionsFor;
}
public void RemoveLocalInstanceSubscription(IMessageConsumer consumer)
{
var messagesConsumes = reflection.GetMessagesConsumed(consumer);
var changed = false;
var list = new List<WeakReference>();
localInstanceSubscriptions.Write(writer =>
{
foreach (var type in messagesConsumes)
{
List<WeakReference> value;
if (writer.TryGetValue(type.FullName, out value) == false)
continue;
writer.Remove(type.FullName);
list.AddRange(value);
}
});
foreach (var reference in list)
{
if (ReferenceEquals(reference.Target, consumer))
continue;
changed = true;
}
if (changed)
RaiseSubscriptionChanged();
}
public object[] GetInstanceSubscriptions(Type type)
{
List<WeakReference> value = null;
localInstanceSubscriptions.Read(reader => reader.TryGetValue(type.FullName, out value));
if (value == null)
return new object[0];
var liveInstances = value
.Select(x => x.Target)
.Where(x => x != null)
.ToArray();
if (liveInstances.Length != value.Count) //cleanup
{
localInstanceSubscriptions.Write(writer => value.RemoveAll(x => x.IsAlive == false));
}
return liveInstances;
}
public event Action SubscriptionChanged;
public bool AddSubscription(string type, string endpoint)
{
var added = false;
subscriptions.Write(writer =>
{
HashSet<Uri> subscriptionsForType;
if (writer.TryGetValue(type, out subscriptionsForType) == false)
{
subscriptionsForType = new HashSet<Uri>();
writer.Add(type, subscriptionsForType);
}
var uri = new Uri(endpoint);
added = subscriptionsForType.Add(uri);
logger.InfoFormat("Added subscription for {0} on {1}",
type, uri);
});
RaiseSubscriptionChanged();
return added;
}
public void RemoveSubscription(string type, string endpoint)
{
var uri = new Uri(endpoint);
RemoveSubscriptionMessageFromPht(type, uri);
subscriptions.Write(writer =>
{
HashSet<Uri> subscriptionsForType;
if (writer.TryGetValue(type, out subscriptionsForType) == false)
{
subscriptionsForType = new HashSet<Uri>();
writer.Add(type, subscriptionsForType);
}
subscriptionsForType.Remove(uri);
logger.InfoFormat("Removed subscription for {0} on {1}",
type, endpoint);
});
RaiseSubscriptionChanged();
}
public void AddLocalInstanceSubscription(IMessageConsumer consumer)
{
localInstanceSubscriptions.Write(writer =>
{
foreach (var type in reflection.GetMessagesConsumed(consumer))
{
List<WeakReference> value;
if (writer.TryGetValue(type.FullName, out value) == false)
{
value = new List<WeakReference>();
writer.Add(type.FullName, value);
}
value.Add(new WeakReference(consumer));
}
});
RaiseSubscriptionChanged();
}
#endregion
private void AddMessageIdentifierForTracking(int messageId, string messageType, Uri uri)
{
subscriptionMessageIds.Write(writer =>
{
var key = new TypeAndUriKey {TypeName = messageType, Uri = uri};
IList<int> value;
if (writer.TryGetValue(key, out value) == false)
{
value = new List<int>();
writer.Add(key, value);
}
value.Add(messageId);
});
}
private void RemoveSubscriptionMessageFromPht(string type, Uri uri)
{
subscriptionMessageIds.Write(writer =>
{
var key = new TypeAndUriKey
{
TypeName = type,
Uri = uri
};
IList<int> messageIds;
if (writer.TryGetValue(key, out messageIds) == false)
return;
pht.Batch(actions =>
{
foreach (var msgId in messageIds)
{
actions.RemoveItem(new RemoveItemRequest
{
Id = msgId,
Key = SubscriptionsKey
});
}
actions.Commit();
});
writer.Remove(key);
});
}
public bool HandleAdministrativeMessage(CurrentMessageInformation msgInfo)
{
var addSubscription = msgInfo.Message as AddSubscription;
if (addSubscription != null)
{
return ConsumeAddSubscription(addSubscription);
}
var removeSubscription = msgInfo.Message as RemoveSubscription;
if (removeSubscription != null)
{
return ConsumeRemoveSubscription(removeSubscription);
}
var addInstanceSubscription = msgInfo.Message as AddInstanceSubscription;
if (addInstanceSubscription != null)
{
return ConsumeAddInstanceSubscription(addInstanceSubscription);
}
var removeInstanceSubscription = msgInfo.Message as RemoveInstanceSubscription;
if (removeInstanceSubscription != null)
{
return ConsumeRemoveInstanceSubscription(removeInstanceSubscription);
}
return false;
}
public bool ConsumeRemoveInstanceSubscription(RemoveInstanceSubscription subscription)
{
int msgId;
if (remoteInstanceSubscriptions.TryRemove(subscription.InstanceSubscriptionKey, out msgId))
{
pht.Batch(actions =>
{
actions.RemoveItem(new RemoveItemRequest
{
Id = msgId,
Key = SubscriptionsKey
});
actions.Commit();
});
RaiseSubscriptionChanged();
}
return true;
}
public bool ConsumeAddInstanceSubscription(
AddInstanceSubscription subscription)
{
pht.Batch(actions =>
{
var message = new MemoryStream();
messageSerializer.Serialize(new[] {subscription}, message);
var itemId = actions.AddItem(new AddItemRequest
{
Key = SubscriptionsKey,
Data = message.ToArray()
});
remoteInstanceSubscriptions.Add(
subscription.InstanceSubscriptionKey,
subscription.Type,
new Uri(subscription.Endpoint),
itemId);
actions.Commit();
});
RaiseSubscriptionChanged();
return true;
}
public bool ConsumeRemoveSubscription(RemoveSubscription removeSubscription)
{
RemoveSubscription(removeSubscription.Type, removeSubscription.Endpoint.Uri.ToString());
return true;
}
public bool ConsumeAddSubscription(AddSubscription addSubscription)
{
var newSubscription = AddSubscription(addSubscription.Type, addSubscription.Endpoint.Uri.ToString());
if (newSubscription && currentlyLoadingPersistentData == false)
{
var itemId = 0;
pht.Batch(actions =>
{
var stream = new MemoryStream();
messageSerializer.Serialize(new[] {addSubscription}, stream);
itemId = actions.AddItem(new AddItemRequest
{
Key = SubscriptionsKey,
Data = stream.ToArray()
});
actions.Commit();
});
AddMessageIdentifierForTracking(
itemId,
addSubscription.Type,
addSubscription.Endpoint.Uri);
return true;
}
return false;
}
private void RaiseSubscriptionChanged()
{
var copy = SubscriptionChanged;
if (copy != null)
copy();
}
}
}
| |
/********************************************************************
The Multiverse Platform is made available under the MIT License.
Copyright (c) 2012 The Multiverse Foundation
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify,
merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
OR OTHER DEALINGS IN THE SOFTWARE.
*********************************************************************/
/***************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
This code is licensed under the Visual Studio SDK license terms.
THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
***************************************************************************/
using System;
using System.Text;
// Unit test framework.
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.VsSDK.UnitTestLibrary;
// Namespaces to test.
using Microsoft.Samples.VisualStudio.IronPythonInterfaces;
using Microsoft.Samples.VisualStudio.IronPythonConsole;
namespace Microsoft.Samples.VisualStudio.IronPythonConsole.UnitTest
{
[TestClass]
public class CommandBufferTest
{
private class ExecuteException : Exception
{
}
private const string standardPrompt = ">>>";
private const string multiLinePrompt = "...";
private static string parseFunctionName = string.Format("{0}.{1}", typeof(IEngine).FullName, "ParseInteractiveInput");
private static void ExecuteToConsoleCallback(object sender, CallbackArgs args)
{
BaseMock mock = (BaseMock)sender;
mock["ExecutedCommand"] = args.GetParameter(0);
}
private static BaseMock CreateDefaultEngine()
{
// Create the mock.
BaseMock mockEngine = MockFactories.EngineFactory.GetInstance();
// Set the callback function for the ExecuteToConsole method of the engine.
mockEngine.AddMethodCallback(
string.Format("{0}.{1}", typeof(IEngine).FullName, "ExecuteToConsole"),
new EventHandler<CallbackArgs>(ExecuteToConsoleCallback));
return mockEngine;
}
// Verify that the command buffer handle as expected a null engine
// in the constructor.
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void CommandBufferNullEngine()
{
CommandBuffer buffer = new CommandBuffer(null);
}
[TestMethod]
public void CommandBufferConstructor()
{
// Build a command buffer with an engine without in, out and err streams.
BaseMock mockEngine = MockFactories.EngineFactory.GetInstance();
CommandBuffer buffer = new CommandBuffer(mockEngine as IEngine);
// Now set a not empty value for the out and err streams.
byte[] streamBuffer = new byte[256];
long usedBytes = 0;
using (System.IO.MemoryStream stream = new System.IO.MemoryStream(streamBuffer, true))
{
mockEngine.AddMethodReturnValues(
string.Format("{0}.{1}", typeof(IEngine).FullName, "get_StdOut"),
new object[] { (System.IO.Stream)stream });
buffer = new CommandBuffer(mockEngine as IEngine);
usedBytes = stream.Position;
}
// Verify that the prompt (and only the prompt) was written on the stream.
using (System.IO.MemoryStream stream = new System.IO.MemoryStream(streamBuffer, 0, (int)usedBytes))
{
using (System.IO.StreamReader reader = new System.IO.StreamReader(stream))
{
string streamText = reader.ReadToEnd();
Assert.AreEqual<string>(streamText, standardPrompt);
}
}
}
[TestMethod]
public void CommandBufferAddMultiLine()
{
BaseMock mockEngine = CreateDefaultEngine();
CommandBuffer buffer = new CommandBuffer(mockEngine as IEngine);
mockEngine.AddMethodReturnValues(parseFunctionName, new object[] { false });
string[] lines = new string[] {
"Line 1",
"Line 2",
"Line 3"
};
const string lastLine = "Last Line";
mockEngine.ResetFunctionCalls(string.Format("{0}.{1}", typeof(IEngine).FullName, "ExecuteToConsole"));
string expected = string.Empty;
foreach (string line in lines)
{
expected += line;
buffer.Add(line);
Assert.AreEqual<string>(expected, buffer.Text);
Assert.AreEqual<int>(0, mockEngine.FunctionCalls(string.Format("{0}.{1}", typeof(IEngine).FullName, "ExecuteToConsole")));
expected += System.Environment.NewLine;
}
// Now change the return value for ParseInteractiveInput so that the execute
// function of the engine is called.
mockEngine.AddMethodReturnValues(parseFunctionName, new object[] { true });
expected += lastLine;
buffer.Add(lastLine);
// Now the buffer should be cleared and the text should be passed to the engine.
Assert.IsTrue(string.IsNullOrEmpty(buffer.Text));
Assert.AreEqual<int>(1, mockEngine.FunctionCalls(string.Format("{0}.{1}", typeof(IEngine).FullName, "ExecuteToConsole")));
Assert.AreEqual<string>(expected, (string)mockEngine["ExecutedCommand"]);
}
[TestMethod]
public void CommandBufferAddNullLine()
{
BaseMock mockEngine = CreateDefaultEngine();
CommandBuffer buffer = new CommandBuffer(mockEngine as IEngine);
mockEngine.AddMethodReturnValues(parseFunctionName, new object[] { true });
mockEngine.ResetFunctionCalls(string.Format("{0}.{1}", typeof(IEngine).FullName, "ExecuteToConsole"));
buffer.Add(null);
Assert.AreEqual<int>(1, mockEngine.FunctionCalls(string.Format("{0}.{1}", typeof(IEngine).FullName, "ExecuteToConsole")));
Assert.IsTrue(string.IsNullOrEmpty((string)mockEngine["ExecutedCommand"]));
}
private static void ThrowingExecuteCallback(object sender, CallbackArgs args)
{
throw new ExecuteException();
}
[TestMethod]
public void CommandBufferAddWithThrowingExecute()
{
// Create the mock engine.
BaseMock mockEngine = MockFactories.EngineFactory.GetInstance();
// Set the callback function for the ExecuteToConsole method of the engine to the throwing one.
mockEngine.AddMethodCallback(
string.Format("{0}.{1}", typeof(IEngine).FullName, "ExecuteToConsole"),
new EventHandler<CallbackArgs>(ThrowingExecuteCallback));
// Make sure that the execute is called.
mockEngine.AddMethodReturnValues(parseFunctionName, new object[] { true });
CommandBuffer buffer = new CommandBuffer(mockEngine as IEngine);
bool exceptionThrown = false;
try
{
buffer.Add("Test Line");
}
catch (ExecuteException)
{
exceptionThrown = true;
}
Assert.IsTrue(exceptionThrown);
Assert.IsTrue(string.IsNullOrEmpty(buffer.Text));
}
[TestMethod]
public void CommandBufferOutput()
{
BaseMock mockEngine = CreateDefaultEngine();
// Make sure that the execute is called.
mockEngine.AddMethodReturnValues(parseFunctionName, new object[] { true });
string expected = standardPrompt + System.Environment.NewLine + standardPrompt;
// Now set a not empty value for the out and err streams.
byte[] streamBuffer = new byte[256];
long usedBytes = 0;
using (System.IO.MemoryStream stream = new System.IO.MemoryStream(streamBuffer, true))
{
// Set this stream as standard output for the mock engine.
mockEngine.AddMethodReturnValues(
string.Format("{0}.{1}", typeof(IEngine).FullName, "get_StdOut"),
new object[] { (System.IO.Stream)stream });
// Create the command buffer.
CommandBuffer buffer = new CommandBuffer(mockEngine as IEngine);
buffer.Add("Test");
usedBytes = stream.Position;
}
// Verify the content of the standard output.
using (System.IO.MemoryStream stream = new System.IO.MemoryStream(streamBuffer, 0, (int)usedBytes))
{
using (System.IO.StreamReader reader = new System.IO.StreamReader(stream))
{
string streamText = reader.ReadToEnd();
Assert.AreEqual<string>(streamText, expected);
}
}
// Redo the same with a multi-line command.
usedBytes = 0;
expected = standardPrompt + System.Environment.NewLine + multiLinePrompt + System.Environment.NewLine + standardPrompt;
using (System.IO.MemoryStream stream = new System.IO.MemoryStream(streamBuffer, true))
{
// Set this stream as standard output for the mock engine.
mockEngine.AddMethodReturnValues(
string.Format("{0}.{1}", typeof(IEngine).FullName, "get_StdOut"),
new object[] { (System.IO.Stream)stream });
// Create the command buffer.
CommandBuffer buffer = new CommandBuffer(mockEngine as IEngine);
// Force a multi-line execution.
mockEngine.AddMethodReturnValues(parseFunctionName, new object[] { false });
buffer.Add("Line 1");
// Now execute the command.
mockEngine.AddMethodReturnValues(parseFunctionName, new object[] { true });
buffer.Add("Line 2");
usedBytes = stream.Position;
}
// Verify the content of the standard output.
using (System.IO.MemoryStream stream = new System.IO.MemoryStream(streamBuffer, 0, (int)usedBytes))
{
using (System.IO.StreamReader reader = new System.IO.StreamReader(stream))
{
string streamText = reader.ReadToEnd();
Assert.AreEqual<string>(streamText, expected);
}
}
}
}
}
| |
#region CVS Log
/*
* Version:
* $Id: EncodedString.cs,v 1.9 2004/12/10 04:49:07 cwoodbury Exp $
*
* Revisions:
* $Log: EncodedString.cs,v $
* Revision 1.9 2004/12/10 04:49:07 cwoodbury
* Made changes to EncodedString and to how it is used to push it down to
* just being involved with frame I/O and not otherwise being used in frames.
*
* Revision 1.8 2004/11/20 23:09:05 cwoodbury
* Fixed bug #1067703: ISO-8859-1 not correctly implemented.
* Added default constructor.
*
* Revision 1.7 2004/11/19 18:38:47 cwoodbury
* Added code to catch and handle malformed data.
*
* Revision 1.6 2004/11/16 06:44:22 cwoodbury
* Refactored code.
*
* Revision 1.4 2004/11/10 06:51:56 cwoodbury
* Hid CVS log messages away in #region
*
* Revision 1.3 2004/11/10 06:31:14 cwoodbury
* Updated documentation.
*
* Revision 1.2 2004/11/10 04:44:16 cwoodbury
* Updated documentation.
*
* Revision 1.1 2004/11/03 01:18:26 cwoodbury
* Added to ID3Sharp
*
*/
#endregion
/*
* Author(s):
* Chris Woodbury
*
* Project Location:
* http://id3sharp.sourceforge.net
*
* License:
* Licensed under the Open Software License version 2.0
*/
using System;
using System.IO;
using System.Text;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using ID3Sharp.Models;
namespace ID3Sharp.IO
{
/// <summary>
/// A string encoded in any of a number of encodings.
/// </summary>
public class EncodedString
{
/// <summary>
/// A delegate that can be passed as a paramter to CreateStrings to retrieve
/// any bytes leftover after string creation.
/// </summary>
/// <param name="leftoverBytes">The bytes leftover from the point at which
/// CreateStrings was unable to parse any more strings from the data bytes given.</param>
public delegate void CreateStringsLeftoverBytes( byte[] leftoverBytes );
#region Static Encoding objects
/// <summary>A static UnicodeEncoding instance for
/// BOM-prefixed Unicode strings.</summary>
private static Encoding utf16Encoding = new UnicodeEncoding( false, true );
/// <summary>A static UnicodeEncoding instance for
/// Big-Endian Unicode strings.</summary>
private static Encoding utf16BEEncoding = new UnicodeEncoding( true, false );
/// <summary>A static UTF8Encoding instance.</summary>
private static Encoding utf8Encoding = new UTF8Encoding();
#endregion
#region Fields
/// <summary>The TextEncodingType of the string.</summary>
private TextEncodingType encodingType;
/// <summary>The string.</summary>
private string str;
/// <summary>A value indicating whether this string is terminated
/// when it is written.</summary>
private bool isTerminated;
/// <summary>A value indicating whether this string has the encoding
/// type prepending when it is written.</summary>
private bool hasEncodingTypePrepended;
#endregion
#region Constructors
/// <summary>
/// Creates a new empty EncodedString with the default text encoding.
/// </summary>
public EncodedString()
{
this.TextEncodingType = TextEncodingType.ISO_8859_1;
this.String = "";
}
public EncodedString( string str )
{
this.String = str;
}
/// <summary>
/// Creates a new EncodedString.
/// </summary>
/// <param name="encodingType">The type of encoding to use.</param>
/// <param name="str">The string from which to create the EncodedString.</param>
public EncodedString( TextEncodingType encodingType, string str )
{
this.TextEncodingType = encodingType;
this.String = str;
}
/// <summary>
/// Creates a new EncodedString.
/// </summary>
/// <param name="encodingType">The type of encoding to use.</param>
/// <param name="stringBytes">The byte array from which to create the EncodedString.</param>
public EncodedString( TextEncodingType encodingType, byte[] stringBytes )
{
this.encodingType = encodingType;
switch( encodingType )
{
case TextEncodingType.ISO_8859_1:
this.SetISO_8859_1Bytes( stringBytes );
break;
case TextEncodingType.UTF_16:
this.SetUTF_16Bytes( stringBytes );
break;
case TextEncodingType.UTF_16BE:
this.SetUTF_16BEBytes( stringBytes );
break;
case TextEncodingType.UTF_8:
this.SetUTF_8Bytes( stringBytes );
break;
}
}
#endregion
#region Factory methods
/// <summary>
/// Parses a byte array and creates and returns one or more strings
/// from the byte array. NULL bytes are interpreted as string terminators.
/// </summary>
/// <param name="stringDataWithEncoding">A byte-array string whose first byte
/// is a text encoding field.</param>
/// <returns>One or more strings created from the byte array.</returns>
public static ReadOnlyCollection<EncodedString>
CreateStrings( byte[] stringDataWithEncoding )
{
// .Length - 1: first byte of string is encoding, not string data
return CreateStrings( stringDataWithEncoding, stringDataWithEncoding.Length - 1, null );
}
/// <summary>
/// Parses a byte array and creates and returns one or more strings
/// from the byte array. NULL bytes are interpreted as string terminators.
/// </summary>
/// <param name="encType">The text encoding of the byte-array string.</param>
/// <param name="stringData">A byte-array string.</param>
/// <returns>One or more strings created from the byte array.</returns>
public static ReadOnlyCollection<EncodedString>
CreateStrings( TextEncodingType encType, byte[] stringData )
{
return CreateStrings( encType, stringData, stringData.Length, null );
}
/// <summary>
/// Parses a byte array and creates and returns one or more strings
/// from the byte array. NULL bytes are interpreted as string terminators.
/// Strings up to and including maxStrings are created and returned; the remainder
/// of the byte array (if any) is passed back using the CreateStringsLeftoverBytes
/// delegate.
/// </summary>
/// <param name="stringDataWithEncoding">A byte-array string whose first byte
/// is a text encoding field.</param>
/// <param name="maxStrings">The maximum number of strings to create.</param>
/// <param name="leftoversDelegate">A delegate to be used to pass back any bytes
/// left over from the string parsing.</param>
/// <returns>One or more strings created from the byte array.</returns>
public static ReadOnlyCollection<EncodedString> CreateStrings( byte[] stringDataWithEncoding,
int maxStrings, CreateStringsLeftoverBytes leftoversDelegate )
{
TextEncodingType encType = (TextEncodingType) stringDataWithEncoding[0];
byte[] textBytes = new byte[ stringDataWithEncoding.Length - 1 ];
Array.Copy( stringDataWithEncoding, 1, textBytes, 0, textBytes.Length );
ReadOnlyCollection<EncodedString> strings;
if ( textBytes.Length > 0 )
{
strings = CreateStrings( encType, textBytes, maxStrings, leftoversDelegate );
}
else
{
List<EncodedString> stringsList = new List<EncodedString>();
stringsList.Add( new EncodedString( encType, "" ) );
strings = new ReadOnlyCollection<EncodedString>( stringsList );
}
return strings;
}
/// <summary>
/// Parses a byte array and creates and returns one or more strings
/// from the byte array. NULL bytes are interpreted as string terminators.
/// Strings up to and including maxStrings are created and returned; the remainder
/// of the byte array (if any) is passed back using the CreateStringsLeftoverBytes
/// delegate.
/// </summary>
/// <param name="encType">The text encoding of the byte-array string.</param>
/// <param name="stringData">A byte-array string.</param>
/// <param name="maxStrings">The maximum number of strings to create.</param>
/// <param name="leftoversDelegate">A delegate to be used to pass back any bytes
/// left over from the string parsing.</param>
/// <returns>One or more strings created from the byte array.</returns>
public static ReadOnlyCollection<EncodedString> CreateStrings( TextEncodingType encType,
byte[] stringData, int maxStrings, CreateStringsLeftoverBytes leftoversDelegate )
{
List<EncodedString> strings = new List<EncodedString>();
List<int> nullIndices;
int incrementSize;
if ( encType == TextEncodingType.ISO_8859_1 ||
encType == TextEncodingType.UTF_8 )
{
nullIndices = FindSingleByteNulls( stringData, maxStrings );
incrementSize = 1;
}
else
{
nullIndices = FindDoubleByteNulls( stringData, maxStrings );
incrementSize = 2;
}
int start = 0;
foreach( int nullIndex in nullIndices )
{
strings.Add( CreateString( start, nullIndex, stringData, encType ) );
start = nullIndex + incrementSize;
}
if ( strings.Count < maxStrings )
{
// Make a string from the remaining bytes
strings.Add( CreateString( start, stringData.Length, stringData, encType ) );
}
else
{
// Add the remaining bytes to the end
byte[] remainingBytes = new byte[ stringData.Length - start ];
Array.Copy( stringData, start, remainingBytes, 0, remainingBytes.Length );
if ( leftoversDelegate != null )
{
leftoversDelegate( remainingBytes );
}
}
return new ReadOnlyCollection<EncodedString>( strings );
}
#endregion
#region Factory method helper methods
/// <summary>
/// Creates and returns a string from a portion of a byte array.
/// </summary>
/// <param name="startIndex">The index (in the byte array) at which to begin
/// creating the string.</param>
/// <param name="endIndex">The index (in the byte array) at which to finish
/// creating the string.</param>
/// <param name="stringData">The byte array from which to create the string.</param>
/// <param name="encType">The TextEncodingType of the byte array.</param>
/// <returns>A string from a portion of a byte array.</returns>
private static EncodedString CreateString(
int startIndex, int endIndex, byte[] stringData, TextEncodingType encType )
{
byte[] stringBytes = new byte[ endIndex - startIndex ];
Array.Copy( stringData, startIndex, stringBytes, 0, stringBytes.Length );
return new EncodedString( encType, stringBytes );
}
/// <summary>
/// Returns a sorted List<int> containing indices of NULL bytes in the
/// given byte array.
/// </summary>
/// <param name="data">The byte array to search.</param>
/// <param name="maxNulls">The maximum number of NULL bytes to find.</param>
/// <returns>A sorted List<int> containing indices of NULL bytes in the
/// given byte array.</returns>
private static List<int> FindSingleByteNulls( byte[] data, int maxNulls )
{
List<int> nulls = new List<int>();
for ( int dataItr = 0; dataItr < data.Length && nulls.Count < maxNulls; dataItr++ )
{
if ( data[ dataItr ] == 0x0 )
{
nulls.Add( dataItr );
}
}
return nulls;
}
/// <summary>
/// Returns a sorted List<int> containing indices of NULL byte-pairs in the
/// given byte array.
/// </summary>
/// <param name="data">The byte array to search.</param>
/// <param name="maxNulls">The maximum number of NULL bytes to find.</param>
/// <returns>A sorted List<int> containing indices of NULL byte-pairs in the
/// given byte array.</returns>
private static List<int> FindDoubleByteNulls( byte[] data, int maxNulls )
{
List<int> nulls = new List<int>();
for ( int dataItr = 0; dataItr < data.Length - 1 && nulls.Count < maxNulls; dataItr += 2 )
{
if ( data[ dataItr ] == 0x0 && data[ dataItr + 1 ] == 0x0 )
{
nulls.Add( dataItr );
}
}
return nulls;
}
#endregion
public static void CommonalizeEncoding( params EncodedString[] strings )
{
TextEncodingType commonType = TextEncodingType.ISO_8859_1;
foreach ( EncodedString encString in strings )
{
if ( (byte) encString.TextEncodingType > (byte) commonType )
{
commonType = encString.TextEncodingType;
}
}
foreach ( EncodedString encString in strings )
{
encString.TextEncodingType = commonType;
}
}
#region Properties
/// <summary>
/// Gets and sets the encoding of this string.
/// </summary>
public TextEncodingType TextEncodingType
{
get
{
return encodingType;
}
set
{
encodingType = value;
}
}
/// <summary>
/// Gets the length of the string (in bytes) according to the current encoding.
/// </summary>
public int Size
{
get
{
return this.ToBytes().Length;
}
}
/// <summary>
/// Gets and sets the String representation of the string.
/// </summary>
public string String
{
get
{
string returnValue = "";
switch( encodingType )
{
case TextEncodingType.ISO_8859_1:
returnValue = this.ToISO_8859_1String();
break;
case TextEncodingType.UTF_16:
returnValue = this.ToUTF_16String();
break;
case TextEncodingType.UTF_16BE:
returnValue = this.ToUTF_16BEString();
break;
case TextEncodingType.UTF_8:
returnValue = this.ToUTF_8String();
break;
}
return returnValue;
}
set
{
if ( value == null )
{
str = "";
}
else
{
str = value;
}
}
}
public bool IsTerminated
{
get { return isTerminated; }
set { isTerminated = value; }
}
public bool HasEncodingTypePrepended
{
get { return hasEncodingTypePrepended; }
set { hasEncodingTypePrepended = value; }
}
#endregion
#region Public Methods
/// <summary>
/// Gets the byte-array representation of the string.
/// </summary>
public byte[] ToBytes()
{
byte[] bytes = null;
switch ( encodingType )
{
case TextEncodingType.ISO_8859_1:
bytes = this.ToISO_8859_1Bytes();
break;
case TextEncodingType.UTF_16:
bytes = this.ToUTF_16Bytes();
break;
case TextEncodingType.UTF_16BE:
bytes = this.ToUTF_16BEBytes();
break;
case TextEncodingType.UTF_8:
bytes = this.ToUTF_8Bytes();
break;
}
return bytes;
}
#endregion
#region Conversions
/// <summary>
/// Gets the string as an ISO-8859-1-encoded byte array.
/// </summary>
private byte[] ToISO_8859_1Bytes()
{
int offset = 0;
if ( hasEncodingTypePrepended ) { offset = 1; }
byte[] stringBytes = PrepareBytes( TextEncodingType.ISO_8859_1 );
for ( int charItr = 0; charItr < str.Length; charItr++ )
{
stringBytes[ charItr + offset ] = (byte) str[ charItr ];
}
return stringBytes;
}
/// <summary>
/// Gets and sets the string as a UTF-16-encoded byte array.
/// </summary>
private byte[] ToUTF_16Bytes()
{
int offset = 0;
if ( hasEncodingTypePrepended ) { offset = 1; }
byte[] stringBytes = PrepareBytes( TextEncodingType.UTF_16 );
byte[] bom = utf16Encoding.GetPreamble();
Array.Copy( bom, 0, stringBytes, offset, bom.Length );
utf16Encoding.GetBytes( str, 0, str.Length, stringBytes, bom.Length + offset );
return stringBytes;
}
/// <summary>
/// Gets the string as a big-endian, UTF-16-encoded byte array.
/// </summary>
private byte[] ToUTF_16BEBytes()
{
int offset = 0;
if ( hasEncodingTypePrepended ) { offset = 1; }
byte[] stringBytes = PrepareBytes( TextEncodingType.UTF_16BE );
utf16BEEncoding.GetBytes( str, 0, str.Length, stringBytes, offset );
return stringBytes;
}
/// <summary>
/// Gets the string as a UTF-8-encoded byte array.
/// </summary>
private byte[] ToUTF_8Bytes()
{
int offset = 0;
if ( hasEncodingTypePrepended ) { offset = 1; }
byte[] stringBytes = PrepareBytes( TextEncodingType.UTF_8 );
utf8Encoding.GetBytes( str, 0, str.Length, stringBytes, offset );
return stringBytes;
}
/// <summary>
/// Prepares a byte array for an EncodedString in byte form by prepending
/// an encoding-type byte and adding termination, according to the settings.
/// </summary>
private byte[] PrepareBytes( TextEncodingType encType )
{
int encodingLength = 0;
int terminationLength = 0;
byte[] termination = this.GetTermination( encType );
if ( hasEncodingTypePrepended ) { encodingLength = 1; }
if ( isTerminated ) { terminationLength = termination.Length; }
int length = 0;
switch ( encType )
{
case TextEncodingType.ISO_8859_1:
length = str.Length;
break;
case TextEncodingType.UTF_16:
byte[] bom = utf16Encoding.GetPreamble();
length = utf16Encoding.GetByteCount( str ) + bom.Length;
break;
case TextEncodingType.UTF_16BE:
length = utf16BEEncoding.GetByteCount( str );
break;
case TextEncodingType.UTF_8:
length = utf8Encoding.GetByteCount( str );
break;
}
length += encodingLength + terminationLength;
byte[] stringBytes = new byte[ length ];
if ( hasEncodingTypePrepended )
{
stringBytes[ 0 ] = (byte) encType;
}
if ( isTerminated )
{
Array.Copy( termination, 0, stringBytes, length - terminationLength, terminationLength );
}
return stringBytes;
}
/// <summary>
/// Gets the string as an ISO-8859-1-encoded String.
/// </summary>
private string ToISO_8859_1String()
{
StringBuilder isoStringBuilder = new StringBuilder();
byte[] stringBytes =
GetStringDataOnly( this.ToISO_8859_1Bytes(), TextEncodingType.ISO_8859_1 );
foreach ( byte stringByte in stringBytes )
{
isoStringBuilder.Append( (char) stringByte );
}
return isoStringBuilder.ToString();
}
/// <summary>
/// Gets the string as a UTF-16-encoded String.
/// </summary>
private string ToUTF_16String()
{
return utf16Encoding.GetString(
GetStringDataOnly( ToUTF_16Bytes(), TextEncodingType.UTF_16 ) );
}
/// <summary>
/// Gets the string as a big-endian, UTF-16-encoded String.
/// </summary>
private string ToUTF_16BEString()
{
return utf16BEEncoding.GetString(
GetStringDataOnly( ToUTF_16BEBytes(), TextEncodingType.UTF_16BE ) );
}
/// <summary>
/// Gets the string as a UTF-8-encoded String.
/// </summary>
private string ToUTF_8String()
{
return utf8Encoding.GetString(
GetStringDataOnly( ToUTF_8Bytes(), TextEncodingType.UTF_8 ) );
}
/// <summary>
/// Removes a byte order mark (BOM), prepended text encoding type byte
/// and appended string termination, if present according to the
/// settings of this EncodedString.
/// </summary>
/// <returns>A byte array with only the character data.</returns>
private byte[] GetStringDataOnly( byte[] stringBytesWithExtras, TextEncodingType encType )
{
int startIndex = 0;
int endIndex = 0;
if ( hasEncodingTypePrepended ) { startIndex += 1; }
if ( encType == TextEncodingType.UTF_16 ) { startIndex += 2; }
if ( isTerminated ) { endIndex += this.GetTerminationLength( encType ); }
int totalExtraLength = startIndex + endIndex;
byte[] bytesWithoutExtras = new byte[ stringBytesWithExtras.Length - totalExtraLength ];
Array.Copy( stringBytesWithExtras, startIndex, bytesWithoutExtras, 0, bytesWithoutExtras.Length );
return bytesWithoutExtras;
}
/// <summary>
/// Sets the string as an ISO-8859-1-encoded byte array.
/// </summary>
private void SetISO_8859_1Bytes( byte[] value )
{
StringBuilder isoStringBuilder = new StringBuilder();
foreach ( byte stringByte in value )
{
isoStringBuilder.Append( (char) stringByte );
}
this.String = isoStringBuilder.ToString();
}
/// <summary>
/// Gets and sets the string as a UTF-16-encoded byte array.
/// </summary>
private void SetUTF_16Bytes( byte[] value )
{
if ( value.Length >= 2 )
{
byte[] valueBom = new byte[ 2 ];
valueBom[ 0 ] = value[ 0 ];
valueBom[ 1 ] = value[ 1 ];
byte[] littleEndianBom = ( new UnicodeEncoding( false, true ) ).GetPreamble();
if ( valueBom[ 0 ] == littleEndianBom[ 0 ] && valueBom[ 1 ] == littleEndianBom[ 1 ] )
{
this.String = utf16Encoding.GetString(
GetStringDataOnly( value, TextEncodingType.UTF_16 ) );
}
else if ( valueBom[ 1 ] == littleEndianBom[ 0 ] && valueBom[ 0 ] == littleEndianBom[ 1 ] )
{
this.String = ( new UnicodeEncoding( true, true ) ).GetString(
GetStringDataOnly( value, TextEncodingType.UTF_16 ) );
}
else
{
this.String = utf16Encoding.GetString( value );
}
}
else
{
this.String = "";
}
}
/// <summary>
/// Sets the string as a big-endian, UTF-16-encoded byte array.
/// </summary>
private void SetUTF_16BEBytes( byte[] value )
{
this.String = utf16BEEncoding.GetString( value );
}
/// <summary>
/// Sets the string as a UTF-8-encoded byte array.
/// </summary>
private void SetUTF_8Bytes( byte[] value )
{
this.String = utf8Encoding.GetString( value );
}
#endregion
#region Private Methods
/// <summary>
/// Gets the termination byte array under the given encoding.
/// </summary>
private byte[] GetTermination( TextEncodingType encType )
{
if ( encType == TextEncodingType.UTF_16 ||
encType == TextEncodingType.UTF_16BE )
{
return new byte[] { 0x00, 0x00 };
}
else
{
return new byte[] { 0x00 };
}
}
/// <summary>
/// Gets the length of the termination byte array under the given encoding.
/// </summary>
private int GetTerminationLength( TextEncodingType encType )
{
if ( encType == TextEncodingType.UTF_16 ||
encType == TextEncodingType.UTF_16BE )
{
return 2;
}
else
{
return 1;
}
}
#endregion
/// <summary>
/// Creates a deep copy of this object.
/// </summary>
/// <returns>A deep copy of this object.</returns>
public EncodedString Copy()
{
EncodedString copy = new EncodedString();
copy.str = this.str;
copy.encodingType = this.encodingType;
copy.isTerminated = this.isTerminated;
copy.hasEncodingTypePrepended = this.hasEncodingTypePrepended;
return copy;
}
/// <summary>
/// Writes the EncodedString to a stream.
/// </summary>
/// <param name="stream">The stream to write to.</param>
public void WriteToStream( Stream stream )
{
if ( stream == null )
{
throw new ArgumentNullException( "stream" );
}
stream.Write( this.ToBytes(), 0, this.Size );
}
public void Validate( ID3Versions version )
{
Exception innerException = null;
bool isV2_2 = (version & ID3Versions.V2_2) == ID3Versions.V2_2;
bool isV2_3 = (version & ID3Versions.V2_3) == ID3Versions.V2_3;
bool isUtf16be = encodingType == TextEncodingType.UTF_16BE;
bool isUtf8 = encodingType == TextEncodingType.UTF_8;
if ( ( isV2_2 || isV2_3 ) && ( isUtf16be || isUtf8 ) )
{
string message = String.Format( "Text encoding type not valid for " +
"given ID3 version.\nEncoding: {0}\nID3 version: {1}", encodingType, version );
innerException = new InvalidTextEncodingTypeException( message,
encodingType );
}
if ( innerException != null )
{
throw new IOValidationException( "Validation failed.", innerException );
}
}
}
}
| |
#pragma warning disable 169 // mcs: unused private method
[assembly: IronRuby.Runtime.RubyLibraryAttribute(typeof(IronRuby.Hpricot.HpricotLibraryInitializer))]
namespace IronRuby.Hpricot {
using System;
using Microsoft.Scripting.Utils;
public sealed class HpricotLibraryInitializer : IronRuby.Builtins.LibraryInitializer {
protected override void LoadModules() {
IronRuby.Builtins.RubyClass classRef0 = GetClass(typeof(System.Object));
IronRuby.Builtins.RubyClass classRef1 = GetClass(typeof(System.SystemException));
IronRuby.Builtins.RubyModule def1 = DefineGlobalModule("Hpricot", typeof(IronRuby.Hpricot.Hpricot), 0x00000008, null, LoadHpricot_Class, LoadHpricot_Constants, IronRuby.Builtins.RubyModule.EmptyArray);
IronRuby.Builtins.RubyClass def2 = DefineClass("Hpricot::BaseEle", typeof(IronRuby.Hpricot.BaseElement), 0x00000008, classRef0, LoadHpricot__BaseEle_Instance, null, null, IronRuby.Builtins.RubyModule.EmptyArray);
IronRuby.Builtins.RubyClass def6 = DefineClass("Hpricot::Doc", typeof(IronRuby.Hpricot.Document), 0x00000008, classRef0, LoadHpricot__Doc_Instance, null, null, IronRuby.Builtins.RubyModule.EmptyArray,
new Func<IronRuby.Builtins.RubyClass, IronRuby.Hpricot.Document>(IronRuby.Hpricot.Document.Allocator)
);
IronRuby.Builtins.RubyClass def10 = DefineClass("Hpricot::ParseError", typeof(IronRuby.Hpricot.ParserException), 0x00000008, classRef1, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray);
ExtendModule(typeof(IronRuby.Builtins.MutableString), 0x00000000, LoadIronRuby__Builtins__MutableString_Instance, null, null, IronRuby.Builtins.RubyModule.EmptyArray);
IronRuby.Builtins.RubyClass def4 = DefineClass("Hpricot::CData", typeof(IronRuby.Hpricot.CData), 0x00000008, def2, LoadHpricot__CData_Instance, null, null, IronRuby.Builtins.RubyModule.EmptyArray,
new Func<IronRuby.Builtins.RubyClass, IronRuby.Hpricot.CData>(IronRuby.Hpricot.CData.Allocator)
);
IronRuby.Builtins.RubyClass def5 = DefineClass("Hpricot::Comment", typeof(IronRuby.Hpricot.Comment), 0x00000008, def2, LoadHpricot__Comment_Instance, null, null, IronRuby.Builtins.RubyModule.EmptyArray,
new Func<IronRuby.Builtins.RubyClass, IronRuby.Hpricot.Comment>(IronRuby.Hpricot.Comment.Allocator)
);
IronRuby.Builtins.RubyClass def7 = DefineClass("Hpricot::DocType", typeof(IronRuby.Hpricot.DocumentType), 0x00000008, def2, LoadHpricot__DocType_Instance, null, null, IronRuby.Builtins.RubyModule.EmptyArray,
new Func<IronRuby.Builtins.RubyClass, IronRuby.Hpricot.DocumentType>(IronRuby.Hpricot.DocumentType.Allocator)
);
IronRuby.Builtins.RubyClass def8 = DefineClass("Hpricot::Elem", typeof(IronRuby.Hpricot.Element), 0x00000008, def2, LoadHpricot__Elem_Instance, null, null, IronRuby.Builtins.RubyModule.EmptyArray,
new Func<IronRuby.Builtins.RubyClass, IronRuby.Hpricot.Element>(IronRuby.Hpricot.Element.Allocator)
);
IronRuby.Builtins.RubyClass def9 = DefineClass("Hpricot::ETag", typeof(IronRuby.Hpricot.ETag), 0x00000008, def2, LoadHpricot__ETag_Instance, null, null, IronRuby.Builtins.RubyModule.EmptyArray,
new Func<IronRuby.Builtins.RubyClass, IronRuby.Hpricot.ETag>(IronRuby.Hpricot.ETag.Allocator)
);
IronRuby.Builtins.RubyClass def11 = DefineClass("Hpricot::ProcIns", typeof(IronRuby.Hpricot.ProcedureInstruction), 0x00000008, def2, LoadHpricot__ProcIns_Instance, null, null, IronRuby.Builtins.RubyModule.EmptyArray,
new Func<IronRuby.Builtins.RubyClass, IronRuby.Hpricot.ProcedureInstruction>(IronRuby.Hpricot.ProcedureInstruction.Allocator)
);
IronRuby.Builtins.RubyClass def12 = DefineClass("Hpricot::Text", typeof(IronRuby.Hpricot.Text), 0x00000008, def2, LoadHpricot__Text_Instance, null, null, IronRuby.Builtins.RubyModule.EmptyArray,
new Func<IronRuby.Builtins.RubyClass, IronRuby.Hpricot.Text>(IronRuby.Hpricot.Text.Allocator)
);
IronRuby.Builtins.RubyClass def13 = DefineClass("Hpricot::XMLDecl", typeof(IronRuby.Hpricot.XmlDeclaration), 0x00000008, def2, LoadHpricot__XMLDecl_Instance, null, null, IronRuby.Builtins.RubyModule.EmptyArray,
new Func<IronRuby.Builtins.RubyClass, IronRuby.Hpricot.XmlDeclaration>(IronRuby.Hpricot.XmlDeclaration.Allocator)
);
IronRuby.Builtins.RubyClass def3 = DefineClass("Hpricot::BogusETag", typeof(IronRuby.Hpricot.BogusETag), 0x00000008, def9, null, null, null, IronRuby.Builtins.RubyModule.EmptyArray,
new Func<IronRuby.Builtins.RubyClass, IronRuby.Hpricot.BogusETag>(IronRuby.Hpricot.BogusETag.Allocator)
);
SetConstant(def1, "BaseEle", def2);
SetConstant(def1, "Doc", def6);
SetConstant(def1, "ParseError", def10);
SetConstant(def1, "CData", def4);
SetConstant(def1, "Comment", def5);
SetConstant(def1, "DocType", def7);
SetConstant(def1, "Elem", def8);
SetConstant(def1, "ETag", def9);
SetConstant(def1, "ProcIns", def11);
SetConstant(def1, "Text", def12);
SetConstant(def1, "XMLDecl", def13);
SetConstant(def1, "BogusETag", def3);
}
private static void LoadHpricot_Constants(IronRuby.Builtins.RubyModule/*!*/ module) {
SetConstant(module, "ProcInsParse", IronRuby.Hpricot.Hpricot.ProcInsParse);
}
private static void LoadHpricot_Class(IronRuby.Builtins.RubyModule/*!*/ module) {
DefineLibraryMethod(module, "buffer_size", 0x21,
0x00000000U,
new Func<IronRuby.Builtins.RubyModule, System.Nullable<System.Int32>>(IronRuby.Hpricot.Hpricot.GetBufferSize)
);
DefineLibraryMethod(module, "buffer_size=", 0x21,
0x00000000U,
new Action<IronRuby.Builtins.RubyModule, System.Int32>(IronRuby.Hpricot.Hpricot.SetBufferSize)
);
DefineLibraryMethod(module, "css", 0x21,
0x00000000U,
new Func<IronRuby.Runtime.RubyContext, IronRuby.Runtime.BlockParam, IronRuby.Builtins.RubyModule, System.Object>(IronRuby.Hpricot.Hpricot.Css)
);
DefineLibraryMethod(module, "scan", 0x21,
0x00000000U,
new Func<IronRuby.Runtime.ConversionStorage<IronRuby.Builtins.MutableString>, IronRuby.Runtime.RespondToStorage, IronRuby.Runtime.BinaryOpStorage, IronRuby.Runtime.BlockParam, IronRuby.Builtins.RubyModule, System.Object, IronRuby.Builtins.Hash, System.Object>(IronRuby.Hpricot.Hpricot.Scan)
);
}
private static void LoadHpricot__BaseEle_Instance(IronRuby.Builtins.RubyModule/*!*/ module) {
DefineLibraryMethod(module, "parent", 0x11,
0x00000000U,
new Func<IronRuby.Hpricot.BaseElement, IronRuby.Hpricot.IHpricotDataContainer>(IronRuby.Hpricot.BaseElement.GetParent)
);
DefineLibraryMethod(module, "parent=", 0x11,
0x00000000U,
new Action<IronRuby.Hpricot.BaseElement, IronRuby.Hpricot.IHpricotDataContainer>(IronRuby.Hpricot.BaseElement.SetParent)
);
DefineLibraryMethod(module, "raw_string", 0x11,
0x00000000U,
new Func<IronRuby.Hpricot.BaseElement, IronRuby.Builtins.MutableString>(IronRuby.Hpricot.BaseElement.GetRawString)
);
}
private static void LoadHpricot__CData_Instance(IronRuby.Builtins.RubyModule/*!*/ module) {
DefineLibraryMethod(module, "content", 0x11,
0x00000000U,
new Func<IronRuby.Hpricot.CData, IronRuby.Builtins.MutableString>(IronRuby.Hpricot.CData.GetContent)
);
DefineLibraryMethod(module, "content=", 0x11,
0x00000000U,
new Action<IronRuby.Hpricot.CData, IronRuby.Builtins.MutableString>(IronRuby.Hpricot.CData.SetContent)
);
}
private static void LoadHpricot__Comment_Instance(IronRuby.Builtins.RubyModule/*!*/ module) {
DefineLibraryMethod(module, "content", 0x11,
0x00000000U,
new Func<IronRuby.Hpricot.Comment, IronRuby.Builtins.MutableString>(IronRuby.Hpricot.Comment.GetContent)
);
DefineLibraryMethod(module, "content=", 0x11,
0x00000000U,
new Action<IronRuby.Hpricot.Comment, IronRuby.Builtins.MutableString>(IronRuby.Hpricot.Comment.SetContent)
);
}
private static void LoadHpricot__Doc_Instance(IronRuby.Builtins.RubyModule/*!*/ module) {
DefineLibraryMethod(module, "children", 0x11,
0x00000000U,
new Func<IronRuby.Hpricot.Document, System.Collections.Generic.IList<Object>>(IronRuby.Hpricot.Document.GetChildren)
);
DefineLibraryMethod(module, "children=", 0x11,
0x00000000U,
new Action<IronRuby.Hpricot.Document, System.Collections.Generic.IList<Object>>(IronRuby.Hpricot.Document.SetChildren)
);
}
private static void LoadHpricot__DocType_Instance(IronRuby.Builtins.RubyModule/*!*/ module) {
DefineLibraryMethod(module, "public_id", 0x11,
0x00000000U,
new Func<IronRuby.Hpricot.DocumentType, System.Object>(IronRuby.Hpricot.DocumentType.GetPublicId)
);
DefineLibraryMethod(module, "public_id=", 0x11,
0x00000000U,
new Action<IronRuby.Runtime.RubyContext, IronRuby.Hpricot.DocumentType, System.Object>(IronRuby.Hpricot.DocumentType.SetPublicId)
);
DefineLibraryMethod(module, "system_id", 0x11,
0x00000000U,
new Func<IronRuby.Hpricot.DocumentType, System.Object>(IronRuby.Hpricot.DocumentType.GetSystemId)
);
DefineLibraryMethod(module, "system_id=", 0x11,
0x00000000U,
new Action<IronRuby.Runtime.RubyContext, IronRuby.Hpricot.DocumentType, System.Object>(IronRuby.Hpricot.DocumentType.SetSystemId)
);
DefineLibraryMethod(module, "target", 0x11,
0x00000000U,
new Func<IronRuby.Hpricot.DocumentType, IronRuby.Builtins.MutableString>(IronRuby.Hpricot.DocumentType.GetTarget)
);
DefineLibraryMethod(module, "target=", 0x11,
0x00000000U,
new Action<IronRuby.Hpricot.DocumentType, IronRuby.Builtins.MutableString>(IronRuby.Hpricot.DocumentType.SetTarget)
);
}
private static void LoadHpricot__Elem_Instance(IronRuby.Builtins.RubyModule/*!*/ module) {
DefineLibraryMethod(module, "children", 0x11,
0x00000000U,
new Func<IronRuby.Hpricot.Element, System.Collections.Generic.IList<Object>>(IronRuby.Hpricot.Element.GetChildren)
);
DefineLibraryMethod(module, "children=", 0x11,
0x00000000U,
new Action<IronRuby.Hpricot.Element, System.Collections.Generic.IList<Object>>(IronRuby.Hpricot.Element.SetChildren)
);
DefineLibraryMethod(module, "clear_raw", 0x11,
0x00000000U,
new Func<IronRuby.Hpricot.Element, System.Boolean>(IronRuby.Hpricot.Element.ClearRaw)
);
DefineLibraryMethod(module, "etag", 0x11,
0x00000000U,
new Func<IronRuby.Hpricot.Element, IronRuby.Hpricot.IHpricotDataContainer>(IronRuby.Hpricot.Element.GetEtag)
);
DefineLibraryMethod(module, "etag=", 0x11,
0x00000000U,
new Action<IronRuby.Hpricot.Element, IronRuby.Hpricot.IHpricotDataContainer>(IronRuby.Hpricot.Element.SetEtag)
);
DefineLibraryMethod(module, "name", 0x11,
0x00000000U,
new Func<IronRuby.Hpricot.Element, IronRuby.Builtins.MutableString>(IronRuby.Hpricot.Element.GetName)
);
DefineLibraryMethod(module, "name=", 0x11,
0x00000000U,
new Action<IronRuby.Hpricot.Element, IronRuby.Builtins.MutableString>(IronRuby.Hpricot.Element.SetName)
);
DefineLibraryMethod(module, "raw_attributes", 0x11,
0x00000000U,
new Func<IronRuby.Hpricot.Element, System.Object>(IronRuby.Hpricot.Element.GetRawAttributes)
);
DefineLibraryMethod(module, "raw_attributes=", 0x11,
0x00000000U,
new Action<IronRuby.Hpricot.Element, System.Object>(IronRuby.Hpricot.Element.SetRawAttributes)
);
DefineLibraryMethod(module, "raw_string", 0x11,
0x00000000U,
new Func<IronRuby.Hpricot.Element, IronRuby.Builtins.MutableString>(IronRuby.Hpricot.Element.GetRawString)
);
}
private static void LoadHpricot__ETag_Instance(IronRuby.Builtins.RubyModule/*!*/ module) {
DefineLibraryMethod(module, "clear_raw", 0x11,
0x00000000U,
new Func<IronRuby.Hpricot.ETag, System.Boolean>(IronRuby.Hpricot.ETag.ClearRaw)
);
DefineLibraryMethod(module, "name", 0x11,
0x00000000U,
new Func<IronRuby.Hpricot.ETag, IronRuby.Builtins.MutableString>(IronRuby.Hpricot.ETag.GetName)
);
DefineLibraryMethod(module, "name=", 0x11,
0x00000000U,
new Action<IronRuby.Hpricot.ETag, IronRuby.Builtins.MutableString>(IronRuby.Hpricot.ETag.SetName)
);
DefineLibraryMethod(module, "raw_string", 0x11,
0x00000000U,
new Func<IronRuby.Hpricot.ETag, IronRuby.Builtins.MutableString>(IronRuby.Hpricot.ETag.GetRawString)
);
}
private static void LoadHpricot__ProcIns_Instance(IronRuby.Builtins.RubyModule/*!*/ module) {
DefineLibraryMethod(module, "content", 0x11,
0x00000000U,
new Func<IronRuby.Hpricot.ProcedureInstruction, IronRuby.Builtins.MutableString>(IronRuby.Hpricot.ProcedureInstruction.GetContent)
);
DefineLibraryMethod(module, "content=", 0x11,
0x00000000U,
new Action<IronRuby.Hpricot.ProcedureInstruction, IronRuby.Builtins.MutableString>(IronRuby.Hpricot.ProcedureInstruction.SetContent)
);
DefineLibraryMethod(module, "target", 0x11,
0x00000000U,
new Func<IronRuby.Hpricot.ProcedureInstruction, IronRuby.Builtins.MutableString>(IronRuby.Hpricot.ProcedureInstruction.GetTarget)
);
DefineLibraryMethod(module, "target=", 0x11,
0x00000000U,
new Action<IronRuby.Hpricot.ProcedureInstruction, IronRuby.Builtins.MutableString>(IronRuby.Hpricot.ProcedureInstruction.SetTarget)
);
}
private static void LoadHpricot__Text_Instance(IronRuby.Builtins.RubyModule/*!*/ module) {
DefineLibraryMethod(module, "content", 0x11,
0x00000000U,
new Func<IronRuby.Hpricot.Text, IronRuby.Builtins.MutableString>(IronRuby.Hpricot.Text.GetContent)
);
DefineLibraryMethod(module, "content=", 0x11,
0x00000000U,
new Action<IronRuby.Hpricot.Text, IronRuby.Builtins.MutableString>(IronRuby.Hpricot.Text.SetContent)
);
}
private static void LoadHpricot__XMLDecl_Instance(IronRuby.Builtins.RubyModule/*!*/ module) {
DefineLibraryMethod(module, "encoding", 0x11,
0x00000000U,
new Func<IronRuby.Hpricot.XmlDeclaration, System.Object>(IronRuby.Hpricot.XmlDeclaration.GetEncoding)
);
DefineLibraryMethod(module, "encoding=", 0x11,
0x00000000U,
new Action<IronRuby.Runtime.RubyContext, IronRuby.Hpricot.XmlDeclaration, System.Object>(IronRuby.Hpricot.XmlDeclaration.SetEncoding)
);
DefineLibraryMethod(module, "standalone", 0x11,
0x00000000U,
new Func<IronRuby.Hpricot.XmlDeclaration, System.Object>(IronRuby.Hpricot.XmlDeclaration.GetStandalone)
);
DefineLibraryMethod(module, "standalone=", 0x11,
0x00000000U,
new Action<IronRuby.Runtime.RubyContext, IronRuby.Hpricot.XmlDeclaration, System.Object>(IronRuby.Hpricot.XmlDeclaration.SetStandalone)
);
DefineLibraryMethod(module, "version", 0x11,
0x00000000U,
new Func<IronRuby.Hpricot.XmlDeclaration, System.Object>(IronRuby.Hpricot.XmlDeclaration.GetVersion)
);
DefineLibraryMethod(module, "version=", 0x11,
0x00000000U,
new Action<IronRuby.Runtime.RubyContext, IronRuby.Hpricot.XmlDeclaration, System.Object>(IronRuby.Hpricot.XmlDeclaration.SetVersion)
);
}
private static void LoadIronRuby__Builtins__MutableString_Instance(IronRuby.Builtins.RubyModule/*!*/ module) {
DefineLibraryMethod(module, "fast_xs", 0x11,
0x00000000U,
new Func<IronRuby.Runtime.RubyContext, IronRuby.Builtins.MutableString, IronRuby.Builtins.MutableString>(IronRuby.Hpricot.FastXs.MutableStringOps.FastXs)
);
}
}
}
| |
#region License
//
// Copyright (c) 2007-2009, Sean Chambers <schambers80@gmail.com>
// Copyright (c) 2010, Nathan Brown
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System;
using System.Data;
using System.IO;
using FluentMigrator.Builders.Execute;
namespace FluentMigrator.Runner.Processors.SqlServer
{
public sealed class SqlServerProcessor : GenericProcessorBase
{
public override string DatabaseType
{
get { return "SqlServer"; }
}
public override bool SupportsTransactions
{
get
{
return true;
}
}
public SqlServerProcessor(IDbConnection connection, IMigrationGenerator generator, IAnnouncer announcer, IMigrationProcessorOptions options, IDbFactory factory)
: base(connection, factory, generator, announcer, options)
{
}
private static string SafeSchemaName(string schemaName)
{
return string.IsNullOrEmpty(schemaName) ? "dbo" : FormatSqlEscape(schemaName);
}
public override bool SchemaExists(string schemaName)
{
return Exists("SELECT * FROM sys.schemas WHERE NAME = '{0}'", SafeSchemaName(schemaName));
}
public override bool TableExists(string schemaName, string tableName)
{
try
{
return Exists("SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '{0}' AND TABLE_NAME = '{1}'", SafeSchemaName(schemaName), FormatSqlEscape(tableName));
}
catch (Exception e)
{
Console.WriteLine(e);
}
return false;
}
public override bool ColumnExists(string schemaName, string tableName, string columnName)
{
return Exists("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '{0}' AND TABLE_NAME = '{1}' AND COLUMN_NAME = '{2}'", SafeSchemaName(schemaName), FormatSqlEscape(tableName), FormatSqlEscape(columnName));
}
public override bool ConstraintExists(string schemaName, string tableName, string constraintName)
{
return Exists("SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE CONSTRAINT_CATALOG = DB_NAME() AND TABLE_SCHEMA = '{0}' AND TABLE_NAME = '{1}' AND CONSTRAINT_NAME = '{2}'", SafeSchemaName(schemaName), FormatSqlEscape(tableName), FormatSqlEscape(constraintName));
}
public override bool IndexExists(string schemaName, string tableName, string indexName)
{
return Exists("SELECT * FROM sys.indexes WHERE name = '{0}' and object_id=OBJECT_ID('{1}.{2}')", FormatSqlEscape(indexName), SafeSchemaName(schemaName), FormatSqlEscape(tableName));
}
public override bool SequenceExists(string schemaName, string sequenceName)
{
return Exists("SELECT * FROM INFORMATION_SCHEMA.SEQUENCES WHERE SEQUENCE_SCHEMA = '{0}' AND SEQUENCE_NAME = '{1}'", SafeSchemaName(schemaName), FormatSqlEscape(sequenceName));
}
public override void Execute(string template, params object[] args)
{
Process(String.Format(template, args));
}
public override bool Exists(string template, params object[] args)
{
EnsureConnectionIsOpen();
using (var command = Factory.CreateCommand(String.Format(template, args), Connection, Transaction))
using (var reader = command.ExecuteReader())
{
return reader.Read();
}
}
public override DataSet ReadTableData(string schemaName, string tableName)
{
return Read("SELECT * FROM [{0}].[{1}]", SafeSchemaName(schemaName), tableName);
}
public override DataSet Read(string template, params object[] args)
{
EnsureConnectionIsOpen();
var ds = new DataSet();
using (var command = Factory.CreateCommand(String.Format(template, args), Connection, Transaction))
{
var adapter = Factory.CreateDataAdapter(command);
adapter.Fill(ds);
return ds;
}
}
protected override void Process(string sql)
{
Announcer.Sql(sql);
if (Options.PreviewOnly || string.IsNullOrEmpty(sql))
return;
EnsureConnectionIsOpen();
if (sql.IndexOf("GO", StringComparison.OrdinalIgnoreCase) >= 0)
{
ExecuteBatchNonQuery(sql);
}
else
{
ExecuteNonQuery(sql);
}
}
private void ExecuteNonQuery(string sql)
{
using (var command = Factory.CreateCommand(sql, Connection, Transaction))
{
try
{
command.CommandTimeout = Options.Timeout;
command.ExecuteNonQuery();
}
catch (Exception ex)
{
using (var message = new StringWriter())
{
message.WriteLine("An error occured executing the following sql:");
message.WriteLine(sql);
message.WriteLine("The error was {0}", ex.Message);
throw new Exception(message.ToString(), ex);
}
}
}
}
private void ExecuteBatchNonQuery(string sql)
{
sql += "\nGO"; // make sure last batch is executed.
string sqlBatch = string.Empty;
using (var command = Factory.CreateCommand(string.Empty, Connection, Transaction))
{
try
{
foreach (string line in sql.Split(new[] { "\n", "\r" }, StringSplitOptions.RemoveEmptyEntries))
{
if (line.ToUpperInvariant().Trim() == "GO")
{
if (!string.IsNullOrEmpty(sqlBatch))
{
command.CommandText = sqlBatch;
command.CommandTimeout = Options.Timeout;
command.ExecuteNonQuery();
sqlBatch = string.Empty;
}
}
else
{
sqlBatch += line + "\n";
}
}
}
catch (Exception ex)
{
using (var message = new StringWriter())
{
message.WriteLine("An error occurred executing the following sql:");
message.WriteLine(sql);
message.WriteLine("The error was {0}", ex.Message);
throw new Exception(message.ToString(), ex);
}
}
}
}
public override void Process(PerformDBOperationExpression expression)
{
Announcer.Say("Performing DB Operation");
if (Options.PreviewOnly)
return;
EnsureConnectionIsOpen();
if (expression.Operation != null)
expression.Operation(Connection, Transaction);
}
private static string FormatSqlEscape(string sql)
{
return sql.Replace("'", "''");
}
}
}
| |
/***************************************************************************
* PipelineVariable.cs
*
* Copyright (C) 2006 Novell, Inc.
* Written by Aaron Bockover <aaron@abock.org>
****************************************************************************/
/* THIS FILE IS LICENSED UNDER THE MIT LICENSE AS OUTLINED IMMEDIATELY BELOW:
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Text;
using System.Xml;
using System.Collections;
using System.Collections.Generic;
namespace Banshee.MediaProfiles
{
public enum PipelineVariableControlType
{
Text,
Slider,
Combo,
Check
}
public class PipelineVariable
{
public struct PossibleValue
{
public string Value;
public string Display;
public string [] Enables;
public string [] Disables;
public PossibleValue(string value, string display)
{
Value = value;
Display = display;
Enables = null;
Disables = null;
}
public override string ToString()
{
return Display;
}
}
private PipelineVariableControlType control_type;
private string id;
private string name;
private string unit;
private string default_value;
private string current_value;
private string min_label;
private string max_label;
private double min_value;
private double max_value;
private double step_value;
private int step_precision;
private string [] enables = new string[0];
private string [] disables = new string[0];
private Dictionary<string, PossibleValue> possible_values = new Dictionary<string, PossibleValue>();
private List<string> possible_values_keys = new List<string>();
private bool advanced;
internal PipelineVariable(XmlNode node)
{
id = node.Attributes["id"].Value.Trim();
name = Banshee.Base.Localization.SelectSingleNode(node, "name").InnerText.Trim();
control_type = StringToControlType(node.SelectSingleNode("control-type").InnerText.Trim());
XmlAttribute enables_attr = node.Attributes["enables"];
if(enables_attr != null && enables_attr.Value != null) {
string [] vars = enables_attr.Value.Split(',');
if(vars != null && vars.Length > 0) {
enables = new string[vars.Length];
for(int i = 0; i < vars.Length; i++) {
enables[i] = vars[i].Trim();
}
}
}
XmlAttribute disables_attr = node.Attributes["disables"];
if(disables_attr != null && disables_attr.Value != null) {
string [] vars = disables_attr.Value.Split(',');
if(vars != null && vars.Length > 0) {
disables = new string[vars.Length];
for(int i = 0; i < vars.Length; i++) {
disables[i] = vars[i].Trim();
}
}
}
try {
XmlNode unit_node = node.SelectSingleNode("unit");
if(unit_node != null) {
unit = node.SelectSingleNode("unit").InnerText.Trim();
}
} catch {
}
try {
XmlNode advanced_node = node.SelectSingleNode("advanced");
if(advanced_node != null) {
advanced = ParseAdvanced(advanced_node.InnerText);
}
} catch {
}
default_value = ReadValue(node, "default-value");
min_value = ToDouble(ReadValue(node, "min-value"));
max_value = ToDouble(ReadValue(node, "max-value"));
min_label = ReadValue(node, "min-label", true);
max_label = ReadValue(node, "max-label", true);
string step_value_str = ReadValue(node, "step-value");
if(step_value_str != null) {
bool zeros = true;
step_precision = step_value_str.IndexOf(".") + 1;
for(int i = step_precision; i > 0 && i < step_value_str.Length; i++) {
if(step_value_str[i] != '0') {
zeros = false;
break;
}
}
step_precision = zeros ? 0 : step_value_str.Length - step_precision;
step_value = ToDouble(step_value_str);
}
if(default_value != null && default_value != String.Empty && (current_value == null ||
current_value == String.Empty)) {
current_value = default_value;
}
foreach(XmlNode possible_value_node in Banshee.Base.Localization.SelectNodes(node, "possible-values/value")) {
try {
string value = possible_value_node.Attributes["value"].Value.Trim();
string display = possible_value_node.InnerText.Trim();
PossibleValue possible_value = new PossibleValue(value, display);
XmlAttribute attr = possible_value_node.Attributes["enables"];
if(attr != null && attr.Value != null) {
string [] vars = attr.Value.Split(',');
if(vars != null && vars.Length > 0) {
possible_value.Enables = new string[vars.Length];
for(int i = 0; i < vars.Length; i++) {
possible_value.Enables[i] = vars[i].Trim();
}
}
}
attr = possible_value_node.Attributes["disables"];
if(attr != null && attr.Value != null) {
string [] vars = attr.Value.Split(',');
if(vars != null && vars.Length > 0) {
possible_value.Disables = new string[vars.Length];
for(int i = 0; i < vars.Length; i++) {
possible_value.Disables[i] = vars[i].Trim();
}
}
}
if(!possible_values.ContainsKey(value)) {
possible_values.Add(value, possible_value);
possible_values_keys.Add(value);
}
} catch {
}
}
}
private static string ReadValue(XmlNode node, string name)
{
return ReadValue(node, name, false);
}
private static string ReadValue(XmlNode node, string name, bool localize)
{
try {
XmlNode str_node = localize ?
Banshee.Base.Localization.SelectSingleNode(node, name) :
node.SelectSingleNode(name);
if(str_node == null) {
return null;
}
string str = str_node.InnerText.Trim();
return str == String.Empty ? null : str;
} catch {
}
return null;
}
private static double ToDouble(string str)
{
try {
return Convert.ToDouble(str, MediaProfileManager.CultureInfo);
} catch {
}
return 0.0;
}
private static PipelineVariableControlType StringToControlType(string str)
{
switch(str.ToLower()) {
case "combo": return PipelineVariableControlType.Combo;
case "slider": return PipelineVariableControlType.Slider;
case "check": return PipelineVariableControlType.Check;
case "text":
default:
return PipelineVariableControlType.Text;
}
}
internal static bool ParseAdvanced(string advanced)
{
if(advanced == null || advanced.Trim() == String.Empty) {
return true;
}
switch(advanced.Trim().ToLower()) {
case "true":
case "yes":
case "1":
case "advanced":
return true;
default:
return false;
}
}
public string Id {
get { return id; }
set { id = value; }
}
public string Name {
get { return name; }
set { name = value; }
}
public string Unit {
get { return unit; }
set { unit = value; }
}
public PipelineVariableControlType ControlType {
get { return control_type; }
set { control_type = value; }
}
public bool Advanced {
get { return advanced; }
set { advanced = value; }
}
public string DefaultValue {
get { return default_value; }
set { default_value = value; }
}
public string CurrentValue {
get { return current_value; }
set { current_value = value; }
}
public string MinLabel {
get { return min_label; }
set { min_label = value; }
}
public string MaxLabel {
get { return max_label; }
set { max_label = value; }
}
public int StepPrecision {
get { return step_precision; }
}
public string [] Enables {
get { return enables; }
}
public string [] Disables {
get { return disables; }
}
public double? DefaultValueNumeric {
get {
try {
return DefaultValue == null || DefaultValue == String.Empty ?
(double?)null :
Convert.ToDouble(DefaultValue, MediaProfileManager.CultureInfo);
} catch {
return null;
}
}
set { DefaultValue = Convert.ToString(value, MediaProfileManager.CultureInfo); }
}
public double? CurrentValueNumeric {
get {
try {
return CurrentValue == null || CurrentValue == String.Empty ?
(double?)null :
Convert.ToDouble(CurrentValue, MediaProfileManager.CultureInfo);
} catch {
return null;
}
}
set { CurrentValue = Convert.ToString(value, MediaProfileManager.CultureInfo); }
}
public double MinValue {
get { return min_value; }
set { min_value = value; }
}
public double MaxValue {
get { return max_value; }
set { max_value = value; }
}
public double StepValue {
get { return step_value; }
set { step_value = value; }
}
public IDictionary<string, PossibleValue> PossibleValues {
get { return possible_values; }
}
public ICollection<string> PossibleValuesKeys {
get { return possible_values_keys; }
}
public int PossibleValuesCount {
get { return possible_values.Count; }
}
public override string ToString()
{
StringBuilder builder = new StringBuilder();
builder.Append(String.Format("\tID = {0}\n", Id));
builder.Append(String.Format("\tName = {0}\n", Name));
builder.Append(String.Format("\tControl Type = {0}\n", ControlType));
builder.Append(String.Format("\tAdvanced = {0}\n", Advanced));
builder.Append(String.Format("\tDefault Value = {0}\n", DefaultValue));
builder.Append(String.Format("\tCurrent Value = {0}\n", CurrentValue));
builder.Append(String.Format("\tMin Value = {0}\n", MinValue));
builder.Append(String.Format("\tMax Value = {0}\n", MaxValue));
builder.Append(String.Format("\tStep Value = {0}\n", StepValue));
builder.Append(String.Format("\tPossible Values:\n"));
foreach(KeyValuePair<string, PossibleValue> value in PossibleValues) {
builder.Append(String.Format("\t\t{0} => {1}\n", value.Value, value.Key));
}
builder.Append("\n");
return builder.ToString();
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Analyzer.Utilities;
using Analyzer.Utilities.Extensions;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
namespace Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines
{
using static MicrosoftCodeQualityAnalyzersResources;
/// <summary>
/// CA1019: Define accessors for attribute arguments
///
/// Cause:
/// In its constructor, an attribute defines arguments that do not have corresponding properties.
/// </summary>
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class DefineAccessorsForAttributeArgumentsAnalyzer : DiagnosticAnalyzer
{
internal const string RuleId = "CA1019";
internal const string AddAccessorCase = "AddAccessor";
internal const string MakePublicCase = "MakePublic";
internal const string RemoveSetterCase = "RemoveSetter";
private static readonly LocalizableString s_localizableTitle = CreateLocalizableResourceString(nameof(DefineAccessorsForAttributeArgumentsTitle));
internal static readonly DiagnosticDescriptor DefaultRule = DiagnosticDescriptorHelper.Create(
RuleId,
s_localizableTitle,
CreateLocalizableResourceString(nameof(DefineAccessorsForAttributeArgumentsMessageDefault)),
DiagnosticCategory.Design,
RuleLevel.Disabled,
description: null,
isPortedFxCopRule: true,
isDataflowRule: false);
internal static readonly DiagnosticDescriptor IncreaseVisibilityRule = DiagnosticDescriptorHelper.Create(
RuleId,
s_localizableTitle,
CreateLocalizableResourceString(nameof(DefineAccessorsForAttributeArgumentsMessageIncreaseVisibility)),
DiagnosticCategory.Design,
RuleLevel.Disabled,
description: null,
isPortedFxCopRule: true,
isDataflowRule: false);
internal static readonly DiagnosticDescriptor RemoveSetterRule = DiagnosticDescriptorHelper.Create(
RuleId,
s_localizableTitle,
CreateLocalizableResourceString(nameof(DefineAccessorsForAttributeArgumentsMessageRemoveSetter)),
DiagnosticCategory.Design,
RuleLevel.Disabled,
description: null,
isPortedFxCopRule: true,
isDataflowRule: false);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = ImmutableArray.Create(DefaultRule, IncreaseVisibilityRule, RemoveSetterRule);
public override void Initialize(AnalysisContext context)
{
context.EnableConcurrentExecution();
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
context.RegisterCompilationStartAction(compilationContext =>
{
INamedTypeSymbol? attributeType = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemAttribute);
if (attributeType == null)
{
return;
}
compilationContext.RegisterSymbolAction(context =>
{
AnalyzeSymbol((INamedTypeSymbol)context.Symbol, attributeType, context.Compilation, context.ReportDiagnostic);
},
SymbolKind.NamedType);
});
}
private static void AnalyzeSymbol(INamedTypeSymbol symbol, INamedTypeSymbol attributeType, Compilation compilation, Action<Diagnostic> addDiagnostic)
{
if (symbol != null && symbol.GetBaseTypesAndThis().Contains(attributeType) && symbol.DeclaredAccessibility != Accessibility.Private)
{
IEnumerable<IParameterSymbol> parametersToCheck = GetAllPublicConstructorParameters(symbol);
if (parametersToCheck.Any())
{
IDictionary<string, IPropertySymbol> propertiesMap = GetAllPropertiesInTypeChain(symbol);
AnalyzeParameters(compilation, parametersToCheck, propertiesMap, symbol, addDiagnostic);
}
}
}
private static IEnumerable<IParameterSymbol> GetAllPublicConstructorParameters(INamedTypeSymbol attributeType)
{
// FxCop compatibility:
// Only examine parameters of public constructors. Can't use protected
// constructors to define an attribute so this rule only applies to
// public constructors.
IEnumerable<IMethodSymbol> instanceConstructorsToCheck = attributeType.InstanceConstructors.Where(c => c.DeclaredAccessibility == Accessibility.Public);
if (instanceConstructorsToCheck.Any())
{
var uniqueParamNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (IMethodSymbol constructor in instanceConstructorsToCheck)
{
foreach (IParameterSymbol parameter in constructor.Parameters)
{
if (uniqueParamNames.Add(parameter.Name))
{
yield return parameter;
}
}
}
}
}
private static IDictionary<string, IPropertySymbol> GetAllPropertiesInTypeChain(INamedTypeSymbol attributeType)
{
var propertiesMap = new Dictionary<string, IPropertySymbol>(StringComparer.OrdinalIgnoreCase);
foreach (INamedTypeSymbol currentType in attributeType.GetBaseTypesAndThis())
{
foreach (IPropertySymbol property in currentType.GetMembers().Where(m => m.Kind == SymbolKind.Property))
{
if (!propertiesMap.ContainsKey(property.Name))
{
propertiesMap.Add(property.Name, property);
}
}
}
return propertiesMap;
}
private static void AnalyzeParameters(Compilation compilation, IEnumerable<IParameterSymbol> parameters, IDictionary<string, IPropertySymbol> propertiesMap, INamedTypeSymbol attributeType, Action<Diagnostic> addDiagnostic)
{
foreach (IParameterSymbol parameter in parameters)
{
if (parameter.Type.Kind != SymbolKind.ErrorType)
{
if (!propertiesMap.TryGetValue(parameter.Name, out IPropertySymbol property) ||
!parameter.Type.IsAssignableTo(property.Type, compilation))
{
// Add a public read-only property accessor for positional argument '{0}' of attribute '{1}'.
addDiagnostic(GetDefaultDiagnostic(parameter, attributeType));
}
else
{
if (property.GetMethod == null)
{
// Add a public read-only property accessor for positional argument '{0}' of attribute '{1}'.
addDiagnostic(GetDefaultDiagnostic(parameter, attributeType));
}
else if (property.DeclaredAccessibility != Accessibility.Public ||
property.GetMethod.DeclaredAccessibility != Accessibility.Public)
{
if (!property.ContainingType.Equals(attributeType))
{
// A non-public getter exists in one of the base types.
// However, we cannot be sure if the user can modify the base type (it could be from a third party library).
// So generate the default diagnostic instead of increase visibility here.
// Add a public read-only property accessor for positional argument '{0}' of attribute '{1}'.
addDiagnostic(GetDefaultDiagnostic(parameter, attributeType));
}
else
{
// If '{0}' is the property accessor for positional argument '{1}', make it public.
addDiagnostic(GetIncreaseVisibilityDiagnostic(parameter, property));
}
}
if (property.SetMethod != null &&
property.SetMethod.DeclaredAccessibility == Accessibility.Public &&
Equals(property.ContainingType, attributeType))
{
// Remove the property setter from '{0}' or reduce its accessibility because it corresponds to positional argument '{1}'.
addDiagnostic(GetRemoveSetterDiagnostic(parameter, property));
}
}
}
}
}
private static Diagnostic GetDefaultDiagnostic(IParameterSymbol parameter, INamedTypeSymbol attributeType)
{
// Add a public read-only property accessor for positional argument '{0}' of attribute '{1}'.
return parameter.Locations.CreateDiagnostic(DefaultRule, new Dictionary<string, string?> { { "case", AddAccessorCase } }.ToImmutableDictionary(), parameter.Name, attributeType.Name);
}
private static Diagnostic GetIncreaseVisibilityDiagnostic(IParameterSymbol parameter, IPropertySymbol property)
{
// If '{0}' is the property accessor for positional argument '{1}', make it public.
return property.GetMethod.Locations.CreateDiagnostic(IncreaseVisibilityRule, new Dictionary<string, string?> { { "case", MakePublicCase } }.ToImmutableDictionary(), property.Name, parameter.Name);
}
private static Diagnostic GetRemoveSetterDiagnostic(IParameterSymbol parameter, IPropertySymbol property)
{
// Remove the property setter from '{0}' or reduce its accessibility because it corresponds to positional argument '{1}'.
return property.SetMethod.Locations.CreateDiagnostic(RemoveSetterRule, new Dictionary<string, string?> { { "case", RemoveSetterCase } }.ToImmutableDictionary(), property.Name, parameter.Name);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Net.Http.Headers;
using System.Text;
namespace System.Net.Http
{
public class HttpResponseMessage : IDisposable
{
private const HttpStatusCode defaultStatusCode = HttpStatusCode.OK;
private HttpStatusCode _statusCode;
private HttpResponseHeaders _headers;
private string _reasonPhrase;
private HttpRequestMessage _requestMessage;
private Version _version;
private HttpContent _content;
private bool _disposed;
public Version Version
{
get { return _version; }
set
{
#if !PHONE
if (value == null)
{
throw new ArgumentNullException("value");
}
#endif
CheckDisposed();
_version = value;
}
}
public HttpContent Content
{
get { return _content; }
set
{
CheckDisposed();
if (HttpEventSource.Log.IsEnabled())
{
if (value == null)
{
HttpEventSource.ContentNull(this);
}
else
{
HttpEventSource.Associate(this, value);
}
}
_content = value;
}
}
public HttpStatusCode StatusCode
{
get { return _statusCode; }
set
{
if (((int)value < 0) || ((int)value > 999))
{
throw new ArgumentOutOfRangeException("value");
}
CheckDisposed();
_statusCode = value;
}
}
public string ReasonPhrase
{
get
{
if (_reasonPhrase != null)
{
return _reasonPhrase;
}
// Provide a default if one was not set.
return HttpStatusDescription.Get(StatusCode);
}
set
{
if ((value != null) && ContainsNewLineCharacter(value))
{
throw new FormatException(SR.net_http_reasonphrase_format_error);
}
CheckDisposed();
_reasonPhrase = value; // It's OK to have a 'null' reason phrase.
}
}
public HttpResponseHeaders Headers
{
get
{
if (_headers == null)
{
_headers = new HttpResponseHeaders();
}
return _headers;
}
}
public HttpRequestMessage RequestMessage
{
get { return _requestMessage; }
set
{
CheckDisposed();
if (HttpEventSource.Log.IsEnabled() && (value != null)) HttpEventSource.Associate(this, value);
_requestMessage = value;
}
}
public bool IsSuccessStatusCode
{
get { return ((int)_statusCode >= 200) && ((int)_statusCode <= 299); }
}
public HttpResponseMessage()
: this(defaultStatusCode)
{
}
public HttpResponseMessage(HttpStatusCode statusCode)
{
if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(NetEventSource.ComponentType.Http, this, ".ctor", "StatusCode: " + (int)statusCode + ", ReasonPhrase: '" + _reasonPhrase + "'");
if (((int)statusCode < 0) || ((int)statusCode > 999))
{
throw new ArgumentOutOfRangeException("statusCode");
}
_statusCode = statusCode;
_version = HttpUtilities.DefaultResponseVersion;
if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(NetEventSource.ComponentType.Http, this, ".ctor", null);
}
public HttpResponseMessage EnsureSuccessStatusCode()
{
if (!IsSuccessStatusCode)
{
// Disposing the content should help users: If users call EnsureSuccessStatusCode(), an exception is
// thrown if the response status code is != 2xx. I.e. the behavior is similar to a failed request (e.g.
// connection failure). Users don't expect to dispose the content in this case: If an exception is
// thrown, the object is responsible fore cleaning up its state.
if (_content != null)
{
_content.Dispose();
}
throw new HttpRequestException(string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_message_not_success_statuscode, (int)_statusCode,
ReasonPhrase));
}
return this;
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append("StatusCode: ");
sb.Append((int)_statusCode);
sb.Append(", ReasonPhrase: '");
sb.Append(ReasonPhrase ?? "<null>");
sb.Append("', Version: ");
sb.Append(_version);
sb.Append(", Content: ");
sb.Append(_content == null ? "<null>" : _content.GetType().ToString());
sb.Append(", Headers:\r\n");
sb.Append(HeaderUtilities.DumpHeaders(_headers, _content == null ? null : _content.Headers));
return sb.ToString();
}
private bool ContainsNewLineCharacter(string value)
{
foreach (char character in value)
{
if ((character == HttpRuleParser.CR) || (character == HttpRuleParser.LF))
{
return true;
}
}
return false;
}
#region IDisposable Members
protected virtual void Dispose(bool disposing)
{
// The reason for this type to implement IDisposable is that it contains instances of types that implement
// IDisposable (content).
if (disposing && !_disposed)
{
_disposed = true;
if (_content != null)
{
_content.Dispose();
}
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
private void CheckDisposed()
{
if (_disposed)
{
throw new ObjectDisposedException(this.GetType().ToString());
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Data.Services.Client;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Runtime.Versioning;
namespace NuGet
{
public class DataServicePackageRepository : PackageRepositoryBase, IHttpClientEvents, ISearchableRepository, ICloneableRepository, ICultureAwareRepository
{
private IDataServiceContext _context;
private readonly IHttpClient _httpClient;
private readonly PackageDownloader _packageDownloader;
private CultureInfo _culture;
// Just forward calls to the package downloader
public event EventHandler<ProgressEventArgs> ProgressAvailable
{
add
{
_packageDownloader.ProgressAvailable += value;
}
remove
{
_packageDownloader.ProgressAvailable -= value;
}
}
public event EventHandler<WebRequestEventArgs> SendingRequest
{
add
{
_packageDownloader.SendingRequest += value;
_httpClient.SendingRequest += value;
}
remove
{
_packageDownloader.SendingRequest -= value;
_httpClient.SendingRequest -= value;
}
}
public PackageDownloader PackageDownloader
{
get { return _packageDownloader; }
}
public DataServicePackageRepository(Uri serviceRoot)
: this(new HttpClient(serviceRoot))
{
}
public DataServicePackageRepository(IHttpClient client)
: this(client, new PackageDownloader())
{
}
public DataServicePackageRepository(IHttpClient client, PackageDownloader packageDownloader)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
if (packageDownloader == null)
{
throw new ArgumentNullException("packageDownloader");
}
_httpClient = client;
_httpClient.AcceptCompression = true;
_packageDownloader = packageDownloader;
}
public CultureInfo Culture
{
get
{
if (_culture == null)
{
// TODO: Technically, if this is a remote server, we have to return the culture of the server
// instead of invariant culture. However, there is no trivial way to retrieve the server's culture,
// So temporarily use Invariant culture here.
_culture = _httpClient.Uri.IsLoopback ? CultureInfo.CurrentCulture : CultureInfo.InvariantCulture;
}
return _culture;
}
}
public override string Source
{
get
{
return _httpClient.Uri.OriginalString;
}
}
public override bool SupportsPrereleasePackages
{
get
{
return Context.SupportsProperty("IsAbsoluteLatestVersion");
}
}
// Don't initialize the Context at the constructor time so that
// we don't make a web request if we are not going to actually use it
// since getting the Uri property of the RedirectedHttpClient will
// trigger that functionality.
internal IDataServiceContext Context
{
private get
{
if (_context == null)
{
_context = new DataServiceContextWrapper(_httpClient.Uri);
_context.SendingRequest += OnSendingRequest;
_context.ReadingEntity += OnReadingEntity;
_context.IgnoreMissingProperties = true;
}
return _context;
}
set
{
_context = value;
}
}
private void OnReadingEntity(object sender, ReadingWritingEntityEventArgs e)
{
var package = (DataServicePackage)e.Entity;
// REVIEW: This is the only way (I know) to download the package on demand
// GetReadStreamUri cannot be evaluated inside of OnReadingEntity. Lazily evaluate it inside DownloadPackage
package.Context = Context;
package.Downloader = _packageDownloader;
}
private void OnSendingRequest(object sender, SendingRequestEventArgs e)
{
// Initialize the request
_httpClient.InitializeRequest(e.Request);
}
public override IQueryable<IPackage> GetPackages()
{
// REVIEW: Is it ok to assume that the package entity set is called packages?
return new SmartDataServiceQuery<DataServicePackage>(Context, Constants.PackageServiceEntitySetName).AsSafeQueryable();
}
[SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Justification = "OData expects a lower case value.")]
public IQueryable<IPackage> Search(string searchTerm, IEnumerable<string> targetFrameworks, bool allowPrereleaseVersions)
{
if (!Context.SupportsServiceMethod("Search"))
{
// If there's no search method then we can't filter by target framework
return GetPackages().Find(searchTerm);
}
// Convert the list of framework names into short names
var shortFrameworkNames = targetFrameworks.Select(name => new FrameworkName(name))
.Select(VersionUtility.GetShortFrameworkName);
// Create a '|' separated string of framework names
string targetFrameworkString = String.Join("|", shortFrameworkNames);
var searchParameters = new Dictionary<string, object> {
{ "searchTerm", "'" + Escape(searchTerm) + "'" },
{ "targetFramework", "'" + Escape(targetFrameworkString) + "'" },
};
if (SupportsPrereleasePackages)
{
searchParameters.Add("includePrerelease", allowPrereleaseVersions.ToString(CultureInfo.InvariantCulture).ToLowerInvariant());
}
// Create a query for the search service method
var query = Context.CreateQuery<DataServicePackage>("Search", searchParameters);
return new SmartDataServiceQuery<DataServicePackage>(Context, query).AsSafeQueryable();
}
public IPackageRepository Clone()
{
return new DataServicePackageRepository(_httpClient, _packageDownloader);
}
/// <summary>
/// Escapes single quotes in the value by replacing them with two single quotes.
/// </summary>
private static string Escape(string value)
{
// REVIEW: Couldn't find another way to do this with odata
if (!String.IsNullOrEmpty(value))
{
return value.Replace("'", "''");
}
return value;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
namespace Lucene.Net.Store
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using IOUtils = Lucene.Net.Util.IOUtils;
/// <summary>
/// A <see cref="Directory"/> is a flat list of files. Files may be written once, when they
/// are created. Once a file is created it may only be opened for read, or
/// deleted. Random access is permitted both when reading and writing.
/// <para/>
/// .NET's i/o APIs not used directly, but rather all i/o is
/// through this API. This permits things such as:
/// <list type="bullet">
/// <item><description> implementation of RAM-based indices;</description></item>
/// <item><description> implementation indices stored in a database;</description></item>
/// <item><description> implementation of an index as a single file;</description></item>
/// </list>
/// <para/>
/// Directory locking is implemented by an instance of
/// <see cref="Store.LockFactory"/>, and can be changed for each <see cref="Directory"/>
/// instance using <see cref="SetLockFactory"/>.
/// </summary>
public abstract class Directory : IDisposable // LUCENENET TODO: Subclass System.IO.FileSystemInfo ?
{
/// <summary>
/// Returns an array of strings, one for each file in the directory.
/// </summary>
/// <exception cref="DirectoryNotFoundException"> if the directory is not prepared for any
/// write operations (such as <see cref="CreateOutput(string, IOContext)"/>). </exception>
/// <exception cref="IOException"> in case of other IO errors </exception>
public abstract string[] ListAll();
/// <summary>
/// Returns <c>true</c> iff a file with the given name exists.
/// </summary>
[Obsolete("this method will be removed in 5.0")]
public abstract bool FileExists(string name);
/// <summary>
/// Removes an existing file in the directory. </summary>
public abstract void DeleteFile(string name);
/// <summary>
/// Returns the length of a file in the directory. this method follows the
/// following contract:
/// <list>
/// <item><description>Throws <see cref="FileNotFoundException"/>
/// if the file does not exist.</description></item>
/// <item><description>Returns a value >=0 if the file exists, which specifies its length.</description></item>
/// </list>
/// </summary>
/// <param name="name"> the name of the file for which to return the length. </param>
/// <exception cref="IOException"> if there was an IO error while retrieving the file's
/// length. </exception>
public abstract long FileLength(string name);
/// <summary>
/// Creates a new, empty file in the directory with the given name.
/// Returns a stream writing this file.
/// </summary>
public abstract IndexOutput CreateOutput(string name, IOContext context);
/// <summary>
/// Ensure that any writes to these files are moved to
/// stable storage. Lucene uses this to properly commit
/// changes to the index, to prevent a machine/OS crash
/// from corrupting the index.<br/>
/// <br/>
/// NOTE: Clients may call this method for same files over
/// and over again, so some impls might optimize for that.
/// For other impls the operation can be a noop, for various
/// reasons.
/// </summary>
public abstract void Sync(ICollection<string> names);
/// <summary>
/// Returns a stream reading an existing file, with the
/// specified read buffer size. The particular <see cref="Directory"/>
/// implementation may ignore the buffer size. Currently
/// the only <see cref="Directory"/> implementations that respect this
/// parameter are <see cref="FSDirectory"/> and
/// <see cref="CompoundFileDirectory"/>.
/// <para/>Throws <see cref="FileNotFoundException"/>
/// if the file does not exist.
/// </summary>
public abstract IndexInput OpenInput(string name, IOContext context);
/// <summary>
/// Returns a stream reading an existing file, computing checksum as it reads </summary>
public virtual ChecksumIndexInput OpenChecksumInput(string name, IOContext context)
{
return new BufferedChecksumIndexInput(OpenInput(name, context));
}
/// <summary>
/// Construct a <see cref="Lock"/>. </summary>
/// <param name="name"> the name of the lock file </param>
public abstract Lock MakeLock(string name);
/// <summary>
/// Attempt to clear (forcefully unlock and remove) the
/// specified lock. Only call this at a time when you are
/// certain this lock is no longer in use. </summary>
/// <param name="name"> name of the lock to be cleared. </param>
public abstract void ClearLock(string name);
/// <summary>
/// Disposes the store. </summary>
// LUCENENET specific - implementing proper dispose pattern
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Disposes the store. </summary>
protected abstract void Dispose(bool disposing);
/// <summary>
/// Set the <see cref="Store.LockFactory"/> that this <see cref="Directory"/> instance should
/// use for its locking implementation. Each * instance of
/// <see cref="Store.LockFactory"/> should only be used for one directory (ie,
/// do not share a single instance across multiple
/// Directories).
/// </summary>
/// <param name="lockFactory"> instance of <see cref="Store.LockFactory"/>. </param>
public abstract void SetLockFactory(LockFactory lockFactory);
/// <summary>
/// Get the <see cref="Store.LockFactory"/> that this <see cref="Directory"/> instance is
/// using for its locking implementation. Note that this
/// may be null for <see cref="Directory"/> implementations that provide
/// their own locking implementation.
/// </summary>
public abstract LockFactory LockFactory { get; }
/// <summary>
/// Return a string identifier that uniquely differentiates
/// this <see cref="Directory"/> instance from other <see cref="Directory"/> instances.
/// This ID should be the same if two <see cref="Directory"/> instances
/// (even in different AppDomains and/or on different machines)
/// are considered "the same index". This is how locking
/// "scopes" to the right index.
/// </summary>
public virtual string GetLockID()
{
return this.ToString();
}
public override string ToString()
{
return this.GetType().Name + '@' + GetHashCode().ToString("x") + " lockFactory=" + LockFactory;
}
/// <summary>
/// Copies the file <paramref name="src"/> to <seealso cref="Directory"/> <paramref name="to"/> under the new
/// file name <paramref name="dest"/>.
/// <para/>
/// If you want to copy the entire source directory to the destination one, you
/// can do so like this:
///
/// <code>
/// Directory to; // the directory to copy to
/// foreach (string file in dir.ListAll()) {
/// dir.Copy(to, file, newFile, IOContext.DEFAULT); // newFile can be either file, or a new name
/// }
/// </code>
/// <para/>
/// <b>NOTE:</b> this method does not check whether <paramref name="dest"/> exist and will
/// overwrite it if it does.
/// </summary>
public virtual void Copy(Directory to, string src, string dest, IOContext context)
{
IndexOutput os = null;
IndexInput @is = null;
IOException priorException = null;
try
{
os = to.CreateOutput(dest, context);
@is = OpenInput(src, context);
os.CopyBytes(@is, @is.Length);
}
catch (IOException ioe)
{
priorException = ioe;
}
finally
{
bool success = false;
try
{
IOUtils.DisposeWhileHandlingException(priorException, os, @is);
success = true;
}
finally
{
if (!success)
{
try
{
to.DeleteFile(dest);
}
catch (Exception)
{
}
}
}
}
}
/// <summary>
/// Creates an <see cref="IndexInputSlicer"/> for the given file name.
/// <see cref="IndexInputSlicer"/> allows other <see cref="Directory"/> implementations to
/// efficiently open one or more sliced <see cref="IndexInput"/> instances from a
/// single file handle. The underlying file handle is kept open until the
/// <see cref="IndexInputSlicer"/> is closed.
/// <para/>Throws <see cref="FileNotFoundException"/>
/// if the file does not exist.
/// <para/>
/// @lucene.internal
/// @lucene.experimental
/// </summary>
/// <exception cref="IOException">
/// if an <seealso cref="IOException"/> occurs</exception>
public virtual IndexInputSlicer CreateSlicer(string name, IOContext context)
{
EnsureOpen();
return new IndexInputSlicerAnonymousInnerClassHelper(this, name, context);
}
private class IndexInputSlicerAnonymousInnerClassHelper : IndexInputSlicer
{
private readonly Directory outerInstance;
private string name;
private IOContext context;
public IndexInputSlicerAnonymousInnerClassHelper(Directory outerInstance, string name, IOContext context)
{
this.outerInstance = outerInstance;
this.name = name;
this.context = context;
@base = outerInstance.OpenInput(name, context);
}
private readonly IndexInput @base;
public override IndexInput OpenSlice(string sliceDescription, long offset, long length)
{
return new SlicedIndexInput("SlicedIndexInput(" + sliceDescription + " in " + @base + ")", @base, offset, length);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
@base.Dispose();
}
}
[Obsolete("Only for reading CFS files from 3.x indexes.")]
public override IndexInput OpenFullSlice()
{
return (IndexInput)@base.Clone();
}
}
/// <exception cref="ObjectDisposedException"> if this Directory is closed </exception>
protected internal virtual void EnsureOpen()
{
}
/// <summary>
/// Allows to create one or more sliced <see cref="IndexInput"/> instances from a single
/// file handle. Some <see cref="Directory"/> implementations may be able to efficiently map slices of a file
/// into memory when only certain parts of a file are required.
/// <para/>
/// @lucene.internal
/// @lucene.experimental
/// </summary>
public abstract class IndexInputSlicer : IDisposable
{
/// <summary>
/// Returns an <see cref="IndexInput"/> slice starting at the given offset with the given length.
/// </summary>
public abstract IndexInput OpenSlice(string sliceDescription, long offset, long length);
/// <summary>
/// Returns an <see cref="IndexInput"/> slice starting at offset <c>0</c> with a
/// length equal to the length of the underlying file </summary>
[Obsolete("Only for reading CFS files from 3.x indexes.")]
public abstract IndexInput OpenFullSlice(); // can we remove this somehow?
protected abstract void Dispose(bool disposing);
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
/// <summary>
/// Implementation of an <see cref="IndexInput"/> that reads from a portion of
/// a file.
/// </summary>
private sealed class SlicedIndexInput : BufferedIndexInput
{
private IndexInput @base;
private long fileOffset;
private long length;
internal SlicedIndexInput(string sliceDescription, IndexInput @base, long fileOffset, long length)
: this(sliceDescription, @base, fileOffset, length, BufferedIndexInput.BUFFER_SIZE)
{
}
internal SlicedIndexInput(string sliceDescription, IndexInput @base, long fileOffset, long length, int readBufferSize)
: base("SlicedIndexInput(" + sliceDescription + " in " + @base + " slice=" + fileOffset + ":" + (fileOffset + length) + ")", readBufferSize)
{
this.@base = (IndexInput)@base.Clone();
this.fileOffset = fileOffset;
this.length = length;
}
public override object Clone()
{
SlicedIndexInput clone = (SlicedIndexInput)base.Clone();
clone.@base = (IndexInput)@base.Clone();
clone.fileOffset = fileOffset;
clone.length = length;
return clone;
}
/// <summary>
/// Expert: implements buffer refill. Reads bytes from the current
/// position in the input. </summary>
/// <param name="b"> the array to read bytes into </param>
/// <param name="offset"> the offset in the array to start storing bytes </param>
/// <param name="len"> the number of bytes to read </param>
protected override void ReadInternal(byte[] b, int offset, int len)
{
long start = GetFilePointer();
if (start + len > length)
{
throw new Exception("read past EOF: " + this);
}
@base.Seek(fileOffset + start);
@base.ReadBytes(b, offset, len, false);
}
/// <summary>
/// Expert: implements seek. Sets current position in this file, where
/// the next <see cref="ReadInternal(byte[], int, int)"/> will occur.
/// </summary>
/// <seealso cref="ReadInternal(byte[], int, int)"/>
protected override void SeekInternal(long pos)
{
}
/// <summary>
/// Closes the stream to further operations.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing)
{
@base.Dispose();
}
}
public override long Length => length;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
namespace Hydra.Framework.Queues.State
{
//
//**************************************************************************
// Interface: Notifier
//**************************************************************************
//
public class Notifier
: INotifier,
IDisposable
{
#region Private Member Variables
private INotifier m_Delegator;
private uint m_UpdateCount = 0;
private bool m_IsDisposed = false;
private List<INotifiable> m_Callbacks = new List<INotifiable>();
private List<INotifier> m_Surrogates = new List<INotifier>();
#endregion
#region Constructors
//
//**********************************************************************
/// <summary>
/// Initializes a new instance of the <see cref="T:Notifier"/> class.
/// </summary>
/// <param name="Delegator">The delegator.</param>
//**********************************************************************
//
public Notifier(INotifier Delegator)
{
m_Delegator = Delegator;
}
//
//**********************************************************************
/// <summary>
/// Initializes a new instance of the <see cref="T:Notifier"/> class.
/// </summary>
//**********************************************************************
//
public Notifier()
{
m_Delegator = this;
}
#endregion
#region IDisposable Implementation
//
//**********************************************************************
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
//**********************************************************************
//
public virtual void Dispose()
{
if (!m_IsDisposed)
{
//
// Generate some debug info and fail if the observers haven't
// disconnected
//
if (m_Callbacks.Count != 0)
{
string ObserverName;
string ThisName = "";
IEnumerator ObserverIter = m_Callbacks.GetEnumerator();
while (ObserverIter.MoveNext())
{
try
{
ObserverName = ((IName)ObserverIter.Current).Name;
}
catch (InvalidCastException)
{
ObserverName = "An unnamed Observer";
}
try
{
ThisName = ((IName)this).Name;
}
catch (InvalidCastException)
{
ThisName = "an unnamed Notifier";
}
Debug.WriteLine("Warning - Disposing and list not empty" + ObserverName + " is still connected to " + ThisName);
}
Debug.Fail("Observer list not empty");
}
m_IsDisposed = true;
}
GC.SuppressFinalize(this);
}
#endregion
#region INotifier Implementation
//
//**********************************************************************
/// <summary>
/// Connects the specified observer.
/// </summary>
/// <param name="Observer">The observer.</param>
//**********************************************************************
//
public void Connect(INotifiable Observer)
{
lock (((ICollection)m_Callbacks).SyncRoot)
{
m_Callbacks.Add(Observer);
}
}
//
//**********************************************************************
/// <summary>
/// Disconnects the specified observer.
/// </summary>
/// <param name="Observer">The observer.</param>
//**********************************************************************
//
public void Disconnect(INotifiable Observer)
{
Debug.Assert(Observer != null);
lock (((ICollection)m_Callbacks).SyncRoot)
{
m_Callbacks.Remove(Observer);
}
}
//
//**********************************************************************
/// <summary>
/// Begins the update.
/// </summary>
//**********************************************************************
//
public void BeginUpdate()
{
lock (((ICollection)m_Callbacks).SyncRoot)
{
++m_UpdateCount;
}
}
//
//**********************************************************************
/// <summary>
/// Ends the update.
/// </summary>
//**********************************************************************
//
public void EndUpdate()
{
lock (((ICollection)m_Callbacks).SyncRoot)
{
if (m_UpdateCount == 0)
{
Trace.WriteLine("Notifier_c.EndUpdate (m_UpdateCount == 0)!");
} // End if
else
{
--m_UpdateCount;
}
}
//
// NOTE: There is a hole here. It is possible for another thread
// return IsLocked = false before we have performed the notifications
// In most cases this is the desired behaviour - we want to be seen
// as unlocked if we are able to Notify
//
if (m_UpdateCount == 0)
{
//
// Lock the surrogates list and notify on behalf of each
// of them; then empty the list
//
lock (((ICollection)m_Callbacks).SyncRoot)
{
foreach (INotifier Item in m_Surrogates)
{
try
{
DoNotifyObservers(Item);
}
catch
{
m_Surrogates.Remove(Item);
}
}
m_Surrogates.Clear();
}
}
}
//
//**********************************************************************
/// <summary>
/// Determines whether this instance is locked.
/// </summary>
/// <returns>
/// <c>true</c> if this instance is locked; otherwise, <c>false</c>.
/// </returns>
//**********************************************************************
//
public bool IsLocked()
{
return (m_UpdateCount > 0);
}
//
//**********************************************************************
/// <summary>
/// Call the call back to notify our parent of a change
/// masquerading as another object that the parent is not
/// connected to.
/// </summary>
/// <param name="Substitute">The substitute.</param>
//**********************************************************************
//
public void Notify(INotifier Substitute)
{
//
// Only perform the notification if the number of begin update calls
// is zero. If non zero record the fact that Notify was called so
// we can decide if to notify when EndUpdate is called.
//
if (m_UpdateCount > 0)
{
//
// We keep track of who has notified us while we were locked -
// but store only one copy of each notifier
//
lock (((ICollection)m_Callbacks).SyncRoot)
{
if (!m_Surrogates.Contains(Substitute))
{
m_Surrogates.Add(Substitute);
}
}
}
else
{
try
{
DoNotifyObservers(Substitute);
}
catch
{
m_Surrogates.Remove(Substitute);
}
}
}
//
//**********************************************************************
/// <summary>
/// Notifies this instance.
/// </summary>
//**********************************************************************
//
public void Notify()
{
Notify(m_Delegator);
}
//
//**********************************************************************
/// <summary>
/// Gets the num observers.
/// </summary>
/// <returns></returns>
//**********************************************************************
//
public int GetNumObservers()
{
lock (((ICollection)m_Callbacks).SyncRoot)
{
return m_Callbacks.Count;
}
}
#endregion
#region Private Methods
//
//**********************************************************************
/// <summary>
/// Actually notify the observers
/// </summary>
/// <param name="Substitute">The substitute.</param>
//**********************************************************************
//
private void DoNotifyObservers(INotifier Substitute)
{
//
// Note - this critical section only has an effect if it is a different
// thread that is doing the disconnecting. Otherwise, we rely on
// saving an iterator to the item that we are calling Update on.
//
lock (((ICollection)m_Callbacks).SyncRoot)
{
//
// Take a copy of the callbacks list so that we can safely iterate
// through the callbacks, even if the notifiable object disconnects
// from this notifier object in the OnNotify method. Without this
// the foreach statement could fail.
//
INotifiable[] CallbacksCopy = new INotifiable[m_Callbacks.Count];
m_Callbacks.CopyTo(CallbacksCopy);
foreach (INotifiable Item in CallbacksCopy)
{
try
{
Item.OnNotify(Substitute);
}
catch (Exception Ex)
{
//
// the callback failed for some reason. Likely that the Observer is no
// longer there.
//
System.Diagnostics.Trace.WriteLine("DoNotifyObservers has " + "failed to run OnNotify (likely that observer has quit " + "without disconnecting).");
System.Diagnostics.Trace.WriteLine("--Exception message says: " + Ex.Message);
//
// Remove this observer from the callbacks list
//
if (m_Callbacks.Remove(Item))
{
System.Diagnostics.Trace.WriteLine("DoNotifyObservers has *successfully* removed a dead Observer.");
}
else
{
System.Diagnostics.Trace.WriteLine("DoNotifyObservers has *FAILED* to remove a dead observer ");
}
}
}
}
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Immutable;
using System.Threading;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.Completion.Providers;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Completion.Providers
{
internal partial class OverrideCompletionProvider : AbstractOverrideCompletionProvider
{
public OverrideCompletionProvider()
{
}
protected override SyntaxNode GetSyntax(SyntaxToken token)
{
return token.GetAncestor<EventFieldDeclarationSyntax>()
?? token.GetAncestor<EventDeclarationSyntax>()
?? token.GetAncestor<PropertyDeclarationSyntax>()
?? token.GetAncestor<IndexerDeclarationSyntax>()
?? (SyntaxNode)token.GetAncestor<MethodDeclarationSyntax>();
}
internal override bool IsInsertionTrigger(SourceText text, int characterPosition, OptionSet options)
{
return CompletionUtilities.IsTriggerAfterSpaceOrStartOfWordCharacter(text, characterPosition, options);
}
protected override SyntaxToken GetToken(CompletionItem completionItem, SyntaxTree tree, CancellationToken cancellationToken)
{
var tokenSpanEnd = MemberInsertionCompletionItem.GetTokenSpanEnd(completionItem);
return tree.FindTokenOnLeftOfPosition(tokenSpanEnd, cancellationToken);
}
public override bool TryDetermineReturnType(SyntaxToken startToken, SemanticModel semanticModel, CancellationToken cancellationToken, out ITypeSymbol returnType, out SyntaxToken nextToken)
{
nextToken = startToken;
returnType = null;
if (startToken.Parent is TypeSyntax typeSyntax)
{
// 'partial' is actually an identifier. If we see it just bail. This does mean
// we won't handle overrides that actually return a type called 'partial'. And
// not a single tear was shed.
if (typeSyntax is IdentifierNameSyntax &&
((IdentifierNameSyntax)typeSyntax).Identifier.IsKindOrHasMatchingText(SyntaxKind.PartialKeyword))
{
return false;
}
returnType = semanticModel.GetTypeInfo(typeSyntax, cancellationToken).Type;
nextToken = typeSyntax.GetFirstToken().GetPreviousToken();
}
return true;
}
public override bool TryDetermineModifiers(SyntaxToken startToken, SourceText text, int startLine, out Accessibility seenAccessibility,
out DeclarationModifiers modifiers)
{
var token = startToken;
modifiers = new DeclarationModifiers();
seenAccessibility = Accessibility.NotApplicable;
var overrideToken = default(SyntaxToken);
bool isUnsafe = false;
bool isSealed = false;
bool isAbstract = false;
while (IsOnStartLine(token.SpanStart, text, startLine) && !token.IsKind(SyntaxKind.None))
{
switch (token.Kind())
{
case SyntaxKind.UnsafeKeyword:
isUnsafe = true;
break;
case SyntaxKind.OverrideKeyword:
overrideToken = token;
break;
case SyntaxKind.SealedKeyword:
isSealed = true;
break;
case SyntaxKind.AbstractKeyword:
isAbstract = true;
break;
case SyntaxKind.ExternKeyword:
break;
// Filter on the most recently typed accessibility; keep the first one we see
case SyntaxKind.PublicKeyword:
if (seenAccessibility == Accessibility.NotApplicable)
{
seenAccessibility = Accessibility.Public;
}
break;
case SyntaxKind.InternalKeyword:
if (seenAccessibility == Accessibility.NotApplicable)
{
seenAccessibility = Accessibility.Internal;
}
// If we see internal AND protected, filter for protected internal
if (seenAccessibility == Accessibility.Protected)
{
seenAccessibility = Accessibility.ProtectedOrInternal;
}
break;
case SyntaxKind.ProtectedKeyword:
if (seenAccessibility == Accessibility.NotApplicable)
{
seenAccessibility = Accessibility.Protected;
}
// If we see protected AND internal, filter for protected internal
if (seenAccessibility == Accessibility.Internal)
{
seenAccessibility = Accessibility.ProtectedOrInternal;
}
break;
default:
// Anything else and we bail.
return false;
}
var previousToken = token.GetPreviousToken();
// We want only want to consume modifiers
if (previousToken.IsKind(SyntaxKind.None) || !IsOnStartLine(previousToken.SpanStart, text, startLine))
{
break;
}
token = previousToken;
}
startToken = token;
modifiers = new DeclarationModifiers(isUnsafe: isUnsafe, isAbstract: isAbstract, isOverride: true, isSealed: isSealed);
return overrideToken.IsKind(SyntaxKind.OverrideKeyword) && IsOnStartLine(overrideToken.Parent.SpanStart, text, startLine);
}
public override SyntaxToken FindStartingToken(SyntaxTree tree, int position, CancellationToken cancellationToken)
{
var token = tree.FindTokenOnLeftOfPosition(position, cancellationToken);
return token.GetPreviousTokenIfTouchingWord(position);
}
public override ImmutableArray<ISymbol> FilterOverrides(ImmutableArray<ISymbol> members, ITypeSymbol returnType)
{
var filteredMembers = members.WhereAsArray(m =>
SymbolEquivalenceComparer.Instance.Equals(GetReturnType(m), returnType));
// Don't filter by return type if we would then have nothing to show.
// This way, the user gets completion even if they speculatively typed the wrong return type
return filteredMembers.Length > 0 ? filteredMembers : members;
}
protected override int GetTargetCaretPosition(SyntaxNode caretTarget)
{
// Inserted Event declarations are a single line, so move to the end of the line.
if (caretTarget is EventFieldDeclarationSyntax)
{
return caretTarget.GetLocation().SourceSpan.End;
}
else if (caretTarget is MethodDeclarationSyntax methodDeclaration)
{
// abstract override blah(); : move to the end of the line
if (methodDeclaration.Body == null)
{
return methodDeclaration.GetLocation().SourceSpan.End;
}
else
{
// move to the end of the last statement in the method
var lastStatement = methodDeclaration.Body.Statements.Last();
return lastStatement.GetLocation().SourceSpan.End;
}
}
else if (caretTarget is BasePropertyDeclarationSyntax propertyDeclaration)
{
// property: no accessors; move to the end of the declaration
if (propertyDeclaration.AccessorList != null && propertyDeclaration.AccessorList.Accessors.Any())
{
// move to the end of the last statement of the first accessor
var firstAccessor = propertyDeclaration.AccessorList.Accessors[0];
var firstAccessorStatement = (SyntaxNode)firstAccessor.Body?.Statements.LastOrDefault() ??
firstAccessor.ExpressionBody.Expression;
return firstAccessorStatement.GetLocation().SourceSpan.End;
}
else
{
return propertyDeclaration.GetLocation().SourceSpan.End;
}
}
else
{
throw ExceptionUtilities.Unreachable;
}
}
}
}
| |
namespace System.Text
{
public class UnicodeEncoding : Encoding
{
private bool bigEndian;
private bool byteOrderMark;
private bool throwOnInvalid;
public UnicodeEncoding() : this(false, true)
{
}
public UnicodeEncoding(bool bigEndian, bool byteOrderMark) : this(bigEndian, byteOrderMark, false)
{
}
public UnicodeEncoding(bool bigEndian, bool byteOrderMark, bool throwOnInvalidBytes)
{
this.bigEndian = bigEndian;
this.byteOrderMark = byteOrderMark;
this.throwOnInvalid = throwOnInvalidBytes;
this.fallbackCharacter = '\uFFFD';
}
public override int CodePage => this.bigEndian ? 1201 : 1200;
public override string EncodingName => this.bigEndian ? "Unicode (Big-Endian)" : "Unicode";
protected override byte[] Encode(string s, byte[] outputBytes, int outputIndex, out int writtenBytes)
{
var hasBuffer = outputBytes != null;
var recorded = 0;
char surrogate_1st = '\u0000';
var fallbackCharacterCode = this.fallbackCharacter;
Action<byte> write = ch =>
{
if (hasBuffer)
{
if (outputIndex >= outputBytes.Length)
{
throw new System.ArgumentException("bytes");
}
outputBytes[outputIndex++] = ch;
}
else
{
outputBytes.Push(ch);
}
recorded++;
};
Action<byte, byte> writePair = (a, b) =>
{
write(a);
write(b);
};
Func<char, char> swap = ch => (char)(((ch & 0xFF) << 8) | ((ch >> 8) & 0xFF));
Action fallback = () =>
{
if (this.throwOnInvalid)
{
throw new System.Exception("Invalid character in UTF16 text");
}
writePair((byte)fallbackCharacterCode, (byte)(fallbackCharacterCode >> 8));
};
if (!hasBuffer)
{
outputBytes = new byte[0];
}
if (this.bigEndian)
{
fallbackCharacterCode = swap(fallbackCharacterCode);
}
for (var i = 0; i < s.Length; i++)
{
var ch = s[i];
if (surrogate_1st != 0)
{
if (ch >= 0xDC00 && ch <= 0xDFFF)
{
if (this.bigEndian)
{
surrogate_1st = swap(surrogate_1st);
ch = swap(ch);
}
writePair((byte)surrogate_1st, (byte)(surrogate_1st >> 8));
writePair((byte)ch, (byte)(ch >> 8));
surrogate_1st = '\u0000';
continue;
}
fallback();
surrogate_1st = '\u0000';
}
if (0xD800 <= ch && ch <= 0xDBFF)
{
surrogate_1st = ch;
continue;
}
else if (0xDC00 <= ch && ch <= 0xDFFF)
{
fallback();
surrogate_1st = '\u0000';
continue;
}
if (ch < 0x10000)
{
if (this.bigEndian)
{
ch = swap(ch);
}
writePair((byte)ch, (byte)(ch >> 8));
}
else if (ch <= 0x10FFFF)
{
ch = Bridge.Script.Write<char>("ch - 0x10000"); //?????
char lowBits = (char)((ch & 0x3FF) | 0xDC00);
char highBits = (char)(((ch >> 10) & 0x3FF) | 0xD800);
if (this.bigEndian)
{
highBits = swap(highBits);
lowBits = swap(lowBits);
}
writePair((byte)highBits, (byte)(highBits >> 8));
writePair((byte)lowBits, (byte)(lowBits >> 8));
}
else
{
fallback();
}
}
if (surrogate_1st != 0)
{
fallback();
}
writtenBytes = recorded;
if (hasBuffer)
{
return null;
}
return outputBytes;
}
protected override string Decode(byte[] bytes, int index, int count, char[] chars, int charIndex)
{
var position = index;
var result = "";
var endpoint = position + count;
this._hasError = false;
Action fallback = () =>
{
if (this.throwOnInvalid)
{
throw new System.Exception("Invalid character in UTF16 text");
}
result += this.fallbackCharacter;
};
Func<char, char> swap = ch => (char)(((byte)ch << 8) | (byte)(ch >> 8));
Func<char?> readPair = () =>
{
if ((position + 2) > endpoint)
{
position = position + 2;
return null;
}
var a = bytes[position++];
var b = bytes[position++];
var point = (char)((a << 8) | b);
if (!this.bigEndian)
{
point = swap(point);
}
return point;
};
while (position < endpoint)
{
var firstWord = readPair();
if (!firstWord.HasValue)
{
fallback();
this._hasError = true;
}
else if ((firstWord < 0xD800) || (firstWord > 0xDFFF))
{
result += Encoding.FromCharCode(firstWord.Value);
}
else if ((firstWord >= 0xD800) && (firstWord <= 0xDBFF))
{
var end = position >= endpoint;
var secondWord = readPair();
if (end)
{
fallback();
this._hasError = true;
}
else if (!secondWord.HasValue)
{
fallback();
fallback();
}
else if ((secondWord >= 0xDC00) && (secondWord <= 0xDFFF))
{
var highBits = firstWord & 0x3FF;
var lowBits = secondWord & 0x3FF;
var charCode = ((highBits << 10) | lowBits) + 0x10000;
result += Encoding.FromCharCode(charCode.Value);
}
else
{
fallback();
position = position - 2;
}
}
else
{
fallback();
}
}
return result;
}
public override int GetMaxByteCount(int charCount)
{
if (charCount < 0)
{
throw new System.ArgumentOutOfRangeException("charCount");
}
var byteCount = (long)charCount + 1;
byteCount <<= 1;
if (byteCount > 0x7fffffff)
{
throw new System.ArgumentOutOfRangeException("charCount");
}
return (int)byteCount;
}
public override int GetMaxCharCount(int byteCount)
{
if (byteCount < 0)
{
throw new System.ArgumentOutOfRangeException("byteCount");
}
var charCount = (long)(byteCount >> 1) + (byteCount & 1) + 1;
if (charCount > 0x7fffffff)
{
throw new System.ArgumentOutOfRangeException("byteCount");
}
return (int)charCount;
}
}
}
| |
/*
MIT License
Copyright (c) 2017 Saied Zarrinmehr
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Media;
using System.Windows.Shapes;
using System.Windows.Controls;
using System.Windows.Input;
using SpatialAnalysis.Visualization;
using System.Collections.Generic;
using System;
using SpatialAnalysis.JustifiedGraph;
using TriangleNet;
using SpatialAnalysis.IsovistUtility;
using SpatialAnalysis.CellularEnvironment;
using SpatialAnalysis.Geometry;
using SpatialAnalysis.Miscellaneous;
namespace SpatialAnalysis.JustifiedGraph.Visualization
{
/// <summary>
/// Class ConvexSpace. Designed for the visualization of the graph.
/// </summary>
/// <seealso cref="System.Windows.Controls.Canvas" />
public class ConvexSpace : Canvas
{
private OSMDocument _host { get; set; }
//menues
private MenuItem JustifiedGraphMenu { get; set; }
private MenuItem CreateCovexGraph { get; set; }
private MenuItem EditGraph { get; set; }
private MenuItem AddVertex { get; set; }
private MenuItem RemoveVertex { get; set; }
private MenuItem MoveVertex { get; set; }
private MenuItem AddEdge { get; set; }
private MenuItem RemoveEdge { get; set; }
private MenuItem DrawJG { get; set; }
private MenuItem Hide_show_Menu { get; set; }
#region Graph field variables
private HashSet<Node> JGNodes = new HashSet<Node>();
private JGGraph jgGraph { get; set; }
List<JGEdge> edges = new List<JGEdge>();
bool nodeRemovingMode = false;
Line edgeLine = null;
public Node node1 = null;
public Node node2 = null;
bool edgeRemoveMode = false;
HashSet<JGEdge> relatedEdges = null;
JGVertex root = null;
private List<HashSet<JGVertex>> JGHierarchy = null;
#endregion
/// <summary>
/// Initializes a new instance of the <see cref="ConvexSpace"/> class.
/// </summary>
public ConvexSpace()
{
//Main Menu
this.JustifiedGraphMenu = new MenuItem() { Header = "Justified Graph" };
//Create Menu
this.CreateCovexGraph = new MenuItem() { Header = "Create Convex Graph" };
this.CreateCovexGraph.Click += CreateConvexGraph_Click;
this.JustifiedGraphMenu.Items.Add(this.CreateCovexGraph);
//Hide and show menu
this.Hide_show_Menu = new MenuItem()
{
Header = "Hide Justified Graph",
IsEnabled = false
};
this.Hide_show_Menu.Click += new RoutedEventHandler(Hide_show_Menu_Click);
this.JustifiedGraphMenu.Items.Add(this.Hide_show_Menu);
//Edit Menu
this.EditGraph = new MenuItem()
{
Header = "Edit Graph",
IsEnabled = false
};
this.JustifiedGraphMenu.Items.Add(this.EditGraph);
//Add vertices
this.AddVertex = new MenuItem() { Header = "Add Convex Space" };
this.AddVertex.Click += AddVertex_Click;
this.EditGraph.Items.Add(this.AddVertex);
//Remove vertices
this.RemoveVertex = new MenuItem() { Header = "Remove Convex Space" };
this.RemoveVertex.Click += RemoveVertex_Click;
this.EditGraph.Items.Add(this.RemoveVertex);
//Move vertex
this.MoveVertex = new MenuItem() { Header = "Move Convex Space" };
this.MoveVertex.Click += MoveVertex_Click;
this.EditGraph.Items.Add(this.MoveVertex);
//Add edge
this.AddEdge = new MenuItem() { Header = "Add Connection" };
this.AddEdge.Click += AddEdge_Click;
this.EditGraph.Items.Add(this.AddEdge);
//Remove Edge
this.RemoveEdge = new MenuItem() { Header = "Remove Connection" };
this.RemoveEdge.Click += RemoveEdge_Click;
this.EditGraph.Items.Add(this.RemoveEdge);
//Draw
this.DrawJG = new MenuItem()
{
Header = "Draw Justified Graph",
IsEnabled=false
};
this.DrawJG.Click += DrawJG_Click;
this.JustifiedGraphMenu.Items.Add(this.DrawJG);
}
void Hide_show_Menu_Click(object sender, RoutedEventArgs e)
{
if ((string)this.Hide_show_Menu.Header == "Hide Justified Graph")
{
this.EditGraph.IsEnabled = false;
this.DrawJG.IsEnabled = false;
this.Hide_show_Menu.Header = "Show Justified Graph";
this.Visibility = System.Windows.Visibility.Collapsed;
}
else
{
this.EditGraph.IsEnabled = true;
this.DrawJG.IsEnabled = true;
this.Hide_show_Menu.Header = "Hide Justified Graph";
this.Visibility = System.Windows.Visibility.Visible;
}
}
private void CreateConvexGraph_Click(object sender, RoutedEventArgs e)
{
if ((string)this.CreateCovexGraph.Header == "Create Convex Graph")
{
this.Visibility = System.Windows.Visibility.Visible;
#region clearing the nodes and edges in case of reset
foreach (Node node in this.JGNodes)
{
node.Clear();
}
Node.LineToUVGuide.Clear();
this.JGNodes.Clear();
JGEdge.LineToEdgeGuide.Clear();
foreach (JGEdge edge in this.edges)
{
edge.Clear();
}
this.edges.Clear();
#endregion
this._host.Menues.IsEnabled = false;
this._host.CommandReset.Click += endBtn_Click;
this._host.UIMessage.Text = "Select points at the center of convex spaces";
this._host.UIMessage.Visibility = System.Windows.Visibility.Visible;
//this.JGraphMode = true;
this._host.Cursor = Cursors.Pen;
this._host.FloorScene.MouseLeftButtonDown += FloorScene_MouseLeftButtonDown;
}
else
{
this.Hide_show_Menu.IsEnabled = false;
this.EditGraph.IsEnabled = false;
this.DrawJG.IsEnabled = false;
this.CreateCovexGraph.Header = "Create Convex Graph";
this.Children.Clear();
//resetting the graph
this.JGNodes.Clear();
this.jgGraph = null;
this.edges.Clear();
this.nodeRemovingMode = false;
edgeLine = null;
node1 = null;
node2 = null;
edgeRemoveMode = false;
relatedEdges = null;
root = null;
JGHierarchy = null;
}
}
private void FloorScene_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
UV p = this._host.TransformInverse(Mouse.GetPosition(this._host.FloorScene));
try
{
Cell cell = this._host.cellularFloor.FindCell(p);
if (cell.VisualOverlapState != OverlapState.Outside)
{
MessageBox.Show("The selected point is outside the walkable filed");
return;
}
Node node = new Node(p);
node.Draw();
this.JGNodes.Add(node);
}
catch (Exception)
{
MessageBox.Show("The selected point is outside the walkable filed");
return;
}
}
private void endBtn_Click(object sender, RoutedEventArgs e)
{
this._host.CommandReset.Click -= endBtn_Click;
this._host.Menues.IsEnabled = true;
this._host.UIMessage.Visibility = Visibility.Hidden;
//this.JGraphMode = false;
this._host.Cursor = Cursors.Arrow;
this._host.FloorScene.MouseLeftButtonDown -= FloorScene_MouseLeftButtonDown;
try
{
#region Create Graph
HashSet<UV> pnts = new HashSet<UV>();
TriangleNet.Behavior behavior = new Behavior();
TriangleNet.Mesh t_mesh = new TriangleNet.Mesh();
TriangleNet.Geometry.InputGeometry geom = new TriangleNet.Geometry.InputGeometry();
foreach (Node node in JGNodes)
{
TriangleNet.Data.Vertex vertex = new TriangleNet.Data.Vertex(node.Coordinates.U, node.Coordinates.V, 0);
geom.AddPoint(vertex);
pnts.Add(node.Coordinates);
}
t_mesh.Triangulate(geom);
var graph = new JGGraph(pnts);
foreach (var item in t_mesh.Triangles)
{
UV a = null;
var vrtx = t_mesh.GetVertex(item.P0);
if (vrtx != null)
{
a = new UV(vrtx.X, vrtx.Y);
}
UV b = null;
vrtx = t_mesh.GetVertex(item.P1);
if (vrtx != null)
{
b = new UV(vrtx.X, vrtx.Y);
}
UV c = null;
vrtx = t_mesh.GetVertex(item.P2);
if (vrtx != null)
{
c = new UV(vrtx.X, vrtx.Y);
}
if (a != null && b != null)
{
graph.AddConnection(a, b);
}
if (a != null && c != null)
{
graph.AddConnection(a, c);
}
if (c != null && b != null)
{
graph.AddConnection(c, b);
}
}
#endregion
#region Remove Edges with isovists at the ends that do not overlap
this.edges = graph.ToEdges();
Dictionary<int, Isovist> IsovistGuid = new Dictionary<int, Isovist>();
foreach (JGVertex item in graph.Vertices)
{
double x = double.NegativeInfinity;
foreach (JGVertex vertex in item.Connections)
{
var y = item.Point.DistanceTo(vertex.Point);
if (y > x)
{
x = y;
}
}
var isovist = CellularIsovistCalculator.GetIsovist(item.Point, x, BarrierType.Visual, this._host.cellularFloor);
IsovistGuid.Add(item.Point.GetHashCode(), isovist);
}
HashSet<JGEdge> visibleVertexes = new HashSet<JGEdge>();
foreach (JGEdge item in this.edges)
{
Isovist v1 = null;
IsovistGuid.TryGetValue(item.P1.GetHashCode(), out v1);
Isovist v2 = null;
IsovistGuid.TryGetValue(item.P2.GetHashCode(), out v2);
if (v1 != null && v2 != null)
{
if (v2.VisibleCells.Overlaps(v1.VisibleCells))
{
visibleVertexes.Add(item);
}
}
}
#endregion
#region setting the edges
JGEdge.LineToEdgeGuide.Clear();
foreach (JGEdge edge in this.edges)
{
edge.Clear();
}
this.edges = visibleVertexes.ToList<JGEdge>();
foreach (JGEdge item in this.edges)
{
item.Draw();
}
#endregion
//cleaning up the used data
t_mesh = null;
graph = null;
geom.Clear();
geom = null;
visibleVertexes = null;
IsovistGuid = null;
//enabling edit mode
this.EditGraph.IsEnabled = true;
this.DrawJG.IsEnabled = true;
this.Hide_show_Menu.IsEnabled = true;
this.CreateCovexGraph.Header = "Reset Convex Graph";
}
catch (Exception error)
{
MessageBox.Show(error.Report());
}
}
private void ClearJGNodes_Click(object sender, RoutedEventArgs e)
{
foreach (Node item in JGNodes)
{
item.Clear();
}
JGNodes.Clear();
Node.LineToUVGuide.Clear();
foreach (JGEdge item in edges)
{
item.Clear();
}
edges.Clear();
JGEdge.LineToEdgeGuide.Clear();
}
/// <summary>
/// Clears this instance.
/// </summary>
public void Clear()
{
this._host = null;
foreach (Node item in JGNodes)
{
item.Clear();
}
JGNodes.Clear();
Node.LineToUVGuide.Clear();
foreach (JGEdge item in edges)
{
item.Clear();
}
edges.Clear();
JGEdge.LineToEdgeGuide.Clear();
this.CreateCovexGraph.Click -= CreateConvexGraph_Click;
this.Hide_show_Menu.Click -= Hide_show_Menu_Click;
this.AddVertex.Click -= AddVertex_Click;
this.RemoveVertex.Click -= RemoveVertex_Click;
this.MoveVertex.Click -= MoveVertex_Click;
this.AddEdge.Click -= AddEdge_Click;
this.RemoveEdge.Click -= RemoveEdge_Click;
this.DrawJG.Click -= DrawJG_Click;
this.JustifiedGraphMenu = null;
this.CreateCovexGraph = null;
this.EditGraph = null;
this.AddVertex = null;
this.RemoveVertex = null;
this.MoveVertex = null;
this.AddEdge = null;
this.RemoveEdge = null;
this.DrawJG = null;
this.Hide_show_Menu = null;
if (this.JGNodes != null)
{
this.JGNodes.Clear();
this.JGNodes = null;
}
this.jgGraph = null;
if (this.edges != null)
{
this.edges.Clear();
this.edges = null;
}
this.edgeLine = null;
this.node1 = null;
this.node2 = null;
if (this.relatedEdges != null)
{
this.relatedEdges.Clear();
this.relatedEdges = null;
}
this.root = null;
if (this.JGHierarchy != null)
{
this.JGHierarchy.Clear();
this.JGHierarchy = null;
}
Node.FloorScene = null;
Node.Transform = null;
JGEdge.FloorScene = null;
JGEdge.Transform = null;
}
#region Adding nodes
private void AddVertex_Click(object sender, RoutedEventArgs e)
{
this._host.Menues.IsEnabled = false;
this._host.UIMessage.Text = "Click to add a new convex space";
this._host.UIMessage.Visibility = Visibility.Visible;
this._host.CommandReset.Click += endAddingNodes_Click;
//this.JGraphMode = true;
this._host.Cursor = Cursors.Pen;
this._host.FloorScene.MouseLeftButtonDown += FloorScene_MouseLeftButtonDown;
}
private void endAddingNodes_Click(object sender, RoutedEventArgs e)
{
this._host.CommandReset.Click -= endAddingNodes_Click;
this._host.Menues.IsEnabled = true;
this._host.UIMessage.Visibility = Visibility.Hidden;
//this.JGraphMode = false;
this._host.Cursor = Cursors.Arrow;
this._host.FloorScene.MouseLeftButtonDown -= FloorScene_MouseLeftButtonDown;
}
#endregion
#region Removing nodes
private void RemoveVertex_Click(object sender, RoutedEventArgs e)
{
Node.SelectToRemove = this.markNodeToRemove;
nodeRemovingMode = true;
this._host.Menues.IsEnabled = false;
this._host.UIMessage.Text = "Click on a vertex to remove it";
this._host.UIMessage.Visibility = Visibility.Visible;
this._host.CommandReset.Click += endRemovingNodes_Click;
}
private void endRemovingNodes_Click(object sender, RoutedEventArgs e)
{
Node.SelectToRemove = null;
this._host.Menues.IsEnabled = true;
this._host.UIMessage.Visibility = Visibility.Hidden;
this._host.CommandReset.Click -= endRemovingNodes_Click;
this.nodeRemovingMode = false;
#region updating the nodes
HashSet<Node> SelectedNodes = new HashSet<Node>();
foreach (Node node in this.JGNodes)
{
if (node.Mark.Visibility == Visibility.Hidden)
{
SelectedNodes.Add(node);
}
}
MessageBox.Show(SelectedNodes.Count.ToString() + " nodes were choosen to remove");
foreach (Node node in SelectedNodes)
{
this.JGNodes.Remove(node);
node.Clear();
}
#endregion
#region
HashSet<UV> removedPoints = new HashSet<UV>();
foreach (Node item in SelectedNodes)
{
removedPoints.Add(item.Coordinates);
}
HashSet<JGEdge> removableEdges = new HashSet<JGEdge>();
foreach (JGEdge edge in this.edges)
{
if (removedPoints.Contains(edge.P1) || removedPoints.Contains(edge.P2))
{
removableEdges.Add(edge);
}
}
MessageBox.Show(removableEdges.Count.ToString() + " edges were choosen to remove");
foreach (JGEdge edge in removableEdges)
{
this.edges.Remove(edge);
edge.Clear();
}
removableEdges = null;
SelectedNodes = null;
#endregion
}
private bool markNodeToRemove(Line line)
{
if (nodeRemovingMode)
{
line.Visibility = System.Windows.Visibility.Hidden;
}
return true;
}
#endregion
#region Adding Edges
private void DrawLine(object sender, MouseEventArgs e)
{
if (edgeLine != null)
{
int index = this._host.FloorScene.Children.IndexOf(edgeLine);
if (index != -1)
{
this._host.FloorScene.Children.RemoveAt(index);
}
}
if (node1 != null)
{
Point p1 = this._host.Transform(node1.Coordinates);
Point p2 = Mouse.GetPosition(this._host.FloorScene);
edgeLine = new Line()
{
X1 = p1.X,
Y1 = p1.Y,
X2 = p2.X,
Y2 = p2.Y,
Stroke = Brushes.Pink,
StrokeThickness = 1,
};
this._host.FloorScene.Children.Add(edgeLine);
}
}
private void AddEdge_Click(object sender, RoutedEventArgs e)
{
this._host.FloorScene.MouseMove += DrawLine;
Node.SelectForEdge = selectNodes;
this._host.Menues.IsEnabled = false;
this._host.UIMessage.Text = "Click on the nodes to add edges";
this._host.UIMessage.Visibility = Visibility.Visible;
this._host.Cursor = Cursors.Pen;
this._host.CommandReset.Click += endAddingEdges_Click;
}
private void endAddingEdges_Click(object sender, RoutedEventArgs e)
{
this._host.FloorScene.MouseMove -= DrawLine;
Node.SelectForEdge = null;
this._host.Menues.IsEnabled = true;
this._host.UIMessage.Visibility = Visibility.Hidden;
this._host.CommandReset.Click -= endAddingEdges_Click;
node1 = null;
node2 = null;
this._host.Cursor = Cursors.Arrow;
}
private bool selectNodes(Line nodeMark)
{
Node n1 = null;
Node.LineToUVGuide.TryGetValue(nodeMark, out n1);
if (n1 != null)
{
if (node1 == null)
{
node1 = n1;
node1.Mark.Stroke = Node.WhenSelected;
}
else
{
node2 = n1;
node2.Mark.Stroke = Node.WhenSelected;
}
if (node1 != null && node2 != null)
{
if (node1.GetHashCode() == node2.GetHashCode())
{
node1.Mark.Stroke = Node.Color;
node2.Mark.Stroke = Node.Color;
node1 = null;
node2 = null;
}
}
}
if (node1 != null && node2 != null)
{
JGEdge newEdge = new JGEdge(node1.Coordinates, node2.Coordinates);
newEdge.Draw();
this.edges.Add(newEdge);
node1.Mark.Stroke = Node.Color;
node2.Mark.Stroke = Node.Color;
node1 = null;
node2 = null;
}
return true;
}
#endregion
#region Remove edge
private void endRemovingEdges_Click(object sender, RoutedEventArgs e)
{
edgeRemoveMode = false;
this._host.Menues.IsEnabled = true;
this._host.UIMessage.Visibility = Visibility.Hidden;
this._host.CommandReset.Click -= endRemovingEdges_Click;
var removedEdges = new HashSet<JGEdge>();
foreach (JGEdge edge in this.edges)
{
if (edge.EdgeLine.Visibility == Visibility.Hidden)
{
removedEdges.Add(edge);
}
}
foreach (JGEdge edge in removedEdges)
{
this.edges.Remove(edge);
edge.Clear();
}
removedEdges = null;
JGEdge.SelectToRemove = null;
}
private void RemoveEdge_Click(object sender, RoutedEventArgs e)
{
JGEdge.SelectToRemove = markEdgeAsRemove;
edgeRemoveMode = true;
this._host.Menues.IsEnabled = false;
this._host.UIMessage.Text = "Click on an connection to remove it";
this._host.UIMessage.Visibility = Visibility.Visible;
this._host.CommandReset.Click += endRemovingEdges_Click;
}
private bool markEdgeAsRemove(Line line)
{
if (edgeRemoveMode)
{
line.Visibility = System.Windows.Visibility.Hidden;
}
return true;
}
#endregion
#region Move Vertex space
bool moveMode = true;
private void MoveVertex_Click(object sender, RoutedEventArgs e)
{
this.node1 = null;
this._host.Menues.IsEnabled = false;
this._host.UIMessage.Text = "Click on a node to move it";
this._host.UIMessage.Visibility = System.Windows.Visibility.Visible;
this._host.CommandReset.Click += endMovingConvexSpace_Click;
foreach (Node item in this.JGNodes)
{
item.Mark.MouseLeftButtonDown += Mark_MouseLeftButtonDown2;
}
moveMode = true;
}
private void endMovingConvexSpace_Click(object sender, RoutedEventArgs e)
{
this._host.Menues.IsEnabled = true;
this._host.UIMessage.Visibility = System.Windows.Visibility.Hidden;
this._host.CommandReset.Click -= endMovingConvexSpace_Click;
foreach (Node item in this.JGNodes)
{
item.Mark.MouseLeftButtonDown -= Mark_MouseLeftButtonDown2;
}
node1 = null;
}
private void Mark_MouseLeftButtonDown2(object sender, MouseButtonEventArgs e)
{
if (this.moveMode)
{
Line line = (Line)sender;
Node.LineToUVGuide.TryGetValue(line, out node1);
if (node1 != null)
{
this.relatedEdges = this.nodeToEdge(line);
this._host.FloorScene.MouseMove += FloorScene_MouseMove2;
}
this.moveMode = false;
return;
}
else
{
this._host.FloorScene.MouseMove -= FloorScene_MouseMove2;
node1 = null;
this.moveMode = true;
return;
}
}
private void FloorScene_MouseMove2(object sender, MouseEventArgs e)
{
if (node1 != null)
{
Point p = Mouse.GetPosition(this._host.FloorScene);
UV uvP = this._host.TransformInverse(p);
foreach (JGEdge item in relatedEdges)
{
if (item.P1 == node1.Coordinates)
{
item.P1 = uvP;
}
if (item.P2 == node1.Coordinates)
{
item.P2 = uvP;
}
item.Draw();
}
node1.Coordinates = uvP;
node1.Draw();
node1.Mark.MouseLeftButtonDown += Mark_MouseLeftButtonDown2;
}
}
private HashSet<JGEdge> nodeToEdge(Line nodeMark)
{
Node node = null;
if (!Node.LineToUVGuide.TryGetValue(nodeMark, out node))
{
return null;
}
HashSet<JGEdge> e = new HashSet<JGEdge>();
foreach (JGEdge item in this.edges)
{
if (item.P1 == node.Coordinates || item.P2 == node.Coordinates)
{
e.Add(item);
}
}
if (e.Count == 0)
{
return null;
}
return e;
}
#endregion
#region Creating and drawing the JGraph
private void DrawJG_Click(object sender, RoutedEventArgs e)
{
CreateJGraph();
this._host.Menues.IsEnabled = false;
this._host.UIMessage.Text = "Pick a node in a convex space ";
this._host.UIMessage.Visibility = Visibility.Visible;
foreach (Node node in this.JGNodes)
{
node.Mark.MouseLeftButtonDown += Mark_MouseLeftButtonDown;
}
}
private void Mark_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
this._host.Menues.IsEnabled = true;
this._host.UIMessage.Visibility = Visibility.Hidden;
foreach (Node node in this.JGNodes)
{
node.Mark.MouseLeftButtonDown -= Mark_MouseLeftButtonDown;
}
Node n = null;
Node.LineToUVGuide.TryGetValue((Line)sender, out n);
if (n != null)
{
foreach (JGVertex item in jgGraph.Vertices)
{
if (item.Point == n.Coordinates)
{
root = item;
break;
}
}
}
if (root == null)
{
MessageBox.Show("Vertex not tracked");
return;
}
n.Mark.Stroke = Brushes.DarkRed;
#region create hierarchy
HashSet<JGVertex> unExplored = new HashSet<JGVertex>();
JGHierarchy = new List<HashSet<JGVertex>>();
foreach (JGVertex item in jgGraph.Vertices)
{
if (item.Point != root.Point)
{
unExplored.Add(item);
}
}
HashSet<JGVertex> firstLevel = new HashSet<JGVertex>();
firstLevel.Add(root);
JGHierarchy.Add(firstLevel);
HashSet<JGVertex> newLevel = new HashSet<JGVertex>();
HashSet<JGVertex> level = new HashSet<JGVertex>();
level.Add(root);
while (unExplored.Count != 0)
{
foreach (JGVertex item in level)
{
foreach (JGVertex vertex in item.Connections)
{
if (unExplored.Contains(vertex))
{
newLevel.Add(vertex);
}
}
}
foreach (JGVertex vertex in newLevel)
{
unExplored.Remove(vertex);
}
if (newLevel.Count == 0 && unExplored.Count != 0)
{
MessageBox.Show("Justified Graph is not a linked graph!\nTry adding connections or removing unconnected nodes...");
return;
}
level.Clear();
level.UnionWith(newLevel);
HashSet<JGVertex> thisLevel = new HashSet<JGVertex>();
foreach (JGVertex item in level)
{
thisLevel.Add(item);
}
JGHierarchy.Add(thisLevel);
newLevel.Clear();
}
#endregion
drawGraph();
}
/// <summary>
/// Draws the graph.
/// </summary>
public void drawGraph()
{
var graph = this.jgGraph.DeepCopy();
List<HashSet<JGVertex>> hierarchy = new List<HashSet<JGVertex>>();
for (int i = 0; i < JGHierarchy.Count; i++)
{
HashSet<JGVertex> newLevel = new HashSet<JGVertex>();
foreach (JGVertex item in JGHierarchy[i])
{
newLevel.Add(graph.Find(item.Point));
}
hierarchy.Add(newLevel);
}
var visualizer = new JustifiedGraphVisualHost()
{
Width = this._host.Width,
Height = this._host.Height
};
visualizer.JGVisualizer.SetGraph(graph, hierarchy);
visualizer.Owner = this._host;
visualizer.ShowDialog();
visualizer = null;
foreach (Node item in JGNodes)
{
item.Mark.Stroke = Node.Color;
}
}
/// <summary>
/// Creates the justified graph using a standard BFS algorithm.
/// </summary>
public void CreateJGraph()
{
#region setting the Nodes
HashSet<UV> vertexPoints = new HashSet<UV>();
foreach (Node node in this.JGNodes)
{
node.Clear();
}
Node.LineToUVGuide.Clear();
this.JGNodes.Clear();
foreach (JGEdge edge in this.edges)
{
this.JGNodes.Add(new Node(edge.P1));
this.JGNodes.Add(new Node(edge.P2));
}
foreach (Node node in this.JGNodes)
{
vertexPoints.Add(node.Coordinates);
node.Draw();
}
#endregion
this.jgGraph = new JGGraph(vertexPoints);
foreach (JGEdge edge in this.edges)
{
this.jgGraph.AddConnection(edge);
}
}
#endregion
/// <summary>
/// Sets the host.
/// </summary>
/// <param name="host">The main document to which this control belongs.</param>
public void SetHost(OSMDocument host)
{
this._host = host;
this._host.Menues.Items.Add(this.JustifiedGraphMenu);
Node.FloorScene = this;
Node.Transform = this._host.Transform;
JGEdge.FloorScene = this;
JGEdge.Transform = this._host.Transform;
}
}
}
| |
// Copyright (C) 2015-2021 The Neo Project.
//
// The neo is free software distributed under the MIT software license,
// see the accompanying file LICENSE in the main directory of the
// project or http://www.opensource.org/licenses/mit-license.php
// for more details.
//
// Redistribution and use in source and binary forms with or without
// modifications are permitted.
using Neo.Cryptography;
using Neo.IO;
using Neo.Network.P2P.Payloads;
using Neo.Persistence;
using Neo.SmartContract;
using Neo.SmartContract.Native;
using Neo.VM;
using Neo.Wallets.NEP6;
using Org.BouncyCastle.Crypto.Generators;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using static Neo.SmartContract.Helper;
using static Neo.Wallets.Helper;
using ECPoint = Neo.Cryptography.ECC.ECPoint;
namespace Neo.Wallets
{
/// <summary>
/// The base class of wallets.
/// </summary>
public abstract class Wallet
{
/// <summary>
/// The <see cref="Neo.ProtocolSettings"/> to be used by the wallet.
/// </summary>
public ProtocolSettings ProtocolSettings { get; }
/// <summary>
/// The name of the wallet.
/// </summary>
public abstract string Name { get; }
/// <summary>
/// The path of the wallet.
/// </summary>
public string Path { get; }
/// <summary>
/// The version of the wallet.
/// </summary>
public abstract Version Version { get; }
/// <summary>
/// Changes the password of the wallet.
/// </summary>
/// <param name="oldPassword">The old password of the wallet.</param>
/// <param name="newPassword">The new password to be used.</param>
/// <returns><see langword="true"/> if the password is changed successfully; otherwise, <see langword="false"/>.</returns>
public abstract bool ChangePassword(string oldPassword, string newPassword);
/// <summary>
/// Determines whether the specified account is included in the wallet.
/// </summary>
/// <param name="scriptHash">The hash of the account.</param>
/// <returns><see langword="true"/> if the account is included in the wallet; otherwise, <see langword="false"/>.</returns>
public abstract bool Contains(UInt160 scriptHash);
/// <summary>
/// Creates a standard account with the specified private key.
/// </summary>
/// <param name="privateKey">The private key of the account.</param>
/// <returns>The created account.</returns>
public abstract WalletAccount CreateAccount(byte[] privateKey);
/// <summary>
/// Creates a contract account for the wallet.
/// </summary>
/// <param name="contract">The contract of the account.</param>
/// <param name="key">The private key of the account.</param>
/// <returns>The created account.</returns>
public abstract WalletAccount CreateAccount(Contract contract, KeyPair key = null);
/// <summary>
/// Creates a watch-only account for the wallet.
/// </summary>
/// <param name="scriptHash">The hash of the account.</param>
/// <returns>The created account.</returns>
public abstract WalletAccount CreateAccount(UInt160 scriptHash);
/// <summary>
/// Deletes the entire database of the wallet.
/// </summary>
public abstract void Delete();
/// <summary>
/// Deletes an account from the wallet.
/// </summary>
/// <param name="scriptHash">The hash of the account.</param>
/// <returns><see langword="true"/> if the account is removed; otherwise, <see langword="false"/>.</returns>
public abstract bool DeleteAccount(UInt160 scriptHash);
/// <summary>
/// Gets the account with the specified hash.
/// </summary>
/// <param name="scriptHash">The hash of the account.</param>
/// <returns>The account with the specified hash.</returns>
public abstract WalletAccount GetAccount(UInt160 scriptHash);
/// <summary>
/// Gets all the accounts from the wallet.
/// </summary>
/// <returns>All accounts in the wallet.</returns>
public abstract IEnumerable<WalletAccount> GetAccounts();
/// <summary>
/// Initializes a new instance of the <see cref="Wallet"/> class.
/// </summary>
/// <param name="path">The path of the wallet file.</param>
/// <param name="settings">The <see cref="Neo.ProtocolSettings"/> to be used by the wallet.</param>
protected Wallet(string path, ProtocolSettings settings)
{
this.ProtocolSettings = settings;
this.Path = path;
}
/// <summary>
/// Creates a standard account for the wallet.
/// </summary>
/// <returns>The created account.</returns>
public WalletAccount CreateAccount()
{
byte[] privateKey = new byte[32];
generate:
try
{
using (RandomNumberGenerator rng = RandomNumberGenerator.Create())
{
rng.GetBytes(privateKey);
}
return CreateAccount(privateKey);
}
catch (ArgumentException)
{
goto generate;
}
finally
{
Array.Clear(privateKey, 0, privateKey.Length);
}
}
/// <summary>
/// Creates a contract account for the wallet.
/// </summary>
/// <param name="contract">The contract of the account.</param>
/// <param name="privateKey">The private key of the account.</param>
/// <returns>The created account.</returns>
public WalletAccount CreateAccount(Contract contract, byte[] privateKey)
{
if (privateKey == null) return CreateAccount(contract);
return CreateAccount(contract, new KeyPair(privateKey));
}
private static List<(UInt160 Account, BigInteger Value)> FindPayingAccounts(List<(UInt160 Account, BigInteger Value)> orderedAccounts, BigInteger amount)
{
var result = new List<(UInt160 Account, BigInteger Value)>();
BigInteger sum_balance = orderedAccounts.Select(p => p.Value).Sum();
if (sum_balance == amount)
{
result.AddRange(orderedAccounts);
orderedAccounts.Clear();
}
else
{
for (int i = 0; i < orderedAccounts.Count; i++)
{
if (orderedAccounts[i].Value < amount)
continue;
if (orderedAccounts[i].Value == amount)
{
result.Add(orderedAccounts[i]);
orderedAccounts.RemoveAt(i);
}
else
{
result.Add((orderedAccounts[i].Account, amount));
orderedAccounts[i] = (orderedAccounts[i].Account, orderedAccounts[i].Value - amount);
}
break;
}
if (result.Count == 0)
{
int i = orderedAccounts.Count - 1;
while (orderedAccounts[i].Value <= amount)
{
result.Add(orderedAccounts[i]);
amount -= orderedAccounts[i].Value;
orderedAccounts.RemoveAt(i);
i--;
}
if (amount > 0)
{
for (i = 0; i < orderedAccounts.Count; i++)
{
if (orderedAccounts[i].Value < amount)
continue;
if (orderedAccounts[i].Value == amount)
{
result.Add(orderedAccounts[i]);
orderedAccounts.RemoveAt(i);
}
else
{
result.Add((orderedAccounts[i].Account, amount));
orderedAccounts[i] = (orderedAccounts[i].Account, orderedAccounts[i].Value - amount);
}
break;
}
}
}
}
return result;
}
/// <summary>
/// Gets the account with the specified public key.
/// </summary>
/// <param name="pubkey">The public key of the account.</param>
/// <returns>The account with the specified public key.</returns>
public WalletAccount GetAccount(ECPoint pubkey)
{
return GetAccount(Contract.CreateSignatureRedeemScript(pubkey).ToScriptHash());
}
/// <summary>
/// Gets the available balance for the specified asset in the wallet.
/// </summary>
/// <param name="snapshot">The snapshot used to read data.</param>
/// <param name="asset_id">The id of the asset.</param>
/// <returns>The available balance for the specified asset.</returns>
public BigDecimal GetAvailable(DataCache snapshot, UInt160 asset_id)
{
UInt160[] accounts = GetAccounts().Where(p => !p.WatchOnly).Select(p => p.ScriptHash).ToArray();
return GetBalance(snapshot, asset_id, accounts);
}
/// <summary>
/// Gets the balance for the specified asset in the wallet.
/// </summary>
/// <param name="snapshot">The snapshot used to read data.</param>
/// <param name="asset_id">The id of the asset.</param>
/// <param name="accounts">The accounts to be counted.</param>
/// <returns>The balance for the specified asset.</returns>
public BigDecimal GetBalance(DataCache snapshot, UInt160 asset_id, params UInt160[] accounts)
{
byte[] script;
using (ScriptBuilder sb = new())
{
sb.EmitPush(0);
foreach (UInt160 account in accounts)
{
sb.EmitDynamicCall(asset_id, "balanceOf", CallFlags.ReadOnly, account);
sb.Emit(OpCode.ADD);
}
sb.EmitDynamicCall(asset_id, "decimals", CallFlags.ReadOnly);
script = sb.ToArray();
}
using ApplicationEngine engine = ApplicationEngine.Run(script, snapshot, settings: ProtocolSettings, gas: 0_60000000L * accounts.Length);
if (engine.State == VMState.FAULT)
return new BigDecimal(BigInteger.Zero, 0);
byte decimals = (byte)engine.ResultStack.Pop().GetInteger();
BigInteger amount = engine.ResultStack.Pop().GetInteger();
return new BigDecimal(amount, decimals);
}
private static byte[] Decrypt(byte[] data, byte[] key)
{
using Aes aes = Aes.Create();
aes.Key = key;
aes.Mode = CipherMode.ECB;
aes.Padding = PaddingMode.None;
using ICryptoTransform decryptor = aes.CreateDecryptor();
return decryptor.TransformFinalBlock(data, 0, data.Length);
}
/// <summary>
/// Decodes a private key from the specified NEP-2 string.
/// </summary>
/// <param name="nep2">The NEP-2 string to be decoded.</param>
/// <param name="passphrase">The passphrase of the private key.</param>
/// <param name="version">The address version of NEO system.</param>
/// <param name="N">The N field of the <see cref="ScryptParameters"/> to be used.</param>
/// <param name="r">The R field of the <see cref="ScryptParameters"/> to be used.</param>
/// <param name="p">The P field of the <see cref="ScryptParameters"/> to be used.</param>
/// <returns>The decoded private key.</returns>
public static byte[] GetPrivateKeyFromNEP2(string nep2, string passphrase, byte version, int N = 16384, int r = 8, int p = 8)
{
if (nep2 == null) throw new ArgumentNullException(nameof(nep2));
if (passphrase == null) throw new ArgumentNullException(nameof(passphrase));
byte[] data = nep2.Base58CheckDecode();
if (data.Length != 39 || data[0] != 0x01 || data[1] != 0x42 || data[2] != 0xe0)
throw new FormatException();
byte[] addresshash = new byte[4];
Buffer.BlockCopy(data, 3, addresshash, 0, 4);
byte[] datapassphrase = Encoding.UTF8.GetBytes(passphrase);
byte[] derivedkey = SCrypt.Generate(datapassphrase, addresshash, N, r, p, 64);
Array.Clear(datapassphrase, 0, datapassphrase.Length);
byte[] derivedhalf1 = derivedkey[..32];
byte[] derivedhalf2 = derivedkey[32..];
Array.Clear(derivedkey, 0, derivedkey.Length);
byte[] encryptedkey = new byte[32];
Buffer.BlockCopy(data, 7, encryptedkey, 0, 32);
Array.Clear(data, 0, data.Length);
byte[] prikey = XOR(Decrypt(encryptedkey, derivedhalf2), derivedhalf1);
Array.Clear(derivedhalf1, 0, derivedhalf1.Length);
Array.Clear(derivedhalf2, 0, derivedhalf2.Length);
ECPoint pubkey = Cryptography.ECC.ECCurve.Secp256r1.G * prikey;
UInt160 script_hash = Contract.CreateSignatureRedeemScript(pubkey).ToScriptHash();
string address = script_hash.ToAddress(version);
if (!Encoding.ASCII.GetBytes(address).Sha256().Sha256().AsSpan(0, 4).SequenceEqual(addresshash))
throw new FormatException();
return prikey;
}
/// <summary>
/// Decodes a private key from the specified WIF string.
/// </summary>
/// <param name="wif">The WIF string to be decoded.</param>
/// <returns>The decoded private key.</returns>
public static byte[] GetPrivateKeyFromWIF(string wif)
{
if (wif is null) throw new ArgumentNullException(nameof(wif));
byte[] data = wif.Base58CheckDecode();
if (data.Length != 34 || data[0] != 0x80 || data[33] != 0x01)
throw new FormatException();
byte[] privateKey = new byte[32];
Buffer.BlockCopy(data, 1, privateKey, 0, privateKey.Length);
Array.Clear(data, 0, data.Length);
return privateKey;
}
private static Signer[] GetSigners(UInt160 sender, Signer[] cosigners)
{
for (int i = 0; i < cosigners.Length; i++)
{
if (cosigners[i].Account.Equals(sender))
{
if (i == 0) return cosigners;
List<Signer> list = new(cosigners);
list.RemoveAt(i);
list.Insert(0, cosigners[i]);
return list.ToArray();
}
}
return cosigners.Prepend(new Signer
{
Account = sender,
Scopes = WitnessScope.None
}).ToArray();
}
/// <summary>
/// Imports an account from a <see cref="X509Certificate2"/>.
/// </summary>
/// <param name="cert">The <see cref="X509Certificate2"/> to import.</param>
/// <returns>The imported account.</returns>
public virtual WalletAccount Import(X509Certificate2 cert)
{
byte[] privateKey;
using (ECDsa ecdsa = cert.GetECDsaPrivateKey())
{
privateKey = ecdsa.ExportParameters(true).D;
}
WalletAccount account = CreateAccount(privateKey);
Array.Clear(privateKey, 0, privateKey.Length);
return account;
}
/// <summary>
/// Imports an account from the specified WIF string.
/// </summary>
/// <param name="wif">The WIF string to import.</param>
/// <returns>The imported account.</returns>
public virtual WalletAccount Import(string wif)
{
byte[] privateKey = GetPrivateKeyFromWIF(wif);
WalletAccount account = CreateAccount(privateKey);
Array.Clear(privateKey, 0, privateKey.Length);
return account;
}
/// <summary>
/// Imports an account from the specified NEP-2 string.
/// </summary>
/// <param name="nep2">The NEP-2 string to import.</param>
/// <param name="passphrase">The passphrase of the private key.</param>
/// <param name="N">The N field of the <see cref="ScryptParameters"/> to be used.</param>
/// <param name="r">The R field of the <see cref="ScryptParameters"/> to be used.</param>
/// <param name="p">The P field of the <see cref="ScryptParameters"/> to be used.</param>
/// <returns>The imported account.</returns>
public virtual WalletAccount Import(string nep2, string passphrase, int N = 16384, int r = 8, int p = 8)
{
byte[] privateKey = GetPrivateKeyFromNEP2(nep2, passphrase, ProtocolSettings.AddressVersion, N, r, p);
WalletAccount account = CreateAccount(privateKey);
Array.Clear(privateKey, 0, privateKey.Length);
return account;
}
/// <summary>
/// Makes a transaction to transfer assets.
/// </summary>
/// <param name="snapshot">The snapshot used to read data.</param>
/// <param name="outputs">The array of <see cref="TransferOutput"/> that contain the asset, amount, and targets of the transfer.</param>
/// <param name="from">The account to transfer from.</param>
/// <param name="cosigners">The cosigners to be added to the transction.</param>
/// <returns>The created transction.</returns>
public Transaction MakeTransaction(DataCache snapshot, TransferOutput[] outputs, UInt160 from = null, Signer[] cosigners = null)
{
UInt160[] accounts;
if (from is null)
{
accounts = GetAccounts().Where(p => !p.Lock && !p.WatchOnly).Select(p => p.ScriptHash).ToArray();
}
else
{
accounts = new[] { from };
}
Dictionary<UInt160, Signer> cosignerList = cosigners?.ToDictionary(p => p.Account) ?? new Dictionary<UInt160, Signer>();
byte[] script;
List<(UInt160 Account, BigInteger Value)> balances_gas = null;
using (ScriptBuilder sb = new())
{
foreach (var (assetId, group, sum) in outputs.GroupBy(p => p.AssetId, (k, g) => (k, g, g.Select(p => p.Value.Value).Sum())))
{
var balances = new List<(UInt160 Account, BigInteger Value)>();
foreach (UInt160 account in accounts)
{
using ScriptBuilder sb2 = new();
sb2.EmitDynamicCall(assetId, "balanceOf", CallFlags.ReadOnly, account);
using ApplicationEngine engine = ApplicationEngine.Run(sb2.ToArray(), snapshot, settings: ProtocolSettings);
if (engine.State != VMState.HALT)
throw new InvalidOperationException($"Execution for {assetId}.balanceOf('{account}' fault");
BigInteger value = engine.ResultStack.Pop().GetInteger();
if (value.Sign > 0) balances.Add((account, value));
}
BigInteger sum_balance = balances.Select(p => p.Value).Sum();
if (sum_balance < sum)
throw new InvalidOperationException($"It does not have enough balance, expected: {sum} found: {sum_balance}");
foreach (TransferOutput output in group)
{
balances = balances.OrderBy(p => p.Value).ToList();
var balances_used = FindPayingAccounts(balances, output.Value.Value);
foreach (var (account, value) in balances_used)
{
if (cosignerList.TryGetValue(account, out Signer signer))
{
if (signer.Scopes != WitnessScope.Global)
signer.Scopes |= WitnessScope.CalledByEntry;
}
else
{
cosignerList.Add(account, new Signer
{
Account = account,
Scopes = WitnessScope.CalledByEntry
});
}
sb.EmitDynamicCall(output.AssetId, "transfer", account, output.ScriptHash, value, output.Data);
sb.Emit(OpCode.ASSERT);
}
}
if (assetId.Equals(NativeContract.GAS.Hash))
balances_gas = balances;
}
script = sb.ToArray();
}
if (balances_gas is null)
balances_gas = accounts.Select(p => (Account: p, Value: NativeContract.GAS.BalanceOf(snapshot, p))).Where(p => p.Value.Sign > 0).ToList();
return MakeTransaction(snapshot, script, cosignerList.Values.ToArray(), Array.Empty<TransactionAttribute>(), balances_gas);
}
/// <summary>
/// Makes a transaction to run a smart contract.
/// </summary>
/// <param name="snapshot">The snapshot used to read data.</param>
/// <param name="script">The script to be loaded in the transaction.</param>
/// <param name="sender">The sender of the transaction.</param>
/// <param name="cosigners">The cosigners to be added to the transction.</param>
/// <param name="attributes">The attributes to be added to the transction.</param>
/// <param name="maxGas">The maximum gas that can be spent to execute the script.</param>
/// <returns>The created transction.</returns>
public Transaction MakeTransaction(DataCache snapshot, byte[] script, UInt160 sender = null, Signer[] cosigners = null, TransactionAttribute[] attributes = null, long maxGas = ApplicationEngine.TestModeGas)
{
UInt160[] accounts;
if (sender is null)
{
accounts = GetAccounts().Where(p => !p.Lock && !p.WatchOnly).Select(p => p.ScriptHash).ToArray();
}
else
{
accounts = new[] { sender };
}
var balances_gas = accounts.Select(p => (Account: p, Value: NativeContract.GAS.BalanceOf(snapshot, p))).Where(p => p.Value.Sign > 0).ToList();
return MakeTransaction(snapshot, script, cosigners ?? Array.Empty<Signer>(), attributes ?? Array.Empty<TransactionAttribute>(), balances_gas, maxGas);
}
private Transaction MakeTransaction(DataCache snapshot, byte[] script, Signer[] cosigners, TransactionAttribute[] attributes, List<(UInt160 Account, BigInteger Value)> balances_gas, long maxGas = ApplicationEngine.TestModeGas)
{
Random rand = new();
foreach (var (account, value) in balances_gas)
{
Transaction tx = new()
{
Version = 0,
Nonce = (uint)rand.Next(),
Script = script,
ValidUntilBlock = NativeContract.Ledger.CurrentIndex(snapshot) + ProtocolSettings.MaxValidUntilBlockIncrement,
Signers = GetSigners(account, cosigners),
Attributes = attributes,
};
// will try to execute 'transfer' script to check if it works
using (ApplicationEngine engine = ApplicationEngine.Run(script, snapshot.CreateSnapshot(), tx, settings: ProtocolSettings, gas: maxGas))
{
if (engine.State == VMState.FAULT)
{
throw new InvalidOperationException($"Failed execution for '{Convert.ToBase64String(script)}'", engine.FaultException);
}
tx.SystemFee = engine.GasConsumed;
}
tx.NetworkFee = CalculateNetworkFee(snapshot, tx);
if (value >= tx.SystemFee + tx.NetworkFee) return tx;
}
throw new InvalidOperationException("Insufficient GAS");
}
/// <summary>
/// Calculates the network fee for the specified transaction.
/// </summary>
/// <param name="snapshot">The snapshot used to read data.</param>
/// <param name="tx">The transaction to calculate.</param>
/// <returns>The network fee of the transaction.</returns>
public long CalculateNetworkFee(DataCache snapshot, Transaction tx)
{
UInt160[] hashes = tx.GetScriptHashesForVerifying(snapshot);
// base size for transaction: includes const_header + signers + attributes + script + hashes
int size = Transaction.HeaderSize + tx.Signers.GetVarSize() + tx.Attributes.GetVarSize() + tx.Script.GetVarSize() + IO.Helper.GetVarSize(hashes.Length);
uint exec_fee_factor = NativeContract.Policy.GetExecFeeFactor(snapshot);
long networkFee = 0;
int index = -1;
foreach (UInt160 hash in hashes)
{
index++;
byte[] witness_script = GetAccount(hash)?.Contract?.Script;
byte[] invocationScript = null;
if (tx.Witnesses != null)
{
if (witness_script is null)
{
// Try to find the script in the witnesses
Witness witness = tx.Witnesses[index];
witness_script = witness?.VerificationScript;
if (witness_script is null || witness_script.Length == 0)
{
// Then it's a contract-based witness, so try to get the corresponding invocation script for it
invocationScript = witness?.InvocationScript;
}
}
}
if (witness_script is null || witness_script.Length == 0)
{
var contract = NativeContract.ContractManagement.GetContract(snapshot, hash);
if (contract is null)
throw new ArgumentException($"The smart contract or address {hash} is not found");
var md = contract.Manifest.Abi.GetMethod("verify", -1);
if (md is null)
throw new ArgumentException($"The smart contract {contract.Hash} haven't got verify method");
if (md.ReturnType != ContractParameterType.Boolean)
throw new ArgumentException("The verify method doesn't return boolean value.");
if (md.Parameters.Length > 0 && invocationScript is null)
throw new ArgumentException("The verify method requires parameters that need to be passed via the witness' invocation script.");
// Empty verification and non-empty invocation scripts
var invSize = invocationScript != null ? invocationScript.GetVarSize() : Array.Empty<byte>().GetVarSize();
size += Array.Empty<byte>().GetVarSize() + invSize;
// Check verify cost
using ApplicationEngine engine = ApplicationEngine.Create(TriggerType.Verification, tx, snapshot.CreateSnapshot(), settings: ProtocolSettings);
engine.LoadContract(contract, md, CallFlags.ReadOnly);
if (invocationScript != null) engine.LoadScript(invocationScript, configureState: p => p.CallFlags = CallFlags.None);
if (engine.Execute() == VMState.FAULT) throw new ArgumentException($"Smart contract {contract.Hash} verification fault.");
if (!engine.ResultStack.Pop().GetBoolean()) throw new ArgumentException($"Smart contract {contract.Hash} returns false.");
networkFee += engine.GasConsumed;
}
else if (witness_script.IsSignatureContract())
{
size += 67 + witness_script.GetVarSize();
networkFee += exec_fee_factor * SignatureContractCost();
}
else if (witness_script.IsMultiSigContract(out int m, out int n))
{
int size_inv = 66 * m;
size += IO.Helper.GetVarSize(size_inv) + size_inv + witness_script.GetVarSize();
networkFee += exec_fee_factor * MultiSignatureContractCost(m, n);
}
else
{
//We can support more contract types in the future.
}
}
networkFee += size * NativeContract.Policy.GetFeePerByte(snapshot);
return networkFee;
}
/// <summary>
/// Signs the <see cref="IVerifiable"/> in the specified <see cref="ContractParametersContext"/> with the wallet.
/// </summary>
/// <param name="context">The <see cref="ContractParametersContext"/> to be used.</param>
/// <returns><see langword="true"/> if the signature is successfully added to the context; otherwise, <see langword="false"/>.</returns>
public bool Sign(ContractParametersContext context)
{
if (context.Network != ProtocolSettings.Network) return false;
bool fSuccess = false;
foreach (UInt160 scriptHash in context.ScriptHashes)
{
WalletAccount account = GetAccount(scriptHash);
if (account != null)
{
// Try to sign self-contained multiSig
Contract multiSigContract = account.Contract;
if (multiSigContract != null &&
multiSigContract.Script.IsMultiSigContract(out int m, out ECPoint[] points))
{
foreach (var point in points)
{
account = GetAccount(point);
if (account?.HasKey != true) continue;
KeyPair key = account.GetKey();
byte[] signature = context.Verifiable.Sign(key, context.Network);
fSuccess |= context.AddSignature(multiSigContract, key.PublicKey, signature);
if (fSuccess) m--;
if (context.Completed || m <= 0) break;
}
continue;
}
else if (account.HasKey)
{
// Try to sign with regular accounts
KeyPair key = account.GetKey();
byte[] signature = context.Verifiable.Sign(key, context.Network);
fSuccess |= context.AddSignature(account.Contract, key.PublicKey, signature);
continue;
}
}
// Try Smart contract verification
var contract = NativeContract.ContractManagement.GetContract(context.Snapshot, scriptHash);
if (contract != null)
{
var deployed = new DeployedContract(contract);
// Only works with verify without parameters
if (deployed.ParameterList.Length == 0)
{
fSuccess |= context.Add(deployed);
}
}
}
return fSuccess;
}
/// <summary>
/// Checks that the specified password is correct for the wallet.
/// </summary>
/// <param name="password">The password to be checked.</param>
/// <returns><see langword="true"/> if the password is correct; otherwise, <see langword="false"/>.</returns>
public abstract bool VerifyPassword(string password);
}
}
| |
--- /dev/null 2016-03-10 13:26:25.000000000 -0500
+++ src/System.IO/src/SR.cs 2016-03-10 13:26:52.552161000 -0500
@@ -0,0 +1,369 @@
+using System;
+using System.Resources;
+
+namespace FxResources.System.IO
+{
+ internal static class SR
+ {
+
+ }
+}
+
+namespace System
+{
+ internal static class SR
+ {
+ private static ResourceManager s_resourceManager;
+
+ private const string s_resourcesName = "FxResources.System.IO.SR";
+
+ internal static string ArgumentOutOfRange_StreamLength
+ {
+ get
+ {
+ return SR.GetResourceString("ArgumentOutOfRange_StreamLength", null);
+ }
+ }
+
+ internal static string IO_IO_StreamTooLong
+ {
+ get
+ {
+ return SR.GetResourceString("IO_IO_StreamTooLong", null);
+ }
+ }
+
+ internal static string ArgumentNull_Stream
+ {
+ get
+ {
+ return SR.GetResourceString("ArgumentNull_Stream", null);
+ }
+ }
+
+ internal static string InvalidOperation_TimeoutsNotSupported
+ {
+ get
+ {
+ return SR.GetResourceString("InvalidOperation_TimeoutsNotSupported", null);
+ }
+ }
+
+ internal static string InvalidOperation_AsyncIOInProgress
+ {
+ get
+ {
+ return SR.GetResourceString("InvalidOperation_AsyncIOInProgress", null);
+ }
+ }
+
+ internal static string Arg_SurrogatesNotAllowedAsSingleChar
+ {
+ get
+ {
+ return SR.GetResourceString("Arg_SurrogatesNotAllowedAsSingleChar", null);
+ }
+ }
+
+ internal static string IO_IO_SeekBeforeBegin
+ {
+ get
+ {
+ return SR.GetResourceString("IO_IO_SeekBeforeBegin", null);
+ }
+ }
+
+ internal static string Argument_InvalidSeekOrigin
+ {
+ get
+ {
+ return SR.GetResourceString("Argument_InvalidSeekOrigin", null);
+ }
+ }
+
+ internal static string ArgumentOutOfRange_SmallCapacity
+ {
+ get
+ {
+ return SR.GetResourceString("ArgumentOutOfRange_SmallCapacity", null);
+ }
+ }
+
+ internal static string NotSupported_MemStreamNotExpandable
+ {
+ get
+ {
+ return SR.GetResourceString("NotSupported_MemStreamNotExpandable", null);
+ }
+ }
+
+ internal static string ArgumentOutOfRange_NegativeCapacity
+ {
+ get
+ {
+ return SR.GetResourceString("ArgumentOutOfRange_NegativeCapacity", null);
+ }
+ }
+
+ internal static string Arg_EndOfStreamException
+ {
+ get
+ {
+ return SR.GetResourceString("Arg_EndOfStreamException", null);
+ }
+ }
+
+
+ internal static string ArgumentOutOfRange_BinaryReaderFillBuffer
+ {
+ get
+ {
+ return SR.GetResourceString("ArgumentOutOfRange_BinaryReaderFillBuffer", null);
+ }
+ }
+
+ internal static string Arg_DecBitCtor
+ {
+ get
+ {
+ return SR.GetResourceString("Arg_DecBitCtor", null);
+ }
+ }
+
+ internal static string IO_IO_InvalidStringLen_Len
+ {
+ get
+ {
+ return SR.GetResourceString("IO_IO_InvalidStringLen_Len", null);
+ }
+ }
+
+ internal static string Argument_StreamNotReadable
+ {
+ get
+ {
+ return SR.GetResourceString("Argument_StreamNotReadable", null);
+ }
+ }
+
+ internal static string Argument_StreamNotWritable
+ {
+ get
+ {
+ return SR.GetResourceString("Argument_StreamNotWritable", null);
+ }
+ }
+
+ internal static string ObjectDisposed_WriterClosed
+ {
+ get
+ {
+ return SR.GetResourceString("ObjectDisposed_WriterClosed", null);
+ }
+ }
+
+ internal static string ArgumentOutOfRange_NeedPosNum
+ {
+ get
+ {
+ return SR.GetResourceString("ArgumentOutOfRange_NeedPosNum", null);
+ }
+ }
+
+ internal static string ObjectDisposed_FileClosed
+ {
+ get
+ {
+ return SR.GetResourceString("ObjectDisposed_FileClosed", null);
+ }
+ }
+
+
+ internal static string ObjectDisposed_ReaderClosed
+ {
+ get
+ {
+ return SR.GetResourceString("ObjectDisposed_ReaderClosed", null);
+ }
+ }
+
+ internal static string Format_Bad7BitInt32
+ {
+ get
+ {
+ return SR.GetResourceString("Format_Bad7BitInt32", null);
+ }
+ }
+
+ internal static string IO_EOF_ReadBeyondEOF
+ {
+ get
+ {
+ return SR.GetResourceString("IO_EOF_ReadBeyondEOF", null);
+ }
+ }
+
+
+ internal static string Argument_InvalidOffLen
+ {
+ get
+ {
+ return SR.GetResourceString("Argument_InvalidOffLen", null);
+ }
+ }
+
+ internal static string ArgumentNull_Buffer
+ {
+ get
+ {
+ return SR.GetResourceString("ArgumentNull_Buffer", null);
+ }
+ }
+
+ internal static string ArgumentOutOfRange_MustBePositive
+ {
+ get
+ {
+ return SR.GetResourceString("ArgumentOutOfRange_MustBePositive", null);
+ }
+ }
+
+ internal static string ArgumentOutOfRange_NeedNonNegNum
+ {
+ get
+ {
+ return SR.GetResourceString("ArgumentOutOfRange_NeedNonNegNum", null);
+ }
+ }
+
+ internal static string GenericInvalidData
+ {
+ get
+ {
+ return SR.GetResourceString("GenericInvalidData", null);
+ }
+ }
+
+ internal static string NotSupported_CannotWriteToBufferedStreamIfReadBufferCannotBeFlushed
+ {
+ get
+ {
+ return SR.GetResourceString("NotSupported_CannotWriteToBufferedStreamIfReadBufferCannotBeFlushed", null);
+ }
+ }
+
+ internal static string NotSupported_UnreadableStream
+ {
+ get
+ {
+ return SR.GetResourceString("NotSupported_UnreadableStream", null);
+ }
+ }
+
+ internal static string NotSupported_UnseekableStream
+ {
+ get
+ {
+ return SR.GetResourceString("NotSupported_UnseekableStream", null);
+ }
+ }
+
+ internal static string NotSupported_UnwritableStream
+ {
+ get
+ {
+ return SR.GetResourceString("NotSupported_UnwritableStream", null);
+ }
+ }
+
+ internal static string ObjectDisposed_StreamClosed
+ {
+ get
+ {
+ return SR.GetResourceString("ObjectDisposed_StreamClosed", null);
+ }
+ }
+
+ private static ResourceManager ResourceManager
+ {
+ get
+ {
+ if (SR.s_resourceManager == null)
+ {
+ SR.s_resourceManager = new ResourceManager(SR.ResourceType);
+ }
+ return SR.s_resourceManager;
+ }
+ }
+
+ internal static Type ResourceType
+ {
+ get
+ {
+ return typeof(FxResources.System.IO.SR);
+ }
+ }
+
+ internal static string Format(string resourceFormat, params object[] args)
+ {
+ if (args == null)
+ {
+ return resourceFormat;
+ }
+ if (!SR.UsingResourceKeys())
+ {
+ return string.Format(resourceFormat, args);
+ }
+ return string.Concat(resourceFormat, string.Join(", ", args));
+ }
+
+ internal static string Format(string resourceFormat, object p1)
+ {
+ if (!SR.UsingResourceKeys())
+ {
+ return string.Format(resourceFormat, p1);
+ }
+ return string.Join(", ", new object[] { resourceFormat, p1 });
+ }
+
+ internal static string Format(string resourceFormat, object p1, object p2)
+ {
+ if (!SR.UsingResourceKeys())
+ {
+ return string.Format(resourceFormat, p1, p2);
+ }
+ return string.Join(", ", new object[] { resourceFormat, p1, p2 });
+ }
+
+ internal static string Format(string resourceFormat, object p1, object p2, object p3)
+ {
+ if (!SR.UsingResourceKeys())
+ {
+ return string.Format(resourceFormat, p1, p2, p3);
+ }
+ return string.Join(", ", new object[] { resourceFormat, p1, p2, p3 });
+ }
+
+ internal static string GetResourceString(string resourceKey, string defaultString)
+ {
+ string str = null;
+ try
+ {
+ str = SR.ResourceManager.GetString(resourceKey);
+ }
+ catch (MissingManifestResourceException missingManifestResourceException)
+ {
+ }
+ if (defaultString != null && resourceKey.Equals(str, StringComparison.Ordinal))
+ {
+ return defaultString;
+ }
+ return str;
+ }
+
+ private static bool UsingResourceKeys()
+ {
+ return false;
+ }
+ }
+}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace CloudNotes.WebAPI.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using Internal.Runtime.Augments;
using System.Diagnostics;
using System.Threading;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace System.Runtime
{
// Initialize the cache eagerly to avoid null checks
[EagerOrderedStaticConstructor(EagerStaticConstructorOrder.SystemRuntimeTypeLoaderExports)]
public static class TypeLoaderExports
{
[RuntimeExport("GetThreadStaticsForDynamicType")]
public static IntPtr GetThreadStaticsForDynamicType(int index)
{
IntPtr result = RuntimeImports.RhGetThreadLocalStorageForDynamicType(index, 0, 0);
if (result != IntPtr.Zero)
return result;
int numTlsCells;
int tlsStorageSize = RuntimeAugments.TypeLoaderCallbacks.GetThreadStaticsSizeForDynamicType(index, out numTlsCells);
result = RuntimeImports.RhGetThreadLocalStorageForDynamicType(index, tlsStorageSize, numTlsCells);
if (result == IntPtr.Zero)
throw new OutOfMemoryException();
return result;
}
[RuntimeExport("ActivatorCreateInstanceAny")]
public static unsafe void ActivatorCreateInstanceAny(ref object ptrToData, IntPtr pEETypePtr)
{
EETypePtr pEEType = new EETypePtr(pEETypePtr);
if (pEEType.IsValueType)
{
// Nothing else to do for value types.
return;
}
// For reference types, we need to:
// 1- Allocate the new object
// 2- Call its default ctor
// 3- Update ptrToData to point to that newly allocated object
ptrToData = RuntimeImports.RhNewObject(pEEType);
Entry entry = LookupInCache(s_cache, pEETypePtr, pEETypePtr);
if (entry == null)
{
entry = CacheMiss(pEETypePtr, pEETypePtr, SignatureKind.DefaultConstructor);
}
RawCalliHelper.Call(entry.Result, ptrToData);
}
//
// Generic lookup cache
//
private class Entry
{
public IntPtr Context;
public IntPtr Signature;
public IntPtr Result;
public IntPtr AuxResult;
public Entry Next;
}
// Initialize the cache eagerly to avoid null checks.
// Use array with just single element to make this pay-for-play. The actual cache will be allocated only
// once the lazy lookups are actually needed.
private static Entry[] s_cache = new Entry[1];
private static Lock s_lock;
private static GCHandle s_previousCache;
private volatile static IntPtr[] s_resolutionFunctionPointers = new IntPtr[4];
private static int s_nextResolutionFunctionPointerIndex = (int)SignatureKind.Count;
[RuntimeExport("GenericLookup")]
public static IntPtr GenericLookup(IntPtr context, IntPtr signature)
{
Entry entry = LookupInCache(s_cache, context, signature);
if (entry == null)
{
entry = CacheMiss(context, signature);
}
return entry.Result;
}
[RuntimeExport("GenericLookupAndCallCtor")]
public static void GenericLookupAndCallCtor(Object arg, IntPtr context, IntPtr signature)
{
Entry entry = LookupInCache(s_cache, context, signature);
if (entry == null)
{
entry = CacheMiss(context, signature);
}
RawCalliHelper.Call(entry.Result, arg);
}
[RuntimeExport("GenericLookupAndAllocObject")]
public static Object GenericLookupAndAllocObject(IntPtr context, IntPtr signature)
{
Entry entry = LookupInCache(s_cache, context, signature);
if (entry == null)
{
entry = CacheMiss(context, signature);
}
return RawCalliHelper.Call<Object>(entry.Result, entry.AuxResult);
}
[RuntimeExport("GenericLookupAndAllocArray")]
public static Object GenericLookupAndAllocArray(IntPtr context, IntPtr arg, IntPtr signature)
{
Entry entry = LookupInCache(s_cache, context, signature);
if (entry == null)
{
entry = CacheMiss(context, signature);
}
return RawCalliHelper.Call<Object>(entry.Result, entry.AuxResult, arg);
}
[RuntimeExport("GenericLookupAndCheckArrayElemType")]
public static void GenericLookupAndCheckArrayElemType(IntPtr context, object arg, IntPtr signature)
{
Entry entry = LookupInCache(s_cache, context, signature);
if (entry == null)
{
entry = CacheMiss(context, signature);
}
RawCalliHelper.Call(entry.Result, entry.AuxResult, arg);
}
[RuntimeExport("GenericLookupAndCast")]
public static Object GenericLookupAndCast(Object arg, IntPtr context, IntPtr signature)
{
Entry entry = LookupInCache(s_cache, context, signature);
if (entry == null)
{
entry = CacheMiss(context, signature);
}
return RawCalliHelper.Call<Object>(entry.Result, arg, entry.AuxResult);
}
public unsafe static IntPtr GetDelegateThunk(object delegateObj, int whichThunk)
{
Entry entry = LookupInCache(s_cache, delegateObj.m_pEEType, new IntPtr(whichThunk));
if (entry == null)
{
entry = CacheMiss(delegateObj.m_pEEType, new IntPtr(whichThunk), SignatureKind.GenericDelegateThunk, delegateObj);
}
return entry.Result;
}
public unsafe static IntPtr GVMLookupForSlot(object obj, RuntimeMethodHandle slot)
{
Entry entry = LookupInCache(s_cache, obj.m_pEEType, *(IntPtr*)&slot);
if (entry == null)
{
entry = CacheMiss(obj.m_pEEType, *(IntPtr*)&slot, SignatureKind.GenericVirtualMethod);
}
return entry.Result;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static IntPtr OpenInstanceMethodLookup(IntPtr openResolver, object obj)
{
Entry entry = LookupInCache(s_cache, obj.m_pEEType, openResolver);
if (entry == null)
{
entry = CacheMiss(obj.m_pEEType, openResolver, SignatureKind.OpenInstanceResolver, obj);
}
return entry.Result;
}
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
private static Entry LookupInCache(Entry[] cache, IntPtr context, IntPtr signature)
{
int key = ((context.GetHashCode() >> 4) ^ signature.GetHashCode()) & (cache.Length - 1);
Entry entry = cache[key];
while (entry != null)
{
if (entry.Context == context && entry.Signature == signature)
break;
entry = entry.Next;
}
return entry;
}
private enum SignatureKind
{
GenericDictionary,
GenericVirtualMethod,
OpenInstanceResolver,
DefaultConstructor,
GenericDelegateThunk,
Count
}
internal static int RegisterResolutionFunction(IntPtr resolutionFunction)
{
if (s_lock == null)
Interlocked.CompareExchange(ref s_lock, new Lock(), null);
s_lock.Acquire();
try
{
int newResolutionFunctionId = s_nextResolutionFunctionPointerIndex;
IntPtr[] resolutionFunctionPointers = null;
if (newResolutionFunctionId < s_resolutionFunctionPointers.Length)
{
resolutionFunctionPointers = s_resolutionFunctionPointers;
}
else
{
resolutionFunctionPointers = new IntPtr[s_resolutionFunctionPointers.Length * 2];
Array.Copy(s_resolutionFunctionPointers, resolutionFunctionPointers, s_resolutionFunctionPointers.Length);
s_resolutionFunctionPointers = resolutionFunctionPointers;
}
Volatile.Write(ref s_resolutionFunctionPointers[newResolutionFunctionId], resolutionFunction);
s_nextResolutionFunctionPointerIndex++;
return newResolutionFunctionId;
}
finally
{
s_lock.Release();
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static IntPtr RuntimeCacheLookupInCache(IntPtr context, IntPtr signature, int registeredResolutionFunction, object contextObject, out IntPtr auxResult)
{
Entry entry = LookupInCache(s_cache, context, signature);
if (entry == null)
{
entry = CacheMiss(context, signature, (SignatureKind)registeredResolutionFunction, contextObject);
}
auxResult = entry.AuxResult;
return entry.Result;
}
private unsafe static Entry CacheMiss(IntPtr context, IntPtr signature, SignatureKind signatureKind = SignatureKind.GenericDictionary, object contextObject = null)
{
IntPtr result = IntPtr.Zero, auxResult = IntPtr.Zero;
bool previouslyCached = false;
//
// Try to find the entry in the previous version of the cache that is kept alive by weak reference
//
if (s_previousCache.IsAllocated)
{
Entry[] previousCache = (Entry[])s_previousCache.Target;
if (previousCache != null)
{
Entry previousEntry = LookupInCache(previousCache, context, signature);
if (previousEntry != null)
{
result = previousEntry.Result;
auxResult = previousEntry.AuxResult;
previouslyCached = true;
}
}
}
//
// Call into the type loader to compute the target
//
if (!previouslyCached)
{
switch (signatureKind)
{
case SignatureKind.GenericDictionary:
result = RuntimeAugments.TypeLoaderCallbacks.GenericLookupFromContextAndSignature(context, signature, out auxResult);
break;
case SignatureKind.GenericVirtualMethod:
result = Internal.Runtime.CompilerServices.GenericVirtualMethodSupport.GVMLookupForSlot(new RuntimeTypeHandle(new EETypePtr(context)), *(RuntimeMethodHandle*)&signature);
break;
case SignatureKind.OpenInstanceResolver:
result = Internal.Runtime.CompilerServices.OpenMethodResolver.ResolveMethodWorker(signature, contextObject);
break;
case SignatureKind.DefaultConstructor:
{
result = RuntimeAugments.Callbacks.TryGetDefaultConstructorForType(new RuntimeTypeHandle(new EETypePtr(context)));
if (result == IntPtr.Zero)
result = RuntimeAugments.GetFallbackDefaultConstructor();
}
break;
case SignatureKind.GenericDelegateThunk:
result = RuntimeAugments.TypeLoaderCallbacks.GetDelegateThunk((Delegate)contextObject, (int)signature);
break;
default:
result = RawCalliHelper.Call<IntPtr>(s_resolutionFunctionPointers[(int)signatureKind], context, signature, contextObject, out auxResult);
break;
}
}
//
// Update the cache under the lock
//
if (s_lock == null)
Interlocked.CompareExchange(ref s_lock, new Lock(), null);
s_lock.Acquire();
try
{
// Avoid duplicate entries
Entry existingEntry = LookupInCache(s_cache, context, signature);
if (existingEntry != null)
return existingEntry;
// Resize cache as necessary
Entry[] cache = ResizeCacheForNewEntryAsNecessary();
int key = ((context.GetHashCode() >> 4) ^ signature.GetHashCode()) & (cache.Length - 1);
Entry newEntry = new Entry() { Context = context, Signature = signature, Result = result, AuxResult = auxResult, Next = cache[key] };
cache[key] = newEntry;
return newEntry;
}
finally
{
s_lock.Release();
}
}
//
// Parameters and state used by generic lookup cache resizing algorithm
//
private const int InitialCacheSize = 128; // MUST BE A POWER OF TWO
private const int DefaultCacheSize = 1024;
private const int MaximumCacheSize = 128 * 1024;
private static long s_tickCountOfLastOverflow;
private static int s_entries;
private static bool s_roundRobinFlushing;
private static Entry[] ResizeCacheForNewEntryAsNecessary()
{
Entry[] cache = s_cache;
if (cache.Length < InitialCacheSize)
{
// Start with small cache size so that the cache entries used by startup one-time only initialization will get flushed soon
return s_cache = new Entry[InitialCacheSize];
}
int entries = s_entries++;
// If the cache has spare space, we are done
if (2 * entries < cache.Length)
{
if (s_roundRobinFlushing)
{
cache[2 * entries] = null;
cache[2 * entries + 1] = null;
}
return cache;
}
//
// Now, we have cache that is overflowing with the stuff. We need to decide whether to resize it or start flushing the old entries instead
//
// Start over counting the entries
s_entries = 0;
// See how long it has been since the last time the cache was overflowing
long tickCount = Environment.TickCount64;
long tickCountSinceLastOverflow = tickCount - s_tickCountOfLastOverflow;
s_tickCountOfLastOverflow = tickCount;
bool shrinkCache = false;
bool growCache = false;
if (cache.Length < DefaultCacheSize)
{
// If the cache have not reached the default size, just grow it without thinking about it much
growCache = true;
}
else
{
if (tickCountSinceLastOverflow < cache.Length / 128)
{
// If the fill rate of the cache is faster than ~0.01ms per entry, grow it
if (cache.Length < MaximumCacheSize)
growCache = true;
}
else
if (tickCountSinceLastOverflow > cache.Length * 16)
{
// If the fill rate of the cache is slower than 16ms per entry, shrink it
if (cache.Length > DefaultCacheSize)
shrinkCache = true;
}
// Otherwise, keep the current size and just keep flushing the entries round robin
}
if (growCache || shrinkCache)
{
s_roundRobinFlushing = false;
// Keep the reference to the old cache in a weak handle. We will try to use to avoid
// hitting the type loader until GC collects it.
if (s_previousCache.IsAllocated)
{
s_previousCache.Target = cache;
}
else
{
s_previousCache = GCHandle.Alloc(cache, GCHandleType.Weak);
}
return s_cache = new Entry[shrinkCache ? (cache.Length / 2) : (cache.Length * 2)];
}
else
{
s_roundRobinFlushing = true;
return cache;
}
}
}
[System.Runtime.InteropServices.McgIntrinsicsAttribute]
internal class RawCalliHelper
{
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static T Call<T>(System.IntPtr pfn, IntPtr arg)
{
return default(T);
}
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static void Call(System.IntPtr pfn, Object arg)
{
}
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static T Call<T>(System.IntPtr pfn, IntPtr arg1, IntPtr arg2)
{
return default(T);
}
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static T Call<T>(System.IntPtr pfn, IntPtr arg1, IntPtr arg2, object arg3, out IntPtr arg4)
{
arg4 = IntPtr.Zero;
return default(T);
}
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static void Call(System.IntPtr pfn, IntPtr arg1, Object arg2)
{
}
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static T Call<T>(System.IntPtr pfn, Object arg1, IntPtr arg2)
{
return default(T);
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Examples.Sql
{
using System;
using System.Linq;
using Apache.Ignite.Core;
using Apache.Ignite.Core.Cache;
using Apache.Ignite.Core.Cache.Affinity;
using Apache.Ignite.Core.Cache.Configuration;
using Apache.Ignite.Core.Cache.Query;
using Apache.Ignite.ExamplesDll.Binary;
using Apache.Ignite.Linq;
/// <summary>
/// This example populates cache with sample data and runs several LINQ queries over this data.
/// <para />
/// 1) Build the project Apache.Ignite.ExamplesDll (select it -> right-click -> Build).
/// 2) Set this class as startup object (Apache.Ignite.Examples project -> right-click -> Properties ->
/// Application -> Startup object);
/// 3) Start example (F5 or Ctrl+F5).
/// <para />
/// This example can be run with standalone Apache Ignite.NET node:
/// 1) Run %IGNITE_HOME%/platforms/dotnet/bin/Apache.Ignite.exe:
/// Apache.Ignite.exe -configFileName=platforms\dotnet\examples\apache.ignite.examples\app.config
/// 2) Start example.
/// </summary>
public class LinqExample
{
/// <summary>Organization cache name.</summary>
private const string OrganizationCacheName = "dotnet_cache_query_organization";
/// <summary>Employee cache name.</summary>
private const string EmployeeCacheName = "dotnet_cache_query_employee";
/// <summary>Colocated employee cache name.</summary>
private const string EmployeeCacheNameColocated = "dotnet_cache_query_employee_colocated";
[STAThread]
public static void Main()
{
using (var ignite = Ignition.StartFromApplicationConfiguration())
{
Console.WriteLine();
Console.WriteLine(">>> Cache LINQ example started.");
var employeeCache = ignite.GetOrCreateCache<int, Employee>(
new CacheConfiguration(EmployeeCacheName, new QueryEntity(typeof(int), typeof(Employee))));
var employeeCacheColocated = ignite.GetOrCreateCache<AffinityKey, Employee>(
new CacheConfiguration(EmployeeCacheNameColocated,
new QueryEntity(typeof(AffinityKey), typeof(Employee))));
var organizationCache = ignite.GetOrCreateCache<int, Organization>(
new CacheConfiguration(OrganizationCacheName, new QueryEntity(typeof(int), typeof(Organization))));
// Populate cache with sample data entries.
PopulateCache(employeeCache);
PopulateCache(employeeCacheColocated);
PopulateCache(organizationCache);
// Run SQL query example.
QueryExample(employeeCache);
// Run compiled SQL query example.
CompiledQueryExample(employeeCache);
// Run SQL query with join example.
JoinQueryExample(employeeCacheColocated, organizationCache);
// Run SQL query with distributed join example.
DistributedJoinQueryExample(employeeCache, organizationCache);
// Run SQL fields query example.
FieldsQueryExample(employeeCache);
Console.WriteLine();
}
Console.WriteLine();
Console.WriteLine(">>> Example finished, press any key to exit ...");
Console.ReadKey();
}
/// <summary>
/// Queries employees that have provided ZIP code in address.
/// </summary>
/// <param name="cache">Cache.</param>
private static void QueryExample(ICache<int, Employee> cache)
{
const int zip = 94109;
IQueryable<ICacheEntry<int, Employee>> qry =
cache.AsCacheQueryable().Where(emp => emp.Value.Address.Zip == zip);
Console.WriteLine();
Console.WriteLine(">>> Employees with zipcode " + zip + ":");
foreach (ICacheEntry<int, Employee> entry in qry)
Console.WriteLine(">>> " + entry.Value);
}
/// <summary>
/// Queries employees that have provided ZIP code in address with a compiled query.
/// </summary>
/// <param name="cache">Cache.</param>
private static void CompiledQueryExample(ICache<int, Employee> cache)
{
const int zip = 94109;
var cache0 = cache.AsCacheQueryable();
// Compile cache query to eliminate LINQ overhead on multiple runs.
Func<int, IQueryCursor<ICacheEntry<int, Employee>>> qry =
CompiledQuery.Compile((int z) => cache0.Where(emp => emp.Value.Address.Zip == z));
Console.WriteLine();
Console.WriteLine(">>> Employees with zipcode {0} using compiled query:", zip);
foreach (ICacheEntry<int, Employee> entry in qry(zip))
Console.WriteLine(">>> " + entry.Value);
}
/// <summary>
/// Queries employees that work for organization with provided name.
/// </summary>
/// <param name="employeeCache">Employee cache.</param>
/// <param name="organizationCache">Organization cache.</param>
private static void JoinQueryExample(ICache<AffinityKey, Employee> employeeCache,
ICache<int, Organization> organizationCache)
{
const string orgName = "Apache";
IQueryable<ICacheEntry<AffinityKey, Employee>> employees = employeeCache.AsCacheQueryable();
IQueryable<ICacheEntry<int, Organization>> organizations = organizationCache.AsCacheQueryable();
IQueryable<ICacheEntry<AffinityKey, Employee>> qry =
from employee in employees
from organization in organizations
where employee.Value.OrganizationId == organization.Key && organization.Value.Name == orgName
select employee;
Console.WriteLine();
Console.WriteLine(">>> Employees working for " + orgName + ":");
foreach (ICacheEntry<AffinityKey, Employee> entry in qry)
Console.WriteLine(">>> " + entry.Value);
}
/// <summary>
/// Queries employees that work for organization with provided name.
/// </summary>
/// <param name="employeeCache">Employee cache.</param>
/// <param name="organizationCache">Organization cache.</param>
private static void DistributedJoinQueryExample(ICache<int, Employee> employeeCache,
ICache<int, Organization> organizationCache)
{
const string orgName = "Apache";
var queryOptions = new QueryOptions {EnableDistributedJoins = true};
IQueryable<ICacheEntry<int, Employee>> employees = employeeCache.AsCacheQueryable(queryOptions);
IQueryable<ICacheEntry<int, Organization>> organizations = organizationCache.AsCacheQueryable(queryOptions);
IQueryable<ICacheEntry<int, Employee>> qry =
from employee in employees
from organization in organizations
where employee.Value.OrganizationId == organization.Key && organization.Value.Name == orgName
select employee;
Console.WriteLine();
Console.WriteLine(">>> Employees working for " + orgName + ":");
foreach (ICacheEntry<int, Employee> entry in qry)
Console.WriteLine(">>> " + entry.Value);
}
/// <summary>
/// Queries names and salaries for all employees.
/// </summary>
/// <param name="cache">Cache.</param>
private static void FieldsQueryExample(ICache<int, Employee> cache)
{
var qry = cache.AsCacheQueryable().Select(entry => new {entry.Value.Name, entry.Value.Salary});
Console.WriteLine();
Console.WriteLine(">>> Employee names and their salaries:");
foreach (var row in qry)
Console.WriteLine(">>> [Name=" + row.Name + ", salary=" + row.Salary + ']');
}
/// <summary>
/// Populate cache with data for this example.
/// </summary>
/// <param name="cache">Cache.</param>
private static void PopulateCache(ICache<int, Organization> cache)
{
cache.Put(1, new Organization(
"Apache",
new Address("1065 East Hillsdale Blvd, Foster City, CA", 94404),
OrganizationType.Private,
DateTime.Now));
cache.Put(2, new Organization(
"Microsoft",
new Address("1096 Eddy Street, San Francisco, CA", 94109),
OrganizationType.Private,
DateTime.Now));
}
/// <summary>
/// Populate cache with data for this example.
/// </summary>
/// <param name="cache">Cache.</param>
private static void PopulateCache(ICache<AffinityKey, Employee> cache)
{
cache.Put(new AffinityKey(1, 1), new Employee(
"James Wilson",
12500,
new Address("1096 Eddy Street, San Francisco, CA", 94109),
new[] {"Human Resources", "Customer Service"},
1));
cache.Put(new AffinityKey(2, 1), new Employee(
"Daniel Adams",
11000,
new Address("184 Fidler Drive, San Antonio, TX", 78130),
new[] {"Development", "QA"},
1));
cache.Put(new AffinityKey(3, 1), new Employee(
"Cristian Moss",
12500,
new Address("667 Jerry Dove Drive, Florence, SC", 29501),
new[] {"Logistics"},
1));
cache.Put(new AffinityKey(4, 2), new Employee(
"Allison Mathis",
25300,
new Address("2702 Freedom Lane, San Francisco, CA", 94109),
new[] {"Development"},
2));
cache.Put(new AffinityKey(5, 2), new Employee(
"Breana Robbin",
6500,
new Address("3960 Sundown Lane, Austin, TX", 78130),
new[] {"Sales"},
2));
cache.Put(new AffinityKey(6, 2), new Employee(
"Philip Horsley",
19800,
new Address("2803 Elsie Drive, Sioux Falls, SD", 57104),
new[] {"Sales"},
2));
cache.Put(new AffinityKey(7, 2), new Employee(
"Brian Peters",
10600,
new Address("1407 Pearlman Avenue, Boston, MA", 12110),
new[] {"Development", "QA"},
2));
}
/// <summary>
/// Populate cache with data for this example.
/// </summary>
/// <param name="cache">Cache.</param>
private static void PopulateCache(ICache<int, Employee> cache)
{
cache.Put(1, new Employee(
"James Wilson",
12500,
new Address("1096 Eddy Street, San Francisco, CA", 94109),
new[] {"Human Resources", "Customer Service"},
1));
cache.Put(2, new Employee(
"Daniel Adams",
11000,
new Address("184 Fidler Drive, San Antonio, TX", 78130),
new[] {"Development", "QA"},
1));
cache.Put(3, new Employee(
"Cristian Moss",
12500,
new Address("667 Jerry Dove Drive, Florence, SC", 29501),
new[] {"Logistics"},
1));
cache.Put(4, new Employee(
"Allison Mathis",
25300,
new Address("2702 Freedom Lane, San Francisco, CA", 94109),
new[] {"Development"},
2));
cache.Put(5, new Employee(
"Breana Robbin",
6500,
new Address("3960 Sundown Lane, Austin, TX", 78130),
new[] {"Sales"},
2));
cache.Put(6, new Employee(
"Philip Horsley",
19800,
new Address("2803 Elsie Drive, Sioux Falls, SD", 57104),
new[] {"Sales"},
2));
cache.Put(7, new Employee(
"Brian Peters",
10600,
new Address("1407 Pearlman Avenue, Boston, MA", 12110),
new[] {"Development", "QA"},
2));
}
}
}
| |
//----------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------
namespace System.ServiceModel.Discovery.Configuration
{
using System.ComponentModel;
using System.Configuration;
using System.Diagnostics.CodeAnalysis;
using System.Runtime;
using System.ServiceModel.Configuration;
using System.Xml;
using System.Xml.Linq;
[Fx.Tag.XamlVisible(false)]
public sealed class FindCriteriaElement : ConfigurationElement
{
ConfigurationPropertyCollection properties;
[ConfigurationProperty(ConfigurationStrings.Types)]
[SuppressMessage(
FxCop.Category.Configuration,
FxCop.Rule.ConfigurationPropertyNameRule,
Justification = "The configuration name for this element is 'types'.")]
public ContractTypeNameElementCollection ContractTypeNames
{
get
{
return (ContractTypeNameElementCollection)base[ConfigurationStrings.Types];
}
}
[ConfigurationProperty(ConfigurationStrings.Scopes)]
public ScopeElementCollection Scopes
{
get
{
return (ScopeElementCollection)base[ConfigurationStrings.Scopes];
}
}
[ConfigurationProperty(ConfigurationStrings.ScopeMatchBy)]
[SuppressMessage(FxCop.Category.Configuration, FxCop.Rule.ConfigurationValidatorAttributeRule, Justification = "No validation requiered.")]
public Uri ScopeMatchBy
{
get
{
return (Uri)base[ConfigurationStrings.ScopeMatchBy];
}
set
{
if (value == null)
{
throw FxTrace.Exception.ArgumentNull("value");
}
base[ConfigurationStrings.ScopeMatchBy] = value;
}
}
[ConfigurationProperty(ConfigurationStrings.Extensions)]
public XmlElementElementCollection Extensions
{
get
{
return (XmlElementElementCollection)base[ConfigurationStrings.Extensions];
}
}
[ConfigurationProperty(ConfigurationStrings.Duration, DefaultValue = DiscoveryDefaults.DiscoveryOperationDurationString)]
[TypeConverter(typeof(TimeSpanOrInfiniteConverter))]
[ServiceModelTimeSpanValidator(MinValueString = "00:00:00.001")]
public TimeSpan Duration
{
get
{
return (TimeSpan)base[ConfigurationStrings.Duration];
}
set
{
base[ConfigurationStrings.Duration] = value;
}
}
[ConfigurationProperty(ConfigurationStrings.MaxResults, DefaultValue = int.MaxValue)]
[IntegerValidator(MinValue = 1, MaxValue = int.MaxValue)]
public int MaxResults
{
get
{
return (int)base[ConfigurationStrings.MaxResults];
}
set
{
base[ConfigurationStrings.MaxResults] = value;
}
}
protected override ConfigurationPropertyCollection Properties
{
get
{
if (this.properties == null)
{
ConfigurationPropertyCollection properties = new ConfigurationPropertyCollection();
properties.Add(
new ConfigurationProperty(
ConfigurationStrings.Types,
typeof(ContractTypeNameElementCollection),
null,
null,
null,
ConfigurationPropertyOptions.None));
properties.Add(
new ConfigurationProperty(
ConfigurationStrings.ScopeMatchBy,
typeof(Uri),
DiscoveryDefaults.ScopeMatchBy,
null,
null,
ConfigurationPropertyOptions.None));
properties.Add(
new ConfigurationProperty(
ConfigurationStrings.Scopes,
typeof(ScopeElementCollection),
null,
null,
null,
ConfigurationPropertyOptions.None));
properties.Add(
new ConfigurationProperty(
ConfigurationStrings.Extensions,
typeof(XmlElementElementCollection),
null,
null,
null,
ConfigurationPropertyOptions.None));
properties.Add(
new ConfigurationProperty(
ConfigurationStrings.Duration,
typeof(TimeSpan),
TimeSpan.FromSeconds(20),
new TimeSpanOrInfiniteConverter(),
new TimeSpanOrInfiniteValidator(TimeSpan.FromMilliseconds(1), TimeSpan.MaxValue),
ConfigurationPropertyOptions.None));
properties.Add(
new ConfigurationProperty(
ConfigurationStrings.MaxResults,
typeof(int),
int.MaxValue,
null,
new IntegerValidator(1, int.MaxValue),
ConfigurationPropertyOptions.None));
this.properties = properties;
}
return this.properties;
}
}
internal void ApplyConfiguration(FindCriteria findCriteria)
{
foreach (ContractTypeNameElement contractTypeNameElement in this.ContractTypeNames)
{
findCriteria.ContractTypeNames.Add(
new XmlQualifiedName(
contractTypeNameElement.Name,
contractTypeNameElement.Namespace));
}
foreach (ScopeElement scopeElement in this.Scopes)
{
findCriteria.Scopes.Add(scopeElement.Scope);
}
foreach (XmlElementElement xmlElement in this.Extensions)
{
findCriteria.Extensions.Add(XElement.Parse(xmlElement.XmlElement.OuterXml));
}
findCriteria.ScopeMatchBy = this.ScopeMatchBy;
findCriteria.Duration = this.Duration;
findCriteria.MaxResults = this.MaxResults;
}
internal void CopyFrom(FindCriteriaElement source)
{
foreach (ContractTypeNameElement contractTypeNameElement in source.ContractTypeNames)
{
this.ContractTypeNames.Add(contractTypeNameElement);
}
foreach (ScopeElement scopeElement in source.Scopes)
{
this.Scopes.Add(scopeElement);
}
foreach (XmlElementElement extensionElement in source.Extensions)
{
this.Extensions.Add(extensionElement);
}
this.ScopeMatchBy = source.ScopeMatchBy;
this.Duration = source.Duration;
this.MaxResults = source.MaxResults;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace System.Linq.Parallel.Tests
{
public static class OfTypeTests
{
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(2)]
[InlineData(16)]
public static void OfType_Unordered_AllValid(int count)
{
IntegerRangeSet seen = new IntegerRangeSet(0, count);
foreach (int i in UnorderedSources.Default(count).Select(x => (object)x).OfType<int>())
{
seen.Add(i);
}
seen.AssertComplete();
}
[Fact]
[OuterLoop]
public static void OfType_Unordered_AllValid_Longrunning()
{
OfType_Unordered_AllValid(Sources.OuterLoopCount);
}
[Theory]
[MemberData(nameof(Sources.Ranges), new[] { 0, 1, 2, 16 }, MemberType = typeof(Sources))]
public static void OfType_AllValid(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
int seen = 0;
foreach (int i in query.Select(x => (object)x).OfType<int>())
{
Assert.Equal(seen++, i);
}
Assert.Equal(count, seen);
}
[Theory]
[OuterLoop]
[MemberData(nameof(Sources.OuterLoopRanges), MemberType = typeof(Sources))]
public static void OfType_AllValid_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
OfType_AllValid(labeled, count);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(2)]
[InlineData(16)]
public static void OfType_Unordered_AllValid_NotPipelined(int count)
{
IntegerRangeSet seen = new IntegerRangeSet(0, count);
Assert.All(UnorderedSources.Default(count).Select(x => (object)x).OfType<int>().ToList(), x => seen.Add(x));
seen.AssertComplete();
}
[Fact]
[OuterLoop]
public static void OfType_Unordered_AllValid_NotPipelined_Longrunning()
{
OfType_Unordered_AllValid_NotPipelined(Sources.OuterLoopCount);
}
[Theory]
[MemberData(nameof(Sources.Ranges), new[] { 0, 1, 2, 16 }, MemberType = typeof(Sources))]
public static void OfType_AllValid_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
int seen = 0;
Assert.All(query.Select(x => (object)x).OfType<int>().ToList(), x => Assert.Equal(seen++, x));
Assert.Equal(count, seen);
}
[Theory]
[OuterLoop]
[MemberData(nameof(Sources.OuterLoopRanges), MemberType = typeof(Sources))]
public static void OfType_AllValid_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
OfType_AllValid_NotPipelined(labeled, count);
}
[Theory]
[MemberData(nameof(Sources.Ranges), new[] { 0, 1, 2, 16 }, MemberType = typeof(Sources))]
[MemberData(nameof(UnorderedSources.Ranges), new[] { 0, 1, 2, 16 }, MemberType = typeof(Sources))]
public static void OfType_NoneValid(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
Assert.Empty(query.OfType<long>());
}
[Theory]
[OuterLoop]
[MemberData(nameof(Sources.Ranges), new[] { 1024 * 64 }, MemberType = typeof(Sources))]
[MemberData(nameof(UnorderedSources.Ranges), new[] { 1024 * 64 }, MemberType = typeof(UnorderedSources))]
public static void OfType_NoneValid_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
OfType_NoneValid(labeled, count);
}
[Theory]
[MemberData(nameof(Sources.Ranges), new[] { 0, 1, 2, 16 }, MemberType = typeof(Sources))]
[MemberData(nameof(UnorderedSources.Ranges), new[] { 0, 1, 2, 16 }, MemberType = typeof(Sources))]
public static void OfType_NoneValid_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
Assert.Empty(query.OfType<long>().ToList());
}
[Theory]
[OuterLoop]
[MemberData(nameof(Sources.Ranges), new[] { 1024 * 64 }, MemberType = typeof(Sources))]
[MemberData(nameof(UnorderedSources.Ranges), new[] { 1024 * 64 }, MemberType = typeof(UnorderedSources))]
public static void OfType_NoneValid_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
OfType_NoneValid_NotPipelined(labeled, count);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(2)]
[InlineData(16)]
public static void OfType_Unordered_SomeValid(int count)
{
IntegerRangeSet seen = new IntegerRangeSet(count / 2, (count + 1) / 2);
foreach (int i in UnorderedSources.Default(count).Select(x => x >= count / 2 ? (object)x : x.ToString()).OfType<int>())
{
seen.Add(i);
}
seen.AssertComplete();
}
[Fact]
[OuterLoop]
public static void OfType_Unordered_SomeValid_Longrunning()
{
OfType_Unordered_SomeValid(Sources.OuterLoopCount);
}
[Theory]
[MemberData(nameof(Sources.Ranges), new[] { 0, 1, 2, 16 }, MemberType = typeof(Sources))]
public static void OfType_SomeValid(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
int seen = count / 2;
foreach (int i in query.Select(x => x >= count / 2 ? (object)x : x.ToString()).OfType<int>())
{
Assert.Equal(seen++, i);
}
Assert.Equal(count, seen);
}
[Theory]
[OuterLoop]
[MemberData(nameof(Sources.OuterLoopRanges), MemberType = typeof(Sources))]
public static void OfType_SomeValid_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
OfType_SomeValid(labeled, count);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(2)]
[InlineData(16)]
public static void OfType_Unordered_SomeValid_NotPipelined(int count)
{
IntegerRangeSet seen = new IntegerRangeSet(count / 2, (count + 1) / 2);
Assert.All(UnorderedSources.Default(count).Select(x => x >= count / 2 ? (object)x : x.ToString()).OfType<int>().ToList(), x => seen.Add(x));
seen.AssertComplete();
}
[Fact]
[OuterLoop]
public static void OfType_Unordered_SomeValid_NotPipelined_Longrunning()
{
OfType_Unordered_SomeValid_NotPipelined(Sources.OuterLoopCount);
}
[Theory]
[MemberData(nameof(Sources.Ranges), new[] { 0, 1, 2, 16 }, MemberType = typeof(Sources))]
public static void OfType_SomeValid_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
int seen = count / 2;
Assert.All(query.Select(x => x >= count / 2 ? (object)x : x.ToString()).OfType<int>().ToList(), x => Assert.Equal(seen++, x));
Assert.Equal(count, seen);
}
[Theory]
[OuterLoop]
[MemberData(nameof(Sources.OuterLoopRanges), MemberType = typeof(Sources))]
public static void OfType_SomeValid_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
OfType_SomeValid_NotPipelined(labeled, count);
}
[Theory]
[MemberData(nameof(Sources.Ranges), new[] { 0, 1, 2, 16 }, MemberType = typeof(Sources))]
public static void OfType_SomeInvalidNull(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
int seen = count / 2;
Assert.All(query.Select(x => x >= count / 2 ? (object)x : null).OfType<int>(), x => Assert.Equal(seen++, x));
Assert.Equal(count, seen);
}
[Theory]
[OuterLoop]
[MemberData(nameof(Sources.OuterLoopRanges), MemberType = typeof(Sources))]
public static void OfType_SomeInvalidNull_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
OfType_SomeInvalidNull(labeled, count);
}
[Theory]
[MemberData(nameof(Sources.Ranges), new[] { 0, 1, 2, 16 }, MemberType = typeof(Sources))]
public static void OfType_SomeValidNull(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
int nullCount = 0;
int seen = count / 2;
Assert.All(query.Select(x => x >= count / 2 ? (object)(x.ToString()) : (object)(string)null).OfType<string>(),
x =>
{
if (string.IsNullOrEmpty(x)) nullCount++;
else Assert.Equal(seen++, int.Parse(x));
});
Assert.Equal(count, seen);
Assert.Equal(0, nullCount);
}
[Theory]
[OuterLoop]
[MemberData(nameof(Sources.OuterLoopRanges), MemberType = typeof(Sources))]
public static void OfType_SomeValidNull_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
OfType_SomeValidNull(labeled, count);
}
[Theory]
[MemberData(nameof(Sources.Ranges), new[] { 0, 1, 2, 16 }, MemberType = typeof(Sources))]
public static void OfType_SomeNull(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
int nullCount = 0;
int seen = count / 2;
Assert.All(query.Select(x => x >= count / 2 ? (object)(int?)x : (int?)null).OfType<int?>(),
x =>
{
if (!x.HasValue) nullCount++;
else Assert.Equal(seen++, x.Value);
});
Assert.Equal(count, seen);
Assert.Equal(0, nullCount);
}
[Theory]
[OuterLoop]
[MemberData(nameof(Sources.OuterLoopRanges), MemberType = typeof(Sources))]
public static void OfType_SomeNull_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
OfType_SomeNull(labeled, count);
}
[Fact]
public static void OfType_ArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((ParallelQuery<object>)null).OfType<int>());
}
}
}
| |
using System;
using System.Collections;
using Drawing = System.Drawing;
using Drawing2D = System.Drawing.Drawing2D;
using WinForms = System.Windows.Forms;
using System.Runtime.InteropServices;
// 4/6/03
public class TreeViewExEventArgs
{
private TreeNodeEx node;
public TreeNodeEx Node
{
get { return node; }
}
public TreeViewExEventArgs(TreeNodeEx node)
{
this.node = node;
}
}
public delegate void TreeViewExEventHandler(object sender, TreeViewExEventArgs args);
/// <summary>
/// Contact tree view.
/// </summary>
public class TreeViewEx : WinForms.Control
{
private TreeNodeCollectionEx nodes;
private TreeNodeEx mouseOverNode = null, selectedNode = null, dragOverNode = null;
private int widthIndent = 5;
private int heightIndent = 2;
private WinForms.ImageList imageList = new WinForms.ImageList();
private WinForms.VScrollBar vScrollBar;
private Drawing2D.Matrix viewMatrix = new Drawing2D.Matrix();
private WinForms.ToolTip toolTip;
private int updateCount = 0;
[DllImport("user32.dll")]
private static extern void SendMessage(IntPtr hwnd, int msg, int wparam, int lparam);
#region Public fields
public Drawing.Brush TextBrush = Drawing.Brushes.Black;
public Drawing.Brush TextMouseOverBrush = Drawing.Brushes.DarkBlue;
public Drawing.Brush TextSelectedBrush = Drawing.Brushes.Red;
public bool ChangeColorOnMouseOver = true;
public bool ChangeColorOnSelected = false;
public bool AllowMovementOfNodes = false;
public bool ShowPlusMinus = false;
#endregion
public event TreeViewExEventHandler Expand, Collapse, NodeMove;
internal void ExecuteExpand(TreeNodeEx node)
{
if (this.Expand != null)
this.Expand(this, new TreeViewExEventArgs(node));
}
internal void ExecuteCollapse(TreeNodeEx node)
{
if (this.Collapse != null)
this.Collapse(this, new TreeViewExEventArgs(node));
if (!this.vScrollBar.Visible)
{
this.Invalidate();
this.Update();
}
}
#region Properties
public int WidthIndent
{
get { return widthIndent; }
set { widthIndent = value; }
}
public int HeightIndent
{
get { return heightIndent; }
set { heightIndent = value; }
}
public WinForms.ImageList ImageList
{
get { return imageList; }
}
public TreeNodeCollectionEx Nodes
{
get { return nodes; }
}
#endregion
public TreeViewEx()
{
this.nodes = new TreeNodeCollectionEx(this);
// initialise scroll bar
this.vScrollBar = new WinForms.VScrollBar();
this.vScrollBar.Minimum = this.vScrollBar.Maximum = 0;
this.vScrollBar.Dock = WinForms.DockStyle.Right;
this.vScrollBar.Visible = false;
this.vScrollBar.Scroll += new WinForms.ScrollEventHandler(OnVerticalScroll);
this.Controls.Add( vScrollBar );
// initialise tool tip
this.toolTip = new WinForms.ToolTip();
this.toolTip.Active = true;
this.AllowDrop = this.AllowMovementOfNodes;
this.SetStyle(WinForms.ControlStyles.DoubleBuffer | WinForms.ControlStyles.UserPaint |
WinForms.ControlStyles.AllPaintingInWmPaint, true);
this.BackColor = Drawing.Color.White;
}
protected override void OnResize(EventArgs e)
{
this.Invalidate();
this.Update();
base.OnResize(e);
}
#region Scrolling methods
private void OnVerticalScroll(object sender, WinForms.ScrollEventArgs args)
{
this.viewMatrix.Reset();
this.viewMatrix.Translate(0.0f, -args.NewValue);
this.Invalidate();
this.Update();
}
#endregion
#region Node methods
public void ExpandAll()
{
foreach (TreeNodeEx node in this.Nodes)
{
node.Expand();
ExpandChildren(node);
}
}
private void ExpandChildren(TreeNodeEx node)
{
foreach (TreeNodeEx childNode in node.Nodes)
{
childNode.Expand();
ExpandChildren(childNode);
}
}
public void CollapseAll()
{
foreach (TreeNodeEx node in this.Nodes)
{
node.Collapse();
CollapseChildren(node);
}
}
private void CollapseChildren(TreeNodeEx node)
{
foreach (TreeNodeEx childNode in node.Nodes)
{
childNode.Collapse();
CollapseChildren(childNode);
}
}
#endregion
#region Drag / drop methods
protected override void OnDragDrop(WinForms.DragEventArgs args)
{
if (AllowMovementOfNodes)
{
TreeNodeEx node = (TreeNodeEx)args.Data.GetData(typeof(TreeNodeEx));
if (node != dragOverNode)
{
// drop the node into the node its over
if (this.dragOverNode.Parent != null)
{
node.Remove();
this.dragOverNode.Parent.Nodes.Insert(this.dragOverNode.Parent.Nodes.IndexOf(dragOverNode), node);
}
else
{
node.Remove();
this.Nodes.Insert(this.Nodes.IndexOf(dragOverNode), node);
}
if (this.NodeMove != null)
this.NodeMove(this, new TreeViewExEventArgs(node));
this.Invalidate();
this.Update();
}
this.dragOverNode = null;
}
base.OnDragDrop(args);
}
protected override void OnDragEnter(WinForms.DragEventArgs args)
{
if (AllowMovementOfNodes)
{
args.Effect = (args.Data.GetDataPresent(typeof(TreeNodeEx))) ?
WinForms.DragDropEffects.Link : WinForms.DragDropEffects.None;
}
base.OnDragEnter(args);
}
protected override void OnDragLeave(EventArgs args)
{
if (AllowMovementOfNodes)
{
this.dragOverNode = null;
}
base.OnDragLeave(args);
}
protected override void OnDragOver(WinForms.DragEventArgs args)
{
if (AllowMovementOfNodes)
{
TreeNodeEx draggedNode = (TreeNodeEx)args.Data.GetData(typeof(TreeNodeEx));
// get node which the mouse is over
if (dragOverNode != null)
{
this.Invalidate( new Drawing.Rectangle(
dragOverNode.Location.X,
dragOverNode.Location.Y - this.HeightIndent,
this.Width - dragOverNode.Location.X,
dragOverNode.Size.Height + this.HeightIndent)
);
}
TreeNodeEx draggedOverNode = (TreeNodeEx)this.GetNodeAt( this.PointToClient( WinForms.Control.MousePosition ) );
if (draggedNode.IsParent(draggedOverNode))
{
this.dragOverNode = null;
args.Effect = WinForms.DragDropEffects.None;
}
else
{
this.dragOverNode = draggedOverNode;
if (dragOverNode != null)
{
this.Invalidate( new Drawing.Rectangle(
dragOverNode.Location.X,
dragOverNode.Location.Y - this.HeightIndent,
this.Width - dragOverNode.Location.X,
dragOverNode.Size.Height + this.HeightIndent)
);
}
args.Effect = WinForms.DragDropEffects.Link;
}
this.Update();
}
base.OnDragOver(args);
}
#endregion
#region Mouse movement methods
protected override void OnMouseMove(WinForms.MouseEventArgs args)
{
TreeNodeEx node = this.GetNodeAt(new Drawing.Point(args.X, args.Y));
if (this.ChangeColorOnMouseOver)
{
if (mouseOverNode != null)
mouseOverNode.Invalidate();
if (node != null && node != mouseOverNode)
node.Invalidate();
else
mouseOverNode = null;
mouseOverNode = node;
this.Update();
}
if (node != null)
this.toolTip.SetToolTip(this, node.ToolTipText);
base.OnMouseMove(args);
}
protected override void OnMouseDown(WinForms.MouseEventArgs args)
{
TreeNodeEx node = GetNodeAt(new Drawing.Point(args.X, args.Y));
switch (args.Button)
{
case WinForms.MouseButtons.Left:
if (
(node != null // clicked on image without showplusminus
&& !this.imageList.Images.Empty && !this.ShowPlusMinus
&& args.X - node.Location.X < this.imageList.ImageSize.Width)
|| // or clicked on the plus/minus
(node != null
&& this.ShowPlusMinus
&& args.X - node.Location.X < 15))
{
node.Toggle();
}
else
{
// clicked on text
if (this.selectedNode != null)
this.selectedNode.Invalidate();
this.selectedNode = node;
// then redraw area
if (ChangeColorOnSelected && this.selectedNode != null)
{
selectedNode.Invalidate();
this.selectedNode.ExecuteSelected(new EventArgs());
this.Update();
}
}
if (node != null && this.AllowMovementOfNodes)
this.DoDragDrop(node, WinForms.DragDropEffects.Link);
break;
case WinForms.MouseButtons.Right:
// right button, show context menu
if (node.ContextMenu != null)
{
node.ContextMenu.Show(this, new Drawing.Point(args.X, args.Y));
}
break;
}
base.OnMouseDown(args);
}
protected override void OnMouseLeave(EventArgs args)
{
this.toolTip.SetToolTip(this, string.Empty);
if (this.mouseOverNode != null)
{
this.mouseOverNode.Invalidate();
this.mouseOverNode = null;
this.Update();
}
base.OnMouseLeave(args);
}
#endregion
#region Rendering methods
private delegate void UpdateHandler();
public void BeginUpdate()
{
if (updateCount++ == 0)
this.Invoke(new UpdateHandler(pBeginUpdate));
}
public void EndUpdate()
{
if (updateCount > 0)
{
if (--updateCount == 0)
this.Invoke(new UpdateHandler(pEndUpdate));
}
}
private void pBeginUpdate()
{
SendMessage(this.Handle, 11 /* WM_SETREDRAW */, 0, 0);
}
private void pEndUpdate()
{
SendMessage(this.Handle, 11 /* WM_SETREDRAW */, -1, 0);
this.Invalidate();
this.Update();
}
protected override void OnPaint(WinForms.PaintEventArgs args)
{
Drawing.Graphics graphics = args.Graphics;
graphics.Clear(this.BackColor);
this.DrawNodes(graphics);
base.OnPaint(args);
}
private void DrawNodes(Drawing.Graphics graphics)
{
Drawing2D.Matrix matrix = viewMatrix.Clone();
int totalHeight = 0;
foreach (TreeNodeEx treeNode in this.nodes)
{
DrawNode(treeNode, graphics, matrix, ref totalHeight);
matrix.Translate(0.0f, this.HeightIndent + this.Font.Height);
}
this.vScrollBar.Visible = (totalHeight > this.Height);
if (this.vScrollBar.Visible)
this.vScrollBar.Maximum = totalHeight - this.Height + this.HeightIndent + this.Font.Height;
else
{
this.viewMatrix.Reset();
this.vScrollBar.Value = 0;
}
}
private void DrawNode(TreeNodeEx node, Drawing.Graphics graphics, Drawing2D.Matrix matrix, ref int totalHeight)
{
if (node.Visible)
{
totalHeight += this.HeightIndent + this.Font.Height;
// transform coordinates
Drawing.PointF[] p = new Drawing.PointF[1];
p[0] = new Drawing.PointF(0.0f, 0.0f);
matrix.TransformPoints(p);
// calculate location and size
node.Location = new Drawing.Point((int)p[0].X, (int)p[0].Y);
node.Size = new Drawing.Size(this.Width, this.Font.Height);
if (dragOverNode == node)
{
// draw drag over line
graphics.DrawLine(Drawing.Pens.Black, node.Location.X, node.Location.Y, this.Width, node.Location.Y);
}
// draw plus/minus
if (this.ShowPlusMinus)
{
if (node.Nodes.Count > 0)
{
graphics.DrawRectangle(Drawing.Pens.Black, (int)p[0].X + 2, (int)p[0].Y + 2, 8, 8);
if (!node.Expanded)
{
// line across
graphics.DrawLine(Drawing.Pens.Black, (int)p[0].X + 4, (int)p[0].Y + 6, (int)p[0].X + 8, (int)p[0].Y + 6);
// down
graphics.DrawLine(Drawing.Pens.Black, (int)p[0].X + 6, (int)p[0].Y + 4, (int)p[0].X + 6, (int)p[0].Y + 8);
}
else
{
graphics.DrawLine(Drawing.Pens.Black, (int)p[0].X + 4, (int)p[0].Y + 6, (int)p[0].X + 8, (int)p[0].Y + 6);
}
}
p[0].X += 12;
}
// draw node image
if (!this.imageList.Images.Empty)
{
this.imageList.Draw(graphics, new Drawing.Point((int)p[0].X, (int)p[0].Y), (node.Expanded) ? node.ExpandedImageIndex : node.CollapsedImageIndex);
p[0].X += this.imageList.ImageSize.Width;
}
// draw node text
Drawing.Brush textBrush;
if (node == this.selectedNode && this.ChangeColorOnSelected)
textBrush = this.TextSelectedBrush;
else if (node == this.mouseOverNode && this.ChangeColorOnMouseOver)
textBrush = this.TextMouseOverBrush;
else
textBrush = node.TextBrush;
Drawing.Font font = new Drawing.Font(this.Font.FontFamily.Name, this.Font.Size, node.FontStyle);
graphics.DrawString(node.Text, font, textBrush, p[0]);
// go through children
if (node.Expanded && node.Nodes.Count > 0)
{
matrix.Translate((float)this.WidthIndent, 0.0f);
foreach (TreeNodeEx treeNode in node.Nodes)
{
matrix.Translate(0.0f, this.HeightIndent + this.Font.Height);
DrawNode(treeNode, graphics, matrix, ref totalHeight);
}
matrix.Translate(-(float)this.WidthIndent, 0.0f);
}
}
else
matrix.Translate(0.0f, -((float)this.HeightIndent + this.Font.Height));
}
#endregion
#region Node position determination methods
public TreeNodeEx GetNodeAt(Drawing.Point p)
{
int childHeight = (int)this.viewMatrix.OffsetY;
return FindChildAtPoint(this.nodes, ref childHeight, p);
}
private TreeNodeEx FindChildAtPoint(TreeNodeCollectionEx nodes, ref int currentPosition, Drawing.Point p)
{
foreach (TreeNodeEx node in nodes)
{
if (node.Visible)
{
currentPosition += this.HeightIndent + this.Font.Height;
if (currentPosition > p.Y)
return node;
if (node.Expanded)
{
TreeNodeEx node2 = FindChildAtPoint(node.Nodes, ref currentPosition, p);
if (node2 != null)
return node2;
}
}
}
return null;
}
#endregion
}
| |
namespace Einstein.PowerShell.LINQ
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
public static class PSEnumerable {
private static Func<object, bool> CreatePredicate(ScriptBlock predicate) {
if (predicate != null) {
return x => {
var context = new List<PSVariable>() {
new PSVariable("_", x),
new PSVariable("this", x)
};
return LanguagePrimitives.IsTrue(predicate.InvokeWithContext(null, context, x));
};
}
else {
return new Func<object, bool>(x => true);
}
}
private static Func<object, object> CreateSelector(ScriptBlock selector) {
if (selector != null) {
return x => {
var context = new List<PSVariable>() {
new PSVariable("_", x),
new PSVariable("this", x)
};
var values = selector.InvokeWithContext(null, context, x);
if (values.Count == 1) {
return values[0];
}
else {
var array = new PSObject[values.Count];
values.CopyTo(array,0);
return array;
}
};
}
else {
return new Func<object,object>(x => x);
}
}
private static T ConvertTo<T>(object value) {
return (T)LanguagePrimitives.ConvertTo(value, typeof(T));
}
private static object ConvertTo(object value, Type type) {
return LanguagePrimitives.ConvertTo(value, type);
}
public static bool All(IEnumerable<object> items, ScriptBlock predicate) {
return Enumerable.All( items, CreatePredicate(predicate) );
}
public static bool Any(IEnumerable<object> items, ScriptBlock predicate) {
return Enumerable.Any( items, CreatePredicate(predicate) );
}
public static int Count(IEnumerable<object> items) {
return Count(items, null);
}
public static int Count(IEnumerable<object> items, ScriptBlock predicate) {
if (predicate != null) {
return items.Count( CreatePredicate(predicate) );
}
else {
return items.Count();
}
}
public static object First(IEnumerable<object> items) {
return First(items, null);
}
public static object First(IEnumerable<object> items, ScriptBlock predicate) {
if (predicate != null) {
return items.FirstOrDefault( CreatePredicate(predicate) );
}
else {
return items.FirstOrDefault();
}
}
public static object Last(IEnumerable<object> items) {
return Last(items, null);
}
public static object Last(IEnumerable<object> items, ScriptBlock predicate) {
if (predicate != null) {
return items.LastOrDefault( CreatePredicate(predicate) );
}
else {
return items.LastOrDefault();
}
}
public static IEnumerable<object> Reverse(IEnumerable<object> items) {
return items.Reverse();
}
public static IEnumerable<object> Take(IEnumerable<object> items, int count) {
return items.Take(count);
}
public static IEnumerable<object> TakeWhile(IEnumerable<object> items, ScriptBlock predicate) {
return items.TakeWhile( CreatePredicate(predicate) );
}
public static IEnumerable<object> Skip(IEnumerable<object> items, int count) {
return items.Skip(count);
}
public static IEnumerable<object> SkipWhile(IEnumerable<object> items, ScriptBlock predicate) {
return items.SkipWhile( CreatePredicate(predicate) );
}
public static int IndexOf(IEnumerable<object> items, ScriptBlock predicate) {
var fPredicate = CreatePredicate(predicate);
int i = 0;
foreach (var x in items) {
if (fPredicate(x)) {
return i;
}
i++;
}
return -1;
}
public static int IndexOf(IEnumerable<object> items, object value) {
int i = 0;
foreach (var x in items) {
if (LanguagePrimitives.Equals(x, value, true) ) {
return i;
}
i++;
}
return -1;
}
public static object Single(IEnumerable<object> items) {
return Single(items, null);
}
public static object Single(IEnumerable<object> items, ScriptBlock predicate) {
if (predicate != null) {
return items.SingleOrDefault(CreatePredicate(predicate));
}
else {
return items.SingleOrDefault();
}
}
public static decimal? Average(IEnumerable<object> items, ScriptBlock selector) {
var fSelector = CreateSelector(selector);
return items.Average( x => ConvertTo<decimal?>(fSelector(x)) );
}
public static decimal? Sum(IEnumerable<object> items, ScriptBlock selector) {
var fSelector = CreateSelector(selector);
return items.Sum( x => ConvertTo<decimal?>(fSelector(x)) );
}
public static decimal? Min(IEnumerable<object> items, ScriptBlock selector) {
var fSelector = CreateSelector(selector);
return items.Min( x => ConvertTo<decimal?>(fSelector(x)) );
}
public static decimal? Max(IEnumerable<object> items, ScriptBlock selector) {
var fSelector = CreateSelector(selector);
return items.Max( x => ConvertTo<decimal?>(fSelector(x)) );
}
public static IEnumerable<object> Concat(IEnumerable<object> items, IEnumerable<object> other) {
return items.Concat(other);
}
public static IEnumerable<object> Except(IEnumerable<object> items, IEnumerable<object> other, bool? ignoreCase) {
var comparer = default(IEqualityComparer<object>);
if (ignoreCase.HasValue) {
comparer = new Einstein.PowerShell.LINQ.PSObjectComparer(ignoreCase.Value);
}
return items.Except(other, comparer);
}
public static IEnumerable<object> Union(IEnumerable<object> items, IEnumerable<object> other, bool? ignoreCase) {
var comparer = default(IEqualityComparer<object>);
if (ignoreCase.HasValue) {
comparer = new Einstein.PowerShell.LINQ.PSObjectComparer(ignoreCase.Value);
}
return items.Union(other, comparer);
}
public static IEnumerable<object> Intersect(IEnumerable<object> items, IEnumerable<object> other, bool? ignoreCase) {
var comparer = default(IEqualityComparer<object>);
if (ignoreCase.HasValue) {
comparer = new Einstein.PowerShell.LINQ.PSObjectComparer(ignoreCase.Value);
}
return items.Intersect(other, comparer);
}
public static bool SequenceEquals(IEnumerable<object> items, IEnumerable<object> other, bool? ignoreCase) {
var comparer = default(IEqualityComparer<object>);
if (ignoreCase.HasValue) {
comparer = new Einstein.PowerShell.LINQ.PSObjectComparer(ignoreCase.Value);
}
return items.SequenceEqual(other, comparer);
}
public static bool SetEquals(IEnumerable<object> items, IEnumerable<object> other, bool? ignoreCase) {
var comparer = default(IEqualityComparer<object>);
if (ignoreCase.HasValue) {
comparer = new Einstein.PowerShell.LINQ.PSObjectComparer(ignoreCase.Value);
}
var hashSet = new HashSet<object>(items, comparer);
return hashSet.SetEquals(other);
}
public static Hashtable ToDictionary(IEnumerable<object> items, ScriptBlock keySelector, ScriptBlock valueSelector = null, bool force = false, bool? ignoreCase = null) {
var keyFunction = CreateSelector(keySelector);
var valFunction = CreateSelector(valueSelector);
var comparer = default(IEqualityComparer);
if ( ignoreCase.HasValue ) {
comparer = new Einstein.PowerShell.LINQ.PSObjectComparer( ignoreCase.Value );
}
var table = new Hashtable(comparer);
foreach (var item in items) {
var key = keyFunction(item);
var val = valFunction(item);
if (force) {
table[key] = val;
}
else {
table.Add(key, val);
}
}
return table;
}
public static ISet<object> ToSet( IEnumerable<object> items, ScriptBlock selector, bool? ignoreCase )
{
var selectorFunc = CreateSelector(selector);
var comparer = default(IEqualityComparer<object>);
if ( ignoreCase.HasValue ) {
comparer = new Einstein.PowerShell.LINQ.PSObjectComparer( ignoreCase.Value );
}
return new HashSet<object>( items.Select( selectorFunc ), comparer );
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace PuppyApp.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using Mono.Addins;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
// using log4net;
// using System.Reflection;
/*****************************************************
*
* WorldCommModule
*
*
* Holding place for world comms - basically llListen
* function implementation.
*
* lLListen(integer channel, string name, key id, string msg)
* The name, id, and msg arguments specify the filtering
* criteria. You can pass the empty string
* (or NULL_KEY for id) for these to set a completely
* open filter; this causes the listen() event handler to be
* invoked for all chat on the channel. To listen only
* for chat spoken by a specific object or avatar,
* specify the name and/or id arguments. To listen
* only for a specific command, specify the
* (case-sensitive) msg argument. If msg is not empty,
* listener will only hear strings which are exactly equal
* to msg. You can also use all the arguments to establish
* the most restrictive filtering criteria.
*
* It might be useful for each listener to maintain a message
* digest, with a list of recent messages by UUID. This can
* be used to prevent in-world repeater loops. However, the
* linden functions do not have this capability, so for now
* thats the way it works.
* Instead it blocks messages originating from the same prim.
* (not Object!)
*
* For LSL compliance, note the following:
* (Tested again 1.21.1 on May 2, 2008)
* 1. 'id' has to be parsed into a UUID. None-UUID keys are
* to be replaced by the ZeroID key. (Well, TryParse does
* that for us.
* 2. Setting up an listen event from the same script, with the
* same filter settings (including step 1), returns the same
* handle as the original filter.
* 3. (TODO) handles should be script-local. Starting from 1.
* Might be actually easier to map the global handle into
* script-local handle in the ScriptEngine. Not sure if its
* worth the effort tho.
*
* **************************************************/
using System.Threading;
namespace OpenSim.Region.CoreModules.Scripting.WorldComm
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "WorldCommModule")]
public class WorldCommModule : IWorldComm, INonSharedRegionModule
{
// private static readonly ILog m_log =
// LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private ListenerManager m_listenerManager;
private ThreadedClasses.NonblockingQueue<ListenerInfo> m_pending;
private Scene m_scene;
private int m_whisperdistance = 10;
private int m_saydistance = 20;
private int m_shoutdistance = 100;
#region INonSharedRegionModule Members
public void Initialise(IConfigSource config)
{
// wrap this in a try block so that defaults will work if
// the config file doesn't specify otherwise.
int maxlisteners = 1000;
int maxhandles = 64;
try
{
m_whisperdistance = config.Configs["Chat"].GetInt(
"whisper_distance", m_whisperdistance);
m_saydistance = config.Configs["Chat"].GetInt(
"say_distance", m_saydistance);
m_shoutdistance = config.Configs["Chat"].GetInt(
"shout_distance", m_shoutdistance);
maxlisteners = config.Configs["LL-Functions"].GetInt(
"max_listens_per_region", maxlisteners);
maxhandles = config.Configs["LL-Functions"].GetInt(
"max_listens_per_script", maxhandles);
}
catch (Exception)
{
}
if (maxlisteners < 1) maxlisteners = int.MaxValue;
if (maxhandles < 1) maxhandles = int.MaxValue;
m_listenerManager = new ListenerManager(maxlisteners, maxhandles);
m_pending = new ThreadedClasses.NonblockingQueue<ListenerInfo>();
}
public void PostInitialise()
{
}
public void AddRegion(Scene scene)
{
m_scene = scene;
m_scene.RegisterModuleInterface<IWorldComm>(this);
m_scene.EventManager.OnChatFromClient += DeliverClientMessage;
m_scene.EventManager.OnChatBroadcast += DeliverClientMessage;
}
public void RegionLoaded(Scene scene) { }
public void RemoveRegion(Scene scene)
{
if (scene != m_scene)
return;
m_scene.UnregisterModuleInterface<IWorldComm>(this);
m_scene.EventManager.OnChatBroadcast -= DeliverClientMessage;
m_scene.EventManager.OnChatBroadcast -= DeliverClientMessage;
}
public void Close()
{
}
public string Name
{
get { return "WorldCommModule"; }
}
public Type ReplaceableInterface { get { return null; } }
#endregion
#region IWorldComm Members
public int ListenerCount
{
get
{
return m_listenerManager.ListenerCount;
}
}
/// <summary>
/// Create a listen event callback with the specified filters.
/// The parameters localID,itemID are needed to uniquely identify
/// the script during 'peek' time. Parameter hostID is needed to
/// determine the position of the script.
/// </summary>
/// <param name="localID">localID of the script engine</param>
/// <param name="itemID">UUID of the script engine</param>
/// <param name="hostID">UUID of the SceneObjectPart</param>
/// <param name="channel">channel to listen on</param>
/// <param name="name">name to filter on</param>
/// <param name="id">
/// key to filter on (user given, could be totally faked)
/// </param>
/// <param name="msg">msg to filter on</param>
/// <returns>number of the scripts handle</returns>
public int Listen(uint localID, UUID itemID, UUID hostID, int channel,
string name, UUID id, string msg)
{
return m_listenerManager.AddListener(localID, itemID, hostID,
channel, name, id, msg);
}
/// <summary>
/// Create a listen event callback with the specified filters.
/// The parameters localID,itemID are needed to uniquely identify
/// the script during 'peek' time. Parameter hostID is needed to
/// determine the position of the script.
/// </summary>
/// <param name="localID">localID of the script engine</param>
/// <param name="itemID">UUID of the script engine</param>
/// <param name="hostID">UUID of the SceneObjectPart</param>
/// <param name="channel">channel to listen on</param>
/// <param name="name">name to filter on</param>
/// <param name="id">
/// key to filter on (user given, could be totally faked)
/// </param>
/// <param name="msg">msg to filter on</param>
/// <param name="regexBitfield">
/// Bitfield indicating which strings should be processed as regex.
/// </param>
/// <returns>number of the scripts handle</returns>
public int Listen(uint localID, UUID itemID, UUID hostID, int channel,
string name, UUID id, string msg, int regexBitfield)
{
return m_listenerManager.AddListener(localID, itemID, hostID,
channel, name, id, msg, regexBitfield);
}
/// <summary>
/// Sets the listen event with handle as active (active = TRUE) or inactive (active = FALSE).
/// The handle used is returned from Listen()
/// </summary>
/// <param name="itemID">UUID of the script engine</param>
/// <param name="handle">handle returned by Listen()</param>
/// <param name="active">temp. activate or deactivate the Listen()</param>
public void ListenControl(UUID itemID, int handle, int active)
{
if (active == 1)
m_listenerManager.Activate(itemID, handle);
else if (active == 0)
m_listenerManager.Deactivate(itemID, handle);
}
/// <summary>
/// Removes the listen event callback with handle
/// </summary>
/// <param name="itemID">UUID of the script engine</param>
/// <param name="handle">handle returned by Listen()</param>
public void ListenRemove(UUID itemID, int handle)
{
m_listenerManager.Remove(itemID, handle);
}
/// <summary>
/// Removes all listen event callbacks for the given itemID
/// (script engine)
/// </summary>
/// <param name="itemID">UUID of the script engine</param>
public void DeleteListener(UUID itemID)
{
m_listenerManager.DeleteListener(itemID);
}
protected static Vector3 CenterOfRegion = new Vector3(128, 128, 20);
public void DeliverMessage(ChatTypeEnum type, int channel, string name, UUID id, string msg)
{
Vector3 position;
SceneObjectPart source;
ScenePresence avatar;
if ((source = m_scene.GetSceneObjectPart(id)) != null)
position = source.AbsolutePosition;
else if ((avatar = m_scene.GetScenePresence(id)) != null)
position = avatar.AbsolutePosition;
else if (ChatTypeEnum.Region == type)
position = CenterOfRegion;
else
return;
DeliverMessage(type, channel, name, id, msg, position);
}
public const int DEBUG_CHANNEL = 0x7FFFFFFF;
/// <summary>
/// This method scans over the objects which registered an interest in listen callbacks.
/// For everyone it finds, it checks if it fits the given filter. If it does, then
/// enqueue the message for delivery to the objects listen event handler.
/// The enqueued ListenerInfo no longer has filter values, but the actually trigged values.
/// Objects that do an llSay have their messages delivered here and for nearby avatars,
/// the OnChatFromClient event is used.
/// </summary>
/// <param name="type">type of delvery (whisper,say,shout or regionwide)</param>
/// <param name="channel">channel to sent on</param>
/// <param name="name">name of sender (object or avatar)</param>
/// <param name="id">key of sender (object or avatar)</param>
/// <param name="msg">msg to sent</param>
public void DeliverMessage(ChatTypeEnum type, int channel,
string name, UUID id, string msg, Vector3 position)
{
// m_log.DebugFormat("[WorldComm] got[2] type {0}, channel {1}, name {2}, id {3}, msg {4}",
// type, channel, name, id, msg);
// Determine which listen event filters match the given set of arguments, this results
// in a limited set of listeners, each belonging a host. If the host is in range, add them
// to the pending queue.
foreach (ListenerInfo li
in m_listenerManager.GetListeners(UUID.Zero, channel,
name, id, msg))
{
// Dont process if this message is from yourself!
if (li.GetHostID().Equals(id))
continue;
SceneObjectPart sPart = m_scene.GetSceneObjectPart(
li.GetHostID());
if (sPart == null)
continue;
double dis = Util.GetDistanceTo(sPart.AbsolutePosition,
position);
if (channel == DEBUG_CHANNEL)
{
msg = "At region " + m_scene.Name + ":\n" + msg;
}
switch (type)
{
case ChatTypeEnum.Whisper:
if (dis < m_whisperdistance)
QueueMessage(new ListenerInfo(li, name, id, msg));
break;
case ChatTypeEnum.Say:
if (dis < m_saydistance)
QueueMessage(new ListenerInfo(li, name, id, msg));
break;
case ChatTypeEnum.Shout:
if (dis < m_shoutdistance)
QueueMessage(new ListenerInfo(li, name, id, msg));
break;
case ChatTypeEnum.Region:
QueueMessage(new ListenerInfo(li, name, id, msg));
break;
}
}
}
/// <summary>
/// Delivers the message to a scene entity.
/// </summary>
/// <param name='target'>
/// Target.
/// </param>
/// <param name='channel'>
/// Channel.
/// </param>
/// <param name='name'>
/// Name.
/// </param>
/// <param name='id'>
/// Identifier.
/// </param>
/// <param name='msg'>
/// Message.
/// </param>
public void DeliverMessageTo(UUID target, int channel, Vector3 pos,
string name, UUID id, string msg)
{
// Is id an avatar?
ScenePresence sp = m_scene.GetScenePresence(target);
if (sp != null)
{
// ignore if a child agent this is restricted to inside one
// region
if (sp.IsChildAgent)
return;
// Send message to the avatar.
// Channel zero only goes to the avatar
// non zero channel messages only go to the attachments
if (channel != 0)
{
List<SceneObjectGroup> attachments = sp.GetAttachments();
if (attachments.Count == 0)
return;
// Get uuid of attachments
List<UUID> targets = new List<UUID>();
foreach (SceneObjectGroup sog in attachments)
{
if (!sog.IsDeleted)
targets.Add(sog.UUID);
}
// Need to check each attachment
foreach (ListenerInfo li
in m_listenerManager.GetListeners(UUID.Zero,
channel, name, id, msg))
{
if (li.GetHostID().Equals(id))
continue;
if (m_scene.GetSceneObjectPart(
li.GetHostID()) == null)
{
continue;
}
if (channel == DEBUG_CHANNEL)
{
msg = "At region " + m_scene.Name + ":\n" + msg;
}
if (targets.Contains(li.GetHostID()))
QueueMessage(new ListenerInfo(li, name, id, msg));
}
}
return;
}
// No avatar found so look for an object
foreach (ListenerInfo li
in m_listenerManager.GetListeners(UUID.Zero, channel,
name, id, msg))
{
// Dont process if this message is from yourself!
if (li.GetHostID().Equals(id))
continue;
SceneObjectPart sPart = m_scene.GetSceneObjectPart(
li.GetHostID());
if (sPart == null)
continue;
if (li.GetHostID().Equals(target))
{
QueueMessage(new ListenerInfo(li, name, id, msg));
break;
}
}
return;
}
protected void QueueMessage(ListenerInfo li)
{
m_pending.Enqueue(li);
}
/// <summary>
/// Are there any listen events ready to be dispatched?
/// </summary>
/// <returns>boolean indication</returns>
public bool HasMessages()
{
return (m_pending.Count > 0);
}
/// <summary>
/// Pop the first availlable listen event from the queue
/// </summary>
/// <returns>ListenerInfo with filter filled in</returns>
public IWorldCommListenerInfo GetNextMessage()
{
return m_pending.Dequeue();
}
#endregion
/********************************************************************
*
* Listener Stuff
*
* *****************************************************************/
private void DeliverClientMessage(Object sender, OSChatMessage e)
{
if (null != e.Sender)
{
DeliverMessage(e.Type, e.Channel, e.Sender.Name,
e.Sender.AgentId, e.Message, e.Position);
}
else
{
DeliverMessage(e.Type, e.Channel, e.From, UUID.Zero,
e.Message, e.Position);
}
}
public Object[] GetSerializationData(UUID itemID)
{
return m_listenerManager.GetSerializationData(itemID);
}
public void CreateFromData(uint localID, UUID itemID, UUID hostID,
Object[] data)
{
m_listenerManager.AddFromData(localID, itemID, hostID, data);
}
}
public class ListenerManager
{
private ThreadedClasses.RwLockedDictionary<int, ThreadedClasses.RwLockedList<ListenerInfo>> m_listeners =
new ThreadedClasses.RwLockedDictionary<int, ThreadedClasses.RwLockedList<ListenerInfo>>();
private int m_maxlisteners;
private int m_maxhandles;
private int m_curlisteners;
/// <summary>
/// Total number of listeners
/// </summary>
public int ListenerCount
{
get
{
return m_listeners.Count;
}
}
public ListenerManager(int maxlisteners, int maxhandles)
{
m_maxlisteners = maxlisteners;
m_maxhandles = maxhandles;
m_curlisteners = 0;
}
public int AddListener(uint localID, UUID itemID, UUID hostID,
int channel, string name, UUID id, string msg)
{
return AddListener(localID, itemID, hostID, channel, name, id,
msg, 0);
}
public int AddListener(uint localID, UUID itemID, UUID hostID,
int channel, string name, UUID id, string msg,
int regexBitfield)
{
// do we already have a match on this particular filter event?
List<ListenerInfo> coll = GetListeners(itemID, channel, name, id,
msg);
if (coll.Count > 0)
{
// special case, called with same filter settings, return same
// handle (2008-05-02, tested on 1.21.1 server, still holds)
return coll[0].GetHandle();
}
if (m_curlisteners < m_maxlisteners)
{
lock(m_listeners) /* serialize handle creation here */
{
int newHandle = GetNewHandle(itemID);
if (newHandle > 0)
{
ListenerInfo li = new ListenerInfo(newHandle, localID,
itemID, hostID, channel, name, id, msg,
regexBitfield);
ThreadedClasses.RwLockedList<ListenerInfo> listeners =
m_listeners.GetOrAddIfNotExists(channel, delegate()
{
return new ThreadedClasses.RwLockedList<ListenerInfo>();
});
listeners.Add(li);
Interlocked.Increment(ref m_curlisteners);
return newHandle;
}
}
}
return -1;
}
public void Remove(UUID itemID, int handle)
{
/* standard foreach is implemented in RwLockedDictionary to make a copy first */
foreach (KeyValuePair<int, ThreadedClasses.RwLockedList<ListenerInfo>> lis
in m_listeners)
{
/* standard foreach is implemented in RwLockedDictionary to make a copy first */
foreach (ListenerInfo li in lis.Value)
{
if (li.GetItemID().Equals(itemID) &&
li.GetHandle().Equals(handle))
{
lis.Value.Remove(li);
if (lis.Value.Count == 0)
{
m_listeners.Remove(lis.Key);
Interlocked.Decrement(ref m_curlisteners);
}
// there should be only one, so we bail out early
return;
}
}
}
}
public void DeleteListener(UUID itemID)
{
List<int> emptyChannels = new List<int>();
List<ListenerInfo> removedListeners = new List<ListenerInfo>();
/* standard foreach is implemented in RwLockedDictionary to make a copy first */
foreach (KeyValuePair<int, ThreadedClasses.RwLockedList<ListenerInfo>> lis
in m_listeners)
{
lis.Value.ForEach(delegate(ListenerInfo li)
{
if (li.GetItemID().Equals(itemID))
{
// store them first, else the enumerated bails on
// us
removedListeners.Add(li);
}
});
foreach (ListenerInfo li in removedListeners)
{
lis.Value.Remove(li);
m_curlisteners--;
}
removedListeners.Clear();
if (lis.Value.Count == 0)
{
// again, store first, remove later
emptyChannels.Add(lis.Key);
}
}
foreach (int channel in emptyChannels)
{
m_listeners.Remove(channel);
}
}
public void Activate(UUID itemID, int handle)
{
try
{
m_listeners.ForEach(delegate(KeyValuePair<int, ThreadedClasses.RwLockedList<ListenerInfo>> lis)
{
lis.Value.ForEach(delegate(ListenerInfo li)
{
if (li.GetItemID().Equals(itemID) &&
li.GetHandle() == handle)
{
li.Activate();
// only one, bail out
throw new ThreadedClasses.ReturnValueException<bool>(true);
}
});
});
}
catch(ThreadedClasses.ReturnValueException<bool>)
{
}
}
public void Deactivate(UUID itemID, int handle)
{
try
{
m_listeners.ForEach(delegate(KeyValuePair<int, ThreadedClasses.RwLockedList<ListenerInfo>> lis)
{
lis.Value.ForEach(delegate(ListenerInfo li)
{
if (li.GetItemID().Equals(itemID) &&
li.GetHandle() == handle)
{
li.Deactivate();
// only one, bail out
throw new ThreadedClasses.ReturnValueException<bool>(true);
}
});
});
}
catch (ThreadedClasses.ReturnValueException<bool>)
{
}
}
/// <summary>
/// non-locked access, since its always called in the context of the
/// lock
/// </summary>
/// <param name="itemID"></param>
/// <returns></returns>
private int GetNewHandle(UUID itemID)
{
List<int> handles = new List<int>();
// build a list of used keys for this specific itemID...
m_listeners.ForEach(delegate(KeyValuePair<int, ThreadedClasses.RwLockedList<ListenerInfo>> lis)
{
lis.Value.ForEach(delegate(ListenerInfo li)
{
if (li.GetItemID().Equals(itemID))
handles.Add(li.GetHandle());
});
});
// Note: 0 is NOT a valid handle for llListen() to return
for (int i = 1; i <= m_maxhandles; i++)
{
if (!handles.Contains(i))
return i;
}
return -1;
}
/// These are duplicated from ScriptBaseClass
/// http://opensimulator.org/mantis/view.php?id=6106#c21945
#region Constants for the bitfield parameter of osListenRegex
/// <summary>
/// process name parameter as regex
/// </summary>
public const int OS_LISTEN_REGEX_NAME = 0x1;
/// <summary>
/// process message parameter as regex
/// </summary>
public const int OS_LISTEN_REGEX_MESSAGE = 0x2;
#endregion
/// <summary>
/// Get listeners matching the input parameters.
/// </summary>
/// <remarks>
/// Theres probably a more clever and efficient way to do this, maybe
/// with regex.
/// PM2008: Ha, one could even be smart and define a specialized
/// Enumerator.
/// </remarks>
/// <param name="itemID"></param>
/// <param name="channel"></param>
/// <param name="name"></param>
/// <param name="id"></param>
/// <param name="msg"></param>
/// <returns></returns>
public List<ListenerInfo> GetListeners(UUID itemID, int channel,
string name, UUID id, string msg)
{
List<ListenerInfo> collection = new List<ListenerInfo>();
ThreadedClasses.RwLockedList<ListenerInfo> listeners;
if (!m_listeners.TryGetValue(channel, out listeners))
{
return collection;
}
listeners.ForEach(delegate(ListenerInfo li)
{
if (!li.IsActive())
{
return;
}
if (!itemID.Equals(UUID.Zero) &&
!li.GetItemID().Equals(itemID))
{
return;
}
if (li.GetName().Length > 0 && (
((li.RegexBitfield & OS_LISTEN_REGEX_NAME) != OS_LISTEN_REGEX_NAME && !li.GetName().Equals(name)) ||
((li.RegexBitfield & OS_LISTEN_REGEX_NAME) == OS_LISTEN_REGEX_NAME && !Regex.IsMatch(name, li.GetName()))
))
{
return;
}
if (!li.GetID().Equals(UUID.Zero) && !li.GetID().Equals(id))
{
return;
}
if (li.GetMessage().Length > 0 && (
((li.RegexBitfield & OS_LISTEN_REGEX_MESSAGE) != OS_LISTEN_REGEX_MESSAGE && !li.GetMessage().Equals(msg)) ||
((li.RegexBitfield & OS_LISTEN_REGEX_MESSAGE) == OS_LISTEN_REGEX_MESSAGE && !Regex.IsMatch(msg, li.GetMessage()))
))
{
return;
}
collection.Add(li);
});
return collection;
}
public Object[] GetSerializationData(UUID itemID)
{
List<Object> data = new List<Object>();
m_listeners.ForEach(delegate(ThreadedClasses.RwLockedList<ListenerInfo> list)
{
foreach (ListenerInfo l in list)
{
if (l.GetItemID() == itemID)
data.AddRange(l.GetSerializationData());
}
});
return (Object[])data.ToArray();
}
public void AddFromData(uint localID, UUID itemID, UUID hostID,
Object[] data)
{
int idx = 0;
Object[] item = new Object[6];
int dataItemLength = 6;
while (idx < data.Length)
{
dataItemLength = (idx + 7 == data.Length || (idx + 7 < data.Length && data[idx + 7] is bool)) ? 7 : 6;
item = new Object[dataItemLength];
Array.Copy(data, idx, item, 0, dataItemLength);
ListenerInfo info =
ListenerInfo.FromData(localID, itemID, hostID, item);
ThreadedClasses.RwLockedList<ListenerInfo> li = m_listeners.GetOrAddIfNotExists((int)item[2], delegate() { return new ThreadedClasses.RwLockedList<ListenerInfo>(); });
li.Add(info);
idx += dataItemLength;
}
}
}
public class ListenerInfo : IWorldCommListenerInfo
{
/// <summary>
/// Listener is active or not
/// </summary>
private bool m_active;
/// <summary>
/// Assigned handle of this listener
/// </summary>
private int m_handle;
/// <summary>
/// Local ID from script engine
/// </summary>
private uint m_localID;
/// <summary>
/// ID of the host script engine
/// </summary>
private UUID m_itemID;
/// <summary>
/// ID of the host/scene part
/// </summary>
private UUID m_hostID;
/// <summary>
/// Channel
/// </summary>
private int m_channel;
/// <summary>
/// ID to filter messages from
/// </summary>
private UUID m_id;
/// <summary>
/// Object name to filter messages from
/// </summary>
private string m_name;
/// <summary>
/// The message
/// </summary>
private string m_message;
public ListenerInfo(int handle, uint localID, UUID ItemID,
UUID hostID, int channel, string name, UUID id,
string message)
{
Initialise(handle, localID, ItemID, hostID, channel, name, id,
message, 0);
}
public ListenerInfo(int handle, uint localID, UUID ItemID,
UUID hostID, int channel, string name, UUID id,
string message, int regexBitfield)
{
Initialise(handle, localID, ItemID, hostID, channel, name, id,
message, regexBitfield);
}
public ListenerInfo(ListenerInfo li, string name, UUID id,
string message)
{
Initialise(li.m_handle, li.m_localID, li.m_itemID, li.m_hostID,
li.m_channel, name, id, message, 0);
}
public ListenerInfo(ListenerInfo li, string name, UUID id,
string message, int regexBitfield)
{
Initialise(li.m_handle, li.m_localID, li.m_itemID, li.m_hostID,
li.m_channel, name, id, message, regexBitfield);
}
private void Initialise(int handle, uint localID, UUID ItemID,
UUID hostID, int channel, string name, UUID id,
string message, int regexBitfield)
{
m_active = true;
m_handle = handle;
m_localID = localID;
m_itemID = ItemID;
m_hostID = hostID;
m_channel = channel;
m_name = name;
m_id = id;
m_message = message;
RegexBitfield = regexBitfield;
}
public Object[] GetSerializationData()
{
Object[] data = new Object[7];
data[0] = m_active;
data[1] = m_handle;
data[2] = m_channel;
data[3] = m_name;
data[4] = m_id;
data[5] = m_message;
data[6] = RegexBitfield;
return data;
}
public static ListenerInfo FromData(uint localID, UUID ItemID,
UUID hostID, Object[] data)
{
ListenerInfo linfo = new ListenerInfo((int)data[1], localID,
ItemID, hostID, (int)data[2], (string)data[3],
(UUID)data[4], (string)data[5]);
linfo.m_active = (bool)data[0];
if (data.Length >= 7)
{
linfo.RegexBitfield = (int)data[6];
}
return linfo;
}
public UUID GetItemID()
{
return m_itemID;
}
public UUID GetHostID()
{
return m_hostID;
}
public int GetChannel()
{
return m_channel;
}
public uint GetLocalID()
{
return m_localID;
}
public int GetHandle()
{
return m_handle;
}
public string GetMessage()
{
return m_message;
}
public string GetName()
{
return m_name;
}
public bool IsActive()
{
return m_active;
}
public void Deactivate()
{
m_active = false;
}
public void Activate()
{
m_active = true;
}
public UUID GetID()
{
return m_id;
}
public int RegexBitfield { get; private set; }
}
}
| |
/*
* Copyright (c) 2007-2008, openmetaverse.org
* All rights reserved.
*
* - Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - Neither the name of the openmetaverse.org nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace OpenMetaverse.StructuredData
{
/// <summary>
///
/// </summary>
public static partial class LLSDParser
{
private const string baseIndent = " ";
private const char undefNotationValue = '!';
private const char trueNotationValueOne = '1';
private const char trueNotationValueTwo = 't';
private static readonly char[] trueNotationValueTwoFull = { 't', 'r', 'u', 'e' };
private const char trueNotationValueThree = 'T';
private static readonly char[] trueNotationValueThreeFull = { 'T', 'R', 'U', 'E' };
private const char falseNotationValueOne = '0';
private const char falseNotationValueTwo = 'f';
private static readonly char[] falseNotationValueTwoFull = { 'f', 'a', 'l', 's', 'e' };
private const char falseNotationValueThree = 'F';
private static readonly char[] falseNotationValueThreeFull = { 'F', 'A', 'L', 'S', 'E' };
private const char integerNotationMarker = 'i';
private const char realNotationMarker = 'r';
private const char uuidNotationMarker = 'u';
private const char binaryNotationMarker = 'b';
private const char stringNotationMarker = 's';
private const char uriNotationMarker = 'l';
private const char dateNotationMarker = 'd';
private const char arrayBeginNotationMarker = '[';
private const char arrayEndNotationMarker = ']';
private const char mapBeginNotationMarker = '{';
private const char mapEndNotationMarker = '}';
private const char kommaNotationDelimiter = ',';
private const char keyNotationDelimiter = ':';
private const char sizeBeginNotationMarker = '(';
private const char sizeEndNotationMarker = ')';
private const char doubleQuotesNotationMarker = '"';
private const char singleQuotesNotationMarker = '\'';
/// <summary>
///
/// </summary>
/// <param name="notationData"></param>
/// <returns></returns>
public static LLSD DeserializeNotation(string notationData)
{
StringReader reader = new StringReader(notationData);
LLSD llsd = DeserializeNotation(reader);
reader.Close();
return llsd;
}
/// <summary>
///
/// </summary>
/// <param name="reader"></param>
/// <returns></returns>
public static LLSD DeserializeNotation(StringReader reader)
{
LLSD llsd = DeserializeNotationElement(reader);
return llsd;
}
/// <summary>
///
/// </summary>
/// <param name="llsd"></param>
/// <returns></returns>
public static string SerializeNotation(LLSD llsd)
{
StringWriter writer = SerializeNotationStream(llsd);
string s = writer.ToString();
writer.Close();
return s;
}
/// <summary>
///
/// </summary>
/// <param name="llsd"></param>
/// <returns></returns>
public static StringWriter SerializeNotationStream(LLSD llsd)
{
StringWriter writer = new StringWriter();
SerializeNotationElement(writer, llsd);
return writer;
}
/// <summary>
///
/// </summary>
/// <param name="llsd"></param>
/// <returns></returns>
public static string SerializeNotationFormatted(LLSD llsd)
{
StringWriter writer = SerializeNotationStreamFormatted(llsd);
string s = writer.ToString();
writer.Close();
return s;
}
/// <summary>
///
/// </summary>
/// <param name="llsd"></param>
/// <returns></returns>
public static StringWriter SerializeNotationStreamFormatted(LLSD llsd)
{
StringWriter writer = new StringWriter();
string indent = String.Empty;
SerializeNotationElementFormatted(writer, indent, llsd);
return writer;
}
/// <summary>
///
/// </summary>
/// <param name="reader"></param>
/// <returns></returns>
private static LLSD DeserializeNotationElement(StringReader reader)
{
int character = ReadAndSkipWhitespace(reader);
if (character < 0)
return new LLSD(); // server returned an empty file, so we're going to pass along a null LLSD object
LLSD llsd;
int matching;
switch ((char)character)
{
case undefNotationValue:
llsd = new LLSD();
break;
case trueNotationValueOne:
llsd = LLSD.FromBoolean(true);
break;
case trueNotationValueTwo:
matching = BufferCharactersEqual(reader, trueNotationValueTwoFull, 1);
if (matching > 1 && matching < trueNotationValueTwoFull.Length)
throw new LLSDException("Notation LLSD parsing: True value parsing error:");
llsd = LLSD.FromBoolean(true);
break;
case trueNotationValueThree:
matching = BufferCharactersEqual(reader, trueNotationValueThreeFull, 1);
if (matching > 1 && matching < trueNotationValueThreeFull.Length)
throw new LLSDException("Notation LLSD parsing: True value parsing error:");
llsd = LLSD.FromBoolean(true);
break;
case falseNotationValueOne:
llsd = LLSD.FromBoolean(false);
break;
case falseNotationValueTwo:
matching = BufferCharactersEqual(reader, falseNotationValueTwoFull, 1);
if (matching > 1 && matching < falseNotationValueTwoFull.Length)
throw new LLSDException("Notation LLSD parsing: True value parsing error:");
llsd = LLSD.FromBoolean(false);
break;
case falseNotationValueThree:
matching = BufferCharactersEqual(reader, falseNotationValueThreeFull, 1);
if (matching > 1 && matching < falseNotationValueThreeFull.Length)
throw new LLSDException("Notation LLSD parsing: True value parsing error:");
llsd = LLSD.FromBoolean(false);
break;
case integerNotationMarker:
llsd = DeserializeNotationInteger(reader);
break;
case realNotationMarker:
llsd = DeserializeNotationReal(reader);
break;
case uuidNotationMarker:
char[] uuidBuf = new char[36];
if (reader.Read(uuidBuf, 0, 36) < 36)
throw new LLSDException("Notation LLSD parsing: Unexpected end of stream in UUID.");
UUID lluuid;
if (!UUID.TryParse(new String(uuidBuf), out lluuid))
throw new LLSDException("Notation LLSD parsing: Invalid UUID discovered.");
llsd = LLSD.FromUUID(lluuid);
break;
case binaryNotationMarker:
byte[] bytes = new byte[0];
int bChar = reader.Peek();
if (bChar < 0)
throw new LLSDException("Notation LLSD parsing: Unexpected end of stream in binary.");
if ((char)bChar == sizeBeginNotationMarker)
{
throw new LLSDException("Notation LLSD parsing: Raw binary encoding not supported.");
}
else if (Char.IsDigit((char)bChar))
{
char[] charsBaseEncoding = new char[2];
if (reader.Read(charsBaseEncoding, 0, 2) < 2)
throw new LLSDException("Notation LLSD parsing: Unexpected end of stream in binary.");
int baseEncoding;
if (!Int32.TryParse(new String(charsBaseEncoding), out baseEncoding))
throw new LLSDException("Notation LLSD parsing: Invalid binary encoding base.");
if (baseEncoding == 64)
{
if (reader.Read() < 0)
throw new LLSDException("Notation LLSD parsing: Unexpected end of stream in binary.");
string bytes64 = GetStringDelimitedBy(reader, doubleQuotesNotationMarker);
bytes = Convert.FromBase64String(bytes64);
}
else
{
throw new LLSDException("Notation LLSD parsing: Encoding base" + baseEncoding + " + not supported.");
}
}
llsd = LLSD.FromBinary(bytes);
break;
case stringNotationMarker:
int numChars = GetLengthInBrackets(reader);
if (reader.Read() < 0)
throw new LLSDException("Notation LLSD parsing: Unexpected end of stream in string.");
char[] chars = new char[numChars];
if (reader.Read(chars, 0, numChars) < numChars)
throw new LLSDException("Notation LLSD parsing: Unexpected end of stream in string.");
if (reader.Read() < 0)
throw new LLSDException("Notation LLSD parsing: Unexpected end of stream in string.");
llsd = LLSD.FromString(new String(chars));
break;
case singleQuotesNotationMarker:
string sOne = GetStringDelimitedBy(reader, singleQuotesNotationMarker);
llsd = LLSD.FromString(sOne);
break;
case doubleQuotesNotationMarker:
string sTwo = GetStringDelimitedBy(reader, doubleQuotesNotationMarker);
llsd = LLSD.FromString(sTwo);
break;
case uriNotationMarker:
if (reader.Read() < 0)
throw new LLSDException("Notation LLSD parsing: Unexpected end of stream in string.");
string sUri = GetStringDelimitedBy(reader, doubleQuotesNotationMarker);
Uri uri;
try
{
uri = new Uri(sUri, UriKind.RelativeOrAbsolute);
}
catch
{
throw new LLSDException("Notation LLSD parsing: Invalid Uri format detected.");
}
llsd = LLSD.FromUri(uri);
break;
case dateNotationMarker:
if (reader.Read() < 0)
throw new LLSDException("Notation LLSD parsing: Unexpected end of stream in date.");
string date = GetStringDelimitedBy(reader, doubleQuotesNotationMarker);
DateTime dt;
if (!DateTime.TryParse(date, out dt))
throw new LLSDException("Notation LLSD parsing: Invalid date discovered.");
llsd = LLSD.FromDate(dt);
break;
case arrayBeginNotationMarker:
llsd = DeserializeNotationArray(reader);
break;
case mapBeginNotationMarker:
llsd = DeserializeNotationMap(reader);
break;
default:
throw new LLSDException("Notation LLSD parsing: Unknown type marker '" + (char)character + "'.");
}
return llsd;
}
private static LLSD DeserializeNotationInteger(StringReader reader)
{
int character;
StringBuilder s = new StringBuilder();
if (((character = reader.Peek()) > 0) && ((char)character == '-'))
{
s.Append((char)character);
reader.Read();
}
while ((character = reader.Peek()) > 0 &&
Char.IsDigit((char)character))
{
s.Append((char)character);
reader.Read();
}
int integer;
if (!Int32.TryParse(s.ToString(), out integer))
throw new LLSDException("Notation LLSD parsing: Can't parse integer value." + s.ToString());
return LLSD.FromInteger(integer);
}
private static LLSD DeserializeNotationReal(StringReader reader)
{
int character;
StringBuilder s = new StringBuilder();
if (((character = reader.Peek()) > 0) &&
((char)character == '-' && (char)character == '+'))
{
s.Append((char)character);
reader.Read();
}
while (((character = reader.Peek()) > 0) &&
(Char.IsDigit((char)character) || (char)character == '.' ||
(char)character == 'e' || (char)character == 'E' ||
(char)character == '+' || (char)character == '-'))
{
s.Append((char)character);
reader.Read();
}
double dbl;
if (!Utils.TryParseDouble(s.ToString(), out dbl))
throw new LLSDException("Notation LLSD parsing: Can't parse real value: " + s.ToString());
return LLSD.FromReal(dbl);
}
private static LLSD DeserializeNotationArray(StringReader reader)
{
int character;
LLSDArray llsdArray = new LLSDArray();
while (((character = PeekAndSkipWhitespace(reader)) > 0) &&
((char)character != arrayEndNotationMarker))
{
llsdArray.Add(DeserializeNotationElement(reader));
character = ReadAndSkipWhitespace(reader);
if (character < 0)
throw new LLSDException("Notation LLSD parsing: Unexpected end of array discovered.");
else if ((char)character == kommaNotationDelimiter)
continue;
else if ((char)character == arrayEndNotationMarker)
break;
}
if (character < 0)
throw new LLSDException("Notation LLSD parsing: Unexpected end of array discovered.");
return (LLSD)llsdArray;
}
private static LLSD DeserializeNotationMap(StringReader reader)
{
int character;
LLSDMap llsdMap = new LLSDMap();
while (((character = PeekAndSkipWhitespace(reader)) > 0) &&
((char)character != mapEndNotationMarker))
{
LLSD llsdKey = DeserializeNotationElement(reader);
if (llsdKey.Type != LLSDType.String)
throw new LLSDException("Notation LLSD parsing: Invalid key in map");
string key = llsdKey.AsString();
character = ReadAndSkipWhitespace(reader);
if ((char)character != keyNotationDelimiter)
throw new LLSDException("Notation LLSD parsing: Unexpected end of stream in map.");
if ((char)character != keyNotationDelimiter)
throw new LLSDException("Notation LLSD parsing: Invalid delimiter in map.");
llsdMap[key] = DeserializeNotationElement(reader);
character = ReadAndSkipWhitespace(reader);
if (character < 0)
throw new LLSDException("Notation LLSD parsing: Unexpected end of map discovered.");
else if ((char)character == kommaNotationDelimiter)
continue;
else if ((char)character == mapEndNotationMarker)
break;
}
if (character < 0)
throw new LLSDException("Notation LLSD parsing: Unexpected end of map discovered.");
return (LLSD)llsdMap;
}
private static void SerializeNotationElement(StringWriter writer, LLSD llsd)
{
switch (llsd.Type)
{
case LLSDType.Unknown:
writer.Write(undefNotationValue);
break;
case LLSDType.Boolean:
if (llsd.AsBoolean())
writer.Write(trueNotationValueTwo);
else
writer.Write(falseNotationValueTwo);
break;
case LLSDType.Integer:
writer.Write(integerNotationMarker);
writer.Write(llsd.AsString());
break;
case LLSDType.Real:
writer.Write(realNotationMarker);
writer.Write(llsd.AsString());
break;
case LLSDType.UUID:
writer.Write(uuidNotationMarker);
writer.Write(llsd.AsString());
break;
case LLSDType.String:
writer.Write(singleQuotesNotationMarker);
writer.Write(EscapeCharacter(llsd.AsString(), singleQuotesNotationMarker));
writer.Write(singleQuotesNotationMarker);
break;
case LLSDType.Binary:
writer.Write(binaryNotationMarker);
writer.Write("64");
writer.Write(doubleQuotesNotationMarker);
writer.Write(llsd.AsString());
writer.Write(doubleQuotesNotationMarker);
break;
case LLSDType.Date:
writer.Write(dateNotationMarker);
writer.Write(doubleQuotesNotationMarker);
writer.Write(llsd.AsString());
writer.Write(doubleQuotesNotationMarker);
break;
case LLSDType.URI:
writer.Write(uriNotationMarker);
writer.Write(doubleQuotesNotationMarker);
writer.Write(EscapeCharacter(llsd.AsString(), doubleQuotesNotationMarker));
writer.Write(doubleQuotesNotationMarker);
break;
case LLSDType.Array:
SerializeNotationArray(writer, (LLSDArray)llsd);
break;
case LLSDType.Map:
SerializeNotationMap(writer, (LLSDMap)llsd);
break;
default:
throw new LLSDException("Notation serialization: Not existing element discovered.");
}
}
private static void SerializeNotationArray(StringWriter writer, LLSDArray llsdArray)
{
writer.Write(arrayBeginNotationMarker);
int lastIndex = llsdArray.Count - 1;
for (int idx = 0; idx <= lastIndex; idx++)
{
SerializeNotationElement(writer, llsdArray[idx]);
if (idx < lastIndex)
writer.Write(kommaNotationDelimiter);
}
writer.Write(arrayEndNotationMarker);
}
private static void SerializeNotationMap(StringWriter writer, LLSDMap llsdMap)
{
writer.Write(mapBeginNotationMarker);
int lastIndex = llsdMap.Count - 1;
int idx = 0;
foreach (KeyValuePair<string, LLSD> kvp in llsdMap)
{
writer.Write(singleQuotesNotationMarker);
writer.Write(EscapeCharacter(kvp.Key, singleQuotesNotationMarker));
writer.Write(singleQuotesNotationMarker);
writer.Write(keyNotationDelimiter);
SerializeNotationElement(writer, kvp.Value);
if (idx < lastIndex)
writer.Write(kommaNotationDelimiter);
idx++;
}
writer.Write(mapEndNotationMarker);
}
private static void SerializeNotationElementFormatted(StringWriter writer, string indent, LLSD llsd)
{
switch (llsd.Type)
{
case LLSDType.Unknown:
writer.Write(undefNotationValue);
break;
case LLSDType.Boolean:
if (llsd.AsBoolean())
writer.Write(trueNotationValueTwo);
else
writer.Write(falseNotationValueTwo);
break;
case LLSDType.Integer:
writer.Write(integerNotationMarker);
writer.Write(llsd.AsString());
break;
case LLSDType.Real:
writer.Write(realNotationMarker);
writer.Write(llsd.AsString());
break;
case LLSDType.UUID:
writer.Write(uuidNotationMarker);
writer.Write(llsd.AsString());
break;
case LLSDType.String:
writer.Write(singleQuotesNotationMarker);
writer.Write(EscapeCharacter(llsd.AsString(), singleQuotesNotationMarker));
writer.Write(singleQuotesNotationMarker);
break;
case LLSDType.Binary:
writer.Write(binaryNotationMarker);
writer.Write("64");
writer.Write(doubleQuotesNotationMarker);
writer.Write(llsd.AsString());
writer.Write(doubleQuotesNotationMarker);
break;
case LLSDType.Date:
writer.Write(dateNotationMarker);
writer.Write(doubleQuotesNotationMarker);
writer.Write(llsd.AsString());
writer.Write(doubleQuotesNotationMarker);
break;
case LLSDType.URI:
writer.Write(uriNotationMarker);
writer.Write(doubleQuotesNotationMarker);
writer.Write(EscapeCharacter(llsd.AsString(), doubleQuotesNotationMarker));
writer.Write(doubleQuotesNotationMarker);
break;
case LLSDType.Array:
SerializeNotationArrayFormatted(writer, indent + baseIndent, (LLSDArray)llsd);
break;
case LLSDType.Map:
SerializeNotationMapFormatted(writer, indent + baseIndent, (LLSDMap)llsd);
break;
default:
throw new LLSDException("Notation serialization: Not existing element discovered.");
}
}
private static void SerializeNotationArrayFormatted(StringWriter writer, string intend, LLSDArray llsdArray)
{
writer.Write(Helpers.NewLine);
writer.Write(intend);
writer.Write(arrayBeginNotationMarker);
int lastIndex = llsdArray.Count - 1;
for (int idx = 0; idx <= lastIndex; idx++)
{
if (llsdArray[idx].Type != LLSDType.Array && llsdArray[idx].Type != LLSDType.Map)
writer.Write(Helpers.NewLine);
writer.Write(intend + baseIndent);
SerializeNotationElementFormatted(writer, intend, llsdArray[idx]);
if (idx < lastIndex)
{
writer.Write(kommaNotationDelimiter);
}
}
writer.Write(Helpers.NewLine);
writer.Write(intend);
writer.Write(arrayEndNotationMarker);
}
private static void SerializeNotationMapFormatted(StringWriter writer, string intend, LLSDMap llsdMap)
{
writer.Write(Helpers.NewLine);
writer.Write(intend);
writer.Write(mapBeginNotationMarker);
writer.Write(Helpers.NewLine);
int lastIndex = llsdMap.Count - 1;
int idx = 0;
foreach (KeyValuePair<string, LLSD> kvp in llsdMap)
{
writer.Write(intend + baseIndent);
writer.Write(singleQuotesNotationMarker);
writer.Write(EscapeCharacter(kvp.Key, singleQuotesNotationMarker));
writer.Write(singleQuotesNotationMarker);
writer.Write(keyNotationDelimiter);
SerializeNotationElementFormatted(writer, intend, kvp.Value);
if (idx < lastIndex)
{
writer.Write(Helpers.NewLine);
writer.Write(intend + baseIndent);
writer.Write(kommaNotationDelimiter);
writer.Write(Helpers.NewLine);
}
idx++;
}
writer.Write(Helpers.NewLine);
writer.Write(intend);
writer.Write(mapEndNotationMarker);
}
/// <summary>
///
/// </summary>
/// <param name="reader"></param>
/// <returns></returns>
public static int PeekAndSkipWhitespace(StringReader reader)
{
int character;
while ((character = reader.Peek()) > 0)
{
char c = (char)character;
if (c == ' ' || c == '\t' || c == '\n' || c == '\r')
{
reader.Read();
continue;
}
else
break;
}
return character;
}
/// <summary>
///
/// </summary>
/// <param name="reader"></param>
/// <returns></returns>
public static int ReadAndSkipWhitespace(StringReader reader)
{
int character = PeekAndSkipWhitespace(reader);
reader.Read();
return character;
}
/// <summary>
///
/// </summary>
/// <param name="reader"></param>
/// <returns></returns>
public static int GetLengthInBrackets(StringReader reader)
{
int character;
StringBuilder s = new StringBuilder();
if (((character = PeekAndSkipWhitespace(reader)) > 0) &&
((char)character == sizeBeginNotationMarker))
{
reader.Read();
}
while (((character = reader.Read()) > 0) &&
Char.IsDigit((char)character) &&
((char)character != sizeEndNotationMarker))
{
s.Append((char)character);
}
if (character < 0)
throw new LLSDException("Notation LLSD parsing: Can't parse length value cause unexpected end of stream.");
int length;
if (!Int32.TryParse(s.ToString(), out length))
throw new LLSDException("Notation LLSD parsing: Can't parse length value.");
return length;
}
/// <summary>
///
/// </summary>
/// <param name="reader"></param>
/// <param name="delimiter"></param>
/// <returns></returns>
public static string GetStringDelimitedBy(StringReader reader, char delimiter)
{
int character;
bool foundEscape = false;
StringBuilder s = new StringBuilder();
while (((character = reader.Read()) > 0) &&
(((char)character != delimiter) ||
((char)character == delimiter && foundEscape)))
{
if (foundEscape)
{
foundEscape = false;
switch ((char)character)
{
case 'a':
s.Append('\a');
break;
case 'b':
s.Append('\b');
break;
case 'f':
s.Append('\f');
break;
case 'n':
s.Append('\n');
break;
case 'r':
s.Append('\r');
break;
case 't':
s.Append('\t');
break;
case 'v':
s.Append('\v');
break;
default:
s.Append((char)character);
break;
}
}
else if ((char)character == '\\')
foundEscape = true;
else
s.Append((char)character);
}
if (character < 0)
throw new LLSDException("Notation LLSD parsing: Can't parse text because unexpected end of stream while expecting a '"
+ delimiter + "' character.");
return s.ToString();
}
/// <summary>
///
/// </summary>
/// <param name="reader"></param>
/// <param name="buffer"></param>
/// <param name="offset"></param>
/// <returns></returns>
public static int BufferCharactersEqual(StringReader reader, char[] buffer, int offset)
{
int character;
int lastIndex = buffer.Length - 1;
int crrIndex = offset;
bool charactersEqual = true;
while ((character = reader.Peek()) > 0 &&
crrIndex <= lastIndex &&
charactersEqual)
{
if (((char)character) != buffer[crrIndex])
{
charactersEqual = false;
break;
}
crrIndex++;
reader.Read();
}
return crrIndex;
}
/// <summary>
///
/// </summary>
/// <param name="s"></param>
/// <param name="c"></param>
/// <returns></returns>
public static string UnescapeCharacter(String s, char c)
{
string oldOne = "\\" + c;
string newOne = new String(c, 1);
String sOne = s.Replace("\\\\", "\\").Replace(oldOne, newOne);
return sOne;
}
/// <summary>
///
/// </summary>
/// <param name="s"></param>
/// <param name="c"></param>
/// <returns></returns>
public static string EscapeCharacter(String s, char c)
{
string oldOne = new String(c, 1);
string newOne = "\\" + c;
String sOne = s.Replace("\\", "\\\\").Replace(oldOne, newOne);
return sOne;
}
}
}
| |
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using CoreCraft.Data;
namespace CoreCraft.Data.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
partial class ApplicationDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
modelBuilder
.HasAnnotation("ProductVersion", "1.0.0-rc2-20901");
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole", b =>
{
b.Property<string>("Id");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Name")
.HasAnnotation("MaxLength", 256);
b.Property<string>("NormalizedName")
.HasAnnotation("MaxLength", 256);
b.HasKey("Id");
b.HasIndex("NormalizedName")
.HasName("RoleNameIndex");
b.ToTable("AspNetRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("RoleId")
.IsRequired();
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider");
b.Property<string>("ProviderKey");
b.Property<string>("ProviderDisplayName");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("RoleId");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.HasIndex("UserId");
b.ToTable("AspNetUserRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserToken<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("LoginProvider");
b.Property<string>("Name");
b.Property<string>("Value");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens");
});
modelBuilder.Entity("CoreCraft.Models.ApplicationUser", b =>
{
b.Property<string>("Id");
b.Property<int>("AccessFailedCount");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Email")
.HasAnnotation("MaxLength", 256);
b.Property<bool>("EmailConfirmed");
b.Property<bool>("LockoutEnabled");
b.Property<DateTimeOffset?>("LockoutEnd");
b.Property<string>("NormalizedEmail")
.HasAnnotation("MaxLength", 256);
b.Property<string>("NormalizedUserName")
.HasAnnotation("MaxLength", 256);
b.Property<string>("PasswordHash");
b.Property<string>("PhoneNumber");
b.Property<bool>("PhoneNumberConfirmed");
b.Property<string>("SecurityStamp");
b.Property<bool>("TwoFactorEnabled");
b.Property<string>("UserName")
.HasAnnotation("MaxLength", 256);
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasName("EmailIndex");
b.HasIndex("NormalizedUserName")
.HasName("UserNameIndex");
b.ToTable("AspNetUsers");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole")
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<string>", b =>
{
b.HasOne("CoreCraft.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<string>", b =>
{
b.HasOne("CoreCraft.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole")
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("CoreCraft.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Runtime;
using System.Runtime.Serialization;
using System.Text;
using System.Xml;
namespace System.Runtime.Serialization.Json
{
internal class XmlJsonWriter : XmlDictionaryWriter, IXmlJsonWriterInitializer
{
private const char BACK_SLASH = '\\';
private const char FORWARD_SLASH = '/';
private const char HIGH_SURROGATE_START = (char)0xd800;
private const char LOW_SURROGATE_END = (char)0xdfff;
private const char MAX_CHAR = (char)0xfffe;
private const char WHITESPACE = ' ';
private const char CARRIAGE_RETURN = '\r';
private const char NEWLINE = '\n';
private const string xmlNamespace = "http://www.w3.org/XML/1998/namespace";
private const string xmlnsNamespace = "http://www.w3.org/2000/xmlns/";
// This array was part of a perf improvement for escaping characters < WHITESPACE.
private static readonly string[] s_escapedJsonStringTable =
{
"\\u0000",
"\\u0001",
"\\u0002",
"\\u0003",
"\\u0004",
"\\u0005",
"\\u0006",
"\\u0007",
"\\b",
"\\t",
"\\n",
"\\u000b",
"\\f",
"\\r",
"\\u000e",
"\\u000f",
"\\u0010",
"\\u0011",
"\\u0012",
"\\u0013",
"\\u0014",
"\\u0015",
"\\u0016",
"\\u0017",
"\\u0018",
"\\u0019",
"\\u001a",
"\\u001b",
"\\u001c",
"\\u001d",
"\\u001e",
"\\u001f"
};
private static BinHexEncoding s_binHexEncoding;
private string _attributeText;
private JsonDataType _dataType;
private int _depth;
private bool _endElementBuffer;
private bool _isWritingDataTypeAttribute;
private bool _isWritingServerTypeAttribute;
private bool _isWritingXmlnsAttribute;
private bool _isWritingXmlnsAttributeDefaultNs;
private NameState _nameState;
private JsonNodeType _nodeType;
private JsonNodeWriter _nodeWriter;
private JsonNodeType[] _scopes;
private string _serverTypeValue;
// Do not use this field's value anywhere other than the WriteState property.
// It's OK to set this field's value anywhere and then change the WriteState property appropriately.
// If it's necessary to check the WriteState outside WriteState, use the WriteState property.
private WriteState _writeState;
private bool _wroteServerTypeAttribute;
private readonly bool _indent;
private readonly string _indentChars;
private int _indentLevel;
public XmlJsonWriter() : this(false, null) { }
public XmlJsonWriter(bool indent, string indentChars)
{
_indent = indent;
if (indent)
{
if (indentChars == null)
{
throw new ArgumentNullException(nameof(indentChars));
}
_indentChars = indentChars;
}
InitializeWriter();
}
private enum JsonDataType
{
None,
Null,
Boolean,
Number,
String,
Object,
Array
};
[Flags]
private enum NameState
{
None = 0,
IsWritingNameWithMapping = 1,
IsWritingNameAttribute = 2,
WrittenNameWithMapping = 4,
}
public override XmlWriterSettings Settings
{
// The XmlWriterSettings object used to create this writer instance.
// If this writer was not created using the Create method, this property
// returns a null reference.
get { return null; }
}
public override WriteState WriteState
{
get
{
if (_writeState == WriteState.Closed)
{
return WriteState.Closed;
}
if (HasOpenAttribute)
{
return WriteState.Attribute;
}
switch (_nodeType)
{
case JsonNodeType.None:
return WriteState.Start;
case JsonNodeType.Element:
return WriteState.Element;
case JsonNodeType.QuotedText:
case JsonNodeType.StandaloneText:
case JsonNodeType.EndElement:
return WriteState.Content;
default:
return WriteState.Error;
}
}
}
public override string XmlLang
{
get { return null; }
}
public override XmlSpace XmlSpace
{
get { return XmlSpace.None; }
}
private static BinHexEncoding BinHexEncoding
{
get
{
if (s_binHexEncoding == null)
{
s_binHexEncoding = new BinHexEncoding();
}
return s_binHexEncoding;
}
}
private bool HasOpenAttribute => (_isWritingDataTypeAttribute || _isWritingServerTypeAttribute || IsWritingNameAttribute || _isWritingXmlnsAttribute);
private bool IsClosed => (WriteState == WriteState.Closed);
private bool IsWritingCollection => (_depth > 0) && (_scopes[_depth] == JsonNodeType.Collection);
private bool IsWritingNameAttribute => (_nameState & NameState.IsWritingNameAttribute) == NameState.IsWritingNameAttribute;
private bool IsWritingNameWithMapping => (_nameState & NameState.IsWritingNameWithMapping) == NameState.IsWritingNameWithMapping;
private bool WrittenNameWithMapping => (_nameState & NameState.WrittenNameWithMapping) == NameState.WrittenNameWithMapping;
protected override void Dispose(bool disposing)
{
if (!IsClosed)
{
try
{
WriteEndDocument();
}
finally
{
try
{
_nodeWriter.Flush();
_nodeWriter.Close();
}
finally
{
_writeState = WriteState.Closed;
if (_depth != 0)
{
_depth = 0;
}
}
}
}
base.Dispose(disposing);
}
public override void Flush()
{
if (IsClosed)
{
ThrowClosed();
}
_nodeWriter.Flush();
}
public override string LookupPrefix(string ns)
{
if (ns == null)
{
throw new ArgumentNullException(nameof(ns));
}
if (ns == Globals.XmlnsNamespace)
{
return Globals.XmlnsPrefix;
}
if (ns == xmlNamespace)
{
return JsonGlobals.xmlPrefix;
}
if (ns == string.Empty)
{
return string.Empty;
}
return null;
}
public void SetOutput(Stream stream, Encoding encoding, bool ownsStream)
{
if (stream == null)
{
throw new ArgumentNullException(nameof(stream));
}
if (encoding == null)
{
throw new ArgumentNullException(nameof(encoding));
}
if (encoding.WebName != Encoding.UTF8.WebName)
{
stream = new JsonEncodingStreamWrapper(stream, encoding, false);
}
else
{
encoding = null;
}
if (_nodeWriter == null)
{
_nodeWriter = new JsonNodeWriter();
}
_nodeWriter.SetOutput(stream, ownsStream, encoding);
InitializeWriter();
}
public override void WriteArray(string prefix, string localName, string namespaceUri, bool[] array, int offset, int count)
{
throw new NotSupportedException(SR.JsonWriteArrayNotSupported);
}
public override void WriteArray(string prefix, string localName, string namespaceUri, short[] array, int offset, int count)
{
throw new NotSupportedException(SR.JsonWriteArrayNotSupported);
}
public override void WriteArray(string prefix, string localName, string namespaceUri, int[] array, int offset, int count)
{
throw new NotSupportedException(SR.JsonWriteArrayNotSupported);
}
public override void WriteArray(string prefix, string localName, string namespaceUri, long[] array, int offset, int count)
{
throw new NotSupportedException(SR.JsonWriteArrayNotSupported);
}
public override void WriteArray(string prefix, string localName, string namespaceUri, float[] array, int offset, int count)
{
throw new NotSupportedException(SR.JsonWriteArrayNotSupported);
}
public override void WriteArray(string prefix, string localName, string namespaceUri, double[] array, int offset, int count)
{
throw new NotSupportedException(SR.JsonWriteArrayNotSupported);
}
public override void WriteArray(string prefix, string localName, string namespaceUri, decimal[] array, int offset, int count)
{
throw new NotSupportedException(SR.JsonWriteArrayNotSupported);
}
public override void WriteArray(string prefix, string localName, string namespaceUri, DateTime[] array, int offset, int count)
{
throw new NotSupportedException(SR.JsonWriteArrayNotSupported);
}
public override void WriteArray(string prefix, string localName, string namespaceUri, Guid[] array, int offset, int count)
{
throw new NotSupportedException(SR.JsonWriteArrayNotSupported);
}
public override void WriteArray(string prefix, string localName, string namespaceUri, TimeSpan[] array, int offset, int count)
{
throw new NotSupportedException(SR.JsonWriteArrayNotSupported);
}
public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, bool[] array, int offset, int count)
{
throw new NotSupportedException(SR.JsonWriteArrayNotSupported);
}
public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, decimal[] array, int offset, int count)
{
throw new NotSupportedException(SR.JsonWriteArrayNotSupported);
}
public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, double[] array, int offset, int count)
{
throw new NotSupportedException(SR.JsonWriteArrayNotSupported);
}
public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, float[] array, int offset, int count)
{
throw new NotSupportedException(SR.JsonWriteArrayNotSupported);
}
public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, int[] array, int offset, int count)
{
throw new NotSupportedException(SR.JsonWriteArrayNotSupported);
}
public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, long[] array, int offset, int count)
{
throw new NotSupportedException(SR.JsonWriteArrayNotSupported);
}
public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, short[] array, int offset, int count)
{
throw new NotSupportedException(SR.JsonWriteArrayNotSupported);
}
public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, DateTime[] array, int offset, int count)
{
throw new NotSupportedException(SR.JsonWriteArrayNotSupported);
}
public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, Guid[] array, int offset, int count)
{
throw new NotSupportedException(SR.JsonWriteArrayNotSupported);
}
public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, TimeSpan[] array, int offset, int count)
{
throw new NotSupportedException(SR.JsonWriteArrayNotSupported);
}
public override void WriteBase64(byte[] buffer, int index, int count)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
// Not checking upper bound because it will be caught by "count". This is what XmlTextWriter does.
if (index < 0)
{
throw new ArgumentOutOfRangeException(nameof(index), SR.ValueMustBeNonNegative);
}
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count), SR.ValueMustBeNonNegative);
}
if (count > buffer.Length - index)
{
throw new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.JsonSizeExceedsRemainingBufferSpace, buffer.Length - index));
}
StartText();
_nodeWriter.WriteBase64Text(buffer, 0, buffer, index, count);
}
public override void WriteBinHex(byte[] buffer, int index, int count)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
// Not checking upper bound because it will be caught by "count". This is what XmlTextWriter does.
if (index < 0)
{
throw new ArgumentOutOfRangeException(nameof(index), SR.ValueMustBeNonNegative);
}
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count), SR.ValueMustBeNonNegative);
}
if (count > buffer.Length - index)
{
throw new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.JsonSizeExceedsRemainingBufferSpace, buffer.Length - index));
}
StartText();
WriteEscapedJsonString(BinHexEncoding.GetString(buffer, index, count));
}
public override void WriteCData(string text)
{
WriteString(text);
}
public override void WriteCharEntity(char ch)
{
WriteString(ch.ToString());
}
public override void WriteChars(char[] buffer, int index, int count)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
// Not checking upper bound because it will be caught by "count". This is what XmlTextWriter does.
if (index < 0)
{
throw new ArgumentOutOfRangeException(nameof(index), SR.ValueMustBeNonNegative);
}
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count), SR.ValueMustBeNonNegative);
}
if (count > buffer.Length - index)
{
throw new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.JsonSizeExceedsRemainingBufferSpace, buffer.Length - index));
}
WriteString(new string(buffer, index, count));
}
public override void WriteComment(string text)
{
throw new NotSupportedException(SR.Format(SR.JsonMethodNotSupported, "WriteComment"));
}
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "2#sysid", Justification = "This method is derived from the base")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "1#pubid", Justification = "This method is derived from the base")]
public override void WriteDocType(string name, string pubid, string sysid, string subset)
{
throw new NotSupportedException(SR.Format(SR.JsonMethodNotSupported, "WriteDocType"));
}
public override void WriteEndAttribute()
{
if (IsClosed)
{
ThrowClosed();
}
if (!HasOpenAttribute)
{
throw new XmlException(SR.JsonNoMatchingStartAttribute);
}
Fx.Assert(!(_isWritingDataTypeAttribute && _isWritingServerTypeAttribute),
"Can not write type attribute and __type attribute at the same time.");
if (_isWritingDataTypeAttribute)
{
switch (_attributeText)
{
case JsonGlobals.numberString:
{
ThrowIfServerTypeWritten(JsonGlobals.numberString);
_dataType = JsonDataType.Number;
break;
}
case JsonGlobals.stringString:
{
ThrowIfServerTypeWritten(JsonGlobals.stringString);
_dataType = JsonDataType.String;
break;
}
case JsonGlobals.arrayString:
{
ThrowIfServerTypeWritten(JsonGlobals.arrayString);
_dataType = JsonDataType.Array;
break;
}
case JsonGlobals.objectString:
{
_dataType = JsonDataType.Object;
break;
}
case JsonGlobals.nullString:
{
ThrowIfServerTypeWritten(JsonGlobals.nullString);
_dataType = JsonDataType.Null;
break;
}
case JsonGlobals.booleanString:
{
ThrowIfServerTypeWritten(JsonGlobals.booleanString);
_dataType = JsonDataType.Boolean;
break;
}
default:
throw new XmlException(SR.Format(SR.JsonUnexpectedAttributeValue, _attributeText));
}
_attributeText = null;
_isWritingDataTypeAttribute = false;
if (!IsWritingNameWithMapping || WrittenNameWithMapping)
{
WriteDataTypeServerType();
}
}
else if (_isWritingServerTypeAttribute)
{
_serverTypeValue = _attributeText;
_attributeText = null;
_isWritingServerTypeAttribute = false;
// we are writing __type after type="object" (enforced by WSE)
if ((!IsWritingNameWithMapping || WrittenNameWithMapping) && _dataType == JsonDataType.Object)
{
WriteServerTypeAttribute();
}
}
else if (IsWritingNameAttribute)
{
WriteJsonElementName(_attributeText);
_attributeText = null;
_nameState = NameState.IsWritingNameWithMapping | NameState.WrittenNameWithMapping;
WriteDataTypeServerType();
}
else if (_isWritingXmlnsAttribute)
{
if (!string.IsNullOrEmpty(_attributeText) && _isWritingXmlnsAttributeDefaultNs)
{
throw new ArgumentException(SR.Format(SR.JsonNamespaceMustBeEmpty, _attributeText));
}
_attributeText = null;
_isWritingXmlnsAttribute = false;
_isWritingXmlnsAttributeDefaultNs = false;
}
}
public override void WriteEndDocument()
{
if (IsClosed)
{
ThrowClosed();
}
if (_nodeType != JsonNodeType.None)
{
while (_depth > 0)
{
WriteEndElement();
}
}
}
public override void WriteEndElement()
{
if (IsClosed)
{
ThrowClosed();
}
if (_depth == 0)
{
throw new XmlException(SR.JsonEndElementNoOpenNodes);
}
if (HasOpenAttribute)
{
throw new XmlException(SR.Format(SR.JsonOpenAttributeMustBeClosedFirst, "WriteEndElement"));
}
_endElementBuffer = false;
JsonNodeType token = ExitScope();
if (token == JsonNodeType.Collection)
{
_indentLevel--;
if (_indent)
{
if (_nodeType == JsonNodeType.Element)
{
_nodeWriter.WriteText(WHITESPACE);
}
else
{
WriteNewLine();
WriteIndent();
}
}
_nodeWriter.WriteText(JsonGlobals.EndCollectionChar);
token = ExitScope();
}
else if (_nodeType == JsonNodeType.QuotedText)
{
// For writing "
WriteJsonQuote();
}
else if (_nodeType == JsonNodeType.Element)
{
if ((_dataType == JsonDataType.None) && (_serverTypeValue != null))
{
throw new XmlException(SR.Format(SR.JsonMustSpecifyDataType, JsonGlobals.typeString, JsonGlobals.objectString, JsonGlobals.serverTypeString));
}
if (IsWritingNameWithMapping && !WrittenNameWithMapping)
{
// Ending </item> without writing item attribute
// Not providing a better error message because localization deadline has passed.
throw new XmlException(SR.Format(SR.JsonMustSpecifyDataType, JsonGlobals.itemString, string.Empty, JsonGlobals.itemString));
}
// the element is empty, it does not have any content,
if ((_dataType == JsonDataType.None) ||
(_dataType == JsonDataType.String))
{
_nodeWriter.WriteText(JsonGlobals.QuoteChar);
_nodeWriter.WriteText(JsonGlobals.QuoteChar);
}
}
else
{
// Assert on only StandaloneText and EndElement because preceding if
// conditions take care of checking for QuotedText and Element.
Fx.Assert((_nodeType == JsonNodeType.StandaloneText) || (_nodeType == JsonNodeType.EndElement),
"nodeType has invalid value " + _nodeType + ". Expected it to be QuotedText, Element, StandaloneText, or EndElement.");
}
if (_depth != 0)
{
if (token == JsonNodeType.Element)
{
_endElementBuffer = true;
}
else if (token == JsonNodeType.Object)
{
_indentLevel--;
if (_indent)
{
if (_nodeType == JsonNodeType.Element)
{
_nodeWriter.WriteText(WHITESPACE);
}
else
{
WriteNewLine();
WriteIndent();
}
}
_nodeWriter.WriteText(JsonGlobals.EndObjectChar);
if ((_depth > 0) && _scopes[_depth] == JsonNodeType.Element)
{
ExitScope();
_endElementBuffer = true;
}
}
}
_dataType = JsonDataType.None;
_nodeType = JsonNodeType.EndElement;
_nameState = NameState.None;
_wroteServerTypeAttribute = false;
}
public override void WriteEntityRef(string name)
{
throw new NotSupportedException(SR.Format(SR.JsonMethodNotSupported, "WriteEntityRef"));
}
public override void WriteFullEndElement()
{
WriteEndElement();
}
public override void WriteProcessingInstruction(string name, string text)
{
if (IsClosed)
{
ThrowClosed();
}
if (!name.Equals("xml", StringComparison.OrdinalIgnoreCase))
{
throw new ArgumentException(SR.JsonXmlProcessingInstructionNotSupported, nameof(name));
}
if (WriteState != WriteState.Start)
{
throw new XmlException(SR.JsonXmlInvalidDeclaration);
}
}
public override void WriteQualifiedName(string localName, string ns)
{
if (localName == null)
{
throw new ArgumentNullException(nameof(localName));
}
if (localName.Length == 0)
{
throw new ArgumentException(SR.JsonInvalidLocalNameEmpty, nameof(localName));
}
if (ns == null)
{
ns = string.Empty;
}
base.WriteQualifiedName(localName, ns);
}
public override void WriteRaw(string data)
{
WriteString(data);
}
public override void WriteRaw(char[] buffer, int index, int count)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
// Not checking upper bound because it will be caught by "count". This is what XmlTextWriter does.
if (index < 0)
{
throw new ArgumentOutOfRangeException(nameof(index), SR.ValueMustBeNonNegative);
}
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count), SR.ValueMustBeNonNegative);
}
if (count > buffer.Length - index)
{
throw new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.JsonSizeExceedsRemainingBufferSpace, buffer.Length - index));
}
WriteString(new string(buffer, index, count));
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase")] // Microsoft, ToLowerInvariant is just used in Json error message
public override void WriteStartAttribute(string prefix, string localName, string ns)
{
if (IsClosed)
{
ThrowClosed();
}
if (!string.IsNullOrEmpty(prefix))
{
if (IsWritingNameWithMapping && prefix == JsonGlobals.xmlnsPrefix)
{
if (ns != null && ns != xmlnsNamespace)
{
throw new ArgumentException(SR.Format(SR.XmlPrefixBoundToNamespace, "xmlns", xmlnsNamespace, ns), nameof(ns));
}
}
else
{
throw new ArgumentException(SR.Format(SR.JsonPrefixMustBeNullOrEmpty, prefix), nameof(prefix));
}
}
else
{
if (IsWritingNameWithMapping && ns == xmlnsNamespace && localName != JsonGlobals.xmlnsPrefix)
{
prefix = JsonGlobals.xmlnsPrefix;
}
}
if (!string.IsNullOrEmpty(ns))
{
if (IsWritingNameWithMapping && ns == xmlnsNamespace)
{
prefix = JsonGlobals.xmlnsPrefix;
}
else if (string.IsNullOrEmpty(prefix) && localName == JsonGlobals.xmlnsPrefix && ns == xmlnsNamespace)
{
prefix = JsonGlobals.xmlnsPrefix;
_isWritingXmlnsAttributeDefaultNs = true;
}
else
{
throw new ArgumentException(SR.Format(SR.JsonNamespaceMustBeEmpty, ns), nameof(ns));
}
}
if (localName == null)
{
throw new ArgumentNullException(nameof(localName));
}
if (localName.Length == 0)
{
throw new ArgumentException(SR.JsonInvalidLocalNameEmpty, nameof(localName));
}
if ((_nodeType != JsonNodeType.Element) && !_wroteServerTypeAttribute)
{
throw new XmlException(SR.JsonAttributeMustHaveElement);
}
if (HasOpenAttribute)
{
throw new XmlException(SR.Format(SR.JsonOpenAttributeMustBeClosedFirst, "WriteStartAttribute"));
}
if (prefix == JsonGlobals.xmlnsPrefix)
{
_isWritingXmlnsAttribute = true;
}
else if (localName == JsonGlobals.typeString)
{
if (_dataType != JsonDataType.None)
{
throw new XmlException(SR.Format(SR.JsonAttributeAlreadyWritten, JsonGlobals.typeString));
}
_isWritingDataTypeAttribute = true;
}
else if (localName == JsonGlobals.serverTypeString)
{
if (_serverTypeValue != null)
{
throw new XmlException(SR.Format(SR.JsonAttributeAlreadyWritten, JsonGlobals.serverTypeString));
}
if ((_dataType != JsonDataType.None) && (_dataType != JsonDataType.Object))
{
throw new XmlException(SR.Format(SR.JsonServerTypeSpecifiedForInvalidDataType,
JsonGlobals.serverTypeString, JsonGlobals.typeString, _dataType.ToString().ToLowerInvariant(), JsonGlobals.objectString));
}
_isWritingServerTypeAttribute = true;
}
else if (localName == JsonGlobals.itemString)
{
if (WrittenNameWithMapping)
{
throw new XmlException(SR.Format(SR.JsonAttributeAlreadyWritten, JsonGlobals.itemString));
}
if (!IsWritingNameWithMapping)
{
// Don't write attribute with local name "item" if <item> element is not open.
// Not providing a better error message because localization deadline has passed.
throw new XmlException(SR.JsonEndElementNoOpenNodes);
}
_nameState |= NameState.IsWritingNameAttribute;
}
else
{
throw new ArgumentException(SR.Format(SR.JsonUnexpectedAttributeLocalName, localName), nameof(localName));
}
}
public override void WriteStartDocument(bool standalone)
{
// In XML, writes the XML declaration with the version "1.0" and the standalone attribute.
WriteStartDocument();
}
public override void WriteStartDocument()
{
// In XML, writes the XML declaration with the version "1.0".
if (IsClosed)
{
ThrowClosed();
}
if (WriteState != WriteState.Start)
{
throw new XmlException(SR.Format(SR.JsonInvalidWriteState, "WriteStartDocument", WriteState.ToString()));
}
}
public override void WriteStartElement(string prefix, string localName, string ns)
{
if (localName == null)
{
throw new ArgumentNullException(nameof(localName));
}
if (localName.Length == 0)
{
throw new ArgumentException(SR.JsonInvalidLocalNameEmpty, nameof(localName));
}
if (!string.IsNullOrEmpty(prefix))
{
if (string.IsNullOrEmpty(ns) || !TrySetWritingNameWithMapping(localName, ns))
{
throw new ArgumentException(SR.Format(SR.JsonPrefixMustBeNullOrEmpty, prefix), nameof(prefix));
}
}
if (!string.IsNullOrEmpty(ns))
{
if (!TrySetWritingNameWithMapping(localName, ns))
{
throw new ArgumentException(SR.Format(SR.JsonNamespaceMustBeEmpty, ns), nameof(ns));
}
}
if (IsClosed)
{
ThrowClosed();
}
if (HasOpenAttribute)
{
throw new XmlException(SR.Format(SR.JsonOpenAttributeMustBeClosedFirst, "WriteStartElement"));
}
if ((_nodeType != JsonNodeType.None) && _depth == 0)
{
throw new XmlException(SR.JsonMultipleRootElementsNotAllowedOnWriter);
}
switch (_nodeType)
{
case JsonNodeType.None:
{
if (!localName.Equals(JsonGlobals.rootString))
{
throw new XmlException(SR.Format(SR.JsonInvalidRootElementName, localName, JsonGlobals.rootString));
}
EnterScope(JsonNodeType.Element);
break;
}
case JsonNodeType.Element:
{
if ((_dataType != JsonDataType.Array) && (_dataType != JsonDataType.Object))
{
throw new XmlException(SR.JsonNodeTypeArrayOrObjectNotSpecified);
}
if (_indent)
{
WriteNewLine();
WriteIndent();
}
if (!IsWritingCollection)
{
if (_nameState != NameState.IsWritingNameWithMapping)
{
WriteJsonElementName(localName);
}
}
else if (!localName.Equals(JsonGlobals.itemString))
{
throw new XmlException(SR.Format(SR.JsonInvalidItemNameForArrayElement, localName, JsonGlobals.itemString));
}
EnterScope(JsonNodeType.Element);
break;
}
case JsonNodeType.EndElement:
{
if (_endElementBuffer)
{
_nodeWriter.WriteText(JsonGlobals.MemberSeparatorChar);
}
if (_indent)
{
WriteNewLine();
WriteIndent();
}
if (!IsWritingCollection)
{
if (_nameState != NameState.IsWritingNameWithMapping)
{
WriteJsonElementName(localName);
}
}
else if (!localName.Equals(JsonGlobals.itemString))
{
throw new XmlException(SR.Format(SR.JsonInvalidItemNameForArrayElement, localName, JsonGlobals.itemString));
}
EnterScope(JsonNodeType.Element);
break;
}
default:
throw new XmlException(SR.JsonInvalidStartElementCall);
}
_isWritingDataTypeAttribute = false;
_isWritingServerTypeAttribute = false;
_isWritingXmlnsAttribute = false;
_wroteServerTypeAttribute = false;
_serverTypeValue = null;
_dataType = JsonDataType.None;
_nodeType = JsonNodeType.Element;
}
public override void WriteString(string text)
{
if (HasOpenAttribute && (text != null))
{
_attributeText += text;
}
else
{
if (text == null)
{
text = string.Empty;
}
// do work only when not indenting whitespace
if (!((_dataType == JsonDataType.Array || _dataType == JsonDataType.Object || _nodeType == JsonNodeType.EndElement) && XmlConverter.IsWhitespace(text)))
{
StartText();
WriteEscapedJsonString(text);
}
}
}
public override void WriteSurrogateCharEntity(char lowChar, char highChar)
{
WriteString(string.Concat(highChar, lowChar));
}
public override void WriteValue(bool value)
{
StartText();
_nodeWriter.WriteBoolText(value);
}
public override void WriteValue(decimal value)
{
StartText();
_nodeWriter.WriteDecimalText(value);
}
public override void WriteValue(double value)
{
StartText();
_nodeWriter.WriteDoubleText(value);
}
public override void WriteValue(float value)
{
StartText();
_nodeWriter.WriteFloatText(value);
}
public override void WriteValue(int value)
{
StartText();
_nodeWriter.WriteInt32Text(value);
}
public override void WriteValue(long value)
{
StartText();
_nodeWriter.WriteInt64Text(value);
}
public override void WriteValue(Guid value)
{
StartText();
_nodeWriter.WriteGuidText(value);
}
public override void WriteValue(DateTime value)
{
StartText();
_nodeWriter.WriteDateTimeText(value);
}
public override void WriteValue(string value)
{
WriteString(value);
}
public override void WriteValue(TimeSpan value)
{
StartText();
_nodeWriter.WriteTimeSpanText(value);
}
public override void WriteValue(UniqueId value)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
StartText();
_nodeWriter.WriteUniqueIdText(value);
}
public override void WriteValue(object value)
{
if (IsClosed)
{
ThrowClosed();
}
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
if (value is Array)
{
WriteValue((Array)value);
}
else if (value is IStreamProvider)
{
WriteValue((IStreamProvider)value);
}
else
{
WritePrimitiveValue(value);
}
}
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace", Justification = "This method is derived from the base")]
public override void WriteWhitespace(string ws)
{
if (IsClosed)
{
ThrowClosed();
}
if (ws == null)
{
throw new ArgumentNullException(nameof(ws));
}
for (int i = 0; i < ws.Length; ++i)
{
char c = ws[i];
if (c != ' ' &&
c != '\t' &&
c != '\n' &&
c != '\r')
{
throw new ArgumentException(SR.Format(SR.JsonOnlyWhitespace, c.ToString(), "WriteWhitespace"), nameof(ws));
}
}
WriteString(ws);
}
public override void WriteXmlAttribute(string localName, string value)
{
throw new NotSupportedException(SR.Format(SR.JsonMethodNotSupported, "WriteXmlAttribute"));
}
public override void WriteXmlAttribute(XmlDictionaryString localName, XmlDictionaryString value)
{
throw new NotSupportedException(SR.Format(SR.JsonMethodNotSupported, "WriteXmlAttribute"));
}
public override void WriteXmlnsAttribute(string prefix, string namespaceUri)
{
if (!IsWritingNameWithMapping)
{
throw new NotSupportedException(SR.Format(SR.JsonMethodNotSupported, "WriteXmlnsAttribute"));
}
}
public override void WriteXmlnsAttribute(string prefix, XmlDictionaryString namespaceUri)
{
if (!IsWritingNameWithMapping)
{
throw new NotSupportedException(SR.Format(SR.JsonMethodNotSupported, "WriteXmlnsAttribute"));
}
}
internal static bool CharacterNeedsEscaping(char ch)
{
return (ch == FORWARD_SLASH || ch == JsonGlobals.QuoteChar || ch < WHITESPACE || ch == BACK_SLASH
|| (ch >= HIGH_SURROGATE_START && (ch <= LOW_SURROGATE_END || ch >= MAX_CHAR)));
}
private static void ThrowClosed()
{
throw new InvalidOperationException(SR.JsonWriterClosed);
}
private void CheckText(JsonNodeType nextNodeType)
{
if (IsClosed)
{
ThrowClosed();
}
if (_depth == 0)
{
throw new InvalidOperationException(SR.XmlIllegalOutsideRoot);
}
if ((nextNodeType == JsonNodeType.StandaloneText) &&
(_nodeType == JsonNodeType.QuotedText))
{
throw new XmlException(SR.JsonCannotWriteStandaloneTextAfterQuotedText);
}
}
private void EnterScope(JsonNodeType currentNodeType)
{
_depth++;
if (_scopes == null)
{
_scopes = new JsonNodeType[4];
}
else if (_scopes.Length == _depth)
{
JsonNodeType[] newScopes = new JsonNodeType[_depth * 2];
Array.Copy(_scopes, 0, newScopes, 0, _depth);
_scopes = newScopes;
}
_scopes[_depth] = currentNodeType;
}
private JsonNodeType ExitScope()
{
JsonNodeType nodeTypeToReturn = _scopes[_depth];
_scopes[_depth] = JsonNodeType.None;
_depth--;
return nodeTypeToReturn;
}
private void InitializeWriter()
{
_nodeType = JsonNodeType.None;
_dataType = JsonDataType.None;
_isWritingDataTypeAttribute = false;
_wroteServerTypeAttribute = false;
_isWritingServerTypeAttribute = false;
_serverTypeValue = null;
_attributeText = null;
if (_depth != 0)
{
_depth = 0;
}
if ((_scopes != null) && (_scopes.Length > JsonGlobals.maxScopeSize))
{
_scopes = null;
}
// Can't let writeState be at Closed if reinitializing.
_writeState = WriteState.Start;
_endElementBuffer = false;
_indentLevel = 0;
}
private static bool IsUnicodeNewlineCharacter(char c)
{
// Newline characters in JSON strings need to be encoded on the way out (DevDiv #665974)
// See Unicode 6.2, Table 5-1 (http://www.unicode.org/versions/Unicode6.2.0/ch05.pdf]) for the full list.
// We only care about NEL, LS, and PS, since the other newline characters are all
// control characters so are already encoded.
return (c == '\u0085' || c == '\u2028' || c == '\u2029');
}
private void StartText()
{
if (HasOpenAttribute)
{
throw new InvalidOperationException(SR.JsonMustUseWriteStringForWritingAttributeValues);
}
if ((_dataType == JsonDataType.None) && (_serverTypeValue != null))
{
throw new XmlException(SR.Format(SR.JsonMustSpecifyDataType, JsonGlobals.typeString, JsonGlobals.objectString, JsonGlobals.serverTypeString));
}
if (IsWritingNameWithMapping && !WrittenNameWithMapping)
{
// Don't write out any text content unless the local name has been written.
// Not providing a better error message because localization deadline has passed.
throw new XmlException(SR.Format(SR.JsonMustSpecifyDataType, JsonGlobals.itemString, string.Empty, JsonGlobals.itemString));
}
if ((_dataType == JsonDataType.String) ||
(_dataType == JsonDataType.None))
{
CheckText(JsonNodeType.QuotedText);
if (_nodeType != JsonNodeType.QuotedText)
{
WriteJsonQuote();
}
_nodeType = JsonNodeType.QuotedText;
}
else if ((_dataType == JsonDataType.Number) ||
(_dataType == JsonDataType.Boolean))
{
CheckText(JsonNodeType.StandaloneText);
_nodeType = JsonNodeType.StandaloneText;
}
else
{
ThrowInvalidAttributeContent();
}
}
private void ThrowIfServerTypeWritten(string dataTypeSpecified)
{
if (_serverTypeValue != null)
{
throw new XmlException(SR.Format(SR.JsonInvalidDataTypeSpecifiedForServerType, JsonGlobals.typeString, dataTypeSpecified, JsonGlobals.serverTypeString, JsonGlobals.objectString));
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase")] // Microsoft, ToLowerInvariant is just used in Json error message
private void ThrowInvalidAttributeContent()
{
if (HasOpenAttribute)
{
throw new XmlException(SR.JsonInvalidMethodBetweenStartEndAttribute);
}
else
{
throw new XmlException(SR.Format(SR.JsonCannotWriteTextAfterNonTextAttribute, _dataType.ToString().ToLowerInvariant()));
}
}
private bool TrySetWritingNameWithMapping(string localName, string ns)
{
if (localName.Equals(JsonGlobals.itemString) && ns.Equals(JsonGlobals.itemString))
{
_nameState = NameState.IsWritingNameWithMapping;
return true;
}
return false;
}
private void WriteDataTypeServerType()
{
if (_dataType != JsonDataType.None)
{
switch (_dataType)
{
case JsonDataType.Array:
{
EnterScope(JsonNodeType.Collection);
_nodeWriter.WriteText(JsonGlobals.CollectionChar);
_indentLevel++;
break;
}
case JsonDataType.Object:
{
EnterScope(JsonNodeType.Object);
_nodeWriter.WriteText(JsonGlobals.ObjectChar);
_indentLevel++;
break;
}
case JsonDataType.Null:
{
_nodeWriter.WriteText(JsonGlobals.nullString);
break;
}
default:
break;
}
if (_serverTypeValue != null)
{
// dataType must be object because we throw in all other case.
WriteServerTypeAttribute();
}
}
}
private unsafe void WriteEscapedJsonString(string str)
{
fixed (char* chars = str)
{
int i = 0;
int j;
for (j = 0; j < str.Length; j++)
{
char ch = chars[j];
if (ch <= FORWARD_SLASH)
{
if (ch == FORWARD_SLASH || ch == JsonGlobals.QuoteChar)
{
_nodeWriter.WriteChars(chars + i, j - i);
_nodeWriter.WriteText(BACK_SLASH);
_nodeWriter.WriteText(ch);
i = j + 1;
}
else if (ch < WHITESPACE)
{
_nodeWriter.WriteChars(chars + i, j - i);
_nodeWriter.WriteText(s_escapedJsonStringTable[ch]);
i = j + 1;
}
}
else if (ch == BACK_SLASH)
{
_nodeWriter.WriteChars(chars + i, j - i);
_nodeWriter.WriteText(BACK_SLASH);
_nodeWriter.WriteText(ch);
i = j + 1;
}
else if ((ch >= HIGH_SURROGATE_START && (ch <= LOW_SURROGATE_END || ch >= MAX_CHAR)) || IsUnicodeNewlineCharacter(ch))
{
_nodeWriter.WriteChars(chars + i, j - i);
_nodeWriter.WriteText(BACK_SLASH);
_nodeWriter.WriteText('u');
_nodeWriter.WriteText(string.Format(CultureInfo.InvariantCulture, "{0:x4}", (int)ch));
i = j + 1;
}
}
if (i < j)
{
_nodeWriter.WriteChars(chars + i, j - i);
}
}
}
private void WriteIndent()
{
for (int i = 0; i < _indentLevel; i++)
{
_nodeWriter.WriteText(_indentChars);
}
}
private void WriteNewLine()
{
_nodeWriter.WriteText(CARRIAGE_RETURN);
_nodeWriter.WriteText(NEWLINE);
}
private void WriteJsonElementName(string localName)
{
WriteJsonQuote();
WriteEscapedJsonString(localName);
WriteJsonQuote();
_nodeWriter.WriteText(JsonGlobals.NameValueSeparatorChar);
if (_indent)
{
_nodeWriter.WriteText(WHITESPACE);
}
}
private void WriteJsonQuote()
{
_nodeWriter.WriteText(JsonGlobals.QuoteChar);
}
private void WritePrimitiveValue(object value)
{
if (IsClosed)
{
ThrowClosed();
}
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
if (value is ulong)
{
WriteValue((ulong)value);
}
else if (value is string)
{
WriteValue((string)value);
}
else if (value is int)
{
WriteValue((int)value);
}
else if (value is long)
{
WriteValue((long)value);
}
else if (value is bool)
{
WriteValue((bool)value);
}
else if (value is double)
{
WriteValue((double)value);
}
else if (value is DateTime)
{
WriteValue((DateTime)value);
}
else if (value is float)
{
WriteValue((float)value);
}
else if (value is decimal)
{
WriteValue((decimal)value);
}
else if (value is XmlDictionaryString)
{
WriteValue((XmlDictionaryString)value);
}
else if (value is UniqueId)
{
WriteValue((UniqueId)value);
}
else if (value is Guid)
{
WriteValue((Guid)value);
}
else if (value is TimeSpan)
{
WriteValue((TimeSpan)value);
}
else if (value.GetType().IsArray)
{
throw new ArgumentException(SR.JsonNestedArraysNotSupported, nameof(value));
}
else
{
base.WriteValue(value);
}
}
private void WriteServerTypeAttribute()
{
string value = _serverTypeValue;
JsonDataType oldDataType = _dataType;
NameState oldNameState = _nameState;
WriteStartElement(JsonGlobals.serverTypeString);
WriteValue(value);
WriteEndElement();
_dataType = oldDataType;
_nameState = oldNameState;
_wroteServerTypeAttribute = true;
}
private void WriteValue(ulong value)
{
StartText();
_nodeWriter.WriteUInt64Text(value);
}
private void WriteValue(Array array)
{
// This method is called only if WriteValue(object) is called with an array
// The contract for XmlWriter.WriteValue(object) requires that this object array be written out as a string.
// E.g. WriteValue(new int[] { 1, 2, 3}) should be equivalent to WriteString("1 2 3").
JsonDataType oldDataType = _dataType;
// Set attribute mode to String because WritePrimitiveValue might write numerical text.
// Calls to methods that write numbers can't be mixed with calls that write quoted text unless the attribute mode is explicitly string.
_dataType = JsonDataType.String;
StartText();
for (int i = 0; i < array.Length; i++)
{
if (i != 0)
{
_nodeWriter.WriteText(JsonGlobals.WhitespaceChar);
}
WritePrimitiveValue(array.GetValue(i));
}
_dataType = oldDataType;
}
private class JsonNodeWriter : XmlUTF8NodeWriter
{
internal unsafe void WriteChars(char* chars, int charCount)
{
base.UnsafeWriteUTF8Chars(chars, charCount);
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace owin_scim_host.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using UnityEngine;
/// <summary>
/// <c>FalkenGame</c> AI player that can be trained to play and test games.
/// </summary>
[Serializable]
public abstract class FalkenGame<PlayerBrainSpec> : MonoBehaviour
where PlayerBrainSpec : Falken.BrainSpecBase, new()
{
[Tooltip("The Falken service project ID.")]
public string falkenProjectId = "";
[Tooltip("The Falken service API Key.")]
public string falkenApiKey = "";
[Tooltip("The Falken brain human readable name.")]
public string brainDisplayName = "A Brain";
[Tooltip("The Falken brain ID.")]
public string brainId = null;
[Tooltip("[Optional] The Falken session snapshot ID.")]
public string snapshotId = null;
[Tooltip("The maximum number of steps per episode.")]
public uint falkenMaxSteps = 300;
[Tooltip("The type of session to create.")]
public Falken.Session.Type sessionType = Falken.Session.Type.InteractiveTraining;
[Tooltip("Determines whether Falken or the Player should be in control.")]
public bool humanControlled = true;
[Tooltip("Set to false to disable the rendering of control and training status.")]
public bool renderGameHUD = true;
private Falken.Service _service = null;
private Falken.BrainBase _brain = null;
private Falken.Session _session = null;
private int _steps;
/// <summary>
/// Getter for brain spec.
/// </summary>
protected PlayerBrainSpec BrainSpec
{
get
{
return (PlayerBrainSpec)(_brain?.BrainSpecBase);
}
}
/// <summary>
/// Getter for training state.
/// </summary>
protected Falken.Session.TrainingState TrainingState
{
get
{
return _session != null ? _session.SessionTrainingState :
Falken.Session.TrainingState.Invalid;
}
}
/// <summary>
/// Getter for training progress.
/// </summary>
protected float TrainingProgress
{
get
{
return _session != null ? _session.SessionTrainingProgress : 0f;
}
}
/// <summary>
/// Returns true if we've had more FixedUpdates than max steps.
/// </summary>
protected bool EpisodeCompleted
{
get
{
return _steps >= falkenMaxSteps - 1;
}
}
/// <summary>
/// Connects to Falken service and creates or loads a brain.
/// </summary>
protected void Init()
{
Init<PlayerBrainSpec>();
}
/// <summary>
/// Connects to Falken service and creates or loads a brain spec subclass.
/// </summary>
protected void Init<BrainSpec>() where BrainSpec : PlayerBrainSpec, new()
{
// Connect to Falken service.
_service = Falken.Service.Connect(falkenProjectId, falkenApiKey);
if (_service == null)
{
Debug.LogWarning(
"Failed to connect to Falken's services. Make sure" +
"You have a valid api key and project id or your " +
"json config is properly formated.");
return;
}
// If there is no brainId, create a new one. Othewise, load an existing
// brain.
if (String.IsNullOrEmpty(brainId))
{
_brain = _service.CreateBrain<BrainSpec>(brainDisplayName);
}
else
{
_brain = _service.LoadBrain<BrainSpec>(brainId, snapshotId);
}
if (_brain == null)
{
return;
}
brainId = _brain.Id;
// Create session.
_session = _brain.StartSession(sessionType, falkenMaxSteps);
if (humanControlled && sessionType != Falken.Session.Type.InteractiveTraining) {
humanControlled = false;
ControlChanged();
}
}
/// <summary>
/// Starts a new episode.
/// </summary>
protected Falken.Episode CreateEpisode()
{
_steps = 0;
return _session?.StartEpisode();
}
/// <summary>
/// Stops a session.
/// </summary>
protected void StopSession()
{
if (_session != null)
{
snapshotId = _session.Stop();
Debug.Log($"Stopped session with snapshot ID: {snapshotId}");
_session = null;
}
}
/// <summary>
/// Deletes the brain and disconnects from the Falken service.
/// </summary>
protected void Shutdown()
{
StopSession();
Debug.Log($"Shutting down brain {brainId}");
_brain = null;
_service = null;
}
protected abstract void ControlChanged();
void FixedUpdate()
{
++_steps;
}
void Update()
{
if (Input.GetButtonDown("ToggleControl") &&
sessionType == Falken.Session.Type.InteractiveTraining)
{
humanControlled = !humanControlled;
ControlChanged();
}
}
void OnGUI()
{
if (!renderGameHUD)
{
return;
}
// Show the current FPS and Timescale
GUIStyle style = new GUIStyle();
style.alignment = TextAnchor.UpperCenter;
style.normal.textColor = new Color(0.0f, 0.0f, 0.0f, 0.8f);
string content = "Control: " + (humanControlled ? "Human" : "Falken");
var trainingState = TrainingState;
int percentComplete = (int)(TrainingProgress * 100);
content += "\n" +
((trainingState == Falken.Session.TrainingState.Complete) ?
"Training Complete" : trainingState.ToString().ToLower()) +
$" ({percentComplete}%)";
const int width = 100;
GUI.Label(new Rect(Screen.width / 2 - width / 2, 10, width, 20), content, style);
}
}
| |
using UnityEngine;
using System;
namespace Stratus
{
public enum StratusNumericType
{
Integer,
Float
}
}
namespace Stratus.Utilities
{
/// <summary>
/// @note Credit to Or Aviram:
/// https://forum.unity3d.com/threads/draw-a-field-only-if-a-condition-is-met.448855/
/// </summary>
public static partial class StratusTypes
{
/// <summary>
/// Whether this object is a numeric type
/// </summary>
/// <param name="obj"></param>
/// <returns>True if its a numeric type, false otherwise.</returns>
public static bool IsNumeric(this object obj)
{
switch (Type.GetTypeCode(obj.GetType()))
{
case TypeCode.Byte:
case TypeCode.SByte:
case TypeCode.UInt16:
case TypeCode.UInt32:
case TypeCode.UInt64:
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.Decimal:
case TypeCode.Double:
case TypeCode.Single:
return true;
default:
return false;
}
}
/// <summary>
/// Whether this type is numeric
/// </summary>
/// <param name="type"></param>
/// <returns>True if the type is numeric, false otherwise.</returns>
public static bool IsNumeric(this Type type)
{
switch (Type.GetTypeCode(type))
{
case TypeCode.Byte:
case TypeCode.SByte:
case TypeCode.UInt16:
case TypeCode.UInt32:
case TypeCode.UInt64:
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.Decimal:
case TypeCode.Double:
case TypeCode.Single:
return true;
default:
return false;
}
}
}
/// <summary>
/// An exception that is thrown whenever a numeric type is expected as an input somewhere but the input wasn't numeric.
/// </summary>
[Serializable]
public class StratusNumericTypeExpectedException : Exception
{
public StratusNumericTypeExpectedException() { }
public StratusNumericTypeExpectedException(string message) : base(message) { }
public StratusNumericTypeExpectedException(string message, Exception inner) : base(message, inner) { }
protected StratusNumericTypeExpectedException(
System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context) : base(info, context) { }
}
public class StratusNumeric : IEquatable<StratusNumeric>
{
object Value;
Type Type;
/// <summary>
/// Constructor
/// </summary>
/// <param name="obj"></param>
public StratusNumeric(object obj)
{
if (!obj.IsNumeric())
throw new StratusNumericTypeExpectedException("The type of the object passed in the constructor must be numeric!");
Value = obj;
Type = obj.GetType();
}
public object GetValue() { return Value; }
public void SetValue(object newValue) { Value = newValue; }
public bool Equals(StratusNumeric other) { return this == other; }
public override bool Equals(object obj)
{
if (obj == null) return false;
if (!(obj is StratusNumeric)) return GetValue() == obj;
return Equals(obj);
}
public override int GetHashCode() { return GetValue().GetHashCode(); }
public override string ToString() { return GetValue().ToString(); }
/// <summary>
/// Checks if the value of the left is lesser than that of the right
/// </summary>
/// <param name="lhs"></param>
/// <param name="rhs"></param>
/// <returns></returns>
public static bool operator <(StratusNumeric lhs, StratusNumeric rhs)
{
object leftValue = lhs.GetValue();
object rightValue = rhs.GetValue();
switch (Type.GetTypeCode(lhs.Type))
{
case TypeCode.Byte:
return (byte)leftValue < (byte)rightValue;
case TypeCode.SByte:
return (sbyte)leftValue < (sbyte)rightValue;
case TypeCode.UInt16:
return (ushort)leftValue < (ushort)rightValue;
case TypeCode.UInt32:
return (uint)leftValue < (uint)rightValue;
case TypeCode.UInt64:
return (ulong)leftValue < (ulong)rightValue;
case TypeCode.Int16:
return (short)leftValue < (short)rightValue;
case TypeCode.Int32:
return (int)leftValue < (int)rightValue;
case TypeCode.Int64:
return (long)leftValue < (long)rightValue;
case TypeCode.Decimal:
return (decimal)leftValue < (decimal)rightValue;
case TypeCode.Double:
return (double)leftValue < (double)rightValue;
case TypeCode.Single:
return (float)leftValue < (float)rightValue;
}
throw new StratusNumericTypeExpectedException("Please compare valid numeric types.");
}
/// <summary>
/// Checks if the value of left is greater than the value of right.
/// </summary>
public static bool operator >(StratusNumeric left, StratusNumeric right)
{
object leftValue = left.GetValue();
object rightValue = right.GetValue();
switch (Type.GetTypeCode(left.Type))
{
case TypeCode.Byte:
return (byte)leftValue > (byte)rightValue;
case TypeCode.SByte:
return (sbyte)leftValue > (sbyte)rightValue;
case TypeCode.UInt16:
return (ushort)leftValue > (ushort)rightValue;
case TypeCode.UInt32:
return (uint)leftValue > (uint)rightValue;
case TypeCode.UInt64:
return (ulong)leftValue > (ulong)rightValue;
case TypeCode.Int16:
return (short)leftValue > (short)rightValue;
case TypeCode.Int32:
return (int)leftValue > (int)rightValue;
case TypeCode.Int64:
return (long)leftValue > (long)rightValue;
case TypeCode.Decimal:
return (decimal)leftValue > (decimal)rightValue;
case TypeCode.Double:
return (double)leftValue > (double)rightValue;
case TypeCode.Single:
return (float)leftValue > (float)rightValue;
}
throw new StratusNumericTypeExpectedException("Please compare valid numeric types.");
}
/// <summary>
/// Checks if the value of left is the same as the value of right.
/// </summary>
public static bool operator ==(StratusNumeric left, StratusNumeric right)
{
return !(left > right) && !(left < right);
}
/// <summary>
/// Checks if the value of left is not the same as the value of right.
/// </summary>
public static bool operator !=(StratusNumeric left, StratusNumeric right)
{
return !(left > right) || !(left < right);
}
/// <summary>
/// Checks if left is either equal or smaller than right.
/// </summary>
public static bool operator <=(StratusNumeric left, StratusNumeric right)
{
return left == right || left < right;
}
/// <summary>
/// Checks if left is either equal or greater than right.
/// </summary>
public static bool operator >=(StratusNumeric left, StratusNumeric right)
{
return left == right || left > right;
}
}
/// <summary>
/// For generic numeric types
/// </summary>
/// <typeparam name="T"></typeparam>
public class INumeric<T> : IEquatable<INumeric<T>>
{
private T value;
private Type type;
public INumeric(T obj)
{
if (!typeof(T).IsNumeric())
{
// Something bad happened.
throw new StratusNumericTypeExpectedException("The type inputted into the NumericType generic must be a numeric type.");
}
type = typeof(T);
value = obj;
}
public T GetValue()
{
return value;
}
public object GetValueAsObject()
{
return value;
}
public void SetValue(T newValue)
{
value = newValue;
}
public bool Equals(INumeric<T> other)
{
return this == other;
}
public override bool Equals(object obj)
{
if (obj != null && !(obj is INumeric<T>))
return false;
return Equals(obj);
}
public override int GetHashCode()
{
return GetValue().GetHashCode();
}
public override string ToString()
{
return GetValue().ToString();
}
/// <summary>
/// Checks if the value of left is smaller than the value of right.
/// </summary>
public static bool operator <(INumeric<T> left, INumeric<T> right)
{
object leftValue = left.GetValueAsObject();
object rightValue = right.GetValueAsObject();
switch (Type.GetTypeCode(left.type))
{
case TypeCode.Byte:
return (byte)leftValue < (byte)rightValue;
case TypeCode.SByte:
return (sbyte)leftValue < (sbyte)rightValue;
case TypeCode.UInt16:
return (ushort)leftValue < (ushort)rightValue;
case TypeCode.UInt32:
return (uint)leftValue < (uint)rightValue;
case TypeCode.UInt64:
return (ulong)leftValue < (ulong)rightValue;
case TypeCode.Int16:
return (short)leftValue < (short)rightValue;
case TypeCode.Int32:
return (int)leftValue < (int)rightValue;
case TypeCode.Int64:
return (long)leftValue < (long)rightValue;
case TypeCode.Decimal:
return (decimal)leftValue < (decimal)rightValue;
case TypeCode.Double:
return (double)leftValue < (double)rightValue;
case TypeCode.Single:
return (float)leftValue < (float)rightValue;
}
throw new StratusNumericTypeExpectedException("Please compare valid numeric types with numeric generics.");
}
/// <summary>
/// Checks if the value of left is greater than the value of right.
/// </summary>
public static bool operator >(INumeric<T> left, INumeric<T> right)
{
object leftValue = left.GetValueAsObject();
object rightValue = right.GetValueAsObject();
switch (Type.GetTypeCode(left.type))
{
case TypeCode.Byte:
return (byte)leftValue > (byte)rightValue;
case TypeCode.SByte:
return (sbyte)leftValue > (sbyte)rightValue;
case TypeCode.UInt16:
return (ushort)leftValue > (ushort)rightValue;
case TypeCode.UInt32:
return (uint)leftValue > (uint)rightValue;
case TypeCode.UInt64:
return (ulong)leftValue > (ulong)rightValue;
case TypeCode.Int16:
return (short)leftValue > (short)rightValue;
case TypeCode.Int32:
return (int)leftValue > (int)rightValue;
case TypeCode.Int64:
return (long)leftValue > (long)rightValue;
case TypeCode.Decimal:
return (decimal)leftValue > (decimal)rightValue;
case TypeCode.Double:
return (double)leftValue > (double)rightValue;
case TypeCode.Single:
return (float)leftValue > (float)rightValue;
}
throw new StratusNumericTypeExpectedException("Please compare valid numeric types.");
}
/// <summary>
/// Checks if the value of left is the same as the value of right.
/// </summary>
public static bool operator ==(INumeric<T> left, INumeric<T> right)
{
return !(left > right) && !(left < right);
}
/// <summary>
/// Checks if the value of left is not the same as the value of right.
/// </summary>
public static bool operator !=(INumeric<T> left, INumeric<T> right)
{
return !(left > right) || !(left < right);
}
/// <summary>
/// Checks if left is either equal or smaller than right.
/// </summary>
public static bool operator <=(INumeric<T> left, INumeric<T> right)
{
return left == right || left < right;
}
/// <summary>
/// Checks if left is either equal or greater than right.
/// </summary>
public static bool operator >=(INumeric<T> left, INumeric<T> right)
{
return left == right || left > right;
}
}
}
| |
// Copyright (c) DotSpatial Team. All rights reserved.
// Licensed under the MIT license. See License.txt file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml;
using System.Xml.Linq;
namespace DotSpatial.Plugins.MapWindowProjectFileCompatibility
{
/// <summary>
/// http://mutable.net/blog/archive/2010/07/07/yet-another-take-on-a-dynamicobject-wrapper-for-xml.aspx.
/// </summary>
public class DynamicXMLNode : DynamicObject
{
#region Fields
private readonly XElement _node;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="DynamicXMLNode"/> class.
/// </summary>
/// <param name="node">The node.</param>
public DynamicXMLNode(XElement node)
{
_node = node;
}
/// <summary>
/// Initializes a new instance of the <see cref="DynamicXMLNode"/> class.
/// </summary>
/// <param name="name">The name.</param>
public DynamicXMLNode(string name)
{
_node = new XElement(name);
}
/// <summary>
/// Initializes a new instance of the <see cref="DynamicXMLNode"/> class.
/// </summary>
public DynamicXMLNode()
{
}
#endregion
#region Methods
/// <summary>
/// Loads the specified URI.
/// </summary>
/// <param name="uri">The URI.</param>
/// <returns>The resulting DynamicXMLNode.</returns>
public static DynamicXMLNode Load(string uri)
{
return new DynamicXMLNode(XElement.Load(uri));
}
/// <summary>
/// Loads the specified stream.
/// </summary>
/// <param name="stream">The stream.</param>
/// <returns>The resulting DynamicXMLNode.</returns>
public static DynamicXMLNode Load(Stream stream)
{
return new DynamicXMLNode(XElement.Load(stream));
}
/// <summary>
/// Loads the specified text reader.
/// </summary>
/// <param name="textReader">The text reader.</param>
/// <returns>The resulting DynamicXMLNode.</returns>
public static DynamicXMLNode Load(TextReader textReader)
{
return new DynamicXMLNode(XElement.Load(textReader));
}
/// <summary>
/// Loads the specified reader.
/// </summary>
/// <param name="reader">The reader.</param>
/// <returns>The resulting DynamicXMLNode.</returns>
public static DynamicXMLNode Load(XmlReader reader)
{
return new DynamicXMLNode(XElement.Load(reader));
}
/// <summary>
/// Loads the specified stream.
/// </summary>
/// <param name="stream">The stream.</param>
/// <param name="options">The options.</param>
/// <returns>The resulting DynamicXMLNode.</returns>
public static DynamicXMLNode Load(Stream stream, LoadOptions options)
{
return new DynamicXMLNode(XElement.Load(stream, options));
}
/// <summary>
/// Loads the specified URI.
/// </summary>
/// <param name="uri">The URI.</param>
/// <param name="options">The options.</param>
/// <returns>The resulting DynamicXMLNode.</returns>
public static DynamicXMLNode Load(string uri, LoadOptions options)
{
return new DynamicXMLNode(XElement.Load(uri, options));
}
/// <summary>
/// Loads the specified text reader.
/// </summary>
/// <param name="textReader">The text reader.</param>
/// <param name="options">The options.</param>
/// <returns>The resulting DynamicXMLNode.</returns>
public static DynamicXMLNode Load(TextReader textReader, LoadOptions options)
{
return new DynamicXMLNode(XElement.Load(textReader, options));
}
/// <summary>
/// Loads the specified reader.
/// </summary>
/// <param name="reader">The reader.</param>
/// <param name="options">The options.</param>
/// <returns>The resulting DynamicXMLNode.</returns>
public static DynamicXMLNode Load(XmlReader reader, LoadOptions options)
{
return new DynamicXMLNode(XElement.Load(reader, options));
}
/// <summary>
/// Parses the specified text.
/// </summary>
/// <param name="text">The text.</param>
/// <returns>The parse result.</returns>
public static DynamicXMLNode Parse(string text)
{
return new DynamicXMLNode(XElement.Parse(text));
}
/// <summary>
/// Parses the specified text.
/// </summary>
/// <param name="text">The text.</param>
/// <param name="options">The options.</param>
/// <returns>The parse result.</returns>
public static DynamicXMLNode Parse(string text, LoadOptions options)
{
return new DynamicXMLNode(XElement.Parse(text, options));
}
/// <summary>
/// Provides implementation for type conversion operations. Classes derived from the <see cref="T:System.Dynamic.DynamicObject"/> class can override this method to specify dynamic behavior for operations that convert an object from one type to another.
/// </summary>
/// <param name="binder">Provides information about the conversion operation. The binder.Type property provides the type to which the object must be converted. For example, for the statement (String)sampleObject in C# (CType(sampleObject, Type) in Visual Basic), where sampleObject is an instance of the class derived from the <see cref="T:System.Dynamic.DynamicObject"/> class, binder.Type returns the <see cref="T:System.String"/> type. The binder.Explicit property provides information about the kind of conversion that occurs. It returns true for explicit conversion and false for implicit conversion.</param>
/// <param name="result">The result of the type conversion operation.</param>
/// <returns>
/// true if the operation is successful; otherwise, false. If this method returns false, the run-time binder of the language determines the behavior. (In most cases, a language-specific run-time exception is thrown.)
/// </returns>
public override bool TryConvert(ConvertBinder binder, out object result)
{
if (binder.Type == typeof(XElement))
{
result = _node;
}
else if (binder.Type == typeof(string))
{
result = _node.Value;
}
else
{
result = false;
return false;
}
return true;
}
/// <summary>
/// Provides the implementation for operations that get a value by index. Classes derived from the <see cref="T:System.Dynamic.DynamicObject"/> class can override this method to specify dynamic behavior for indexing operations.
/// </summary>
/// <param name="binder">Provides information about the operation.</param>
/// <param name="indexes">The indexes that are used in the operation. </param>
/// <param name="result">The result of the index operation.</param>
/// <returns>
/// true if the operation is successful; otherwise, false. If this method returns false, the run-time binder of the language determines the behavior. (In most cases, a run-time exception is thrown.)
/// </returns>
public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result)
{
var s = indexes[0] as string;
if (s != null)
{
XAttribute attr = _node.Attribute(s);
if (attr != null)
{
result = attr.Value;
return true;
}
}
result = null;
return false;
}
/// <summary>
/// Provides the implementation for operations that get member values. Classes derived from the <see cref="T:System.Dynamic.DynamicObject"/> class can override this method to specify dynamic behavior for operations such as getting a value for a property.
/// </summary>
/// <param name="binder">Provides information about the object that called the dynamic operation. The binder.Name property provides the name of the member on which the dynamic operation is performed. For example, for the Console.WriteLine(sampleObject.SampleProperty) statement, where sampleObject is an instance of the class derived from the <see cref="T:System.Dynamic.DynamicObject"/> class, binder.Name returns "SampleProperty". The binder.IgnoreCase property specifies whether the member name is case-sensitive.</param>
/// <param name="result">The result of the get operation. For example, if the method is called for a property, you can assign the property value to <paramref name="result"/>.</param>
/// <returns>
/// true if the operation is successful; otherwise, false. If this method returns false, the run-time binder of the language determines the behavior. (In most cases, a run-time exception is thrown.)
/// </returns>
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
XElement getNode = _node.Element(binder.Name);
if (getNode != null)
{
result = new DynamicXMLNode(getNode);
return true;
}
result = null;
return false;
}
/// <summary>
/// Provides the implementation for operations that invoke a member. Classes derived from the <see cref="T:System.Dynamic.DynamicObject"/> class can override this method to specify dynamic behavior for operations such as calling a method.
/// </summary>
/// <param name="binder">Provides information about the dynamic operation. The binder.Name property provides the name of the member on which the dynamic operation is performed. For example, for the statement sampleObject.SampleMethod(100), where sampleObject is an instance of the class derived from the <see cref="T:System.Dynamic.DynamicObject"/> class, binder.Name returns "SampleMethod". The binder.IgnoreCase property specifies whether the member name is case-sensitive.</param>
/// <param name="args">The arguments that are passed to the object member during the invoke operation. </param>
/// <param name="result">The result of the member invocation.</param>
/// <returns>
/// true if the operation is successful; otherwise, false. If this method returns false, the run-time binder of the language determines the behavior. (In most cases, a language-specific run-time exception is thrown.)
/// </returns>
public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
{
Type xmlType = typeof(XElement);
try
{
// unwrap parameters: if the parameters are DynamicXMLNode then pass in the inner XElement node
List<object> newargs = null;
var argtypes = args.Select(x => x.GetType()).ToList(); // because GetTypeArray is not supported in Silverlight
if (argtypes.Contains(typeof(DynamicXMLNode)) || argtypes.Contains(typeof(DynamicXMLNode[])))
{
newargs = new List<object>();
foreach (var arg in args)
{
if (arg.GetType() == typeof(DynamicXMLNode))
{
newargs.Add(((DynamicXMLNode)arg)._node);
}
else if (arg.GetType() == typeof(DynamicXMLNode[]))
{
// unwrap array of DynamicXMLNode
newargs.Add(((DynamicXMLNode[])arg).Select(x => x._node));
}
else
{
newargs.Add(arg);
}
}
}
result = xmlType.InvokeMember(binder.Name, BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance, null, _node, newargs?.ToArray() ?? args);
// wrap return value: if the results are an IEnumerable<XElement>, then return a wrapped collection of DynamicXMLNode
if (result != null && typeof(IEnumerable<XElement>).IsAssignableFrom(result.GetType()))
{
result = ((IEnumerable<XElement>)result).Select(x => new DynamicXMLNode(x));
}
// Note: we could wrap single XElement too but nothing returns that
return true;
}
catch
{
result = null;
return false;
}
}
/// <summary>
/// Provides the implementation for operations that set a value by index. Classes derived from the <see cref="T:System.Dynamic.DynamicObject"/> class can override this method to specify dynamic behavior for operations that access objects by a specified index.
/// </summary>
/// <param name="binder">Provides information about the operation.</param>
/// <param name="indexes">The indexes that are used in the operation.</param>
/// <param name="value">The value to set to the object that has the specified index. For example, for the sampleObject[3] = 10 operation in C# (sampleObject(3) = 10 in Visual Basic), where sampleObject is derived from the <see cref="T:System.Dynamic.DynamicObject"/> class, <paramref name="value"/> is equal to 10.</param>
/// <returns>
/// true if the operation is successful; otherwise, false. If this method returns false, the run-time binder of the language determines the behavior. (In most cases, a language-specific run-time exception is thrown.
/// </returns>
public override bool TrySetIndex(SetIndexBinder binder, object[] indexes, object value)
{
var s = indexes[0] as string;
if (s != null)
{
_node.SetAttributeValue(s, value);
return true;
}
return false;
}
/// <summary>
/// Provides the implementation for operations that set member values. Classes derived from the <see cref="T:System.Dynamic.DynamicObject"/> class can override this method to specify dynamic behavior for operations such as setting a value for a property.
/// </summary>
/// <param name="binder">Provides information about the object that called the dynamic operation. The binder.Name property provides the name of the member to which the value is being assigned. For example, for the statement sampleObject.SampleProperty = "Test", where sampleObject is an instance of the class derived from the <see cref="T:System.Dynamic.DynamicObject"/> class, binder.Name returns "SampleProperty". The binder.IgnoreCase property specifies whether the member name is case-sensitive.</param>
/// <param name="value">The value to set to the member. For example, for sampleObject.SampleProperty = "Test", where sampleObject is an instance of the class derived from the <see cref="T:System.Dynamic.DynamicObject"/> class, the <paramref name="value"/> is "Test".</param>
/// <returns>
/// true if the operation is successful; otherwise, false. If this method returns false, the run-time binder of the language determines the behavior. (In most cases, a language-specific run-time exception is thrown.)
/// </returns>
public override bool TrySetMember(SetMemberBinder binder, object value)
{
XElement setNode = _node.Element(binder.Name);
if (setNode != null)
{
setNode.SetValue(value);
}
else
{
_node.Add(value.GetType() == typeof(DynamicXMLNode) ? new XElement(binder.Name) : new XElement(binder.Name, value));
}
return true;
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
using System;
using Microsoft.Scripting.Utils;
namespace Microsoft.Scripting.Interpreter {
internal abstract class NumericConvertInstruction : Instruction {
internal readonly TypeCode _from, _to;
protected NumericConvertInstruction(TypeCode from, TypeCode to) {
_from = from;
_to = to;
}
public override int ConsumedStack => 1;
public override int ProducedStack => 1;
public override string ToString() {
return InstructionName + "(" + _from + "->" + _to + ")";
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")]
public sealed class Unchecked : NumericConvertInstruction {
public override string InstructionName => "UncheckedConvert";
public Unchecked(TypeCode from, TypeCode to)
: base(from, to) {
}
public override int Run(InterpretedFrame frame) {
frame.Push(Convert(frame.Pop()));
return +1;
}
private object Convert(object obj) {
switch (_from) {
case TypeCode.Byte: return ConvertInt32((Byte)obj);
case TypeCode.SByte: return ConvertInt32((SByte)obj);
case TypeCode.Int16: return ConvertInt32((Int16)obj);
case TypeCode.Char: return ConvertInt32((Char)obj);
case TypeCode.Int32: return ConvertInt32((Int32)obj);
case TypeCode.Int64: return ConvertInt64((Int64)obj);
case TypeCode.UInt16: return ConvertInt32((UInt16)obj);
case TypeCode.UInt32: return ConvertInt64((UInt32)obj);
case TypeCode.UInt64: return ConvertUInt64((UInt64)obj);
case TypeCode.Single: return ConvertDouble((Single)obj);
case TypeCode.Double: return ConvertDouble((Double)obj);
default: throw Assert.Unreachable;
}
}
private object ConvertInt32(int obj) {
unchecked {
switch (_to) {
case TypeCode.Byte: return (Byte)obj;
case TypeCode.SByte: return (SByte)obj;
case TypeCode.Int16: return (Int16)obj;
case TypeCode.Char: return (Char)obj;
case TypeCode.Int32: return (Int32)obj;
case TypeCode.Int64: return (Int64)obj;
case TypeCode.UInt16: return (UInt16)obj;
case TypeCode.UInt32: return (UInt32)obj;
case TypeCode.UInt64: return (UInt64)obj;
case TypeCode.Single: return (Single)obj;
case TypeCode.Double: return (Double)obj;
default: throw Assert.Unreachable;
}
}
}
private object ConvertInt64(Int64 obj) {
unchecked {
switch (_to) {
case TypeCode.Byte: return (Byte)obj;
case TypeCode.SByte: return (SByte)obj;
case TypeCode.Int16: return (Int16)obj;
case TypeCode.Char: return (Char)obj;
case TypeCode.Int32: return (Int32)obj;
case TypeCode.Int64: return (Int64)obj;
case TypeCode.UInt16: return (UInt16)obj;
case TypeCode.UInt32: return (UInt32)obj;
case TypeCode.UInt64: return (UInt64)obj;
case TypeCode.Single: return (Single)obj;
case TypeCode.Double: return (Double)obj;
default: throw Assert.Unreachable;
}
}
}
private object ConvertUInt64(UInt64 obj) {
unchecked {
switch (_to) {
case TypeCode.Byte: return (Byte)obj;
case TypeCode.SByte: return (SByte)obj;
case TypeCode.Int16: return (Int16)obj;
case TypeCode.Char: return (Char)obj;
case TypeCode.Int32: return (Int32)obj;
case TypeCode.Int64: return (Int64)obj;
case TypeCode.UInt16: return (UInt16)obj;
case TypeCode.UInt32: return (UInt32)obj;
case TypeCode.UInt64: return (UInt64)obj;
case TypeCode.Single: return (Single)obj;
case TypeCode.Double: return (Double)obj;
default: throw Assert.Unreachable;
}
}
}
private object ConvertDouble(Double obj) {
unchecked {
switch (_to) {
case TypeCode.Byte: return (Byte)obj;
case TypeCode.SByte: return (SByte)obj;
case TypeCode.Int16: return (Int16)obj;
case TypeCode.Char: return (Char)obj;
case TypeCode.Int32: return (Int32)obj;
case TypeCode.Int64: return (Int64)obj;
case TypeCode.UInt16: return (UInt16)obj;
case TypeCode.UInt32: return (UInt32)obj;
case TypeCode.UInt64: return (UInt64)obj;
case TypeCode.Single: return (Single)obj;
case TypeCode.Double: return (Double)obj;
default: throw Assert.Unreachable;
}
}
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")]
public sealed class Checked : NumericConvertInstruction {
public override string InstructionName => "CheckedConvert";
public Checked(TypeCode from, TypeCode to)
: base(from, to) {
}
public override int Run(InterpretedFrame frame) {
frame.Push(Convert(frame.Pop()));
return +1;
}
private object Convert(object obj) {
switch (_from) {
case TypeCode.Byte: return ConvertInt32((Byte)obj);
case TypeCode.SByte: return ConvertInt32((SByte)obj);
case TypeCode.Int16: return ConvertInt32((Int16)obj);
case TypeCode.Char: return ConvertInt32((Char)obj);
case TypeCode.Int32: return ConvertInt32((Int32)obj);
case TypeCode.Int64: return ConvertInt64((Int64)obj);
case TypeCode.UInt16: return ConvertInt32((UInt16)obj);
case TypeCode.UInt32: return ConvertInt64((UInt32)obj);
case TypeCode.UInt64: return ConvertUInt64((UInt64)obj);
case TypeCode.Single: return ConvertDouble((Single)obj);
case TypeCode.Double: return ConvertDouble((Double)obj);
default: throw Assert.Unreachable;
}
}
private object ConvertInt32(int obj) {
checked {
switch (_to) {
case TypeCode.Byte: return (Byte)obj;
case TypeCode.SByte: return (SByte)obj;
case TypeCode.Int16: return (Int16)obj;
case TypeCode.Char: return (Char)obj;
case TypeCode.Int32: return (Int32)obj;
case TypeCode.Int64: return (Int64)obj;
case TypeCode.UInt16: return (UInt16)obj;
case TypeCode.UInt32: return (UInt32)obj;
case TypeCode.UInt64: return (UInt64)obj;
case TypeCode.Single: return (Single)obj;
case TypeCode.Double: return (Double)obj;
default: throw Assert.Unreachable;
}
}
}
private object ConvertInt64(Int64 obj) {
checked {
switch (_to) {
case TypeCode.Byte: return (Byte)obj;
case TypeCode.SByte: return (SByte)obj;
case TypeCode.Int16: return (Int16)obj;
case TypeCode.Char: return (Char)obj;
case TypeCode.Int32: return (Int32)obj;
case TypeCode.Int64: return (Int64)obj;
case TypeCode.UInt16: return (UInt16)obj;
case TypeCode.UInt32: return (UInt32)obj;
case TypeCode.UInt64: return (UInt64)obj;
case TypeCode.Single: return (Single)obj;
case TypeCode.Double: return (Double)obj;
default: throw Assert.Unreachable;
}
}
}
private object ConvertUInt64(UInt64 obj) {
checked {
switch (_to) {
case TypeCode.Byte: return (Byte)obj;
case TypeCode.SByte: return (SByte)obj;
case TypeCode.Int16: return (Int16)obj;
case TypeCode.Char: return (Char)obj;
case TypeCode.Int32: return (Int32)obj;
case TypeCode.Int64: return (Int64)obj;
case TypeCode.UInt16: return (UInt16)obj;
case TypeCode.UInt32: return (UInt32)obj;
case TypeCode.UInt64: return (UInt64)obj;
case TypeCode.Single: return (Single)obj;
case TypeCode.Double: return (Double)obj;
default: throw Assert.Unreachable;
}
}
}
private object ConvertDouble(Double obj) {
checked {
switch (_to) {
case TypeCode.Byte: return (Byte)obj;
case TypeCode.SByte: return (SByte)obj;
case TypeCode.Int16: return (Int16)obj;
case TypeCode.Char: return (Char)obj;
case TypeCode.Int32: return (Int32)obj;
case TypeCode.Int64: return (Int64)obj;
case TypeCode.UInt16: return (UInt16)obj;
case TypeCode.UInt32: return (UInt32)obj;
case TypeCode.UInt64: return (UInt64)obj;
case TypeCode.Single: return (Single)obj;
case TypeCode.Double: return (Double)obj;
default: throw Assert.Unreachable;
}
}
}
}
}
}
| |
#region license
// Copyright (c) 2009 Rodrigo B. de Oliveira (rbo@acm.org)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of Rodrigo B. de Oliveira nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
//
// DO NOT EDIT THIS FILE!
//
// This file was generated automatically by astgen.boo.
//
namespace Boo.Lang.Compiler.Ast
{
using System.Collections;
using System.Runtime.Serialization;
[System.Serializable]
public partial class IfStatement : ConditionalStatement
{
protected Block _trueBlock;
protected Block _falseBlock;
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
new public IfStatement CloneNode()
{
return (IfStatement)Clone();
}
/// <summary>
/// <see cref="Node.CleanClone"/>
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
new public IfStatement CleanClone()
{
return (IfStatement)base.CleanClone();
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public NodeType NodeType
{
get { return NodeType.IfStatement; }
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public void Accept(IAstVisitor visitor)
{
visitor.OnIfStatement(this);
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public bool Matches(Node node)
{
if (node == null) return false;
if (NodeType != node.NodeType) return false;
var other = ( IfStatement)node;
if (!Node.Matches(_modifier, other._modifier)) return NoMatch("IfStatement._modifier");
if (!Node.Matches(_condition, other._condition)) return NoMatch("IfStatement._condition");
if (!Node.Matches(_trueBlock, other._trueBlock)) return NoMatch("IfStatement._trueBlock");
if (!Node.Matches(_falseBlock, other._falseBlock)) return NoMatch("IfStatement._falseBlock");
return true;
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public bool Replace(Node existing, Node newNode)
{
if (base.Replace(existing, newNode))
{
return true;
}
if (_modifier == existing)
{
this.Modifier = (StatementModifier)newNode;
return true;
}
if (_condition == existing)
{
this.Condition = (Expression)newNode;
return true;
}
if (_trueBlock == existing)
{
this.TrueBlock = (Block)newNode;
return true;
}
if (_falseBlock == existing)
{
this.FalseBlock = (Block)newNode;
return true;
}
return false;
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public object Clone()
{
IfStatement clone = (IfStatement)FormatterServices.GetUninitializedObject(typeof(IfStatement));
clone._lexicalInfo = _lexicalInfo;
clone._endSourceLocation = _endSourceLocation;
clone._documentation = _documentation;
clone._entity = _entity;
if (_annotations != null) clone._annotations = (Hashtable)_annotations.Clone();
if (null != _modifier)
{
clone._modifier = _modifier.Clone() as StatementModifier;
clone._modifier.InitializeParent(clone);
}
if (null != _condition)
{
clone._condition = _condition.Clone() as Expression;
clone._condition.InitializeParent(clone);
}
if (null != _trueBlock)
{
clone._trueBlock = _trueBlock.Clone() as Block;
clone._trueBlock.InitializeParent(clone);
}
if (null != _falseBlock)
{
clone._falseBlock = _falseBlock.Clone() as Block;
clone._falseBlock.InitializeParent(clone);
}
return clone;
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override internal void ClearTypeSystemBindings()
{
_annotations = null;
_entity = null;
if (null != _modifier)
{
_modifier.ClearTypeSystemBindings();
}
if (null != _condition)
{
_condition.ClearTypeSystemBindings();
}
if (null != _trueBlock)
{
_trueBlock.ClearTypeSystemBindings();
}
if (null != _falseBlock)
{
_falseBlock.ClearTypeSystemBindings();
}
}
[System.Xml.Serialization.XmlElement]
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public Block TrueBlock
{
get { return _trueBlock; }
set
{
if (_trueBlock != value)
{
_trueBlock = value;
if (null != _trueBlock)
{
_trueBlock.InitializeParent(this);
}
}
}
}
[System.Xml.Serialization.XmlElement]
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public Block FalseBlock
{
get { return _falseBlock; }
set
{
if (_falseBlock != value)
{
_falseBlock = value;
if (null != _falseBlock)
{
_falseBlock.InitializeParent(this);
}
}
}
}
}
}
| |
#region MigraDoc - Creating Documents on the Fly
//
// Authors:
// Stefan Lange (mailto:Stefan.Lange@pdfsharp.com)
// Klaus Potzesny (mailto:Klaus.Potzesny@pdfsharp.com)
// David Stephensen (mailto:David.Stephensen@pdfsharp.com)
//
// Copyright (c) 2001-2009 empira Software GmbH, Cologne (Germany)
//
// http://www.pdfsharp.com
// http://www.migradoc.com
// http://sourceforge.net/projects/pdfsharp
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using MigraDoc.DocumentObjectModel.Internals;
using MigraDoc.DocumentObjectModel.Visitors;
using MigraDoc.DocumentObjectModel.Fields;
using MigraDoc.DocumentObjectModel.Shapes;
namespace MigraDoc.DocumentObjectModel
{
/// <summary>
/// A Hyperlink is used to reference targets in the document (Local), on a drive (File) or a network (Web).
/// </summary>
public class Hyperlink : DocumentObject, IVisitable
{
/// <summary>
/// Initializes a new instance of the Hyperlink class.
/// </summary>
public Hyperlink()
{
}
/// <summary>
/// Initializes a new instance of the Hyperlink class with the specified parent.
/// </summary>
internal Hyperlink(DocumentObject parent) : base(parent) { }
/// <summary>
/// Initializes a new instance of the Hyperlink class with the text the hyperlink shall content.
/// The type will be treated as Local by default.
/// </summary>
internal Hyperlink(string name, string text)
: this()
{
this.Name = name;
this.Elements.AddText(text);
}
/// <summary>
/// Initializes a new instance of the Hyperlink class with the type and text the hyperlink shall
/// represent.
/// </summary>
internal Hyperlink(string name, HyperlinkType type, string text)
: this()
{
this.Name = name;
this.Type = type;
this.Elements.AddText(text);
}
#region Methods
/// <summary>
/// Creates a deep copy of this object.
/// </summary>
public new Hyperlink Clone()
{
return (Hyperlink)DeepCopy();
}
/// <summary>
/// Implements the deep copy of the object.
/// </summary>
protected override object DeepCopy()
{
Hyperlink hyperlink = (Hyperlink)base.DeepCopy();
if (hyperlink.elements != null)
{
hyperlink.elements = hyperlink.elements.Clone();
hyperlink.elements.parent = hyperlink;
}
return hyperlink;
}
/// <summary>
/// Adds a text phrase to the hyperlink.
/// </summary>
public Text AddText(String text)
{
return this.Elements.AddText(text);
}
/// <summary>
/// Adds a single character repeated the specified number of times to the hyperlink.
/// </summary>
public Text AddChar(char ch, int count)
{
return this.Elements.AddChar(ch, count);
}
/// <summary>
/// Adds a single character to the hyperlink.
/// </summary>
public Text AddChar(char ch)
{
return this.Elements.AddChar(ch);
}
/// <summary>
/// Adds one or more Symbol objects.
/// </summary>
public Character AddCharacter(SymbolName symbolType, int count)
{
return this.Elements.AddCharacter(symbolType, count);
}
/// <summary>
/// Adds a Symbol object.
/// </summary>
public Character AddCharacter(SymbolName symbolType)
{
return this.Elements.AddCharacter(symbolType);
}
/// <summary>
/// Adds one or more Symbol objects defined by a character.
/// </summary>
public Character AddCharacter(char ch, int count)
{
return this.Elements.AddCharacter(ch, count);
}
/// <summary>
/// Adds a Symbol object defined by a character.
/// </summary>
public Character AddCharacter(char ch)
{
return this.Elements.AddCharacter(ch);
}
/// <summary>
/// Adds a space character as many as count.
/// </summary>
public Character AddSpace(int count)
{
return this.Elements.AddSpace(count);
}
/// <summary>
/// Adds a horizontal tab.
/// </summary>
public void AddTab()
{
this.Elements.AddTab();
}
/// <summary>
/// Adds a new FormattedText.
/// </summary>
public FormattedText AddFormattedText()
{
return this.Elements.AddFormattedText();
}
/// <summary>
/// Adds a new FormattedText object with the given format.
/// </summary>
public FormattedText AddFormattedText(TextFormat textFormat)
{
return this.Elements.AddFormattedText(textFormat);
}
/// <summary>
/// Adds a new FormattedText with the given Font.
/// </summary>
public FormattedText AddFormattedText(Font font)
{
return this.Elements.AddFormattedText(font);
}
/// <summary>
/// Adds a new FormattedText with the given text.
/// </summary>
public FormattedText AddFormattedText(string text)
{
return this.Elements.AddFormattedText(text);
}
/// <summary>
/// Adds a new FormattedText object with the given text and format.
/// </summary>
public FormattedText AddFormattedText(string text, TextFormat textFormat)
{
return this.Elements.AddFormattedText(text, textFormat);
}
/// <summary>
/// Adds a new FormattedText object with the given text and font.
/// </summary>
public FormattedText AddFormattedText(string text, Font font)
{
return this.Elements.AddFormattedText(text, font);
}
/// <summary>
/// Adds a new FormattedText object with the given text and style.
/// </summary>
public FormattedText AddFormattedText(string text, string style)
{
return this.Elements.AddFormattedText(text, style);
}
/// <summary>
/// Adds a new Bookmark.
/// </summary>
public BookmarkField AddBookmark(string name)
{
return this.Elements.AddBookmark(name);
}
/// <summary>
/// Adds a new PageField.
/// </summary>
public PageField AddPageField()
{
return this.Elements.AddPageField();
}
/// <summary>
/// Adds a new PageRefField.
/// </summary>
public PageRefField AddPageRefField(string name)
{
return this.Elements.AddPageRefField(name);
}
/// <summary>
/// Adds a new NumPagesField.
/// </summary>
public NumPagesField AddNumPagesField()
{
return this.Elements.AddNumPagesField();
}
/// <summary>
/// Adds a new SectionField.
/// </summary>
public SectionField AddSectionField()
{
return this.Elements.AddSectionField();
}
/// <summary>
/// Adds a new SectionPagesField.
/// </summary>
public SectionPagesField AddSectionPagesField()
{
return this.Elements.AddSectionPagesField();
}
/// <summary>
/// Adds a new DateField.
/// </summary>
public DateField AddDateField()
{
return this.Elements.AddDateField();
}
/// <summary>
/// Adds a new DateField.
/// </summary>
public DateField AddDateField(string format)
{
return this.Elements.AddDateField(format);
}
/// <summary>
/// Adds a new InfoField.
/// </summary>
public InfoField AddInfoField(InfoFieldType iType)
{
return this.Elements.AddInfoField(iType);
}
/// <summary>
/// Adds a new Footnote with the specified text.
/// </summary>
public Footnote AddFootnote(string text)
{
return this.Elements.AddFootnote(text);
}
/// <summary>
/// Adds a new Footnote.
/// </summary>
public Footnote AddFootnote()
{
return this.Elements.AddFootnote();
}
/// <summary>
/// Adds a new Image object
/// </summary>
public Image AddImage(string fileName)
{
return this.Elements.AddImage(fileName);
}
/// <summary>
/// Adds a new Image to the paragraph from a MemoryStream.
/// </summary>
/// <returns></returns>
public Image AddImage(MemoryStream stream)
{
return this.Elements.AddImage(stream);
}
/// <summary>
/// Adds a new Bookmark
/// </summary>
public void Add(BookmarkField bookmark)
{
this.Elements.Add(bookmark);
}
/// <summary>
/// Adds a new PageField
/// </summary>
public void Add(PageField pageField)
{
this.Elements.Add(pageField);
}
/// <summary>
/// Adds a new PageRefField
/// </summary>
public void Add(PageRefField pageRefField)
{
this.Elements.Add(pageRefField);
}
/// <summary>
/// Adds a new NumPagesField
/// </summary>
public void Add(NumPagesField numPagesField)
{
this.Elements.Add(numPagesField);
}
/// <summary>
/// Adds a new SectionField
/// </summary>
public void Add(SectionField sectionField)
{
this.Elements.Add(sectionField);
}
/// <summary>
/// Adds a new SectionPagesField
/// </summary>
public void Add(SectionPagesField sectionPagesField)
{
this.Elements.Add(sectionPagesField);
}
/// <summary>
/// Adds a new DateField
/// </summary>
public void Add(DateField dateField)
{
this.Elements.Add(dateField);
}
/// <summary>
/// Adds a new InfoField
/// </summary>
public void Add(InfoField infoField)
{
this.Elements.Add(infoField);
}
/// <summary>
/// Adds a new Footnote
/// </summary>
public void Add(Footnote footnote)
{
this.Elements.Add(footnote);
}
/// <summary>
/// Adds a new Text
/// </summary>
public void Add(Text text)
{
this.Elements.Add(text);
}
/// <summary>
/// Adds a new FormattedText
/// </summary>
public void Add(FormattedText formattedText)
{
this.Elements.Add(formattedText);
}
/// <summary>
/// Adds a new Image
/// </summary>
public void Add(Image image)
{
this.Elements.Add(image);
}
/// <summary>
/// Adds a new Character
/// </summary>
public void Add(Character character)
{
this.Elements.Add(character);
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the font object.
/// </summary>
public Font Font
{
get
{
if (this.font == null)
this.font = new Font(this);
return this.font;
}
set
{
SetParent(value);
this.font = value;
}
}
[DV]
internal Font font;
/// <summary>
/// Gets or sets the target name of the Hyperlink, e.g. an URL or a bookmark's name.
/// </summary>
public string Name
{
get { return this.name.Value; }
set { this.name.Value = value; }
}
[DV]
internal NString name = NString.NullValue;
/// <summary>
/// Gets or sets the target type of the Hyperlink.
/// </summary>
public HyperlinkType Type
{
get { return (HyperlinkType)this.type.Value; }
set { this.type.Value = (int)value; }
}
[DV(Type = typeof(HyperlinkType))]
internal NEnum type = NEnum.NullValue(typeof(HyperlinkType));
/// <summary>
/// Gets the ParagraphElements of the Hyperlink specifying its 'clickable area'.
/// </summary>
public ParagraphElements Elements
{
get
{
if (this.elements == null)
this.elements = new ParagraphElements(this);
return this.elements;
}
set
{
SetParent(value);
this.elements = value;
}
}
[DV(ItemType = typeof(DocumentObject))]
internal ParagraphElements elements;
#endregion
#region Internal
/// <summary>
/// Converts Hyperlink into DDL.
/// </summary>
internal override void Serialize(Serializer serializer)
{
if (this.name.Value == string.Empty)
throw new InvalidOperationException(DomSR.MissingObligatoryProperty("Name", "Hyperlink"));
serializer.Write("\\hyperlink");
string str = "[Name = \"" + this.Name.Replace("\\", "\\\\").Replace("\"", "\\\"") + "\"";
if (!this.type.IsNull)
str += " Type = " + this.Type;
str += "]";
serializer.Write(str);
serializer.Write("{");
if (this.elements != null)
elements.Serialize(serializer);
serializer.Write("}");
}
/// <summary>
/// Returns the meta object of this instance.
/// </summary>
internal override Meta Meta
{
get
{
if (meta == null)
meta = new Meta(typeof(Hyperlink));
return meta;
}
}
static Meta meta;
#endregion
#region IDomVisitable Members
public void AcceptVisitor(DocumentObjectVisitor visitor, bool visitChildren)
{
visitor.VisitHyperlink(this);
if (visitChildren && this.elements != null)
{
((IVisitable)this.elements).AcceptVisitor(visitor, visitChildren);
}
}
#endregion
}
}
| |
using System;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Text;
using System.Xml;
using System.Globalization;
namespace WeifenLuo.WinFormsUI.Docking
{
partial class DockPanel
{
private static class Persistor
{
private const string ConfigFileVersion = "1.0";
private static string[] CompatibleConfigFileVersions = new string[] { };
private class DummyContent : DockContent
{
}
private struct DockPanelStruct
{
private double m_dockLeftPortion;
public double DockLeftPortion
{
get { return m_dockLeftPortion; }
set { m_dockLeftPortion = value; }
}
private double m_dockRightPortion;
public double DockRightPortion
{
get { return m_dockRightPortion; }
set { m_dockRightPortion = value; }
}
private double m_dockTopPortion;
public double DockTopPortion
{
get { return m_dockTopPortion; }
set { m_dockTopPortion = value; }
}
private double m_dockBottomPortion;
public double DockBottomPortion
{
get { return m_dockBottomPortion; }
set { m_dockBottomPortion = value; }
}
private int m_indexActiveDocumentPane;
public int IndexActiveDocumentPane
{
get { return m_indexActiveDocumentPane; }
set { m_indexActiveDocumentPane = value; }
}
private int m_indexActivePane;
public int IndexActivePane
{
get { return m_indexActivePane; }
set { m_indexActivePane = value; }
}
}
private struct ContentStruct
{
private string m_persistString;
public string PersistString
{
get { return m_persistString; }
set { m_persistString = value; }
}
private double m_autoHidePortion;
public double AutoHidePortion
{
get { return m_autoHidePortion; }
set { m_autoHidePortion = value; }
}
private bool m_isHidden;
public bool IsHidden
{
get { return m_isHidden; }
set { m_isHidden = value; }
}
private bool m_isFloat;
public bool IsFloat
{
get { return m_isFloat; }
set { m_isFloat = value; }
}
}
private struct PaneStruct
{
private DockState m_dockState;
public DockState DockState
{
get { return m_dockState; }
set { m_dockState = value; }
}
private int m_indexActiveContent;
public int IndexActiveContent
{
get { return m_indexActiveContent; }
set { m_indexActiveContent = value; }
}
private int[] m_indexContents;
public int[] IndexContents
{
get { return m_indexContents; }
set { m_indexContents = value; }
}
private int m_zOrderIndex;
public int ZOrderIndex
{
get { return m_zOrderIndex; }
set { m_zOrderIndex = value; }
}
}
private struct NestedPane
{
private int m_indexPane;
public int IndexPane
{
get { return m_indexPane; }
set { m_indexPane = value; }
}
private int m_indexPrevPane;
public int IndexPrevPane
{
get { return m_indexPrevPane; }
set { m_indexPrevPane = value; }
}
private DockAlignment m_alignment;
public DockAlignment Alignment
{
get { return m_alignment; }
set { m_alignment = value; }
}
private double m_proportion;
public double Proportion
{
get { return m_proportion; }
set { m_proportion = value; }
}
}
private struct DockWindowStruct
{
private DockState m_dockState;
public DockState DockState
{
get { return m_dockState; }
set { m_dockState = value; }
}
private int m_zOrderIndex;
public int ZOrderIndex
{
get { return m_zOrderIndex; }
set { m_zOrderIndex = value; }
}
private NestedPane[] m_nestedPanes;
public NestedPane[] NestedPanes
{
get { return m_nestedPanes; }
set { m_nestedPanes = value; }
}
}
private struct FloatWindowStruct
{
private Rectangle m_bounds;
public Rectangle Bounds
{
get { return m_bounds; }
set { m_bounds = value; }
}
private int m_zOrderIndex;
public int ZOrderIndex
{
get { return m_zOrderIndex; }
set { m_zOrderIndex = value; }
}
private NestedPane[] m_nestedPanes;
public NestedPane[] NestedPanes
{
get { return m_nestedPanes; }
set { m_nestedPanes = value; }
}
}
public static void SaveAsXml(DockPanel dockPanel, string fileName)
{
SaveAsXml(dockPanel, fileName, Encoding.Unicode);
}
public static void SaveAsXml(DockPanel dockPanel, string fileName, Encoding encoding)
{
using (var fs = new FileStream(fileName, FileMode.Create))
{
try
{
SaveAsXml(dockPanel, fs, encoding);
}
finally
{
fs.Close();
}
}
}
public static void SaveAsXml(DockPanel dockPanel, Stream stream, Encoding encoding)
{
SaveAsXml(dockPanel, stream, encoding, false);
}
public static void SaveAsXml(DockPanel dockPanel, Stream stream, Encoding encoding, bool upstream)
{
using (var xmlOut = new XmlTextWriter(stream, encoding))
{
xmlOut.Formatting = Formatting.Indented;
if (!upstream)
xmlOut.WriteStartDocument();
// Always begin file with identification and warning
xmlOut.WriteComment(Strings.DockPanel_Persistor_XmlFileComment1);
xmlOut.WriteComment(Strings.DockPanel_Persistor_XmlFileComment2);
// Associate a version number with the root element so that future version of the code
// will be able to be backwards compatible or at least recognise out of date versions
xmlOut.WriteStartElement("DockPanel");
xmlOut.WriteAttributeString("FormatVersion", ConfigFileVersion);
xmlOut.WriteAttributeString("DockLeftPortion", dockPanel.DockLeftPortion.ToString(CultureInfo.InvariantCulture));
xmlOut.WriteAttributeString("DockRightPortion", dockPanel.DockRightPortion.ToString(CultureInfo.InvariantCulture));
xmlOut.WriteAttributeString("DockTopPortion", dockPanel.DockTopPortion.ToString(CultureInfo.InvariantCulture));
xmlOut.WriteAttributeString("DockBottomPortion", dockPanel.DockBottomPortion.ToString(CultureInfo.InvariantCulture));
if (!Win32Helper.IsRunningOnMono)
{
xmlOut.WriteAttributeString("ActiveDocumentPane", dockPanel.Panes.IndexOf(dockPanel.ActiveDocumentPane).ToString(CultureInfo.InvariantCulture));
xmlOut.WriteAttributeString("ActivePane", dockPanel.Panes.IndexOf(dockPanel.ActivePane).ToString(CultureInfo.InvariantCulture));
}
// Contents
xmlOut.WriteStartElement("Contents");
xmlOut.WriteAttributeString("Count", dockPanel.Contents.Count.ToString(CultureInfo.InvariantCulture));
foreach (IDockContent content in dockPanel.Contents)
{
xmlOut.WriteStartElement("Content");
xmlOut.WriteAttributeString("ID", dockPanel.Contents.IndexOf(content).ToString(CultureInfo.InvariantCulture));
xmlOut.WriteAttributeString("PersistString", content.DockHandler.PersistString);
xmlOut.WriteAttributeString("AutoHidePortion", content.DockHandler.AutoHidePortion.ToString(CultureInfo.InvariantCulture));
xmlOut.WriteAttributeString("IsHidden", content.DockHandler.IsHidden.ToString(CultureInfo.InvariantCulture));
xmlOut.WriteAttributeString("IsFloat", content.DockHandler.IsFloat.ToString(CultureInfo.InvariantCulture));
xmlOut.WriteEndElement();
}
xmlOut.WriteEndElement();
// Panes
xmlOut.WriteStartElement("Panes");
xmlOut.WriteAttributeString("Count", dockPanel.Panes.Count.ToString(CultureInfo.InvariantCulture));
foreach (DockPane pane in dockPanel.Panes)
{
xmlOut.WriteStartElement("Pane");
xmlOut.WriteAttributeString("ID", dockPanel.Panes.IndexOf(pane).ToString(CultureInfo.InvariantCulture));
xmlOut.WriteAttributeString("DockState", pane.DockState.ToString());
xmlOut.WriteAttributeString("ActiveContent", dockPanel.Contents.IndexOf(pane.ActiveContent).ToString(CultureInfo.InvariantCulture));
xmlOut.WriteStartElement("Contents");
xmlOut.WriteAttributeString("Count", pane.Contents.Count.ToString(CultureInfo.InvariantCulture));
foreach (IDockContent content in pane.Contents)
{
xmlOut.WriteStartElement("Content");
xmlOut.WriteAttributeString("ID", pane.Contents.IndexOf(content).ToString(CultureInfo.InvariantCulture));
xmlOut.WriteAttributeString("RefID", dockPanel.Contents.IndexOf(content).ToString(CultureInfo.InvariantCulture));
xmlOut.WriteEndElement();
}
xmlOut.WriteEndElement();
xmlOut.WriteEndElement();
}
xmlOut.WriteEndElement();
// DockWindows
xmlOut.WriteStartElement("DockWindows");
int dockWindowId = 0;
foreach (DockWindow dw in dockPanel.DockWindows)
{
xmlOut.WriteStartElement("DockWindow");
xmlOut.WriteAttributeString("ID", dockWindowId.ToString(CultureInfo.InvariantCulture));
dockWindowId++;
xmlOut.WriteAttributeString("DockState", dw.DockState.ToString());
xmlOut.WriteAttributeString("ZOrderIndex", dockPanel.Controls.IndexOf(dw).ToString(CultureInfo.InvariantCulture));
xmlOut.WriteStartElement("NestedPanes");
xmlOut.WriteAttributeString("Count", dw.NestedPanes.Count.ToString(CultureInfo.InvariantCulture));
foreach (DockPane pane in dw.NestedPanes)
{
xmlOut.WriteStartElement("Pane");
xmlOut.WriteAttributeString("ID", dw.NestedPanes.IndexOf(pane).ToString(CultureInfo.InvariantCulture));
xmlOut.WriteAttributeString("RefID", dockPanel.Panes.IndexOf(pane).ToString(CultureInfo.InvariantCulture));
NestedDockingStatus status = pane.NestedDockingStatus;
xmlOut.WriteAttributeString("PrevPane", dockPanel.Panes.IndexOf(status.PreviousPane).ToString(CultureInfo.InvariantCulture));
xmlOut.WriteAttributeString("Alignment", status.Alignment.ToString());
xmlOut.WriteAttributeString("Proportion", status.Proportion.ToString(CultureInfo.InvariantCulture));
xmlOut.WriteEndElement();
}
xmlOut.WriteEndElement();
xmlOut.WriteEndElement();
}
xmlOut.WriteEndElement();
// FloatWindows
RectangleConverter rectConverter = new RectangleConverter();
xmlOut.WriteStartElement("FloatWindows");
xmlOut.WriteAttributeString("Count", dockPanel.FloatWindows.Count.ToString(CultureInfo.InvariantCulture));
foreach (FloatWindow fw in dockPanel.FloatWindows)
{
xmlOut.WriteStartElement("FloatWindow");
xmlOut.WriteAttributeString("ID", dockPanel.FloatWindows.IndexOf(fw).ToString(CultureInfo.InvariantCulture));
xmlOut.WriteAttributeString("Bounds", rectConverter.ConvertToInvariantString(fw.Bounds));
xmlOut.WriteAttributeString("ZOrderIndex", fw.DockPanel.FloatWindows.IndexOf(fw).ToString(CultureInfo.InvariantCulture));
xmlOut.WriteStartElement("NestedPanes");
xmlOut.WriteAttributeString("Count", fw.NestedPanes.Count.ToString(CultureInfo.InvariantCulture));
foreach (DockPane pane in fw.NestedPanes)
{
xmlOut.WriteStartElement("Pane");
xmlOut.WriteAttributeString("ID", fw.NestedPanes.IndexOf(pane).ToString(CultureInfo.InvariantCulture));
xmlOut.WriteAttributeString("RefID", dockPanel.Panes.IndexOf(pane).ToString(CultureInfo.InvariantCulture));
NestedDockingStatus status = pane.NestedDockingStatus;
xmlOut.WriteAttributeString("PrevPane", dockPanel.Panes.IndexOf(status.PreviousPane).ToString(CultureInfo.InvariantCulture));
xmlOut.WriteAttributeString("Alignment", status.Alignment.ToString());
xmlOut.WriteAttributeString("Proportion", status.Proportion.ToString(CultureInfo.InvariantCulture));
xmlOut.WriteEndElement();
}
xmlOut.WriteEndElement();
xmlOut.WriteEndElement();
}
xmlOut.WriteEndElement(); // </FloatWindows>
xmlOut.WriteEndElement();
if (!upstream)
{
xmlOut.WriteEndDocument();
xmlOut.Close();
}
else
xmlOut.Flush();
}
}
public static void LoadFromXml(DockPanel dockPanel, string fileName, DeserializeDockContent deserializeContent)
{
using (var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
{
try
{
LoadFromXml(dockPanel, fs, deserializeContent);
}
finally
{
fs.Close();
}
}
}
public static void LoadFromXml(DockPanel dockPanel, Stream stream, DeserializeDockContent deserializeContent)
{
LoadFromXml(dockPanel, stream, deserializeContent, true);
}
private static ContentStruct[] LoadContents(XmlTextReader xmlIn)
{
int countOfContents = Convert.ToInt32(xmlIn.GetAttribute("Count"), CultureInfo.InvariantCulture);
ContentStruct[] contents = new ContentStruct[countOfContents];
MoveToNextElement(xmlIn);
for (int i = 0; i < countOfContents; i++)
{
int id = Convert.ToInt32(xmlIn.GetAttribute("ID"), CultureInfo.InvariantCulture);
if (xmlIn.Name != "Content" || id != i)
throw new ArgumentException(Strings.DockPanel_LoadFromXml_InvalidXmlFormat);
contents[i].PersistString = xmlIn.GetAttribute("PersistString");
contents[i].AutoHidePortion = Convert.ToDouble(xmlIn.GetAttribute("AutoHidePortion"), CultureInfo.InvariantCulture);
contents[i].IsHidden = Convert.ToBoolean(xmlIn.GetAttribute("IsHidden"), CultureInfo.InvariantCulture);
contents[i].IsFloat = Convert.ToBoolean(xmlIn.GetAttribute("IsFloat"), CultureInfo.InvariantCulture);
MoveToNextElement(xmlIn);
}
return contents;
}
private static PaneStruct[] LoadPanes(XmlTextReader xmlIn)
{
EnumConverter dockStateConverter = new EnumConverter(typeof(DockState));
int countOfPanes = Convert.ToInt32(xmlIn.GetAttribute("Count"), CultureInfo.InvariantCulture);
PaneStruct[] panes = new PaneStruct[countOfPanes];
MoveToNextElement(xmlIn);
for (int i = 0; i < countOfPanes; i++)
{
int id = Convert.ToInt32(xmlIn.GetAttribute("ID"), CultureInfo.InvariantCulture);
if (xmlIn.Name != "Pane" || id != i)
throw new ArgumentException(Strings.DockPanel_LoadFromXml_InvalidXmlFormat);
panes[i].DockState = (DockState)dockStateConverter.ConvertFrom(xmlIn.GetAttribute("DockState"));
panes[i].IndexActiveContent = Convert.ToInt32(xmlIn.GetAttribute("ActiveContent"), CultureInfo.InvariantCulture);
panes[i].ZOrderIndex = -1;
MoveToNextElement(xmlIn);
if (xmlIn.Name != "Contents")
throw new ArgumentException(Strings.DockPanel_LoadFromXml_InvalidXmlFormat);
int countOfPaneContents = Convert.ToInt32(xmlIn.GetAttribute("Count"), CultureInfo.InvariantCulture);
panes[i].IndexContents = new int[countOfPaneContents];
MoveToNextElement(xmlIn);
for (int j = 0; j < countOfPaneContents; j++)
{
int id2 = Convert.ToInt32(xmlIn.GetAttribute("ID"), CultureInfo.InvariantCulture);
if (xmlIn.Name != "Content" || id2 != j)
throw new ArgumentException(Strings.DockPanel_LoadFromXml_InvalidXmlFormat);
panes[i].IndexContents[j] = Convert.ToInt32(xmlIn.GetAttribute("RefID"), CultureInfo.InvariantCulture);
MoveToNextElement(xmlIn);
}
}
return panes;
}
private static DockWindowStruct[] LoadDockWindows(XmlTextReader xmlIn, DockPanel dockPanel)
{
EnumConverter dockStateConverter = new EnumConverter(typeof(DockState));
EnumConverter dockAlignmentConverter = new EnumConverter(typeof(DockAlignment));
int countOfDockWindows = dockPanel.DockWindows.Count;
DockWindowStruct[] dockWindows = new DockWindowStruct[countOfDockWindows];
MoveToNextElement(xmlIn);
for (int i = 0; i < countOfDockWindows; i++)
{
int id = Convert.ToInt32(xmlIn.GetAttribute("ID"), CultureInfo.InvariantCulture);
if (xmlIn.Name != "DockWindow" || id != i)
throw new ArgumentException(Strings.DockPanel_LoadFromXml_InvalidXmlFormat);
dockWindows[i].DockState = (DockState)dockStateConverter.ConvertFrom(xmlIn.GetAttribute("DockState"));
dockWindows[i].ZOrderIndex = Convert.ToInt32(xmlIn.GetAttribute("ZOrderIndex"), CultureInfo.InvariantCulture);
MoveToNextElement(xmlIn);
if (xmlIn.Name != "DockList" && xmlIn.Name != "NestedPanes")
throw new ArgumentException(Strings.DockPanel_LoadFromXml_InvalidXmlFormat);
int countOfNestedPanes = Convert.ToInt32(xmlIn.GetAttribute("Count"), CultureInfo.InvariantCulture);
dockWindows[i].NestedPanes = new NestedPane[countOfNestedPanes];
MoveToNextElement(xmlIn);
for (int j = 0; j < countOfNestedPanes; j++)
{
int id2 = Convert.ToInt32(xmlIn.GetAttribute("ID"), CultureInfo.InvariantCulture);
if (xmlIn.Name != "Pane" || id2 != j)
throw new ArgumentException(Strings.DockPanel_LoadFromXml_InvalidXmlFormat);
dockWindows[i].NestedPanes[j].IndexPane = Convert.ToInt32(xmlIn.GetAttribute("RefID"), CultureInfo.InvariantCulture);
dockWindows[i].NestedPanes[j].IndexPrevPane = Convert.ToInt32(xmlIn.GetAttribute("PrevPane"), CultureInfo.InvariantCulture);
dockWindows[i].NestedPanes[j].Alignment = (DockAlignment)dockAlignmentConverter.ConvertFrom(xmlIn.GetAttribute("Alignment"));
dockWindows[i].NestedPanes[j].Proportion = Convert.ToDouble(xmlIn.GetAttribute("Proportion"), CultureInfo.InvariantCulture);
MoveToNextElement(xmlIn);
}
}
return dockWindows;
}
private static FloatWindowStruct[] LoadFloatWindows(XmlTextReader xmlIn)
{
EnumConverter dockAlignmentConverter = new EnumConverter(typeof(DockAlignment));
RectangleConverter rectConverter = new RectangleConverter();
int countOfFloatWindows = Convert.ToInt32(xmlIn.GetAttribute("Count"), CultureInfo.InvariantCulture);
FloatWindowStruct[] floatWindows = new FloatWindowStruct[countOfFloatWindows];
MoveToNextElement(xmlIn);
for (int i = 0; i < countOfFloatWindows; i++)
{
int id = Convert.ToInt32(xmlIn.GetAttribute("ID"), CultureInfo.InvariantCulture);
if (xmlIn.Name != "FloatWindow" || id != i)
throw new ArgumentException(Strings.DockPanel_LoadFromXml_InvalidXmlFormat);
floatWindows[i].Bounds = (Rectangle)rectConverter.ConvertFromInvariantString(xmlIn.GetAttribute("Bounds"));
floatWindows[i].ZOrderIndex = Convert.ToInt32(xmlIn.GetAttribute("ZOrderIndex"), CultureInfo.InvariantCulture);
MoveToNextElement(xmlIn);
if (xmlIn.Name != "DockList" && xmlIn.Name != "NestedPanes")
throw new ArgumentException(Strings.DockPanel_LoadFromXml_InvalidXmlFormat);
int countOfNestedPanes = Convert.ToInt32(xmlIn.GetAttribute("Count"), CultureInfo.InvariantCulture);
floatWindows[i].NestedPanes = new NestedPane[countOfNestedPanes];
MoveToNextElement(xmlIn);
for (int j = 0; j < countOfNestedPanes; j++)
{
int id2 = Convert.ToInt32(xmlIn.GetAttribute("ID"), CultureInfo.InvariantCulture);
if (xmlIn.Name != "Pane" || id2 != j)
throw new ArgumentException(Strings.DockPanel_LoadFromXml_InvalidXmlFormat);
floatWindows[i].NestedPanes[j].IndexPane = Convert.ToInt32(xmlIn.GetAttribute("RefID"), CultureInfo.InvariantCulture);
floatWindows[i].NestedPanes[j].IndexPrevPane = Convert.ToInt32(xmlIn.GetAttribute("PrevPane"), CultureInfo.InvariantCulture);
floatWindows[i].NestedPanes[j].Alignment = (DockAlignment)dockAlignmentConverter.ConvertFrom(xmlIn.GetAttribute("Alignment"));
floatWindows[i].NestedPanes[j].Proportion = Convert.ToDouble(xmlIn.GetAttribute("Proportion"), CultureInfo.InvariantCulture);
MoveToNextElement(xmlIn);
}
}
return floatWindows;
}
public static void LoadFromXml(DockPanel dockPanel, Stream stream, DeserializeDockContent deserializeContent, bool closeStream)
{
if (dockPanel.Contents.Count != 0)
throw new InvalidOperationException(Strings.DockPanel_LoadFromXml_AlreadyInitialized);
DockPanelStruct dockPanelStruct;
ContentStruct[] contents;
PaneStruct[] panes;
DockWindowStruct[] dockWindows;
FloatWindowStruct[] floatWindows;
using (var xmlIn = new XmlTextReader(stream) { WhitespaceHandling = WhitespaceHandling.None })
{
xmlIn.MoveToContent();
while (!xmlIn.Name.Equals("DockPanel"))
{
if (!MoveToNextElement(xmlIn))
throw new ArgumentException(Strings.DockPanel_LoadFromXml_InvalidXmlFormat);
}
string formatVersion = xmlIn.GetAttribute("FormatVersion");
if (!IsFormatVersionValid(formatVersion))
throw new ArgumentException(Strings.DockPanel_LoadFromXml_InvalidFormatVersion);
dockPanelStruct = new DockPanelStruct();
dockPanelStruct.DockLeftPortion = Convert.ToDouble(xmlIn.GetAttribute("DockLeftPortion"), CultureInfo.InvariantCulture);
dockPanelStruct.DockRightPortion = Convert.ToDouble(xmlIn.GetAttribute("DockRightPortion"), CultureInfo.InvariantCulture);
dockPanelStruct.DockTopPortion = Convert.ToDouble(xmlIn.GetAttribute("DockTopPortion"), CultureInfo.InvariantCulture);
dockPanelStruct.DockBottomPortion = Convert.ToDouble(xmlIn.GetAttribute("DockBottomPortion"), CultureInfo.InvariantCulture);
dockPanelStruct.IndexActiveDocumentPane = Convert.ToInt32(xmlIn.GetAttribute("ActiveDocumentPane"), CultureInfo.InvariantCulture);
dockPanelStruct.IndexActivePane = Convert.ToInt32(xmlIn.GetAttribute("ActivePane"), CultureInfo.InvariantCulture);
// Load Contents
MoveToNextElement(xmlIn);
if (xmlIn.Name != "Contents")
throw new ArgumentException(Strings.DockPanel_LoadFromXml_InvalidXmlFormat);
contents = LoadContents(xmlIn);
// Load Panes
if (xmlIn.Name != "Panes")
throw new ArgumentException(Strings.DockPanel_LoadFromXml_InvalidXmlFormat);
panes = LoadPanes(xmlIn);
// Load DockWindows
if (xmlIn.Name != "DockWindows")
throw new ArgumentException(Strings.DockPanel_LoadFromXml_InvalidXmlFormat);
dockWindows = LoadDockWindows(xmlIn, dockPanel);
// Load FloatWindows
if (xmlIn.Name != "FloatWindows")
throw new ArgumentException(Strings.DockPanel_LoadFromXml_InvalidXmlFormat);
floatWindows = LoadFloatWindows(xmlIn);
if (closeStream)
xmlIn.Close();
}
dockPanel.SuspendLayout(true);
dockPanel.DockLeftPortion = dockPanelStruct.DockLeftPortion;
dockPanel.DockRightPortion = dockPanelStruct.DockRightPortion;
dockPanel.DockTopPortion = dockPanelStruct.DockTopPortion;
dockPanel.DockBottomPortion = dockPanelStruct.DockBottomPortion;
// Set DockWindow ZOrders
int prevMaxDockWindowZOrder = int.MaxValue;
for (int i = 0; i < dockWindows.Length; i++)
{
int maxDockWindowZOrder = -1;
int index = -1;
for (int j = 0; j < dockWindows.Length; j++)
{
if (dockWindows[j].ZOrderIndex > maxDockWindowZOrder && dockWindows[j].ZOrderIndex < prevMaxDockWindowZOrder)
{
maxDockWindowZOrder = dockWindows[j].ZOrderIndex;
index = j;
}
}
dockPanel.DockWindows[dockWindows[index].DockState].BringToFront();
prevMaxDockWindowZOrder = maxDockWindowZOrder;
}
// Create Contents
for (int i = 0; i < contents.Length; i++)
{
IDockContent content = deserializeContent(contents[i].PersistString);
if (content == null)
content = new DummyContent();
content.DockHandler.DockPanel = dockPanel;
content.DockHandler.AutoHidePortion = contents[i].AutoHidePortion;
content.DockHandler.IsHidden = true;
content.DockHandler.IsFloat = contents[i].IsFloat;
}
// Create panes
for (int i = 0; i < panes.Length; i++)
{
DockPane pane = null;
for (int j = 0; j < panes[i].IndexContents.Length; j++)
{
IDockContent content = dockPanel.Contents[panes[i].IndexContents[j]];
if (j == 0)
pane = dockPanel.DockPaneFactory.CreateDockPane(content, panes[i].DockState, false);
else if (panes[i].DockState == DockState.Float)
content.DockHandler.FloatPane = pane;
else
content.DockHandler.PanelPane = pane;
}
}
// Assign Panes to DockWindows
for (int i = 0; i < dockWindows.Length; i++)
{
for (int j = 0; j < dockWindows[i].NestedPanes.Length; j++)
{
DockWindow dw = dockPanel.DockWindows[dockWindows[i].DockState];
int indexPane = dockWindows[i].NestedPanes[j].IndexPane;
DockPane pane = dockPanel.Panes[indexPane];
int indexPrevPane = dockWindows[i].NestedPanes[j].IndexPrevPane;
DockPane prevPane = (indexPrevPane == -1) ? dw.NestedPanes.GetDefaultPreviousPane(pane) : dockPanel.Panes[indexPrevPane];
DockAlignment alignment = dockWindows[i].NestedPanes[j].Alignment;
double proportion = dockWindows[i].NestedPanes[j].Proportion;
pane.DockTo(dw, prevPane, alignment, proportion);
if (panes[indexPane].DockState == dw.DockState)
panes[indexPane].ZOrderIndex = dockWindows[i].ZOrderIndex;
}
}
// Create float windows
for (int i = 0; i < floatWindows.Length; i++)
{
FloatWindow fw = null;
for (int j = 0; j < floatWindows[i].NestedPanes.Length; j++)
{
int indexPane = floatWindows[i].NestedPanes[j].IndexPane;
DockPane pane = dockPanel.Panes[indexPane];
if (j == 0)
fw = dockPanel.FloatWindowFactory.CreateFloatWindow(dockPanel, pane, floatWindows[i].Bounds);
else
{
int indexPrevPane = floatWindows[i].NestedPanes[j].IndexPrevPane;
DockPane prevPane = indexPrevPane == -1 ? null : dockPanel.Panes[indexPrevPane];
DockAlignment alignment = floatWindows[i].NestedPanes[j].Alignment;
double proportion = floatWindows[i].NestedPanes[j].Proportion;
pane.DockTo(fw, prevPane, alignment, proportion);
}
if (panes[indexPane].DockState == fw.DockState)
panes[indexPane].ZOrderIndex = floatWindows[i].ZOrderIndex;
}
}
// sort IDockContent by its Pane's ZOrder
int[] sortedContents = null;
if (contents.Length > 0)
{
sortedContents = new int[contents.Length];
for (int i = 0; i < contents.Length; i++)
sortedContents[i] = i;
int lastDocument = contents.Length;
for (int i = 0; i < contents.Length - 1; i++)
{
for (int j = i + 1; j < contents.Length; j++)
{
DockPane pane1 = dockPanel.Contents[sortedContents[i]].DockHandler.Pane;
int ZOrderIndex1 = pane1 == null ? 0 : panes[dockPanel.Panes.IndexOf(pane1)].ZOrderIndex;
DockPane pane2 = dockPanel.Contents[sortedContents[j]].DockHandler.Pane;
int ZOrderIndex2 = pane2 == null ? 0 : panes[dockPanel.Panes.IndexOf(pane2)].ZOrderIndex;
if (ZOrderIndex1 > ZOrderIndex2)
{
int temp = sortedContents[i];
sortedContents[i] = sortedContents[j];
sortedContents[j] = temp;
}
}
}
}
// show non-document IDockContent first to avoid screen flickers
for (int i = 0; i < contents.Length; i++)
{
IDockContent content = dockPanel.Contents[sortedContents[i]];
if (content.DockHandler.Pane != null && content.DockHandler.Pane.DockState != DockState.Document)
content.DockHandler.IsHidden = contents[sortedContents[i]].IsHidden;
}
// after all non-document IDockContent, show document IDockContent
for (int i = 0; i < contents.Length; i++)
{
IDockContent content = dockPanel.Contents[sortedContents[i]];
if (content.DockHandler.Pane != null && content.DockHandler.Pane.DockState == DockState.Document)
content.DockHandler.IsHidden = contents[sortedContents[i]].IsHidden;
}
for (int i = 0; i < panes.Length; i++)
dockPanel.Panes[i].ActiveContent = panes[i].IndexActiveContent == -1 ? null : dockPanel.Contents[panes[i].IndexActiveContent];
if (dockPanelStruct.IndexActiveDocumentPane != -1)
dockPanel.Panes[dockPanelStruct.IndexActiveDocumentPane].Activate();
if (dockPanelStruct.IndexActivePane != -1)
dockPanel.Panes[dockPanelStruct.IndexActivePane].Activate();
for (int i = dockPanel.Contents.Count - 1; i >= 0; i--)
if (dockPanel.Contents[i] is DummyContent)
dockPanel.Contents[i].DockHandler.Form.Close();
dockPanel.ResumeLayout(true, true);
}
private static bool MoveToNextElement(XmlTextReader xmlIn)
{
if (!xmlIn.Read())
return false;
while (xmlIn.NodeType == XmlNodeType.EndElement)
{
if (!xmlIn.Read())
return false;
}
return true;
}
private static bool IsFormatVersionValid(string formatVersion)
{
if (formatVersion == ConfigFileVersion)
return true;
foreach (string s in CompatibleConfigFileVersions)
if (s == formatVersion)
return true;
return false;
}
}
public void SaveAsXml(string fileName)
{
Persistor.SaveAsXml(this, fileName);
}
public void SaveAsXml(string fileName, Encoding encoding)
{
Persistor.SaveAsXml(this, fileName, encoding);
}
public void SaveAsXml(Stream stream, Encoding encoding)
{
Persistor.SaveAsXml(this, stream, encoding);
}
public void SaveAsXml(Stream stream, Encoding encoding, bool upstream)
{
Persistor.SaveAsXml(this, stream, encoding, upstream);
}
public void LoadFromXml(string fileName, DeserializeDockContent deserializeContent)
{
Persistor.LoadFromXml(this, fileName, deserializeContent);
}
public void LoadFromXml(Stream stream, DeserializeDockContent deserializeContent)
{
Persistor.LoadFromXml(this, stream, deserializeContent);
}
public void LoadFromXml(Stream stream, DeserializeDockContent deserializeContent, bool closeStream)
{
Persistor.LoadFromXml(this, stream, deserializeContent, closeStream);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Globalization;
using System.Text;
namespace System.Net.Http.Headers
{
public class WarningHeaderValue : ICloneable
{
private int _code;
private string _agent;
private string _text;
private DateTimeOffset? _date;
public int Code
{
get { return _code; }
}
public string Agent
{
get { return _agent; }
}
public string Text
{
get { return _text; }
}
public DateTimeOffset? Date
{
get { return _date; }
}
public WarningHeaderValue(int code, string agent, string text)
{
CheckCode(code);
CheckAgent(agent);
HeaderUtilities.CheckValidQuotedString(text, nameof(text));
_code = code;
_agent = agent;
_text = text;
}
public WarningHeaderValue(int code, string agent, string text, DateTimeOffset date)
{
CheckCode(code);
CheckAgent(agent);
HeaderUtilities.CheckValidQuotedString(text, nameof(text));
_code = code;
_agent = agent;
_text = text;
_date = date;
}
private WarningHeaderValue()
{
}
private WarningHeaderValue(WarningHeaderValue source)
{
Debug.Assert(source != null);
_code = source._code;
_agent = source._agent;
_text = source._text;
_date = source._date;
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
// Warning codes are always 3 digits according to RFC2616
sb.Append(_code.ToString("000", NumberFormatInfo.InvariantInfo));
sb.Append(' ');
sb.Append(_agent);
sb.Append(' ');
sb.Append(_text);
if (_date.HasValue)
{
sb.Append(" \"");
sb.Append(HttpRuleParser.DateToString(_date.Value));
sb.Append('\"');
}
return sb.ToString();
}
public override bool Equals(object obj)
{
WarningHeaderValue other = obj as WarningHeaderValue;
if (other == null)
{
return false;
}
// 'agent' is a host/token, i.e. use case-insensitive comparison. Use case-sensitive comparison for 'text'
// since it is a quoted string.
if ((_code != other._code) || (!string.Equals(_agent, other._agent, StringComparison.OrdinalIgnoreCase)) ||
(!string.Equals(_text, other._text, StringComparison.Ordinal)))
{
return false;
}
// We have a date set. Verify 'other' has also a date that matches our value.
if (_date.HasValue)
{
return other._date.HasValue && (_date.Value == other._date.Value);
}
// We don't have a date. If 'other' has a date, we're not equal.
return !other._date.HasValue;
}
public override int GetHashCode()
{
int result = _code.GetHashCode() ^
StringComparer.OrdinalIgnoreCase.GetHashCode(_agent) ^
_text.GetHashCode();
if (_date.HasValue)
{
result = result ^ _date.Value.GetHashCode();
}
return result;
}
public static WarningHeaderValue Parse(string input)
{
int index = 0;
return (WarningHeaderValue)GenericHeaderParser.SingleValueWarningParser.ParseValue(input, null, ref index);
}
public static bool TryParse(string input, out WarningHeaderValue parsedValue)
{
int index = 0;
object output;
parsedValue = null;
if (GenericHeaderParser.SingleValueWarningParser.TryParseValue(input, null, ref index, out output))
{
parsedValue = (WarningHeaderValue)output;
return true;
}
return false;
}
internal static int GetWarningLength(string input, int startIndex, out object parsedValue)
{
Debug.Assert(startIndex >= 0);
parsedValue = null;
if (string.IsNullOrEmpty(input) || (startIndex >= input.Length))
{
return 0;
}
// Read <code> in '<code> <agent> <text> ["<date>"]'
int code;
int current = startIndex;
if (!TryReadCode(input, ref current, out code))
{
return 0;
}
// Read <agent> in '<code> <agent> <text> ["<date>"]'
string agent;
if (!TryReadAgent(input, current, ref current, out agent))
{
return 0;
}
// Read <text> in '<code> <agent> <text> ["<date>"]'
int textLength = 0;
int textStartIndex = current;
if (HttpRuleParser.GetQuotedStringLength(input, current, out textLength) != HttpParseResult.Parsed)
{
return 0;
}
current = current + textLength;
// Read <date> in '<code> <agent> <text> ["<date>"]'
DateTimeOffset? date = null;
if (!TryReadDate(input, ref current, out date))
{
return 0;
}
WarningHeaderValue result = new WarningHeaderValue();
result._code = code;
result._agent = agent;
result._text = input.Substring(textStartIndex, textLength);
result._date = date;
parsedValue = result;
return current - startIndex;
}
private static bool TryReadAgent(string input, int startIndex, ref int current, out string agent)
{
agent = null;
int agentLength = HttpRuleParser.GetHostLength(input, startIndex, true, out agent);
if (agentLength == 0)
{
return false;
}
current = current + agentLength;
int whitespaceLength = HttpRuleParser.GetWhitespaceLength(input, current);
current = current + whitespaceLength;
// At least one whitespace required after <agent>. Also make sure we have characters left for <text>
if ((whitespaceLength == 0) || (current == input.Length))
{
return false;
}
return true;
}
private static bool TryReadCode(string input, ref int current, out int code)
{
code = 0;
int codeLength = HttpRuleParser.GetNumberLength(input, current, false);
// code must be a 3 digit value. We accept less digits, but we don't accept more.
if ((codeLength == 0) || (codeLength > 3))
{
return false;
}
if (!HeaderUtilities.TryParseInt32(input.Substring(current, codeLength), out code))
{
Debug.Assert(false, "Unable to parse value even though it was parsed as <=3 digits string. Input: '" +
input + "', Current: " + current + ", CodeLength: " + codeLength);
return false;
}
current = current + codeLength;
int whitespaceLength = HttpRuleParser.GetWhitespaceLength(input, current);
current = current + whitespaceLength;
// Make sure the number is followed by at least one whitespace and that we have characters left to parse.
if ((whitespaceLength == 0) || (current == input.Length))
{
return false;
}
return true;
}
private static bool TryReadDate(string input, ref int current, out DateTimeOffset? date)
{
date = null;
// Make sure we have at least one whitespace between <text> and <date> (if we have <date>)
int whitespaceLength = HttpRuleParser.GetWhitespaceLength(input, current);
current = current + whitespaceLength;
// Read <date> in '<code> <agent> <text> ["<date>"]'
if ((current < input.Length) && (input[current] == '"'))
{
if (whitespaceLength == 0)
{
return false; // we have characters after <text> but they were not separated by a whitespace
}
current++; // skip opening '"'
// Find the closing '"'
int dateStartIndex = current;
while (current < input.Length)
{
if (input[current] == '"')
{
break;
}
current++;
}
if ((current == input.Length) || (current == dateStartIndex))
{
return false; // we couldn't find the closing '"' or we have an empty quoted string.
}
DateTimeOffset temp;
if (!HttpRuleParser.TryStringToDate(input.Substring(dateStartIndex, current - dateStartIndex), out temp))
{
return false;
}
date = temp;
current++; // skip closing '"'
current = current + HttpRuleParser.GetWhitespaceLength(input, current);
}
return true;
}
object ICloneable.Clone()
{
return new WarningHeaderValue(this);
}
private static void CheckCode(int code)
{
if ((code < 0) || (code > 999))
{
throw new ArgumentOutOfRangeException(nameof(code));
}
}
private static void CheckAgent(string agent)
{
if (string.IsNullOrEmpty(agent))
{
throw new ArgumentException("The value cannot be null or empty.", nameof(agent));
}
// 'receivedBy' can either be a host or a token. Since a token is a valid host, we only verify if the value
// is a valid host.
string host = null;
if (HttpRuleParser.GetHostLength(agent, 0, true, out host) != agent.Length)
{
throw new FormatException(string.Format(System.Globalization.CultureInfo.InvariantCulture, "The format of value '{0}' is invalid.", agent));
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace System.Numerics.Tests
{
public class BigIntegerConstructorTest
{
private static int s_samples = 10;
private static Random s_random = new Random(100);
[Fact]
public static void RunCtorInt32Tests()
{
// ctor(Int32): Int32.MinValue
VerifyCtorInt32(Int32.MinValue);
// ctor(Int32): -1
VerifyCtorInt32((Int32)(-1));
// ctor(Int32): 0
VerifyCtorInt32((Int32)0);
// ctor(Int32): 1
VerifyCtorInt32((Int32)1);
// ctor(Int32): Int32.MaxValue
VerifyCtorInt32(Int32.MaxValue);
// ctor(Int32): Random Positive
for (int i = 0; i < s_samples; ++i)
{
VerifyCtorInt32((Int32)s_random.Next(1, Int32.MaxValue));
}
// ctor(Int32): Random Negative
for (int i = 0; i < s_samples; ++i)
{
VerifyCtorInt32((Int32)s_random.Next(Int32.MinValue, 0));
}
}
private static void VerifyCtorInt32(Int32 value)
{
BigInteger bigInteger = new BigInteger(value);
Assert.Equal(value, bigInteger);
Assert.Equal(0, String.CompareOrdinal(value.ToString(), bigInteger.ToString()));
Assert.Equal(value, (Int32)bigInteger);
if (value != Int32.MaxValue)
{
Assert.Equal((Int32)(value + 1), (Int32)(bigInteger + 1));
}
if (value != Int32.MinValue)
{
Assert.Equal((Int32)(value - 1), (Int32)(bigInteger - 1));
}
VerifyBigIntegerUsingIdentities(bigInteger, 0 == value);
}
[Fact]
public static void RunCtorInt64Tests()
{
// ctor(Int64): Int64.MinValue
VerifyCtorInt64(Int64.MinValue);
// ctor(Int64): Int32.MinValue-1
VerifyCtorInt64(((Int64)Int32.MinValue) - 1);
// ctor(Int64): Int32.MinValue
VerifyCtorInt64((Int64)Int32.MinValue);
// ctor(Int64): -1
VerifyCtorInt64((Int64)(-1));
// ctor(Int64): 0
VerifyCtorInt64((Int64)0);
// ctor(Int64): 1
VerifyCtorInt64((Int64)1);
// ctor(Int64): Int32.MaxValue
VerifyCtorInt64((Int64)Int32.MaxValue);
// ctor(Int64): Int32.MaxValue+1
VerifyCtorInt64(((Int64)Int32.MaxValue) + 1);
// ctor(Int64): Int64.MaxValue
VerifyCtorInt64(Int64.MaxValue);
// ctor(Int64): Random Positive
for (int i = 0; i < s_samples; ++i)
{
VerifyCtorInt64((Int64)(Int64.MaxValue * s_random.NextDouble()));
}
// ctor(Int64): Random Negative
for (int i = 0; i < s_samples; ++i)
{
VerifyCtorInt64((Int64)(Int64.MaxValue * s_random.NextDouble()) - Int64.MaxValue);
}
}
private static void VerifyCtorInt64(Int64 value)
{
BigInteger bigInteger = new BigInteger(value);
Assert.Equal(value, bigInteger);
Assert.Equal(0, String.CompareOrdinal(value.ToString(), bigInteger.ToString()));
Assert.Equal(value, (Int64)bigInteger);
if (value != Int64.MaxValue)
{
Assert.Equal((Int64)(value + 1), (Int64)(bigInteger + 1));
}
if (value != Int64.MinValue)
{
Assert.Equal((Int64)(value - 1), (Int64)(bigInteger - 1));
}
VerifyBigIntegerUsingIdentities(bigInteger, 0 == value);
}
[Fact]
public static void RunCtorUInt32Tests()
{
// ctor(UInt32): UInt32.MinValue
VerifyCtorUInt32(UInt32.MinValue);
// ctor(UInt32): 0
VerifyCtorUInt32((UInt32)0);
// ctor(UInt32): 1
VerifyCtorUInt32((UInt32)1);
// ctor(UInt32): Int32.MaxValue
VerifyCtorUInt32((UInt32)Int32.MaxValue);
// ctor(UInt32): Int32.MaxValue+1
VerifyCtorUInt32(((UInt32)Int32.MaxValue) + 1);
// ctor(UInt32): UInt32.MaxValue
VerifyCtorUInt32(UInt32.MaxValue);
// ctor(UInt32): Random Positive
for (int i = 0; i < s_samples; ++i)
{
VerifyCtorUInt32((UInt32)(UInt32.MaxValue * s_random.NextDouble()));
}
}
private static void VerifyCtorUInt32(UInt32 value)
{
BigInteger bigInteger = new BigInteger(value);
Assert.Equal(value, bigInteger);
Assert.Equal(0, String.CompareOrdinal(value.ToString(), bigInteger.ToString()));
Assert.Equal(value, (UInt32)bigInteger);
if (value != UInt32.MaxValue)
{
Assert.Equal((UInt32)(value + 1), (UInt32)(bigInteger + 1));
}
if (value != UInt32.MinValue)
{
Assert.Equal((UInt32)(value - 1), (UInt32)(bigInteger - 1));
}
VerifyBigIntegerUsingIdentities(bigInteger, 0 == value);
}
[Fact]
public static void RunCtorUInt64Tests()
{
// ctor(UInt64): UInt64.MinValue
VerifyCtorUInt64(UInt64.MinValue);
// ctor(UInt64): 0
VerifyCtorUInt64((UInt64)0);
// ctor(UInt64): 1
VerifyCtorUInt64((UInt64)1);
// ctor(UInt64): Int32.MaxValue
VerifyCtorUInt64((UInt64)Int32.MaxValue);
// ctor(UInt64): Int32.MaxValue+1
VerifyCtorUInt64(((UInt64)Int32.MaxValue) + 1);
// ctor(UInt64): UInt64.MaxValue
VerifyCtorUInt64(UInt64.MaxValue);
// ctor(UInt64): Random Positive
for (int i = 0; i < s_samples; ++i)
{
VerifyCtorUInt64((UInt64)(UInt64.MaxValue * s_random.NextDouble()));
}
}
private static void VerifyCtorUInt64(UInt64 value)
{
BigInteger bigInteger = new BigInteger(value);
Assert.Equal(value, bigInteger);
Assert.Equal(0, String.CompareOrdinal(value.ToString(), bigInteger.ToString()));
Assert.Equal(value, (UInt64)bigInteger);
if (value != UInt64.MaxValue)
{
Assert.Equal((UInt64)(value + 1), (UInt64)(bigInteger + 1));
}
if (value != UInt64.MinValue)
{
Assert.Equal((UInt64)(value - 1), (UInt64)(bigInteger - 1));
}
VerifyBigIntegerUsingIdentities(bigInteger, 0 == value);
}
[Fact]
public static void RunCtorSingleTests()
{
// ctor(Single): Single.Minvalue
VerifyCtorSingle(Single.MinValue);
// ctor(Single): Int32.MinValue-1
VerifyCtorSingle(((Single)Int32.MinValue) - 1);
// ctor(Single): Int32.MinValue
VerifyCtorSingle(((Single)Int32.MinValue));
// ctor(Single): Int32.MinValue+1
VerifyCtorSingle(((Single)Int32.MinValue) + 1);
// ctor(Single): -1
VerifyCtorSingle((Single)(-1));
// ctor(Single): 0
VerifyCtorSingle((Single)0);
// ctor(Single): 1
VerifyCtorSingle((Single)1);
// ctor(Single): Int32.MaxValue-1
VerifyCtorSingle(((Single)Int32.MaxValue) - 1);
// ctor(Single): Int32.MaxValue
VerifyCtorSingle(((Single)Int32.MaxValue));
// ctor(Single): Int32.MaxValue+1
VerifyCtorSingle(((Single)Int32.MaxValue) + 1);
// ctor(Single): Single.MaxValue
VerifyCtorSingle(Single.MaxValue);
// ctor(Single): Random Positive
for (int i = 0; i < s_samples; i++)
{
VerifyCtorSingle((Single)(Single.MaxValue * s_random.NextDouble()));
}
// ctor(Single): Random Negative
for (int i = 0; i < s_samples; i++)
{
VerifyCtorSingle(((Single)(Single.MaxValue * s_random.NextDouble())) - Single.MaxValue);
}
// ctor(Single): Small Random Positive with fractional part
for (int i = 0; i < s_samples; i++)
{
VerifyCtorSingle((Single)(s_random.Next(0, 100) + s_random.NextDouble()));
}
// ctor(Single): Small Random Negative with fractional part
for (int i = 0; i < s_samples; i++)
{
VerifyCtorSingle(((Single)(s_random.Next(-100, 0) - s_random.NextDouble())));
}
// ctor(Single): Large Random Positive with fractional part
for (int i = 0; i < s_samples; i++)
{
VerifyCtorSingle((Single)((Single.MaxValue * s_random.NextDouble()) + s_random.NextDouble()));
}
// ctor(Single): Large Random Negative with fractional part
for (int i = 0; i < s_samples; i++)
{
VerifyCtorSingle(((Single)((-(Single.MaxValue - 1) * s_random.NextDouble()) - s_random.NextDouble())));
}
// ctor(Single): Single.Epsilon
VerifyCtorSingle(Single.Epsilon);
// ctor(Single): Single.NegativeInfinity
Assert.Throws<OverflowException>(() => new BigInteger(Single.NegativeInfinity));
// ctor(Single): Single.PositiveInfinity
Assert.Throws<OverflowException>(() =>
{
BigInteger temp = new BigInteger(Single.PositiveInfinity);
});
// ctor(Single): Single.NaN
Assert.Throws<OverflowException>(() =>
{
BigInteger temp = new BigInteger(Single.NaN);
});
// ctor(Single): Single.NaN 2
Assert.Throws<OverflowException>(() =>
{
BigInteger temp = new BigInteger(ConvertInt32ToSingle(0x7FC00000));
});
// ctor(Single): Smallest Exponent
VerifyCtorSingle((Single)Math.Pow(2, -126));
// ctor(Single): Largest Exponent
VerifyCtorSingle((Single)Math.Pow(2, 127));
// ctor(Single): Largest number less than 1
Single value = 0;
for (int i = 1; i <= 24; ++i)
{
value += (Single)(Math.Pow(2, -i));
}
VerifyCtorSingle(value);
// ctor(Single): Smallest number greater than 1
value = (Single)(1 + Math.Pow(2, -23));
VerifyCtorSingle(value);
// ctor(Single): Largest number less than 2
value = 0;
for (int i = 1; i <= 23; ++i)
{
value += (Single)(Math.Pow(2, -i));
}
value += 1;
VerifyCtorSingle(value);
}
private static void VerifyCtorSingle(Single value)
{
BigInteger bigInteger = new BigInteger(value);
Single expectedValue;
if (value < 0)
{
expectedValue = (Single)Math.Ceiling(value);
}
else
{
expectedValue = (Single)Math.Floor(value);
}
Assert.Equal(expectedValue, (Single)bigInteger);
// Single can only accurately represent integers between -16777216 and 16777216 exclusive.
// ToString starts to become inaccurate at this point.
if (expectedValue < 16777216 && -16777216 < expectedValue)
{
Assert.True(expectedValue.ToString("G9").Equals(bigInteger.ToString(), StringComparison.OrdinalIgnoreCase), "Single.ToString() and BigInteger.ToString() not equal");
}
VerifyBigIntegerUsingIdentities(bigInteger, 0 == expectedValue);
}
[Fact]
public static void RunCtorDoubleTests()
{
// ctor(Double): Double.Minvalue
VerifyCtorDouble(Double.MinValue);
// ctor(Double): Single.Minvalue
VerifyCtorDouble((Double)Single.MinValue);
// ctor(Double): Int64.MinValue-1
VerifyCtorDouble(((Double)Int64.MinValue) - 1);
// ctor(Double): Int64.MinValue
VerifyCtorDouble(((Double)Int64.MinValue));
// ctor(Double): Int64.MinValue+1
VerifyCtorDouble(((Double)Int64.MinValue) + 1);
// ctor(Double): Int32.MinValue-1
VerifyCtorDouble(((Double)Int32.MinValue) - 1);
// ctor(Double): Int32.MinValue
VerifyCtorDouble(((Double)Int32.MinValue));
// ctor(Double): Int32.MinValue+1
VerifyCtorDouble(((Double)Int32.MinValue) + 1);
// ctor(Double): -1
VerifyCtorDouble((Double)(-1));
// ctor(Double): 0
VerifyCtorDouble((Double)0);
// ctor(Double): 1
VerifyCtorDouble((Double)1);
// ctor(Double): Int32.MaxValue-1
VerifyCtorDouble(((Double)Int32.MaxValue) - 1);
// ctor(Double): Int32.MaxValue
VerifyCtorDouble(((Double)Int32.MaxValue));
// ctor(Double): Int32.MaxValue+1
VerifyCtorDouble(((Double)Int32.MaxValue) + 1);
// ctor(Double): Int64.MaxValue-1
VerifyCtorDouble(((Double)Int64.MaxValue) - 1);
// ctor(Double): Int64.MaxValue
VerifyCtorDouble(((Double)Int64.MaxValue));
// ctor(Double): Int64.MaxValue+1
VerifyCtorDouble(((Double)Int64.MaxValue) + 1);
// ctor(Double): Single.MaxValue
VerifyCtorDouble((Double)Single.MaxValue);
// ctor(Double): Double.MaxValue
VerifyCtorDouble(Double.MaxValue);
// ctor(Double): Random Positive
for (int i = 0; i < s_samples; i++)
{
VerifyCtorDouble((Double)(Double.MaxValue * s_random.NextDouble()));
}
// ctor(Double): Random Negative
for (int i = 0; i < s_samples; i++)
{
VerifyCtorDouble((Double.MaxValue * s_random.NextDouble()) - Double.MaxValue);
}
// ctor(Double): Small Random Positive with fractional part
for (int i = 0; i < s_samples; i++)
{
VerifyCtorDouble((Double)(s_random.Next(0, 100) + s_random.NextDouble()));
}
// ctor(Double): Small Random Negative with fractional part
for (int i = 0; i < s_samples; i++)
{
VerifyCtorDouble(((Double)(s_random.Next(-100, 0) - s_random.NextDouble())));
}
// ctor(Double): Large Random Positive with fractional part
for (int i = 0; i < s_samples; i++)
{
VerifyCtorDouble((Double)((Int64.MaxValue / 100 * s_random.NextDouble()) + s_random.NextDouble()));
}
// ctor(Double): Large Random Negative with fractional part
for (int i = 0; i < s_samples; i++)
{
VerifyCtorDouble(((Double)((-(Int64.MaxValue / 100) * s_random.NextDouble()) - s_random.NextDouble())));
}
// ctor(Double): Double.Epsilon
VerifyCtorDouble(Double.Epsilon);
// ctor(Double): Double.NegativeInfinity
Assert.Throws<OverflowException>(() =>
{
BigInteger temp = new BigInteger(Double.NegativeInfinity);
});
// ctor(Double): Double.PositiveInfinity
Assert.Throws<OverflowException>(() =>
{
BigInteger temp = new BigInteger(Double.PositiveInfinity);
});
// ctor(Double): Double.NaN
Assert.Throws<OverflowException>(() =>
{
BigInteger temp = new BigInteger(Double.NaN);
});
// ctor(Double): Double.NaN 2
Assert.Throws<OverflowException>(() =>
{
BigInteger temp = new BigInteger(ConvertInt64ToDouble(0x7FF8000000000000));
});
// ctor(Double): Smallest Exponent
VerifyCtorDouble((Double)Math.Pow(2, -1022));
// ctor(Double): Largest Exponent
VerifyCtorDouble((Double)Math.Pow(2, 1023));
// ctor(Double): Largest number less than 1
Double value = 0;
for (int i = 1; i <= 53; ++i)
{
value += (Double)(Math.Pow(2, -i));
}
VerifyCtorDouble(value);
// ctor(Double): Smallest number greater than 1
value = (Double)(1 + Math.Pow(2, -52));
VerifyCtorDouble(value);
// ctor(Double): Largest number less than 2
value = 0;
for (int i = 1; i <= 52; ++i)
{
value += (Double)(Math.Pow(2, -i));
}
value += 2;
VerifyCtorDouble(value);
}
private static void VerifyCtorDouble(Double value)
{
BigInteger bigInteger = new BigInteger(value);
Double expectedValue;
if (value < 0)
{
expectedValue = (Double)Math.Ceiling(value);
}
else
{
expectedValue = (Double)Math.Floor(value);
}
Assert.Equal(expectedValue, (Double)bigInteger);
// Single can only accurately represent integers between -16777216 and 16777216 exclusive.
// ToString starts to become inaccurate at this point.
if (expectedValue < 9007199254740992 && -9007199254740992 < expectedValue)
{
Assert.True(expectedValue.ToString("G17").Equals(bigInteger.ToString(), StringComparison.OrdinalIgnoreCase), "Double.ToString() and BigInteger.ToString() not equal");
}
VerifyBigIntegerUsingIdentities(bigInteger, 0 == expectedValue);
}
[Fact]
public static void RunCtorDecimalTests()
{
Decimal value;
// ctor(Decimal): Decimal.MinValue
VerifyCtorDecimal(Decimal.MinValue);
// ctor(Decimal): -1
VerifyCtorDecimal(-1);
// ctor(Decimal): 0
VerifyCtorDecimal(0);
// ctor(Decimal): 1
VerifyCtorDecimal(1);
// ctor(Decimal): Decimal.MaxValue
VerifyCtorDecimal(Decimal.MaxValue);
// ctor(Decimal): Random Positive
for (int i = 0; i < s_samples; i++)
{
value = new Decimal(
s_random.Next(Int32.MinValue, Int32.MaxValue),
s_random.Next(Int32.MinValue, Int32.MaxValue),
s_random.Next(Int32.MinValue, Int32.MaxValue),
false,
(byte)s_random.Next(0, 29));
VerifyCtorDecimal(value);
}
// ctor(Decimal): Random Negative
for (int i = 0; i < s_samples; i++)
{
value = new Decimal(
s_random.Next(Int32.MinValue, Int32.MaxValue),
s_random.Next(Int32.MinValue, Int32.MaxValue),
s_random.Next(Int32.MinValue, Int32.MaxValue),
true,
(byte)s_random.Next(0, 29));
VerifyCtorDecimal(value);
}
// ctor(Decimal): Smallest Exponent
unchecked
{
value = new Decimal(1, 0, 0, false, 0);
}
VerifyCtorDecimal(value);
// ctor(Decimal): Largest Exponent and zero integer
unchecked
{
value = new Decimal(0, 0, 0, false, 28);
}
VerifyCtorDecimal(value);
// ctor(Decimal): Largest Exponent and non zero integer
unchecked
{
value = new Decimal(1, 0, 0, false, 28);
}
VerifyCtorDecimal(value);
// ctor(Decimal): Largest number less than 1
value = 1 - new Decimal(1, 0, 0, false, 28);
VerifyCtorDecimal(value);
// ctor(Decimal): Smallest number greater than 1
value = 1 + new Decimal(1, 0, 0, false, 28);
VerifyCtorDecimal(value);
// ctor(Decimal): Largest number less than 2
value = 2 - new Decimal(1, 0, 0, false, 28);
VerifyCtorDecimal(value);
}
private static void VerifyCtorDecimal(Decimal value)
{
BigInteger bigInteger = new BigInteger(value);
Decimal expectedValue;
if (value < 0)
{
expectedValue = Math.Ceiling(value);
}
else
{
expectedValue = Math.Floor(value);
}
Assert.True(expectedValue.ToString().Equals(bigInteger.ToString(), StringComparison.OrdinalIgnoreCase), "Decimal.ToString() and BigInteger.ToString()");
Assert.Equal(expectedValue, (Decimal)bigInteger);
if (expectedValue != Math.Floor(Decimal.MaxValue))
{
Assert.Equal((Decimal)(expectedValue + 1), (Decimal)(bigInteger + 1));
}
if (expectedValue != Math.Ceiling(Decimal.MinValue))
{
Assert.Equal((Decimal)(expectedValue - 1), (Decimal)(bigInteger - 1));
}
VerifyBigIntegerUsingIdentities(bigInteger, 0 == expectedValue);
}
[Fact]
public static void RunCtorByteArrayTests()
{
UInt64 tempUInt64;
byte[] tempByteArray;
// ctor(byte[]): array is null
Assert.Throws<ArgumentNullException>(() =>
{
BigInteger bigInteger = new BigInteger((byte[])null);
});
// ctor(byte[]): array is empty
VerifyCtorByteArray(new byte[0], 0);
// ctor(byte[]): array is 1 byte
tempUInt64 = (UInt32)s_random.Next(0, 256);
tempByteArray = BitConverter.GetBytes(tempUInt64);
if (tempByteArray[0] > 127)
{
VerifyCtorByteArray(new byte[] { tempByteArray[0] });
VerifyCtorByteArray(new byte[] { tempByteArray[0], 0 }, tempUInt64);
}
else
{
VerifyCtorByteArray(new byte[] { tempByteArray[0] }, tempUInt64);
}
// ctor(byte[]): Small array with all zeros
VerifyCtorByteArray(new byte[] { 0, 0, 0, 0 });
// ctor(byte[]): Large array with all zeros
VerifyCtorByteArray(
new byte[] {
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0
});
// ctor(byte[]): Small array with all ones
VerifyCtorByteArray(new byte[] { 0xFF, 0xFF, 0xFF, 0xFF });
// ctor(byte[]): Large array with all ones
VerifyCtorByteArray(
new byte[] {
0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF
});
// ctor(byte[]): array with a lot of leading zeros
for (int i = 0; i < s_samples; i++)
{
tempUInt64 = unchecked((UInt32)s_random.Next(Int32.MinValue, Int32.MaxValue));
tempByteArray = BitConverter.GetBytes(tempUInt64);
VerifyCtorByteArray(
new byte[] {
tempByteArray[0],
tempByteArray[1],
tempByteArray[2],
tempByteArray[3],
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0
},
tempUInt64);
}
// ctor(byte[]): array 4 bytes
for (int i = 0; i < s_samples; i++)
{
tempUInt64 = unchecked((UInt32)s_random.Next(Int32.MinValue, Int32.MaxValue));
tempByteArray = BitConverter.GetBytes(tempUInt64);
if (tempUInt64 > Int32.MaxValue)
{
VerifyCtorByteArray(
new byte[] {
tempByteArray[0],
tempByteArray[1],
tempByteArray[2],
tempByteArray[3]
});
VerifyCtorByteArray(
new byte[] {
tempByteArray[0],
tempByteArray[1],
tempByteArray[2],
tempByteArray[3],
0
},
tempUInt64);
}
else
{
VerifyCtorByteArray(
new byte[] {
tempByteArray[0],
tempByteArray[1],
tempByteArray[2],
tempByteArray[3]
},
tempUInt64);
}
}
// ctor(byte[]): array 5 bytes
for (int i = 0; i < s_samples; i++)
{
tempUInt64 = unchecked((UInt32)s_random.Next(Int32.MinValue, Int32.MaxValue));
tempUInt64 <<= 8;
tempUInt64 += (UInt64)s_random.Next(0, 256);
tempByteArray = BitConverter.GetBytes(tempUInt64);
if (tempUInt64 >= (UInt64)0x00080000)
{
VerifyCtorByteArray(
new byte[] {
tempByteArray[0],
tempByteArray[1],
tempByteArray[2],
tempByteArray[3],
tempByteArray[4]
});
VerifyCtorByteArray(
new byte[] {
tempByteArray[0],
tempByteArray[1],
tempByteArray[2],
tempByteArray[3],
tempByteArray[4],
0
}, tempUInt64);
}
else
{
VerifyCtorByteArray(
new byte[] {
tempByteArray[0],
tempByteArray[1],
tempByteArray[2],
tempByteArray[3],
tempByteArray[4]
}, tempUInt64);
}
}
// ctor(byte[]): array 8 bytes
for (int i = 0; i < s_samples; i++)
{
tempUInt64 = unchecked((UInt32)s_random.Next(Int32.MinValue, Int32.MaxValue));
tempUInt64 <<= 32;
tempUInt64 += unchecked((UInt32)s_random.Next(Int32.MinValue, Int32.MaxValue));
tempByteArray = BitConverter.GetBytes(tempUInt64);
if (tempUInt64 > Int64.MaxValue)
{
VerifyCtorByteArray(
new byte[] {
tempByteArray[0],
tempByteArray[1],
tempByteArray[2],
tempByteArray[3],
tempByteArray[4],
tempByteArray[5],
tempByteArray[6],
tempByteArray[7]
});
VerifyCtorByteArray(
new byte[] {
tempByteArray[0],
tempByteArray[1],
tempByteArray[2],
tempByteArray[3],
tempByteArray[4],
tempByteArray[5],
tempByteArray[6],
tempByteArray[7],
0
}, tempUInt64);
}
else
{
VerifyCtorByteArray(
new byte[] {
tempByteArray[0],
tempByteArray[1],
tempByteArray[2],
tempByteArray[3],
tempByteArray[4],
tempByteArray[5],
tempByteArray[6],
tempByteArray[7]
},
tempUInt64);
}
}
// ctor(byte[]): array 9 bytes
for (int i = 0; i < s_samples; i++)
{
VerifyCtorByteArray(
new byte[] {
(byte)s_random.Next(0, 256),
(byte)s_random.Next(0, 256),
(byte)s_random.Next(0, 256),
(byte)s_random.Next(0, 256),
(byte)s_random.Next(0, 256),
(byte)s_random.Next(0, 256),
(byte)s_random.Next(0, 256),
(byte)s_random.Next(0, 256),
(byte)s_random.Next(0, 256)
});
}
// ctor(byte[]): array is UInt32.MaxValue
VerifyCtorByteArray(new byte[] { 0xFF, 0xFF, 0xFF, 0xFF, 0 }, UInt32.MaxValue);
// ctor(byte[]): array is UInt32.MaxValue + 1
VerifyCtorByteArray(new byte[] { 0, 0, 0, 0, 1 }, (UInt64)UInt32.MaxValue + 1);
// ctor(byte[]): array is UInt64.MaxValue
VerifyCtorByteArray(new byte[] { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0 }, UInt64.MaxValue);
// ctor(byte[]): UInt64.MaxValue + 1
VerifyCtorByteArray(
new byte[] {
0, 0, 0, 0,
0, 0, 0, 0,
1
});
// ctor(byte[]): UInt64.MaxValue + 2^64
VerifyCtorByteArray(
new byte[] {
0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF,
1
});
// ctor(byte[]): array is random > UInt64
for (int i = 0; i < s_samples; i++)
{
tempByteArray = new byte[s_random.Next(0, 1024)];
for (int arrayIndex = 0; arrayIndex < tempByteArray.Length; ++arrayIndex)
{
tempByteArray[arrayIndex] = (byte)s_random.Next(0, 256);
}
VerifyCtorByteArray(tempByteArray);
}
// ctor(byte[]): array is large
for (int i = 0; i < s_samples; i++)
{
tempByteArray = new byte[s_random.Next(16384, 2097152)];
for (int arrayIndex = 0; arrayIndex < tempByteArray.Length; ++arrayIndex)
{
tempByteArray[arrayIndex] = (byte)s_random.Next(0, 256);
}
VerifyCtorByteArray(tempByteArray);
}
}
private static void VerifyCtorByteArray(byte[] value, UInt64 expectedValue)
{
BigInteger bigInteger = new BigInteger(value);
Assert.Equal(expectedValue, bigInteger);
Assert.True(expectedValue.ToString().Equals(bigInteger.ToString(), StringComparison.OrdinalIgnoreCase), "UInt64.ToString() and BigInteger.ToString()");
Assert.Equal(expectedValue, (UInt64)bigInteger);
if (expectedValue != UInt64.MaxValue)
{
Assert.Equal((UInt64)(expectedValue + 1), (UInt64)(bigInteger + 1));
}
if (expectedValue != UInt64.MinValue)
{
Assert.Equal((UInt64)(expectedValue - 1), (UInt64)(bigInteger - 1));
}
VerifyCtorByteArray(value);
}
private static void VerifyCtorByteArray(byte[] value)
{
BigInteger bigInteger;
byte[] roundTrippedByteArray;
bool isZero = MyBigIntImp.IsZero(value);
bigInteger = new BigInteger(value);
roundTrippedByteArray = bigInteger.ToByteArray();
for (int i = Math.Min(value.Length, roundTrippedByteArray.Length) - 1; 0 <= i; --i)
{
Assert.True(value[i] == roundTrippedByteArray[i], String.Format("Round Tripped ByteArray at {0}", i));
}
if (value.Length < roundTrippedByteArray.Length)
{
for (int i = value.Length; i < roundTrippedByteArray.Length; ++i)
{
Assert.True(0 == roundTrippedByteArray[i],
String.Format("Round Tripped ByteArray is larger than the original array and byte is non zero at {0}", i));
}
}
else if (value.Length > roundTrippedByteArray.Length)
{
for (int i = roundTrippedByteArray.Length; i < value.Length; ++i)
{
Assert.False((((0 != value[i]) && ((roundTrippedByteArray[roundTrippedByteArray.Length - 1] & 0x80) == 0)) ||
((0xFF != value[i]) && ((roundTrippedByteArray[roundTrippedByteArray.Length - 1] & 0x80) != 0))),
String.Format("Round Tripped ByteArray is smaller than the original array and byte is non zero at {0}", i));
}
}
if (value.Length < 8)
{
byte[] newvalue = new byte[8];
for (int i = 0; i < 8; i++)
{
if (bigInteger < 0)
{
newvalue[i] = 0xFF;
}
else
{
newvalue[i] = 0;
}
}
for (int i = 0; i < value.Length; i++)
{
newvalue[i] = value[i];
}
value = newvalue;
}
else if (value.Length > 8)
{
int newlength = value.Length;
for (; newlength > 8; newlength--)
{
if (bigInteger < 0)
{
if ((value[newlength - 1] != 0xFF) | ((value[newlength - 2] & 0x80) == 0))
{
break;
}
}
else
{
if ((value[newlength - 1] != 0) | ((value[newlength - 2] & 0x80) != 0))
{
break;
}
}
}
byte[] newvalue = new byte[newlength];
for (int i = 0; i < newlength; i++)
{
newvalue[i] = value[i];
}
value = newvalue;
}
if (IsOutOfRangeInt64(value))
{
// Try subtracting a value from the BigInteger that will allow it to be represented as an Int64
byte[] tempByteArray;
BigInteger tempBigInteger;
bool isNeg = ((value[value.Length - 1] & 0x80) != 0);
tempByteArray = new byte[value.Length];
Array.Copy(value, 8, tempByteArray, 8, value.Length - 8);
tempBigInteger = bigInteger - (new BigInteger(tempByteArray));
tempByteArray = new byte[8];
Array.Copy(value, 0, tempByteArray, 0, 8);
if (!(((tempByteArray[7] & 0x80) == 0) ^ isNeg))
{
tempByteArray[7] ^= 0x80;
tempBigInteger = tempBigInteger + (new BigInteger(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0x80 }));
}
if (isNeg & (tempBigInteger > 0))
{
tempBigInteger = tempBigInteger + (new BigInteger(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0xFF }));
}
Assert.Equal(BitConverter.ToInt64(tempByteArray, 0), (Int64)tempBigInteger);
}
else
{
Assert.Equal(BitConverter.ToInt64(value, 0), (Int64)bigInteger);
}
if (IsOutOfRangeUInt64(value))
{
// Try subtracting a value from the BigInteger that will allow it to be represented as an UInt64
byte[] tempByteArray;
BigInteger tempBigInteger;
bool isNeg = ((value[value.Length - 1] & 0x80) != 0);
tempByteArray = new byte[value.Length];
Array.Copy(value, 8, tempByteArray, 8, value.Length - 8);
tempBigInteger = bigInteger - (new BigInteger(tempByteArray));
tempByteArray = new byte[8];
Array.Copy(value, 0, tempByteArray, 0, 8);
if ((tempByteArray[7] & 0x80) != 0)
{
tempByteArray[7] &= 0x7f;
if (tempBigInteger < 0)
{
tempBigInteger = tempBigInteger - (new BigInteger(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0x80 }));
}
else
{
tempBigInteger = tempBigInteger + (new BigInteger(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0x80 }));
}
}
Assert.Equal(BitConverter.ToUInt64(tempByteArray, 0), (UInt64)tempBigInteger);
}
else
{
Assert.Equal(BitConverter.ToUInt64(value, 0), (UInt64)bigInteger);
}
VerifyBigIntegerUsingIdentities(bigInteger, isZero);
}
private static Single ConvertInt32ToSingle(Int32 value)
{
return BitConverter.ToSingle(BitConverter.GetBytes(value), 0);
}
private static Double ConvertInt64ToDouble(Int64 value)
{
return BitConverter.ToDouble(BitConverter.GetBytes(value), 0);
}
private static void VerifyBigIntegerUsingIdentities(BigInteger bigInteger, bool isZero)
{
BigInteger tempBigInteger = new BigInteger(bigInteger.ToByteArray());
Assert.Equal(bigInteger, tempBigInteger);
if (isZero)
{
Assert.Equal(BigInteger.Zero, bigInteger);
}
else
{
Assert.NotEqual(BigInteger.Zero, bigInteger);
Assert.Equal(BigInteger.One, bigInteger / bigInteger);
}
// (x + 1) - 1 = x
Assert.Equal(bigInteger, ((bigInteger + BigInteger.One) - BigInteger.One));
// (x + 1) - x = 1
Assert.Equal(BigInteger.One, ((bigInteger + BigInteger.One) - bigInteger));
// x - x = 0
Assert.Equal(BigInteger.Zero, (bigInteger - bigInteger));
// x + x = 2x
Assert.Equal((2 * bigInteger), (bigInteger + bigInteger));
// x/1 = x
Assert.Equal(bigInteger, (bigInteger / BigInteger.One));
// 1 * x = x
Assert.Equal(bigInteger, (BigInteger.One * bigInteger));
}
private static bool IsOutOfRangeUInt64(byte[] value)
{
if (value.Length == 0)
{
return false;
}
if ((0x80 & value[value.Length - 1]) != 0)
{
return true;
}
byte zeroValue = 0;
if (value.Length <= 8)
{
return false;
}
for (int i = 8; i < value.Length; ++i)
{
if (zeroValue != value[i])
{
return true;
}
}
return false;
}
private static bool IsOutOfRangeInt64(byte[] value)
{
if (value.Length == 0)
{
return false;
}
bool isNeg = ((0x80 & value[value.Length - 1]) != 0);
byte zeroValue = 0;
if (isNeg)
{
zeroValue = 0xFF;
}
if (value.Length < 8)
{
return false;
}
for (int i = 8; i < value.Length; i++)
{
if (zeroValue != value[i])
{
return true;
}
}
return (!((0 == (0x80 & value[7])) ^ isNeg));
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
//
// This file was autogenerated by a tool.
// Do not modify it.
//
namespace Microsoft.Azure.Batch
{
using FileStaging;
using Models = Microsoft.Azure.Batch.Protocol.Models;
using System;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// An Azure Batch task. A task is a piece of work that is associated with a job and runs on a compute node.
/// </summary>
public partial class CloudTask : ITransportObjectProvider<Models.TaskAddParameter>, IInheritedBehaviors, IPropertyMetadata
{
private class PropertyContainer : PropertyCollection
{
public readonly PropertyAccessor<AffinityInformation> AffinityInformationProperty;
public readonly PropertyAccessor<IList<ApplicationPackageReference>> ApplicationPackageReferencesProperty;
public readonly PropertyAccessor<AuthenticationTokenSettings> AuthenticationTokenSettingsProperty;
public readonly PropertyAccessor<string> CommandLineProperty;
public readonly PropertyAccessor<ComputeNodeInformation> ComputeNodeInformationProperty;
public readonly PropertyAccessor<TaskConstraints> ConstraintsProperty;
public readonly PropertyAccessor<DateTime?> CreationTimeProperty;
public readonly PropertyAccessor<TaskDependencies> DependsOnProperty;
public readonly PropertyAccessor<string> DisplayNameProperty;
public readonly PropertyAccessor<IList<EnvironmentSetting>> EnvironmentSettingsProperty;
public readonly PropertyAccessor<string> ETagProperty;
public readonly PropertyAccessor<TaskExecutionInformation> ExecutionInformationProperty;
public readonly PropertyAccessor<ExitConditions> ExitConditionsProperty;
public readonly PropertyAccessor<IList<IFileStagingProvider>> FilesToStageProperty;
public readonly PropertyAccessor<string> IdProperty;
public readonly PropertyAccessor<DateTime?> LastModifiedProperty;
public readonly PropertyAccessor<MultiInstanceSettings> MultiInstanceSettingsProperty;
public readonly PropertyAccessor<Common.TaskState?> PreviousStateProperty;
public readonly PropertyAccessor<DateTime?> PreviousStateTransitionTimeProperty;
public readonly PropertyAccessor<IList<ResourceFile>> ResourceFilesProperty;
public readonly PropertyAccessor<Common.TaskState?> StateProperty;
public readonly PropertyAccessor<DateTime?> StateTransitionTimeProperty;
public readonly PropertyAccessor<TaskStatistics> StatisticsProperty;
public readonly PropertyAccessor<string> UrlProperty;
public readonly PropertyAccessor<UserIdentity> UserIdentityProperty;
public PropertyContainer() : base(BindingState.Unbound)
{
this.AffinityInformationProperty = this.CreatePropertyAccessor<AffinityInformation>("AffinityInformation", BindingAccess.Read | BindingAccess.Write);
this.ApplicationPackageReferencesProperty = this.CreatePropertyAccessor<IList<ApplicationPackageReference>>("ApplicationPackageReferences", BindingAccess.Read | BindingAccess.Write);
this.AuthenticationTokenSettingsProperty = this.CreatePropertyAccessor<AuthenticationTokenSettings>("AuthenticationTokenSettings", BindingAccess.Read | BindingAccess.Write);
this.CommandLineProperty = this.CreatePropertyAccessor<string>("CommandLine", BindingAccess.Read | BindingAccess.Write);
this.ComputeNodeInformationProperty = this.CreatePropertyAccessor<ComputeNodeInformation>("ComputeNodeInformation", BindingAccess.None);
this.ConstraintsProperty = this.CreatePropertyAccessor<TaskConstraints>("Constraints", BindingAccess.Read | BindingAccess.Write);
this.CreationTimeProperty = this.CreatePropertyAccessor<DateTime?>("CreationTime", BindingAccess.None);
this.DependsOnProperty = this.CreatePropertyAccessor<TaskDependencies>("DependsOn", BindingAccess.Read | BindingAccess.Write);
this.DisplayNameProperty = this.CreatePropertyAccessor<string>("DisplayName", BindingAccess.Read | BindingAccess.Write);
this.EnvironmentSettingsProperty = this.CreatePropertyAccessor<IList<EnvironmentSetting>>("EnvironmentSettings", BindingAccess.Read | BindingAccess.Write);
this.ETagProperty = this.CreatePropertyAccessor<string>("ETag", BindingAccess.None);
this.ExecutionInformationProperty = this.CreatePropertyAccessor<TaskExecutionInformation>("ExecutionInformation", BindingAccess.None);
this.ExitConditionsProperty = this.CreatePropertyAccessor<ExitConditions>("ExitConditions", BindingAccess.Read | BindingAccess.Write);
this.FilesToStageProperty = this.CreatePropertyAccessor<IList<IFileStagingProvider>>("FilesToStage", BindingAccess.Read | BindingAccess.Write);
this.IdProperty = this.CreatePropertyAccessor<string>("Id", BindingAccess.Read | BindingAccess.Write);
this.LastModifiedProperty = this.CreatePropertyAccessor<DateTime?>("LastModified", BindingAccess.None);
this.MultiInstanceSettingsProperty = this.CreatePropertyAccessor<MultiInstanceSettings>("MultiInstanceSettings", BindingAccess.Read | BindingAccess.Write);
this.PreviousStateProperty = this.CreatePropertyAccessor<Common.TaskState?>("PreviousState", BindingAccess.None);
this.PreviousStateTransitionTimeProperty = this.CreatePropertyAccessor<DateTime?>("PreviousStateTransitionTime", BindingAccess.None);
this.ResourceFilesProperty = this.CreatePropertyAccessor<IList<ResourceFile>>("ResourceFiles", BindingAccess.Read | BindingAccess.Write);
this.StateProperty = this.CreatePropertyAccessor<Common.TaskState?>("State", BindingAccess.None);
this.StateTransitionTimeProperty = this.CreatePropertyAccessor<DateTime?>("StateTransitionTime", BindingAccess.None);
this.StatisticsProperty = this.CreatePropertyAccessor<TaskStatistics>("Statistics", BindingAccess.None);
this.UrlProperty = this.CreatePropertyAccessor<string>("Url", BindingAccess.None);
this.UserIdentityProperty = this.CreatePropertyAccessor<UserIdentity>("UserIdentity", BindingAccess.Read | BindingAccess.Write);
}
public PropertyContainer(Models.CloudTask protocolObject) : base(BindingState.Bound)
{
this.AffinityInformationProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.AffinityInfo, o => new AffinityInformation(o).Freeze()),
"AffinityInformation",
BindingAccess.Read);
this.ApplicationPackageReferencesProperty = this.CreatePropertyAccessor(
ApplicationPackageReference.ConvertFromProtocolCollectionAndFreeze(protocolObject.ApplicationPackageReferences),
"ApplicationPackageReferences",
BindingAccess.Read);
this.AuthenticationTokenSettingsProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.AuthenticationTokenSettings, o => new AuthenticationTokenSettings(o).Freeze()),
"AuthenticationTokenSettings",
BindingAccess.Read);
this.CommandLineProperty = this.CreatePropertyAccessor(
protocolObject.CommandLine,
"CommandLine",
BindingAccess.Read);
this.ComputeNodeInformationProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.NodeInfo, o => new ComputeNodeInformation(o).Freeze()),
"ComputeNodeInformation",
BindingAccess.Read);
this.ConstraintsProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.Constraints, o => new TaskConstraints(o)),
"Constraints",
BindingAccess.Read | BindingAccess.Write);
this.CreationTimeProperty = this.CreatePropertyAccessor(
protocolObject.CreationTime,
"CreationTime",
BindingAccess.Read);
this.DependsOnProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.DependsOn, o => new TaskDependencies(o).Freeze()),
"DependsOn",
BindingAccess.Read);
this.DisplayNameProperty = this.CreatePropertyAccessor(
protocolObject.DisplayName,
"DisplayName",
BindingAccess.Read);
this.EnvironmentSettingsProperty = this.CreatePropertyAccessor(
EnvironmentSetting.ConvertFromProtocolCollectionAndFreeze(protocolObject.EnvironmentSettings),
"EnvironmentSettings",
BindingAccess.Read);
this.ETagProperty = this.CreatePropertyAccessor(
protocolObject.ETag,
"ETag",
BindingAccess.Read);
this.ExecutionInformationProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.ExecutionInfo, o => new TaskExecutionInformation(o).Freeze()),
"ExecutionInformation",
BindingAccess.Read);
this.ExitConditionsProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.ExitConditions, o => new ExitConditions(o).Freeze()),
"ExitConditions",
BindingAccess.Read);
this.FilesToStageProperty = this.CreatePropertyAccessor<IList<IFileStagingProvider>>(
"FilesToStage",
BindingAccess.None);
this.IdProperty = this.CreatePropertyAccessor(
protocolObject.Id,
"Id",
BindingAccess.Read);
this.LastModifiedProperty = this.CreatePropertyAccessor(
protocolObject.LastModified,
"LastModified",
BindingAccess.Read);
this.MultiInstanceSettingsProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.MultiInstanceSettings, o => new MultiInstanceSettings(o).Freeze()),
"MultiInstanceSettings",
BindingAccess.Read);
this.PreviousStateProperty = this.CreatePropertyAccessor(
UtilitiesInternal.MapNullableEnum<Models.TaskState, Common.TaskState>(protocolObject.PreviousState),
"PreviousState",
BindingAccess.Read);
this.PreviousStateTransitionTimeProperty = this.CreatePropertyAccessor(
protocolObject.PreviousStateTransitionTime,
"PreviousStateTransitionTime",
BindingAccess.Read);
this.ResourceFilesProperty = this.CreatePropertyAccessor(
ResourceFile.ConvertFromProtocolCollectionAndFreeze(protocolObject.ResourceFiles),
"ResourceFiles",
BindingAccess.Read);
this.StateProperty = this.CreatePropertyAccessor(
UtilitiesInternal.MapNullableEnum<Models.TaskState, Common.TaskState>(protocolObject.State),
"State",
BindingAccess.Read);
this.StateTransitionTimeProperty = this.CreatePropertyAccessor(
protocolObject.StateTransitionTime,
"StateTransitionTime",
BindingAccess.Read);
this.StatisticsProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.Stats, o => new TaskStatistics(o).Freeze()),
"Statistics",
BindingAccess.Read);
this.UrlProperty = this.CreatePropertyAccessor(
protocolObject.Url,
"Url",
BindingAccess.Read);
this.UserIdentityProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.UserIdentity, o => new UserIdentity(o).Freeze()),
"UserIdentity",
BindingAccess.Read);
}
}
private PropertyContainer propertyContainer;
private readonly BatchClient parentBatchClient;
private readonly string parentJobId;
internal string ParentJobId
{
get
{
return this.parentJobId;
}
}
#region Constructors
internal CloudTask(
BatchClient parentBatchClient,
string parentJobId,
Models.CloudTask protocolObject,
IEnumerable<BatchClientBehavior> baseBehaviors)
{
this.parentJobId = parentJobId;
this.parentBatchClient = parentBatchClient;
InheritUtil.InheritClientBehaviorsAndSetPublicProperty(this, baseBehaviors);
this.propertyContainer = new PropertyContainer(protocolObject);
}
#endregion Constructors
#region IInheritedBehaviors
/// <summary>
/// Gets or sets a list of behaviors that modify or customize requests to the Batch service
/// made via this <see cref="CloudTask"/>.
/// </summary>
/// <remarks>
/// <para>These behaviors are inherited by child objects.</para>
/// <para>Modifications are applied in the order of the collection. The last write wins.</para>
/// </remarks>
public IList<BatchClientBehavior> CustomBehaviors { get; set; }
#endregion IInheritedBehaviors
#region CloudTask
/// <summary>
/// Gets or sets a locality hint that can be used by the Batch service to select a node on which to start the task.
/// </summary>
public AffinityInformation AffinityInformation
{
get { return this.propertyContainer.AffinityInformationProperty.Value; }
set { this.propertyContainer.AffinityInformationProperty.Value = value; }
}
/// <summary>
/// Gets or sets a list of application packages that the Batch service will deploy to the compute node before running
/// the command line.
/// </summary>
public IList<ApplicationPackageReference> ApplicationPackageReferences
{
get { return this.propertyContainer.ApplicationPackageReferencesProperty.Value; }
set
{
this.propertyContainer.ApplicationPackageReferencesProperty.Value = ConcurrentChangeTrackedModifiableList<ApplicationPackageReference>.TransformEnumerableToConcurrentModifiableList(value);
}
}
/// <summary>
/// Gets or sets the settings for an authentication token that the task can use to perform Batch service operations.
/// </summary>
/// <remarks>
/// If this property is set, the Batch service provides the task with an authentication token which can be used to
/// authenticate Batch service operations without requiring an account access key. The token is provided via the
/// AZ_BATCH_AUTHENTICATION_TOKEN environment variable. The operations that the task can carry out using the token
/// depend on the settings. For example, a task can request job permissions in order to add other tasks to the job,
/// or check the status of the job or of other tasks.
/// </remarks>
public AuthenticationTokenSettings AuthenticationTokenSettings
{
get { return this.propertyContainer.AuthenticationTokenSettingsProperty.Value; }
set { this.propertyContainer.AuthenticationTokenSettingsProperty.Value = value; }
}
/// <summary>
/// Gets or sets the command line of the task.
/// </summary>
/// <remarks>
/// The command line does not run under a shell, and therefore cannot take advantage of shell features such as environment
/// variable expansion. If you want to take advantage of such features, you should invoke the shell in the command
/// line, for example using "cmd /c MyCommand" in Windows or "/bin/sh -c MyCommand" in Linux.
/// </remarks>
public string CommandLine
{
get { return this.propertyContainer.CommandLineProperty.Value; }
set { this.propertyContainer.CommandLineProperty.Value = value; }
}
/// <summary>
/// Gets information about the compute node on which the task ran.
/// </summary>
public ComputeNodeInformation ComputeNodeInformation
{
get { return this.propertyContainer.ComputeNodeInformationProperty.Value; }
}
/// <summary>
/// Gets or sets the execution constraints that apply to this task.
/// </summary>
public TaskConstraints Constraints
{
get { return this.propertyContainer.ConstraintsProperty.Value; }
set { this.propertyContainer.ConstraintsProperty.Value = value; }
}
/// <summary>
/// Gets the creation time of the task.
/// </summary>
public DateTime? CreationTime
{
get { return this.propertyContainer.CreationTimeProperty.Value; }
}
/// <summary>
/// Gets or sets any other tasks that this <see cref="CloudTask"/> depends on. The task will not be scheduled until
/// all depended-on tasks have completed successfully.
/// </summary>
/// <remarks>
/// The job must set <see cref="CloudJob.UsesTaskDependencies"/> to true in order to use task dependencies. If UsesTaskDependencies
/// is false (the default), adding a task with dependencies will fail with an error.
/// </remarks>
public TaskDependencies DependsOn
{
get { return this.propertyContainer.DependsOnProperty.Value; }
set { this.propertyContainer.DependsOnProperty.Value = value; }
}
/// <summary>
/// Gets or sets the display name of the task.
/// </summary>
public string DisplayName
{
get { return this.propertyContainer.DisplayNameProperty.Value; }
set { this.propertyContainer.DisplayNameProperty.Value = value; }
}
/// <summary>
/// Gets or sets a list of environment variable settings for the task.
/// </summary>
public IList<EnvironmentSetting> EnvironmentSettings
{
get { return this.propertyContainer.EnvironmentSettingsProperty.Value; }
set
{
this.propertyContainer.EnvironmentSettingsProperty.Value = ConcurrentChangeTrackedModifiableList<EnvironmentSetting>.TransformEnumerableToConcurrentModifiableList(value);
}
}
/// <summary>
/// Gets the ETag for the task.
/// </summary>
public string ETag
{
get { return this.propertyContainer.ETagProperty.Value; }
}
/// <summary>
/// Gets the execution information for the task.
/// </summary>
public TaskExecutionInformation ExecutionInformation
{
get { return this.propertyContainer.ExecutionInformationProperty.Value; }
}
/// <summary>
/// Gets or sets how the Batch service should respond when the task completes.
/// </summary>
public ExitConditions ExitConditions
{
get { return this.propertyContainer.ExitConditionsProperty.Value; }
set { this.propertyContainer.ExitConditionsProperty.Value = value; }
}
/// <summary>
/// Gets or sets a list of files to be staged for the task.
/// </summary>
public IList<IFileStagingProvider> FilesToStage
{
get { return this.propertyContainer.FilesToStageProperty.Value; }
set
{
this.propertyContainer.FilesToStageProperty.Value = ConcurrentChangeTrackedList<IFileStagingProvider>.TransformEnumerableToConcurrentList(value);
}
}
/// <summary>
/// Gets or sets the id of the task.
/// </summary>
public string Id
{
get { return this.propertyContainer.IdProperty.Value; }
set { this.propertyContainer.IdProperty.Value = value; }
}
/// <summary>
/// Gets the last modified time of the task.
/// </summary>
public DateTime? LastModified
{
get { return this.propertyContainer.LastModifiedProperty.Value; }
}
/// <summary>
/// Gets or sets information about how to run the multi-instance task.
/// </summary>
public MultiInstanceSettings MultiInstanceSettings
{
get { return this.propertyContainer.MultiInstanceSettingsProperty.Value; }
set { this.propertyContainer.MultiInstanceSettingsProperty.Value = value; }
}
/// <summary>
/// Gets the previous state of the task.
/// </summary>
/// <remarks>
/// If the task is in its initial <see cref="Common.TaskState.Active"/> state, the PreviousState property is not
/// defined.
/// </remarks>
public Common.TaskState? PreviousState
{
get { return this.propertyContainer.PreviousStateProperty.Value; }
}
/// <summary>
/// Gets the time at which the task entered its previous state.
/// </summary>
/// <remarks>
/// If the task is in its initial <see cref="Common.TaskState.Active"/> state, the PreviousStateTransitionTime property
/// is not defined.
/// </remarks>
public DateTime? PreviousStateTransitionTime
{
get { return this.propertyContainer.PreviousStateTransitionTimeProperty.Value; }
}
/// <summary>
/// Gets or sets a list of files that the Batch service will download to the compute node before running the command
/// line.
/// </summary>
public IList<ResourceFile> ResourceFiles
{
get { return this.propertyContainer.ResourceFilesProperty.Value; }
set
{
this.propertyContainer.ResourceFilesProperty.Value = ConcurrentChangeTrackedModifiableList<ResourceFile>.TransformEnumerableToConcurrentModifiableList(value);
}
}
/// <summary>
/// Gets the current state of the task.
/// </summary>
public Common.TaskState? State
{
get { return this.propertyContainer.StateProperty.Value; }
}
/// <summary>
/// Gets the time at which the task entered its current state.
/// </summary>
public DateTime? StateTransitionTime
{
get { return this.propertyContainer.StateTransitionTimeProperty.Value; }
}
/// <summary>
/// Gets resource usage statistics for the task.
/// </summary>
/// <remarks>
/// This property is populated only if the <see cref="CloudTask"/> was retrieved with an <see cref="ODATADetailLevel.ExpandClause"/>
/// including the 'stats' attribute; otherwise it is null.
/// </remarks>
public TaskStatistics Statistics
{
get { return this.propertyContainer.StatisticsProperty.Value; }
}
/// <summary>
/// Gets the URL of the task.
/// </summary>
public string Url
{
get { return this.propertyContainer.UrlProperty.Value; }
}
/// <summary>
/// Gets or sets the user identity under which the task runs.
/// </summary>
/// <remarks>
/// If omitted, the task runs as a non-administrative user unique to the task.
/// </remarks>
public UserIdentity UserIdentity
{
get { return this.propertyContainer.UserIdentityProperty.Value; }
set { this.propertyContainer.UserIdentityProperty.Value = value; }
}
#endregion // CloudTask
#region IPropertyMetadata
bool IModifiable.HasBeenModified
{
get { return this.propertyContainer.HasBeenModified; }
}
bool IReadOnly.IsReadOnly
{
get { return this.propertyContainer.IsReadOnly; }
set { this.propertyContainer.IsReadOnly = value; }
}
#endregion //IPropertyMetadata
#region Internal/private methods
/// <summary>
/// Return a protocol object of the requested type.
/// </summary>
/// <returns>The protocol object of the requested type.</returns>
Models.TaskAddParameter ITransportObjectProvider<Models.TaskAddParameter>.GetTransportObject()
{
Models.TaskAddParameter result = new Models.TaskAddParameter()
{
AffinityInfo = UtilitiesInternal.CreateObjectWithNullCheck(this.AffinityInformation, (o) => o.GetTransportObject()),
ApplicationPackageReferences = UtilitiesInternal.ConvertToProtocolCollection(this.ApplicationPackageReferences),
AuthenticationTokenSettings = UtilitiesInternal.CreateObjectWithNullCheck(this.AuthenticationTokenSettings, (o) => o.GetTransportObject()),
CommandLine = this.CommandLine,
Constraints = UtilitiesInternal.CreateObjectWithNullCheck(this.Constraints, (o) => o.GetTransportObject()),
DependsOn = UtilitiesInternal.CreateObjectWithNullCheck(this.DependsOn, (o) => o.GetTransportObject()),
DisplayName = this.DisplayName,
EnvironmentSettings = UtilitiesInternal.ConvertToProtocolCollection(this.EnvironmentSettings),
ExitConditions = UtilitiesInternal.CreateObjectWithNullCheck(this.ExitConditions, (o) => o.GetTransportObject()),
Id = this.Id,
MultiInstanceSettings = UtilitiesInternal.CreateObjectWithNullCheck(this.MultiInstanceSettings, (o) => o.GetTransportObject()),
ResourceFiles = UtilitiesInternal.ConvertToProtocolCollection(this.ResourceFiles),
UserIdentity = UtilitiesInternal.CreateObjectWithNullCheck(this.UserIdentity, (o) => o.GetTransportObject()),
};
return result;
}
#endregion // Internal/private methods
}
}
| |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web.UI;
using AjaxPro;
using ASC.Web.Core;
using ASC.Web.Core.ModuleManagement.Common;
using ASC.Web.Core.Utility;
using ASC.Web.Core.Utility.Skins;
using ASC.Web.Studio.Controls.Common;
using ASC.Web.Studio.Core.Search;
using ASC.Web.Studio.PublicResources;
using ASC.Web.Studio.UserControls.Common.Search;
using ASC.Web.Studio.Utility;
namespace ASC.Web.Studio
{
[AjaxNamespace("SearchController")]
public partial class Search : MainPage
{
protected string SearchText;
protected void Page_Load(object sender, EventArgs e)
{
AjaxPro.Utility.RegisterTypeForAjax(GetType());
Master.DisabledSidePanel = true;
Title = HeaderStringHelper.GetPageTitle(Resource.Search);
var productID = !string.IsNullOrEmpty(Request["productID"]) ? new Guid(Request["productID"]) : Guid.Empty;
var moduleID = !string.IsNullOrEmpty(Request["moduleID"]) ? new Guid(Request["moduleID"]) : Guid.Empty;
SearchText = (Request["search"] ?? "").Trim();
var searchResultsData = new List<SearchResult>();
if (!string.IsNullOrEmpty(SearchText))
{
List<ISearchHandlerEx> handlers = null;
var products = !string.IsNullOrEmpty(Request["products"]) ? Request["products"] : string.Empty;
if (!string.IsNullOrEmpty(products))
{
try
{
var productsStr = products.Split(new[] { ',' });
var productsGuid = productsStr.Select(p => new Guid(p)).ToArray();
handlers = SearchHandlerManager.GetHandlersExForProductModule(productsGuid);
}
catch (Exception err)
{
Log.Error(err);
}
}
if (handlers == null)
{
handlers = SearchHandlerManager.GetHandlersExForProductModule(productID, moduleID);
}
searchResultsData = GetSearchresultByHandlers(handlers, SearchText);
}
if (searchResultsData.Count <= 0)
{
var emptyScreenControl = new EmptyScreenControl
{
ImgSrc = WebImageSupplier.GetAbsoluteWebPath("empty_search.png"),
Header = Resource.SearchNotFoundMessage,
Describe = Resource.SearchNotFoundDescript
};
SearchContent.Controls.Add(emptyScreenControl);
}
else
{
searchResultsData = GroupSearchresult(productID, searchResultsData);
var oSearchView = (SearchResults)LoadControl(SearchResults.Location);
oSearchView.SearchResultsData = searchResultsData;
SearchContent.Controls.Add(oSearchView);
}
}
private List<SearchResult> GroupSearchresult(Guid productID, List<SearchResult> searchResult)
{
if (!productID.Equals(Guid.Empty) && productID != WebItemManager.CommunityProductID) return searchResult;
var groupedData = GroupDataModules(searchResult);
groupedData.Sort(new SearchComparer());
return groupedData;
}
private List<SearchResult> GroupDataModules(List<SearchResult> data)
{
var guids = data.Select(searchResult => searchResult.ProductID).ToList();
if (!guids.Any())
return data;
guids = guids.Distinct().ToList();
var groupedData = new List<SearchResult>();
foreach (var productID in guids)
{
foreach (var searchResult in data)
{
if (searchResult.ProductID != productID) continue;
var item = GetContainer(groupedData, productID);
foreach (var searchResultItem in searchResult.Items)
{
if (searchResultItem.Additional == null)
searchResultItem.Additional = new Dictionary<string, object>();
if (!searchResultItem.Additional.ContainsKey("imageRef"))
searchResultItem.Additional.Add("imageRef", searchResult.LogoURL);
if (!searchResultItem.Additional.ContainsKey("Hint"))
searchResultItem.Additional.Add("Hint", searchResult.Name);
}
item.Items.AddRange(searchResult.Items);
if (item.PresentationControl == null) item.PresentationControl = searchResult.PresentationControl;
if (string.IsNullOrEmpty(item.LogoURL)) item.LogoURL = searchResult.LogoURL;
if (string.IsNullOrEmpty(item.Name)) item.Name = searchResult.Name;
}
}
return groupedData;
}
private SearchResult GetContainer(ICollection<SearchResult> newData, Guid productID)
{
foreach (var searchResult in newData.Where(searchResult => searchResult.ProductID == productID))
return searchResult;
var newResult = CreateCertainContainer(productID);
newData.Add(newResult);
return newResult;
}
private SearchResult CreateCertainContainer(Guid productID)
{
var certainProduct = WebItemManager.Instance[productID];
var container = new SearchResult
{
ProductID = productID,
Name = (certainProduct != null) ? certainProduct.Name : string.Empty,
LogoURL = (certainProduct != null) ? certainProduct.GetIconAbsoluteURL() : string.Empty
};
if (productID == WebItemManager.CommunityProductID || productID == Guid.Empty)
container.PresentationControl = new CommonResultsView { MaxCount = 7, Text = SearchText };
return container;
}
private static List<SearchResult> GetSearchresultByHandlers(IEnumerable<ISearchHandlerEx> handlers, string searchText)
{
var searchResults = new List<SearchResult>();
foreach (var sh in handlers)
{
var module = WebItemManager.Instance[sh.ModuleID];
if (module != null && module.IsDisabled())
continue;
var items = sh.Search(searchText).OrderByDescending(item => item.Date).ToArray();
if (items.Length == 0)
continue;
var searchResult = new SearchResult
{
ProductID = sh.ProductID,
PresentationControl = (ItemSearchControl)sh.Control,
Name = module != null ? module.Name : sh.SearchName,
LogoURL = module != null
? module.GetIconAbsoluteURL()
: WebImageSupplier.GetAbsoluteWebPath(sh.Logo.ImageFileName, sh.Logo.PartID)
};
searchResult.PresentationControl.Text = searchText;
searchResult.PresentationControl.MaxCount = 7;
searchResult.Items.AddRange(items);
searchResults.Add(searchResult);
}
return searchResults;
}
[AjaxMethod]
public string GetAllData(string product, string text)
{
if (string.IsNullOrEmpty(text)) return string.Empty;
var productID = new Guid(product);
var handlers = SearchHandlerManager.GetHandlersExForProductModule(productID, Guid.Empty);
var searchResultsData = GetSearchresultByHandlers(handlers, text);
searchResultsData = GroupSearchresult(productID, searchResultsData);
if (searchResultsData.Count <= 0) return string.Empty;
var control = searchResultsData[0].PresentationControl ?? new CommonResultsView();
control.Items = new List<SearchResultItem>();
foreach (var searchResult in searchResultsData)
{
control.Items.AddRange(searchResult.Items);
}
control.MaxCount = int.MaxValue;
control.Text = control.Text ?? text;
var stringWriter = new StringWriter();
var htmlWriter = new HtmlTextWriter(stringWriter);
control.RenderControl(htmlWriter);
return stringWriter.ToString();
}
}
}
| |
using System;
using System.Text;
namespace DevTreks.Helpers
{
// <summary>
///Purpose: Help xslt stylesheet display effectiveness analyses
///Author: www.devtreks.org
///Original script author is: Gerardo A., ARS, SW Watershed Research Center
///Date: 2016, March
///References: www.devtreks.org/helptreks/linkedviews/help/linkedview/HelpFile/148
/// </summary>
public class DisplayEffectiveness
{
public DisplayEffectiveness()
{
//individual object
}
private string[] arrValues = null;
private string[] arrNOPs = null;
private static char[] DELIMITER_NAME = new char[] {';'};
public string writeTitles(string fullColCount)
{
int iFullColCount = (isNumber(fullColCount))? Convert.ToInt32(fullColCount) : 0;
int i = 0;
string sHtml = string.Empty;
StringBuilder oHtml = new StringBuilder();
while(i != iFullColCount)
{
if(i == 0)
{
oHtml.Append("<th scope='col'>All</th>");
}
else
{
oHtml.Append("<th scope='col'>Alt. ");
oHtml.Append((i - 1));
oHtml.Append("</th>");
}
i++;
}
sHtml = oHtml.ToString();
oHtml = null;
return sHtml;
}
public string writeNames(string description, string fullColCount)
{
string sHtml = string.Empty;
if (description != string.Empty && description != null)
{
string[] arrNames = description.Split(DELIMITER_NAME);
if (arrNames != null)
{
StringBuilder oHtml = new StringBuilder();
string sDisplayName = string.Empty;
string sNewFileCountExtension = string.Empty;
string sOldFileCountExtension = string.Empty;
int iCount = arrNames.Length;
int i = 0;
int iCurrentColCount = 0;
int j = 0;
while(i != iCount)
{
//limited to 30 chars for displaying
string sName = arrNames[i];
DisplayComparisons.GetValues(sName, out sDisplayName, out sNewFileCountExtension);
int iNewFileCountExtension = (isNumber(sNewFileCountExtension))? Convert.ToInt32(sNewFileCountExtension) : 0;
//keep indentically numbered files (mult tp names) out of colcount and don't display
if (sNewFileCountExtension.Equals(sOldFileCountExtension) == false)
{
//insert placeholder cols, so names line up with correct column
for(j = iCurrentColCount; j < iNewFileCountExtension; j++)
{
oHtml.Append("<td>");
oHtml.Append("</td>");
iCurrentColCount += 1;
}
AppendName(sName, ref oHtml);
iCurrentColCount += 1;
}
sOldFileCountExtension = sNewFileCountExtension;
i++;
}
sHtml = oHtml.ToString();
oHtml = null;
}
arrNames = null;
}
return sHtml;
}
private void AppendName(string name, ref StringBuilder html)
{
int iLength = name.Length;
if (iLength > 30) iLength = 30;
html.Append("<td>");
html.Append(name.Substring(0, iLength));
html.Append("</td>");
}
//temporary array to hold all values
public void initValues(string fullColCount)
{
int iFullColCount = (isNumber(fullColCount))? Convert.ToInt32(fullColCount) : 0;
int i = 0;
//always init the arrays
arrValues = new string[iFullColCount];
while(i != (iFullColCount - 1))
{
arrValues[i] = "empty";
i++;
}
}
//temporary array to hold all values for NOP
public void initValuesNOP(string fullColCount)
{
int iFullColCount = (isNumber(fullColCount))? Convert.ToInt32(fullColCount) : 0;
int j = 0;
arrNOPs = new string[iFullColCount];
while(j != (iFullColCount - 1))
{
arrNOPs[j] = "empty";
j++;
}
}
//print the net operating profits values
public void printNOP(string attName, string attValue)
{
string sPlot = string.Empty;
int iPlot = 0;
if(attName.Substring(0, attName.LastIndexOf("_") + 1) == "TAMR_")
{
int iPlotStart = attName.LastIndexOf("_");
int iLength = attName.Length;
if (iLength > (iPlotStart + 2))
{
//_10
sPlot = attName.Substring(iPlotStart + 1, 2);
}
else
{
//_1
sPlot = attName.Substring(iPlotStart + 1, 1);
}
//keep MEAN and STDDEV suffixes out
if (isNumber(sPlot))
{
iPlot = Convert.ToInt32(sPlot);
arrNOPs[iPlot] = attValue;
}
}
if(attName.Substring(0,attName.LastIndexOf("_") + 1) == "TAMOC_")
{
int iPlotStart = attName.LastIndexOf("_");
int iLength = attName.Length;
if (iLength > (iPlotStart + 2))
{
//_10
sPlot = attName.Substring(iPlotStart + 1, 2);
}
else
{
//_1
sPlot = attName.Substring(iPlotStart + 1, 1);
}
if (isNumber(sPlot))
{
iPlot = Convert.ToInt32(sPlot);
double dbAttValue = (isNumber(attValue))? Convert.ToDouble(attValue) : 0;
double dbPlotNOP = (isNumber(arrNOPs[iPlot]))? Convert.ToDouble(arrNOPs[iPlot]) : 0;
double dbNOP = dbPlotNOP - dbAttValue;
arrValues[iPlot] = dbNOP.ToString("f2");
//stateful array used with remaining print nets
arrNOPs[iPlot] = dbNOP.ToString("f2");
}
}
}
//print the net profits values
public void printNProfits(string attName, string attValue)
{
string sPlot = string.Empty;
int iPlot = 0;
if(attName.Substring(0,attName.LastIndexOf("_") + 1) == "TAMAOH_")
{
int iPlotStart = attName.LastIndexOf("_");
int iLength = attName.Length;
if (iLength > (iPlotStart + 2))
{
//_10
sPlot = attName.Substring(iPlotStart + 1, 2);
}
else
{
//_1
sPlot = attName.Substring(iPlotStart + 1, 1);
}
if (isNumber(sPlot))
{
iPlot = Convert.ToInt32(sPlot);
double dbAttValue = (isNumber(attValue))? Convert.ToDouble(attValue) : 0;
double dbPlotNOP = (isNumber(arrNOPs[iPlot]) )? Convert.ToDouble(arrNOPs[iPlot]) : 0;
double dbNOP = dbPlotNOP - dbAttValue;
arrValues[iPlot] = dbNOP.ToString("f2");
//stateful array used with remaining print nets
arrNOPs[iPlot] = dbNOP.ToString("f2");
}
}
}
//print the nets including cash capital costs
public void printNCAP(string attName, string attValue)
{
string sPlot = string.Empty;
int iPlot = 0;
if(attName.Substring(0,attName.LastIndexOf("_") + 1) == "TAMCAP_")
{
int iPlotStart = attName.LastIndexOf("_");
int iLength = attName.Length;
if (iLength > (iPlotStart + 2))
{
//_10
sPlot = attName.Substring(iPlotStart + 1, 2);
}
else
{
//_1
sPlot = attName.Substring(iPlotStart + 1, 1);
}
if (isNumber(sPlot))
{
iPlot = Convert.ToInt32(sPlot);
double dbAttValue = (isNumber(attValue))? Convert.ToDouble(attValue) : 0;
double dbPlotNOP = (isNumber(arrNOPs[iPlot]) )? Convert.ToDouble(arrNOPs[iPlot]) : 0;
double dbNOP = dbPlotNOP - dbAttValue;
arrValues[iPlot] = dbNOP.ToString("f2");
}
}
}
//print the net profits values
public void printValue(string attTest, string attName, string attValue)
{
string sPlot = string.Empty;
int iPlot = 0;
int iPlotStart = attName.LastIndexOf("_");
if(attName.Substring(0, iPlotStart + 1) == attTest)
{
int iLength = attName.Length;
if (iLength > (iPlotStart + 2))
{
//_10; 99 comparison limitation
sPlot = attName.Substring(iPlotStart + 1, 2);
}
else
{
//_1
sPlot = attName.Substring(iPlotStart + 1, 1);
}
if (isNumber(sPlot))
{
iPlot = Convert.ToInt32(sPlot);
arrValues[iPlot] = attValue;
}
}
}
//print all values
public string doPrintValues(string fullColCount)
{
int iFullColCount = (isNumber(fullColCount))? Convert.ToInt32(fullColCount) : 0;
//write a new table column with it's value
int i = 0;
string sHtml = string.Empty;
StringBuilder oHtml = new StringBuilder();
while(i != (iFullColCount - 1))
{
oHtml.Append("<td>");
if(arrValues[i] == "empty")
{
oHtml.Append("0.00");
}
else
{
oHtml.Append(arrValues[i]);
}
oHtml.Append("</td>");
i++;
}
sHtml = oHtml.ToString();
oHtml = null;
//reset the arrays
arrValues = null;
arrNOPs = null;
return sHtml;
}
private bool isNumber(string test)
{
bool bIsNumber = false;
if (test != string.Empty && test != null)
{
if (test.StartsWith("0"))
{
bIsNumber = true;
return bIsNumber;
}
else if (test.StartsWith("1"))
{
bIsNumber = true;
return bIsNumber;
}
else if (test.StartsWith("2"))
{
bIsNumber = true;
return bIsNumber;
}
else if (test.StartsWith("3"))
{
bIsNumber = true;
return bIsNumber;
}
else if (test.StartsWith("4"))
{
bIsNumber = true;
return bIsNumber;
}
else if (test.StartsWith("5"))
{
bIsNumber = true;
return bIsNumber;
}
else if (test.StartsWith("6"))
{
bIsNumber = true;
return bIsNumber;
}
else if (test.StartsWith("7"))
{
bIsNumber = true;
return bIsNumber;
}
else if (test.StartsWith("8"))
{
bIsNumber = true;
return bIsNumber;
}
else if (test.StartsWith("9"))
{
bIsNumber = true;
return bIsNumber;
}
else if (test.StartsWith("-"))
{
//negative number
bIsNumber = true;
return bIsNumber;
}
}
return bIsNumber;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.