content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
#if UNITY_EDITOR
using UnityEngine;
using UnityEditor;
using System.Reflection;
using System.Linq;
namespace ParadoxNotion.Design
{
///Will show value only if another field is equal to target
public class ShowIfDrawer : AttributeDrawer<ShowIfAttribute>
{
public override object OnGUI(GUIContent content, object instance) {
var targetField = context.GetType().GetField(attribute.fieldName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
if ( targetField != null ) {
var fieldValue = (int)System.Convert.ChangeType(targetField.GetValue(context), typeof(int));
if ( fieldValue != attribute.checkValue ) {
return instance; //return instance without any editor (thus hide it)
}
}
return MoveNextDrawer();
}
}
///Will show in red if value is null or empty
public class RequiredFieldDrawer : AttributeDrawer<RequiredFieldAttribute>
{
public override object OnGUI(GUIContent content, object instance) {
var isNull = instance == null || instance.Equals(null) || ( ( instance is string ) && string.IsNullOrEmpty((string)instance) );
GUI.backgroundColor = isNull ? Colors.lightRed : Color.white;
instance = MoveNextDrawer();
GUI.backgroundColor = Color.white;
return instance;
}
}
///Will invoke a callback method when value change
public class CallbackDrawer : AttributeDrawer<CallbackAttribute>
{
public override object OnGUI(GUIContent content, object instance) {
var newValue = MoveNextDrawer();
if ( !Equals(newValue, instance) ) {
var method = context.GetType().RTGetMethod(attribute.methodName);
if ( method != null ) {
fieldInfo.SetValue(context, newValue); //manual set field before invoke
method.Invoke(context, null);
}
}
return newValue;
}
}
///----------------------------------------------------------------------------------------------
///Will clamp float or int value to min
public class MinValueDrawer : AttributeDrawer<MinValueAttribute>
{
public override object OnGUI(GUIContent content, object instance) {
instance = MoveNextDrawer();
if ( fieldInfo.FieldType == typeof(float) ) {
instance = Mathf.Max((float)instance, (float)attribute.min);
}
if ( fieldInfo.FieldType == typeof(int) ) {
instance = Mathf.Max((int)instance, (int)attribute.min);
}
return instance;
}
}
///----------------------------------------------------------------------------------------------
///Will make float, int or string field show in a delayed control
public class DelayedFieldDrawer : AttributeDrawer<DelayedFieldAttribute>
{
public override object OnGUI(GUIContent content, object instance) {
if ( fieldInfo.FieldType == typeof(float) ) {
return EditorGUILayout.DelayedFloatField(content, (float)instance);
}
if ( fieldInfo.FieldType == typeof(int) ) {
return EditorGUILayout.DelayedIntField(content, (int)instance);
}
if ( fieldInfo.FieldType == typeof(string) ) {
return EditorGUILayout.DelayedTextField(content, (string)instance);
}
return MoveNextDrawer();
}
}
///Will force to use ObjectField editor, usefull for interfaces
public class ForceObjectFieldDrawer : AttributeDrawer<ForceObjectFieldAttribute>
{
public override object OnGUI(GUIContent content, object instance) {
if ( typeof(UnityEngine.Object).IsAssignableFrom(fieldInfo.FieldType) || fieldInfo.FieldType.IsInterface ) {
return EditorGUILayout.ObjectField(content, instance as UnityEngine.Object, fieldInfo.FieldType, true);
}
return MoveNextDrawer();
}
}
///Will restrict selection on provided values
public class PopupFieldDrawer : AttributeDrawer<PopupFieldAttribute>
{
public override object OnGUI(GUIContent content, object instance) {
if ( attribute.options != null ) {
return EditorUtils.Popup<object>(content, instance, attribute.options.ToList());
}
return MoveNextDrawer();
}
}
///Will show a slider for int and float values
public class SliderFieldDrawer : AttributeDrawer<SliderFieldAttribute>
{
public override object OnGUI(GUIContent content, object instance) {
if ( fieldInfo.FieldType == typeof(float) ) {
return EditorGUILayout.Slider(content, (float)instance, (float)attribute.min, (float)attribute.max);
}
if ( fieldInfo.FieldType == typeof(int) ) {
return EditorGUILayout.IntSlider(content, (int)instance, (int)attribute.min, (int)attribute.max);
}
return MoveNextDrawer();
}
}
///Will show a layer selection for int values
public class LayerFieldDrawer : AttributeDrawer<LayerFieldAttribute>
{
public override object OnGUI(GUIContent content, object instance) {
if ( fieldInfo.FieldType == typeof(int) ) {
return EditorGUILayout.LayerField(content, (int)instance);
}
return MoveNextDrawer();
}
}
///Will show a Tag selection for string values
public class TagFieldDrawer : AttributeDrawer<TagFieldAttribute>
{
public override object OnGUI(GUIContent content, object instance) {
if ( fieldInfo.FieldType == typeof(string) ) {
return EditorGUILayout.TagField(content, (string)instance);
}
return MoveNextDrawer();
}
}
///Will show a text area for string values
public class TextAreaDrawer : AttributeDrawer<TextAreaFieldAttribute>
{
private static GUIStyle areaStyle;
static TextAreaDrawer() {
areaStyle = new GUIStyle(GUI.skin.GetStyle("TextArea"));
areaStyle.wordWrap = true;
}
public override object OnGUI(GUIContent content, object instance) {
if ( fieldInfo.FieldType == typeof(string) ) {
GUILayout.Label(content);
return EditorGUILayout.TextArea((string)instance, areaStyle, GUILayout.Height(attribute.numberOfLines * areaStyle.lineHeight));
}
return MoveNextDrawer();
}
}
///Will show a button above field
public class ShowButtonDrawer : AttributeDrawer<ShowButtonAttribute>
{
public override object OnGUI(GUIContent content, object instance) {
if ( !string.IsNullOrEmpty(attribute.methodnameCallback) ) {
var method = context.GetType().RTGetMethod(attribute.methodnameCallback);
if ( method != null && method.GetParameters().Length == 0 ) {
if ( GUILayout.Button(attribute.buttonTitle) ) {
method.Invoke(context, null);
}
} else {
GUILayout.Label(string.Format("Can't find method '{0}'.", attribute.methodnameCallback));
}
}
return MoveNextDrawer();
}
}
}
#endif | 41.798913 | 149 | 0.584189 | [
"MIT"
] | lihaochen910/UnityGoapAIDemo | Assets/Plugins/ParadoxNotion/CanvasCore/Common/Design/PartialEditor/AttributeDrawers.cs | 7,693 | C# |
// Copyright (c) All contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#if !UNITY_2018_3_OR_NEWER
using System;
using System.Buffers;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using MessagePack.Internal;
namespace MessagePack.Formatters
{
/// <summary>
/// For `object` field that holds derived from `object` value, ex: var arr = new object[] { 1, "a", new Model() };.
/// </summary>
public sealed class TypelessFormatter : IMessagePackFormatter<object>
{
private delegate void SerializeMethod(object dynamicContractlessFormatter, ref MessagePackWriter writer, object value, MessagePackSerializerOptions options);
private delegate object DeserializeMethod(object dynamicContractlessFormatter, ref MessagePackReader reader, MessagePackSerializerOptions options);
/// <summary>
/// The singleton instance that can be used.
/// </summary>
public static readonly IMessagePackFormatter<object> Instance = new TypelessFormatter();
private readonly ThreadsafeTypeKeyHashTable<SerializeMethod> serializers = new ThreadsafeTypeKeyHashTable<SerializeMethod>();
private readonly ThreadsafeTypeKeyHashTable<DeserializeMethod> deserializers = new ThreadsafeTypeKeyHashTable<DeserializeMethod>();
private readonly ThreadsafeTypeKeyHashTable<byte[]> fullTypeNameCache = new ThreadsafeTypeKeyHashTable<byte[]>();
private readonly ThreadsafeTypeKeyHashTable<byte[]> shortenedTypeNameCache = new ThreadsafeTypeKeyHashTable<byte[]>();
private readonly AsymmetricKeyHashTable<byte[], ArraySegment<byte>, Type> typeCache = new AsymmetricKeyHashTable<byte[], ArraySegment<byte>, Type>(new StringArraySegmentByteAscymmetricEqualityComparer());
private static readonly HashSet<Type> UseBuiltinTypes = new HashSet<Type>
{
typeof(Boolean),
////typeof(Char),
typeof(SByte),
typeof(Byte),
typeof(Int16),
typeof(UInt16),
typeof(Int32),
typeof(UInt32),
typeof(Int64),
typeof(UInt64),
typeof(Single),
typeof(Double),
typeof(string),
typeof(byte[]),
// array should save their types.
////typeof(Boolean[]),
////typeof(Char[]),
////typeof(SByte[]),
////typeof(Int16[]),
////typeof(UInt16[]),
////typeof(Int32[]),
////typeof(UInt32[]),
////typeof(Int64[]),
////typeof(UInt64[]),
////typeof(Single[]),
////typeof(Double[]),
////typeof(string[]),
typeof(Boolean?),
////typeof(Char?),
typeof(SByte?),
typeof(Byte?),
typeof(Int16?),
typeof(UInt16?),
typeof(Int32?),
typeof(UInt32?),
typeof(Int64?),
typeof(UInt64?),
typeof(Single?),
typeof(Double?),
};
//ForceSizePrimitiveObjectResolver.Instance,
//ContractlessStandardResolverAllowPrivate.Instance);
// mscorlib or System.Private.CoreLib
private static readonly bool IsMscorlib = typeof(int).AssemblyQualifiedName.Contains("mscorlib");
private TypelessFormatter()
{
this.serializers.TryAdd(typeof(object), _ => (object p1, ref MessagePackWriter p2, object p3, MessagePackSerializerOptions p4) => { });
this.deserializers.TryAdd(typeof(object), _ => (object p1, ref MessagePackReader p2, MessagePackSerializerOptions p3) => new object());
}
private string BuildTypeName(Type type, MessagePackSerializerOptions options)
{
if (options.OmitAssemblyVersion)
{
string full = type.AssemblyQualifiedName;
var shortened = MessagePackSerializerOptions.AssemblyNameVersionSelectorRegex.Replace(full, string.Empty);
if (Type.GetType(shortened, false) == null)
{
// if type cannot be found with shortened name - use full name
shortened = full;
}
return shortened;
}
else
{
return type.AssemblyQualifiedName;
}
}
public void Serialize(ref MessagePackWriter writer, object value, MessagePackSerializerOptions options)
{
if (value == null)
{
writer.WriteNil();
return;
}
Type type = value.GetType();
byte[] typeName;
var typeNameCache = options.OmitAssemblyVersion ? this.shortenedTypeNameCache : this.fullTypeNameCache;
if (!typeNameCache.TryGetValue(type, out typeName))
{
TypeInfo ti = type.GetTypeInfo();
if (ti.IsAnonymous() || UseBuiltinTypes.Contains(type))
{
typeName = null;
}
else
{
typeName = StringEncoding.UTF8.GetBytes(this.BuildTypeName(type, options));
}
typeNameCache.TryAdd(type, typeName);
}
if (typeName == null)
{
DynamicObjectTypeFallbackFormatter.Instance.Serialize(ref writer, value, options);
return;
}
var formatter = options.Resolver.GetFormatterDynamicWithVerify(type);
// don't use GetOrAdd for avoid closure capture.
if (!this.serializers.TryGetValue(type, out SerializeMethod serializeMethod))
{
// double check locking...
lock (this.serializers)
{
if (!this.serializers.TryGetValue(type, out serializeMethod))
{
TypeInfo ti = type.GetTypeInfo();
Type formatterType = typeof(IMessagePackFormatter<>).MakeGenericType(type);
ParameterExpression param0 = Expression.Parameter(typeof(object), "formatter");
ParameterExpression param1 = Expression.Parameter(typeof(MessagePackWriter).MakeByRefType(), "writer");
ParameterExpression param2 = Expression.Parameter(typeof(object), "value");
ParameterExpression param3 = Expression.Parameter(typeof(MessagePackSerializerOptions), "options");
MethodInfo serializeMethodInfo = formatterType.GetRuntimeMethod("Serialize", new[] { typeof(MessagePackWriter).MakeByRefType(), type, typeof(MessagePackSerializerOptions) });
MethodCallExpression body = Expression.Call(
Expression.Convert(param0, formatterType),
serializeMethodInfo,
param1,
ti.IsValueType ? Expression.Unbox(param2, type) : Expression.Convert(param2, type),
param3);
serializeMethod = Expression.Lambda<SerializeMethod>(body, param0, param1, param2, param3).Compile();
this.serializers.TryAdd(type, serializeMethod);
}
}
}
// mark will be written at the end, when size is known
using (var scratchRental = SequencePool.Shared.Rent())
{
MessagePackWriter scratchWriter = writer.Clone(scratchRental.Value);
scratchWriter.WriteString(typeName);
serializeMethod(formatter, ref scratchWriter, value, options);
scratchWriter.Flush();
// mark as extension with code 100
writer.WriteExtensionFormat(new ExtensionResult((sbyte)ThisLibraryExtensionTypeCodes.TypelessFormatter, scratchRental.Value));
}
}
public object Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options)
{
if (reader.TryReadNil())
{
return null;
}
if (reader.NextMessagePackType == MessagePackType.Extension)
{
MessagePackReader peekReader = reader.CreatePeekReader();
ExtensionHeader ext = peekReader.ReadExtensionFormatHeader();
if (ext.TypeCode == ThisLibraryExtensionTypeCodes.TypelessFormatter)
{
reader = peekReader; // commit the experimental read made earlier.
// it has type name serialized
ReadOnlySequence<byte> typeName = reader.ReadStringSequence().Value;
ArraySegment<byte> typeNameArraySegment;
byte[] rented = null;
if (!typeName.IsSingleSegment || !MemoryMarshal.TryGetArray(typeName.First, out typeNameArraySegment))
{
rented = ArrayPool<byte>.Shared.Rent((int)typeName.Length);
typeName.CopyTo(rented);
typeNameArraySegment = new ArraySegment<byte>(rented, 0, (int)typeName.Length);
}
var result = this.DeserializeByTypeName(typeNameArraySegment, ref reader, options);
if (rented != null)
{
ArrayPool<byte>.Shared.Return(rented);
}
return result;
}
}
// fallback
return DynamicObjectTypeFallbackFormatter.Instance.Deserialize(ref reader, options);
}
/// <summary>
/// Does not support deserializing of anonymous types
/// Type should be covered by preceeding resolvers in complex/standard resolver.
/// </summary>
private object DeserializeByTypeName(ArraySegment<byte> typeName, ref MessagePackReader byteSequence, MessagePackSerializerOptions options)
{
// try get type with assembly name, throw if not found
Type type;
if (!this.typeCache.TryGetValue(typeName, out type))
{
var buffer = new byte[typeName.Count];
Buffer.BlockCopy(typeName.Array, typeName.Offset, buffer, 0, buffer.Length);
var str = StringEncoding.UTF8.GetString(buffer);
type = options.LoadType(str);
if (type == null)
{
if (IsMscorlib && str.Contains("System.Private.CoreLib"))
{
str = str.Replace("System.Private.CoreLib", "mscorlib");
type = Type.GetType(str, true); // throw
}
else if (!IsMscorlib && str.Contains("mscorlib"))
{
str = str.Replace("mscorlib", "System.Private.CoreLib");
type = Type.GetType(str, true); // throw
}
else
{
type = Type.GetType(str, true); // re-throw
}
}
this.typeCache.TryAdd(buffer, type);
}
options.ThrowIfDeserializingTypeIsDisallowed(type);
var formatter = options.Resolver.GetFormatterDynamicWithVerify(type);
if (!this.deserializers.TryGetValue(type, out DeserializeMethod deserializeMethod))
{
lock (this.deserializers)
{
if (!this.deserializers.TryGetValue(type, out deserializeMethod))
{
TypeInfo ti = type.GetTypeInfo();
Type formatterType = typeof(IMessagePackFormatter<>).MakeGenericType(type);
ParameterExpression param0 = Expression.Parameter(typeof(object), "formatter");
ParameterExpression param1 = Expression.Parameter(typeof(MessagePackReader).MakeByRefType(), "reader");
ParameterExpression param2 = Expression.Parameter(typeof(MessagePackSerializerOptions), "options");
MethodInfo deserializeMethodInfo = formatterType.GetRuntimeMethod("Deserialize", new[] { typeof(MessagePackReader).MakeByRefType(), typeof(MessagePackSerializerOptions) });
MethodCallExpression deserialize = Expression.Call(
Expression.Convert(param0, formatterType),
deserializeMethodInfo,
param1,
param2);
Expression body = deserialize;
if (ti.IsValueType)
{
body = Expression.Convert(deserialize, typeof(object));
}
deserializeMethod = Expression.Lambda<DeserializeMethod>(body, param0, param1, param2).Compile();
this.deserializers.TryAdd(type, deserializeMethod);
}
}
}
return deserializeMethod(formatter, ref byteSequence, options);
}
}
}
#endif
| 42.876972 | 212 | 0.56548 | [
"BSD-2-Clause"
] | ChenLongxi666/MessagePack-CSharp | src/MessagePack.UnityClient/Assets/Scripts/MessagePack/Formatters/TypelessFormatter.cs | 13,594 | C# |
using Koralium.SqlParser.Expressions;
using Koralium.SqlParser.Literals;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Text;
namespace Koralium.SqlParser.Tests
{
public class ExpressionEqualsTests
{
[Test]
public void TestBooleanScalarExpressionEquals()
{
BooleanScalarExpression left = new BooleanScalarExpression()
{
ScalarExpression = new ColumnReference() { Identifiers = new List<string>() { "test" } }
};
BooleanScalarExpression leftClone = new BooleanScalarExpression()
{
ScalarExpression = new ColumnReference() { Identifiers = new List<string>() { "test" } }
};
BooleanScalarExpression right = new BooleanScalarExpression()
{
ScalarExpression = new ColumnReference() { Identifiers = new List<string>() { "t2" } }
};
//Equals
Assert.IsTrue(Equals(left, leftClone));
Assert.IsFalse(Equals(left, null));
Assert.IsFalse(Equals(left, right));
Assert.IsFalse(Equals(left, "other type"));
//Hash code
Assert.AreEqual(left.GetHashCode(), leftClone.GetHashCode());
Assert.AreNotEqual(left.GetHashCode(), right.GetHashCode());
}
[Test]
public void TestLambdaExpressionEquals()
{
LambdaExpression first = new LambdaExpression()
{
Expression = new BooleanLiteral() { Value = true },
Parameters = new List<string>() { "p1" }
};
LambdaExpression firstClone = new LambdaExpression()
{
Expression = new BooleanLiteral() { Value = true },
Parameters = new List<string>() { "p1" }
};
LambdaExpression second = new LambdaExpression()
{
Expression = new BooleanLiteral() { Value = false },
Parameters = new List<string>() { "p1" }
};
LambdaExpression third = new LambdaExpression()
{
Expression = new BooleanLiteral() { Value = true },
Parameters = new List<string>() { "p2" }
};
//Equals
Assert.IsTrue(Equals(first, firstClone));
Assert.IsFalse(Equals(first, null));
Assert.IsFalse(Equals(first, second));
Assert.IsFalse(Equals(first, third));
Assert.IsFalse(Equals(first, "other type"));
//Hash code
Assert.AreEqual(first.GetHashCode(), firstClone.GetHashCode());
Assert.AreNotEqual(first.GetHashCode(), second.GetHashCode());
Assert.AreNotEqual(first.GetHashCode(), third.GetHashCode());
}
[Test]
public void TestFunctionCallEquals()
{
FunctionCall first = new FunctionCall()
{
FunctionName = "test",
Parameters = new List<SqlExpression>()
{
new ColumnReference(){ Identifiers = new List<string>() {"c1" }}
},
Wildcard = false
};
FunctionCall firstClone = new FunctionCall()
{
FunctionName = "test",
Parameters = new List<SqlExpression>()
{
new ColumnReference(){ Identifiers = new List<string>() {"c1" }}
},
Wildcard = false
};
FunctionCall second = new FunctionCall()
{
FunctionName = "test2",
Parameters = new List<SqlExpression>()
{
new ColumnReference(){ Identifiers = new List<string>() {"c1" }}
},
Wildcard = false
};
FunctionCall third = new FunctionCall()
{
FunctionName = "test",
Parameters = new List<SqlExpression>()
{
new ColumnReference(){ Identifiers = new List<string>() {"c2" }}
},
Wildcard = false
};
FunctionCall fourth = new FunctionCall()
{
FunctionName = "test",
Parameters = new List<SqlExpression>()
{
new ColumnReference(){ Identifiers = new List<string>() {"c1" }}
},
Wildcard = true
};
//Equals
Assert.IsTrue(Equals(first, firstClone));
Assert.IsFalse(Equals(first, null));
Assert.IsFalse(Equals(first, second));
Assert.IsFalse(Equals(first, third));
Assert.IsFalse(Equals(first, fourth));
Assert.IsFalse(Equals(first, "other type"));
//Hash code
Assert.AreEqual(first.GetHashCode(), firstClone.GetHashCode());
Assert.AreNotEqual(first.GetHashCode(), second.GetHashCode());
Assert.AreNotEqual(first.GetHashCode(), third.GetHashCode());
Assert.AreNotEqual(first.GetHashCode(), fourth.GetHashCode());
}
[Test]
public void TestColumnReferenceEquals()
{
ColumnReference first = new ColumnReference()
{
Identifiers = new List<string>() { "test" }
};
ColumnReference firstClone = new ColumnReference()
{
Identifiers = new List<string>() { "test" }
};
ColumnReference second = new ColumnReference()
{
Identifiers = new List<string>() { "test2" }
};
//Equals
Assert.IsTrue(Equals(first, firstClone));
Assert.IsFalse(Equals(first, null));
Assert.IsFalse(Equals(first, "test"));
Assert.IsFalse(Equals(first, second));
//Hash code
Assert.AreEqual(first.GetHashCode(), firstClone.GetHashCode());
Assert.AreNotEqual(first.GetHashCode(), second.GetHashCode());
}
[Test]
public void TestBetweenExpressionEquals()
{
BetweenExpression first = new BetweenExpression()
{
Expression = new ColumnReference { Identifiers = new List<string>() { "c1" } },
From = new IntegerLiteral() { Value = 3 },
To = new IntegerLiteral() { Value = 17 }
};
BetweenExpression firstClone = new BetweenExpression()
{
Expression = new ColumnReference { Identifiers = new List<string>() { "c1" } },
From = new IntegerLiteral() { Value = 3 },
To = new IntegerLiteral() { Value = 17 }
};
BetweenExpression second = new BetweenExpression()
{
Expression = new ColumnReference { Identifiers = new List<string>() { "c2" } },
From = new IntegerLiteral() { Value = 3 },
To = new IntegerLiteral() { Value = 17 }
};
BetweenExpression third = new BetweenExpression()
{
Expression = new ColumnReference { Identifiers = new List<string>() { "c1" } },
From = new IntegerLiteral() { Value = 4 },
To = new IntegerLiteral() { Value = 17 }
};
BetweenExpression fourth = new BetweenExpression()
{
Expression = new ColumnReference { Identifiers = new List<string>() { "c1" } },
From = new IntegerLiteral() { Value = 3 },
To = new IntegerLiteral() { Value = 19 }
};
//Equals
Assert.IsTrue(Equals(first, firstClone));
Assert.IsFalse(Equals(first, null));
Assert.IsFalse(Equals(first, second));
Assert.IsFalse(Equals(first, third));
Assert.IsFalse(Equals(first, fourth));
Assert.IsFalse(Equals(first, "other type"));
//Hash code
Assert.AreEqual(first.GetHashCode(), firstClone.GetHashCode());
Assert.AreNotEqual(first.GetHashCode(), second.GetHashCode());
Assert.AreNotEqual(first.GetHashCode(), third.GetHashCode());
Assert.AreNotEqual(first.GetHashCode(), fourth.GetHashCode());
}
[Test]
public void TestBinaryExpressionEquals()
{
BinaryExpression first = new BinaryExpression()
{
Type = BinaryType.Add,
Left = new ColumnReference() { Identifiers = new List<string>() { "c1" } },
Right = new IntegerLiteral() { Value = 3 }
};
BinaryExpression firstClone = new BinaryExpression()
{
Type = BinaryType.Add,
Left = new ColumnReference() { Identifiers = new List<string>() { "c1" } },
Right = new IntegerLiteral() { Value = 3 }
};
BinaryExpression second = new BinaryExpression()
{
Type = BinaryType.Divide,
Left = new ColumnReference() { Identifiers = new List<string>() { "c1" } },
Right = new IntegerLiteral() { Value = 3 }
};
BinaryExpression third = new BinaryExpression()
{
Type = BinaryType.Add,
Left = new ColumnReference() { Identifiers = new List<string>() { "c2" } },
Right = new IntegerLiteral() { Value = 3 }
};
BinaryExpression fourth = new BinaryExpression()
{
Type = BinaryType.Add,
Left = new ColumnReference() { Identifiers = new List<string>() { "c1" } },
Right = new IntegerLiteral() { Value = 17 }
};
//Equals
Assert.IsTrue(Equals(first, firstClone));
Assert.IsFalse(Equals(first, null));
Assert.IsFalse(Equals(first, second));
Assert.IsFalse(Equals(first, third));
Assert.IsFalse(Equals(first, fourth));
Assert.IsFalse(Equals(first, "other type"));
//Hash code
Assert.AreEqual(first.GetHashCode(), firstClone.GetHashCode());
Assert.AreNotEqual(first.GetHashCode(), second.GetHashCode());
Assert.AreNotEqual(first.GetHashCode(), third.GetHashCode());
Assert.AreNotEqual(first.GetHashCode(), fourth.GetHashCode());
}
[Test]
public void TestBooleanBinaryExpressionEquals()
{
BooleanBinaryExpression first = new BooleanBinaryExpression()
{
Type = BooleanBinaryType.AND,
Left = new BooleanComparisonExpression()
{
Type = BooleanComparisonType.Equals,
Left = new ColumnReference() { Identifiers = new List<string>() { "c1" } },
Right = new IntegerLiteral() { Value = 3 }
},
Right = new BooleanComparisonExpression()
{
Type = BooleanComparisonType.GreaterThan,
Left = new ColumnReference() { Identifiers = new List<string>() { "c2" } },
Right = new IntegerLiteral() { Value = 17 }
}
};
BooleanBinaryExpression firstClone = new BooleanBinaryExpression()
{
Type = BooleanBinaryType.AND,
Left = new BooleanComparisonExpression()
{
Type = BooleanComparisonType.Equals,
Left = new ColumnReference() { Identifiers = new List<string>() { "c1" } },
Right = new IntegerLiteral() { Value = 3 }
},
Right = new BooleanComparisonExpression()
{
Type = BooleanComparisonType.GreaterThan,
Left = new ColumnReference() { Identifiers = new List<string>() { "c2" } },
Right = new IntegerLiteral() { Value = 17 }
}
};
BooleanBinaryExpression second = new BooleanBinaryExpression()
{
Type = BooleanBinaryType.OR,
Left = new BooleanComparisonExpression()
{
Type = BooleanComparisonType.Equals,
Left = new ColumnReference() { Identifiers = new List<string>() { "c1" } },
Right = new IntegerLiteral() { Value = 3 }
},
Right = new BooleanComparisonExpression()
{
Type = BooleanComparisonType.GreaterThan,
Left = new ColumnReference() { Identifiers = new List<string>() { "c2" } },
Right = new IntegerLiteral() { Value = 17 }
}
};
BooleanBinaryExpression third = new BooleanBinaryExpression()
{
Type = BooleanBinaryType.AND,
Left = new BooleanComparisonExpression()
{
Type = BooleanComparisonType.Equals,
Left = new ColumnReference() { Identifiers = new List<string>() { "c1" } },
Right = new IntegerLiteral() { Value = 4 }
},
Right = new BooleanComparisonExpression()
{
Type = BooleanComparisonType.GreaterThan,
Left = new ColumnReference() { Identifiers = new List<string>() { "c2" } },
Right = new IntegerLiteral() { Value = 17 }
}
};
BooleanBinaryExpression fourth = new BooleanBinaryExpression()
{
Type = BooleanBinaryType.AND,
Left = new BooleanComparisonExpression()
{
Type = BooleanComparisonType.Equals,
Left = new ColumnReference() { Identifiers = new List<string>() { "c1" } },
Right = new IntegerLiteral() { Value = 3 }
},
Right = new BooleanComparisonExpression()
{
Type = BooleanComparisonType.GreaterThan,
Left = new ColumnReference() { Identifiers = new List<string>() { "c2" } },
Right = new IntegerLiteral() { Value = 18 }
}
};
//Equals
Assert.IsTrue(Equals(first, firstClone));
Assert.IsFalse(Equals(first, null));
Assert.IsFalse(Equals(first, second));
Assert.IsFalse(Equals(first, third));
Assert.IsFalse(Equals(first, fourth));
Assert.IsFalse(Equals(first, "other type"));
//Hash code
Assert.AreEqual(first.GetHashCode(), firstClone.GetHashCode());
Assert.AreNotEqual(first.GetHashCode(), second.GetHashCode());
Assert.AreNotEqual(first.GetHashCode(), third.GetHashCode());
Assert.AreNotEqual(first.GetHashCode(), fourth.GetHashCode());
}
[Test]
public void TestBooleanComparisonExpressionEquals()
{
BooleanComparisonExpression first = new BooleanComparisonExpression()
{
Type = BooleanComparisonType.Equals,
Left = new ColumnReference() { Identifiers = new List<string>() { "c1" } },
Right = new IntegerLiteral() { Value = 3 }
};
BooleanComparisonExpression firstClone = new BooleanComparisonExpression()
{
Type = BooleanComparisonType.Equals,
Left = new ColumnReference() { Identifiers = new List<string>() { "c1" } },
Right = new IntegerLiteral() { Value = 3 }
};
BooleanComparisonExpression second = new BooleanComparisonExpression()
{
Type = BooleanComparisonType.GreaterThan,
Left = new ColumnReference() { Identifiers = new List<string>() { "c1" } },
Right = new IntegerLiteral() { Value = 3 }
};
BooleanComparisonExpression third = new BooleanComparisonExpression()
{
Type = BooleanComparisonType.Equals,
Left = new ColumnReference() { Identifiers = new List<string>() { "c2" } },
Right = new IntegerLiteral() { Value = 3 }
};
BooleanComparisonExpression fourth = new BooleanComparisonExpression()
{
Type = BooleanComparisonType.Equals,
Left = new ColumnReference() { Identifiers = new List<string>() { "c1" } },
Right = new IntegerLiteral() { Value = 17 }
};
//Equals
Assert.IsTrue(Equals(first, firstClone));
Assert.IsFalse(Equals(first, null));
Assert.IsFalse(Equals(first, second));
Assert.IsFalse(Equals(first, third));
Assert.IsFalse(Equals(first, fourth));
Assert.IsFalse(Equals(first, "other type"));
//Hash code
Assert.AreEqual(first.GetHashCode(), firstClone.GetHashCode());
Assert.AreNotEqual(first.GetHashCode(), second.GetHashCode());
Assert.AreNotEqual(first.GetHashCode(), third.GetHashCode());
Assert.AreNotEqual(first.GetHashCode(), fourth.GetHashCode());
}
[Test]
public void TestBooleanIsNullExpressionEquals()
{
BooleanIsNullExpression first = new BooleanIsNullExpression()
{
IsNot = false,
ScalarExpression = new ColumnReference() { Identifiers = new List<string>() { "c1" } }
};
BooleanIsNullExpression firstClone = new BooleanIsNullExpression()
{
IsNot = false,
ScalarExpression = new ColumnReference() { Identifiers = new List<string>() { "c1" } }
};
BooleanIsNullExpression second = new BooleanIsNullExpression()
{
IsNot = true,
ScalarExpression = new ColumnReference() { Identifiers = new List<string>() { "c1" } }
};
BooleanIsNullExpression third = new BooleanIsNullExpression()
{
IsNot = false,
ScalarExpression = new ColumnReference() { Identifiers = new List<string>() { "c2" } }
};
//Equals
Assert.IsTrue(Equals(first, firstClone));
Assert.IsFalse(Equals(first, null));
Assert.IsFalse(Equals(first, second));
Assert.IsFalse(Equals(first, third));
Assert.IsFalse(Equals(first, "other type"));
//Hash code
Assert.AreEqual(first.GetHashCode(), firstClone.GetHashCode());
Assert.AreNotEqual(first.GetHashCode(), second.GetHashCode());
Assert.AreNotEqual(first.GetHashCode(), third.GetHashCode());
}
[Test]
public void TestCastExpressionEquals()
{
CastExpression first = new CastExpression()
{
ScalarExpression = new StringLiteral() { Value = "test" },
ToType = "t"
};
CastExpression firstClone = new CastExpression()
{
ScalarExpression = new StringLiteral() { Value = "test" },
ToType = "t"
};
CastExpression second = new CastExpression()
{
ScalarExpression = new StringLiteral() { Value = "test2" },
ToType = "t"
};
CastExpression third = new CastExpression()
{
ScalarExpression = new StringLiteral() { Value = "test" },
ToType = "t2"
};
//Equals
Assert.IsTrue(Equals(first, firstClone));
Assert.IsFalse(Equals(first, null));
Assert.IsFalse(Equals(first, second));
Assert.IsFalse(Equals(first, third));
Assert.IsFalse(Equals(first, "other type"));
//Hash code
Assert.AreEqual(first.GetHashCode(), firstClone.GetHashCode());
Assert.AreNotEqual(first.GetHashCode(), second.GetHashCode());
Assert.AreNotEqual(first.GetHashCode(), third.GetHashCode());
}
[Test]
public void TestInExpressionEquals()
{
InExpression first = new InExpression()
{
Expression = new ColumnReference() { Identifiers = new List<string>() { "c1" } },
Not = false,
Values = new List<ScalarExpression>()
{
new StringLiteral() { Value = "test" }
}
};
InExpression firstClone = new InExpression()
{
Expression = new ColumnReference() { Identifiers = new List<string>() { "c1" } },
Not = false,
Values = new List<ScalarExpression>()
{
new StringLiteral() { Value = "test" }
}
};
InExpression second = new InExpression()
{
Expression = new ColumnReference() { Identifiers = new List<string>() { "c2" } },
Not = false,
Values = new List<ScalarExpression>()
{
new StringLiteral() { Value = "test" }
}
};
InExpression third = new InExpression()
{
Expression = new ColumnReference() { Identifiers = new List<string>() { "c1" } },
Not = true,
Values = new List<ScalarExpression>()
{
new StringLiteral() { Value = "test" }
}
};
InExpression fourth = new InExpression()
{
Expression = new ColumnReference() { Identifiers = new List<string>() { "c1" } },
Not = false,
Values = new List<ScalarExpression>()
{
new StringLiteral() { Value = "test2" }
}
};
//Equals
Assert.IsTrue(Equals(first, firstClone));
Assert.IsFalse(Equals(first, null));
Assert.IsFalse(Equals(first, second));
Assert.IsFalse(Equals(first, third));
Assert.IsFalse(Equals(first, fourth));
Assert.IsFalse(Equals(first, "other type"));
//Hash code
Assert.AreEqual(first.GetHashCode(), firstClone.GetHashCode());
Assert.AreNotEqual(first.GetHashCode(), second.GetHashCode());
Assert.AreNotEqual(first.GetHashCode(), third.GetHashCode());
Assert.AreNotEqual(first.GetHashCode(), fourth.GetHashCode());
}
[Test]
public void TestLikeExpressionEquals()
{
LikeExpression first = new LikeExpression()
{
Left = new ColumnReference() { Identifiers = new List<string>() { "c1" } },
Right = new StringLiteral() { Value = "test" },
Not = false
};
LikeExpression firstClone = new LikeExpression()
{
Left = new ColumnReference() { Identifiers = new List<string>() { "c1" } },
Right = new StringLiteral() { Value = "test" },
Not = false
};
LikeExpression second = new LikeExpression()
{
Left = new ColumnReference() { Identifiers = new List<string>() { "c2" } },
Right = new StringLiteral() { Value = "test" },
Not = false
};
LikeExpression third = new LikeExpression()
{
Left = new ColumnReference() { Identifiers = new List<string>() { "c1" } },
Right = new StringLiteral() { Value = "test2" },
Not = false
};
LikeExpression fourth = new LikeExpression()
{
Left = new ColumnReference() { Identifiers = new List<string>() { "c1" } },
Right = new StringLiteral() { Value = "test" },
Not = true
};
//Equals
Assert.IsTrue(Equals(first, firstClone));
Assert.IsFalse(Equals(first, null));
Assert.IsFalse(Equals(first, second));
Assert.IsFalse(Equals(first, third));
Assert.IsFalse(Equals(first, fourth));
Assert.IsFalse(Equals(first, "other type"));
//Hash code
Assert.AreEqual(first.GetHashCode(), firstClone.GetHashCode());
Assert.AreNotEqual(first.GetHashCode(), second.GetHashCode());
Assert.AreNotEqual(first.GetHashCode(), third.GetHashCode());
Assert.AreNotEqual(first.GetHashCode(), fourth.GetHashCode());
}
[Test]
public void TestNotExpressionEquals()
{
NotExpression first = new NotExpression()
{
BooleanExpression = new BooleanScalarExpression() { ScalarExpression = new ColumnReference() { Identifiers = new List<string>() { "c1" } } }
};
NotExpression firstClone = new NotExpression()
{
BooleanExpression = new BooleanScalarExpression() { ScalarExpression = new ColumnReference() { Identifiers = new List<string>() { "c1" } } }
};
NotExpression second = new NotExpression()
{
BooleanExpression = new BooleanScalarExpression() { ScalarExpression = new ColumnReference() { Identifiers = new List<string>() { "c2" } } }
};
//Equals
Assert.IsTrue(Equals(first, firstClone));
Assert.IsFalse(Equals(first, null));
Assert.IsFalse(Equals(first, second));
Assert.IsFalse(Equals(first, "other type"));
//Hash code
Assert.AreEqual(first.GetHashCode(), firstClone.GetHashCode());
Assert.AreNotEqual(first.GetHashCode(), second.GetHashCode());
}
[Test]
public void TestSearchExpressionEquals()
{
SearchExpression first = new SearchExpression()
{
AllColumns = false,
Columns = new List<ColumnReference>() { new ColumnReference() { Identifiers = new List<string>() { "c1" } } },
Value = new StringLiteral() { Value = "test" }
};
SearchExpression firstClone = new SearchExpression()
{
AllColumns = false,
Columns = new List<ColumnReference>() { new ColumnReference() { Identifiers = new List<string>() { "c1" } } },
Value = new StringLiteral() { Value = "test" }
};
SearchExpression second = new SearchExpression()
{
AllColumns = true,
Columns = new List<ColumnReference>() { new ColumnReference() { Identifiers = new List<string>() { "c1" } } },
Value = new StringLiteral() { Value = "test" }
};
SearchExpression third = new SearchExpression()
{
AllColumns = false,
Columns = new List<ColumnReference>() { new ColumnReference() { Identifiers = new List<string>() { "c2" } } },
Value = new StringLiteral() { Value = "test" }
};
SearchExpression fourth = new SearchExpression()
{
AllColumns = false,
Columns = new List<ColumnReference>() { new ColumnReference() { Identifiers = new List<string>() { "c1" } } },
Value = new StringLiteral() { Value = "test2" }
};
//Equals
Assert.IsTrue(Equals(first, firstClone));
Assert.IsFalse(Equals(first, null));
Assert.IsFalse(Equals(first, second));
Assert.IsFalse(Equals(first, third));
Assert.IsFalse(Equals(first, fourth));
Assert.IsFalse(Equals(first, "other type"));
//Hash code
Assert.AreEqual(first.GetHashCode(), firstClone.GetHashCode());
Assert.AreNotEqual(first.GetHashCode(), second.GetHashCode());
Assert.AreNotEqual(first.GetHashCode(), third.GetHashCode());
Assert.AreNotEqual(first.GetHashCode(), fourth.GetHashCode());
}
[Test]
public void TestSelectNullExpressionEquals()
{
SelectNullExpression first = new SelectNullExpression()
{
Alias = "test"
};
SelectNullExpression firstClone = new SelectNullExpression()
{
Alias = "test"
};
SelectNullExpression second = new SelectNullExpression()
{
Alias = "test2"
};
//Equals
Assert.IsTrue(Equals(first, firstClone));
Assert.IsFalse(Equals(first, null));
Assert.IsFalse(Equals(first, second));
Assert.IsFalse(Equals(first, "other type"));
//Hash code
Assert.AreEqual(first.GetHashCode(), firstClone.GetHashCode());
Assert.AreNotEqual(first.GetHashCode(), second.GetHashCode());
}
[Test]
public void TestSelectScalarExpressionEquals()
{
SelectScalarExpression first = new SelectScalarExpression()
{
Alias = "test",
Expression = new StringLiteral() { Value = "t" }
};
SelectScalarExpression firstClone = new SelectScalarExpression()
{
Alias = "test",
Expression = new StringLiteral() { Value = "t" }
};
SelectScalarExpression second = new SelectScalarExpression()
{
Alias = "test2",
Expression = new StringLiteral() { Value = "t" }
};
SelectScalarExpression third = new SelectScalarExpression()
{
Alias = "test",
Expression = new StringLiteral() { Value = "t2" }
};
//Equals
Assert.IsTrue(Equals(first, firstClone));
Assert.IsFalse(Equals(first, null));
Assert.IsFalse(Equals(first, second));
Assert.IsFalse(Equals(first, third));
Assert.IsFalse(Equals(first, "other type"));
//Hash code
Assert.AreEqual(first.GetHashCode(), firstClone.GetHashCode());
Assert.AreNotEqual(first.GetHashCode(), second.GetHashCode());
Assert.AreNotEqual(first.GetHashCode(), third.GetHashCode());
}
[Test]
public void TestSelectStarExpressionEquals()
{
SelectStarExpression first = new SelectStarExpression()
{
Alias = "test"
};
SelectStarExpression firstClone = new SelectStarExpression()
{
Alias = "test"
};
SelectStarExpression second = new SelectStarExpression()
{
Alias = "test2"
};
//Equals
Assert.IsTrue(Equals(first, firstClone));
Assert.IsFalse(Equals(first, null));
Assert.IsFalse(Equals(first, second));
Assert.IsFalse(Equals(first, "other type"));
//Hash code
Assert.AreEqual(first.GetHashCode(), firstClone.GetHashCode());
Assert.AreNotEqual(first.GetHashCode(), second.GetHashCode());
}
[Test]
public void TestVariableReferenceEquals()
{
VariableReference first = new VariableReference()
{
Name = "test"
};
VariableReference firstClone = new VariableReference()
{
Name = "test"
};
VariableReference second = new VariableReference()
{
Name = "test2"
};
//Equals
Assert.IsTrue(Equals(first, firstClone));
Assert.IsFalse(Equals(first, null));
Assert.IsFalse(Equals(first, second));
Assert.IsFalse(Equals(first, "other type"));
//Hash code
Assert.AreEqual(first.GetHashCode(), firstClone.GetHashCode());
Assert.AreNotEqual(first.GetHashCode(), second.GetHashCode());
}
}
}
| 38.572268 | 156 | 0.515004 | [
"Apache-2.0"
] | rs-swc/Koralium | netcore/tests/Koralium.SqlParser.Tests/ExpressionEqualsTests.cs | 32,827 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Trivial.Chemistry
{
/// <summary>
/// The model of the molecular formula.
/// </summary>
public class MolecularFormula : IEquatable<MolecularFormula>
{
/// <summary>
/// The item.
/// </summary>
public class Item : IEquatable<Item>
{
/// <summary>
/// Initializes a new instance of the MolecularFormula.Item class.
/// </summary>
/// <param name="element">The chemical element.</param>
/// <param name="count">The atom count.</param>
public Item(ChemicalElement element, int count = 1)
{
Element = element;
Count = count;
}
/// <summary>
/// Initializes a new instance of the MolecularFormula.Item class.
/// </summary>
/// <param name="symbol">The symbol of the chemical element.</param>
/// <param name="count">The atom count.</param>
public Item(string symbol, int count = 1)
: this(ChemicalElement.Get(symbol), count)
{
}
/// <summary>
/// Gets the chemical element.
/// </summary>
public ChemicalElement Element { get; }
/// <summary>
/// Gets the atom count.
/// </summary>
public int Count { get; }
/// <summary>
/// Peturns a string that represents the current chemical element information.
/// </summary>
/// <returns>A string that represents the current chemical element information.</returns>
public override string ToString()
{
var symbol = Element?.Symbol?.Trim();
if (string.IsNullOrWhiteSpace(symbol) || Count < 1) return null;
if (Count == 1) return symbol;
return symbol + Count
.ToString("g")
.Replace('0', '₀')
.Replace('1', '₁')
.Replace('2', '₂')
.Replace('3', '₃')
.Replace('4', '₄')
.Replace('5', '₅')
.Replace('6', '₆')
.Replace('7', '₇')
.Replace('8', '₈')
.Replace('9', '₉');
}
/// <inheritdoc />
public override int GetHashCode()
=>new Tuple<ChemicalElement, int>(Element, Count).GetHashCode();
/// <summary>
/// Indicates whether this instance and a specified object are equal.
/// </summary>
/// <param name="other">The object to compare with the current instance.</param>
/// <returns>true if obj and this instance represent the same value; otherwise, false.</returns>
public bool Equals(Item other)
{
if (other is null) return false;
if (ReferenceEquals(this, other)) return true;
return Element == other.Element
&& Count == other.Count;
}
/// <summary>
/// Indicates whether this instance and a specified object are equal.
/// </summary>
/// <param name="other">The object to compare with the current instance.</param>
/// <returns>true if obj and this instance represent the same value; otherwise, false.</returns>
public override bool Equals(object other)
{
if (other is null) return false;
if (other is Item isotope) return Equals(isotope);
if (other is ChemicalElement element) return Count == 1 && element.Equals(Element);
return false;
}
/// <summary>
/// Compares two molecular formula items to indicate if they are same.
/// leftValue == rightValue
/// </summary>
/// <param name="leftValue">The left value to compare.</param>
/// <param name="rightValue">The right value to compare.</param>
/// <returns>true if they are same; otherwise, false.</returns>
public static bool operator ==(Item leftValue, Item rightValue)
{
if (ReferenceEquals(leftValue, rightValue)) return true;
if (leftValue is null || rightValue is null) return false;
return leftValue.Equals(rightValue);
}
/// <summary>
/// Compares two molecular formula items to indicate if they are different.
/// leftValue != rightValue
/// </summary>
/// <param name="leftValue">The left value to compare.</param>
/// <param name="rightValue">The right value to compare.</param>
/// <returns>true if they are different; otherwise, false.</returns>
public static bool operator !=(Item leftValue, Item rightValue)
{
if (ReferenceEquals(leftValue, rightValue)) return false;
if (leftValue is null || rightValue is null) return true;
return !leftValue.Equals(rightValue);
}
}
/// <summary>
/// The source cache.
/// </summary>
private readonly List<Item> list;
/// <summary>
/// The string format cache.
/// </summary>
private string s;
/// <summary>
/// Initializes a new instance of the MolecularFormula class.
/// </summary>
/// <param name="col">The items.</param>
public MolecularFormula(IEnumerable<Item> col)
{
list = new List<Item>(col);
}
/// <summary>
/// Initializes a new instance of the MolecularFormula class.
/// </summary>
/// <param name="col">The items.</param>
/// <param name="chargeNumber">The ionic charge numbe.</param>
public MolecularFormula(IEnumerable<Item> col, int chargeNumber)
{
list = new List<Item>(col.Where(ele => ele?.Element != null && ele.Count > 0));
ChargeNumber = chargeNumber;
}
/// <summary>
/// Initializes a new instance of the MolecularFormula class.
/// </summary>
/// <param name="element">The chemical element.</param>
/// <param name="count">The count of the specific chemical element.</param>
public MolecularFormula(ChemicalElement element, int count = 1)
{
list = string.IsNullOrEmpty(element?.Symbol) || count < 1
? new List<Item>()
: new List<Item> { new Item(element, count) };
}
/// <summary>
/// Initializes a new instance of the MolecularFormula class.
/// </summary>
/// <param name="elementA">The chemical element A.</param>
/// <param name="countA">The count of the specific chemical element A.</param>
/// <param name="elementB">The chemical element B.</param>
/// <param name="countB">The count of the specific chemical element B.</param>
/// <param name="elementC">The chemical element C.</param>
/// <param name="countC">The count of the specific chemical element C.</param>
/// <param name="elementD">The chemical element D.</param>
/// <param name="countD">The count of the specific chemical element D.</param>
/// <param name="elementE">The chemical element F.</param>
/// <param name="countE">The count of the specific chemical element E.</param>
/// <param name="elementF">The chemical element E.</param>
/// <param name="countF">The count of the specific chemical element F.</param>
/// <param name="elementG">The chemical element G.</param>
/// <param name="countG">The count of the specific chemical element G.</param>
public MolecularFormula(ChemicalElement elementA, int countA, ChemicalElement elementB, int countB, ChemicalElement elementC = null, int countC = 1, ChemicalElement elementD = null, int countD = 1, ChemicalElement elementE = null, int countE = 1, ChemicalElement elementF = null, int countF = 1, ChemicalElement elementG = null, int countG = 1)
{
list = new List<Item>();
if (!string.IsNullOrEmpty(elementA?.Symbol) && countA > 0)
list.Add(new Item(elementA, countA));
if (!string.IsNullOrEmpty(elementB?.Symbol) && countB > 0)
list.Add(new Item(elementB, countB));
if (!string.IsNullOrEmpty(elementC?.Symbol) && countC > 0)
list.Add(new Item(elementC, countC));
if (!string.IsNullOrEmpty(elementD?.Symbol) && countD > 0)
list.Add(new Item(elementD, countD));
if (!string.IsNullOrEmpty(elementE?.Symbol) && countE > 0)
list.Add(new Item(elementE, countE));
if (!string.IsNullOrEmpty(elementF?.Symbol) && countF > 0)
list.Add(new Item(elementF, countF));
if (!string.IsNullOrEmpty(elementG?.Symbol) && countG > 0)
list.Add(new Item(elementG, countG));
}
/// <summary>
/// Gets the ionic charge number.
/// </summary>
public int ChargeNumber { get; }
/// <summary>
/// Gets a value indicating whether this is an ion.
/// </summary>
public bool IsIon => ChargeNumber != 0;
/// <summary>
/// Gets the items.
/// </summary>
public IReadOnlyList<Item> Items => list.AsReadOnly();
/// <summary>
/// Gets all elements.
/// </summary>
public IEnumerable<ChemicalElement> Elements
=> list.Select(ele => ele.Element).Where(ele => !string.IsNullOrEmpty(ele?.Symbol)).Distinct();
/// <summary>
/// Gets the atom count.
/// </summary>
public int Count => list.Sum(ele => ele.Count);
/// <summary>
/// Gets the proton numbers.
/// </summary>
public int ProtonNumber => list.Sum(ele => ele.Count * (ele.Element?.AtomicNumber ?? 0));
/// <summary>
/// Gets a collection of all elements and their numbers.
/// </summary>
/// <returns>A collection of all elements and their numbers.</returns>
public IEnumerable<Item> Zip()
{
var list = new List<Item>();
foreach (var item in this.list)
{
Zip(list, item);
}
return list;
}
/// <summary>
/// Reports the zero-based index of the first occurrence of the specified string in this instance.
/// </summary>
/// <param name="symbol">The string to seek.</param>
/// <returns>The zero-based index position of value if that string is found, or -1 if it is not. If value is System.String.Empty, the return value is 0.</returns>
/// <exception cref="ArgumentNullException">symbol should not be null.</exception>
/// <exception cref="ArgumentException">symbol should not be empty.</exception>
public int IndexOf(string symbol)
{
if (symbol == null) throw new ArgumentNullException(nameof(symbol), "symbol was null");
symbol = symbol.Trim();
if (symbol.Length < 1) throw new ArgumentException("symbol was empty", nameof(symbol));
return list.FindIndex(ele => symbol.Equals(ele.Element?.Symbol, StringComparison.OrdinalIgnoreCase));
}
/// <summary>
/// Reports the zero-based index of the first occurrence of the specified string in this instance.
/// </summary>
/// <param name="symbol">The string to seek.</param>
/// <param name="startIndex">The search starting position.</param>
/// <param name="count">The optional number of character positions to examine.</param>
/// <returns>The zero-based index position of value if that string is found, or -1 if it is not. If value is System.String.Empty, the return value is 0.</returns>
/// <exception cref="ArgumentNullException">symbol should not be null.</exception>
public int IndexOf(string symbol, int startIndex, int? count = null)
{
if (symbol == null) throw new ArgumentNullException(nameof(symbol), "symbol was null");
symbol = symbol.Trim();
if (symbol.Length < 1) throw new ArgumentException("symbol was empty", nameof(symbol));
return count.HasValue
? list.FindIndex(startIndex, count.Value, ele => symbol.Equals(ele.Element?.Symbol, StringComparison.OrdinalIgnoreCase))
: list.FindIndex(startIndex, ele => symbol.Equals(ele.Element?.Symbol, StringComparison.OrdinalIgnoreCase));
}
/// <summary>
/// Reports the zero-based index position of the last occurrence of a specified string within this instance.
/// </summary>
/// <param name="symbol">The string to seek.</param>
/// <returns>The zero-based starting index position of value if that string is found, or -1 if it is not. If value is System.String.Empty, the return value is the last index position in this instance.</returns>
/// <exception cref="ArgumentNullException">symbol should not be null.</exception>
public int LastIndexOf(string symbol)
{
if (symbol == null) throw new ArgumentNullException(nameof(symbol), "symbol was null");
symbol = symbol.Trim();
if (symbol.Length < 1) throw new ArgumentException("symbol was empty", nameof(symbol));
return list.FindLastIndex(ele => symbol.Equals(ele.Element?.Symbol, StringComparison.OrdinalIgnoreCase));
}
/// <summary>
/// Reports the zero-based index position of the last occurrence of a specified string within this instance.
/// </summary>
/// <param name="symbol">The string to seek.</param>
/// <param name="startIndex">The search starting position. The search proceeds from startIndex toward the beginning of this instance.</param>
/// <param name="count">The optional number of character positions to examine.</param>
/// <returns>The zero-based starting index position of value if that string is found, or -1 if it is not. If value is System.String.Empty, the return value is the last index position in this instance.</returns>
/// <exception cref="ArgumentNullException">symbol should not be null.</exception>
public int LastIndexOf(string symbol, int startIndex, int? count = null)
{
if (symbol == null) throw new ArgumentNullException(nameof(symbol), "symbol was null");
symbol = symbol.Trim();
if (symbol.Length < 1) throw new ArgumentException("symbol was empty", nameof(symbol));
return count.HasValue
? list.FindLastIndex(startIndex, count.Value, ele => symbol.Equals(ele.Element?.Symbol, StringComparison.OrdinalIgnoreCase))
: list.FindLastIndex(startIndex, ele => symbol.Equals(ele.Element?.Symbol, StringComparison.OrdinalIgnoreCase));
}
/// <summary>
/// Reports the zero-based index of the first occurrence of the specified string in this instance.
/// </summary>
/// <param name="element">The chemical element to seek.</param>
/// <returns>The zero-based index position of value if that string is found, or -1 if it is not. If value is System.String.Empty, the return value is 0.</returns>
/// <exception cref="ArgumentNullException">element should not be null.</exception>
public int IndexOf(ChemicalElement element)
=> element != null ? list.FindIndex(ele => ele.Element == element) : throw new ArgumentNullException(nameof(element), "element was null.");
/// <summary>
/// Reports the zero-based index position of the last occurrence of a specified string within this instance.
/// </summary>
/// <param name="element">The chemical element to seek.</param>
/// <returns>The zero-based starting index position of value if that string is found, or -1 if it is not. If value is System.String.Empty, the return value is the last index position in this instance.</returns>
/// <exception cref="ArgumentNullException">element should not be null.</exception>
public int LastIndexOf(ChemicalElement element)
=> element != null ? list.FindLastIndex(ele => ele.Element == element) : throw new ArgumentNullException(nameof(element), "element was null.");
/// <summary>
/// Reports the zero-based index of the first occurrence of the specified string in this instance.
/// </summary>
/// <param name="element">The chemical element to seek.</param>
/// <param name="startIndex">The search starting position.</param>
/// <param name="count">The optional number of character positions to examine.</param>
/// <returns>The zero-based index position of value if that string is found, or -1 if it is not. If value is System.String.Empty, the return value is 0.</returns>
/// <exception cref="ArgumentNullException">element should not be null.</exception>
public int IndexOf(ChemicalElement element, int startIndex, int? count = null)
=> element != null ? (count.HasValue
? list.FindIndex(startIndex, count.Value, ele => ele.Element == element)
: list.FindIndex(startIndex, ele => ele.Element == element)) : throw new ArgumentNullException(nameof(element), "element was null.");
/// <summary>
/// Reports the zero-based index position of the last occurrence of a specified string within this instance.
/// </summary>
/// <param name="element">The chemical element to seek.</param>
/// <param name="startIndex">The search starting position. The search proceeds from startIndex toward the beginning of this instance.</param>
/// <param name="count">The optional number of character positions to examine.</param>
/// <returns>The zero-based starting index position of value if that string is found, or -1 if it is not. If value is System.String.Empty, the return value is the last index position in this instance.</returns>
/// <exception cref="ArgumentNullException">element should not be null.</exception>
public int LastIndexOf(ChemicalElement element, int startIndex, int? count = null)
=> element != null ? (count.HasValue
? list.FindLastIndex(startIndex, count.Value, ele => ele.Element == element)
: list.FindLastIndex(startIndex, ele => ele.Element == element)) : throw new ArgumentNullException(nameof(element), "element was null.");
/// <summary>
/// Gets the count of the specific chemical element.
/// </summary>
/// <param name="element">The chemcial element to get count.</param>
/// <returns>The total.</returns>
public int GetCount(ChemicalElement element)
{
if (element is null) return 0;
return list.Where(ele => ele.Element == element)?.Sum(ele => ele.Count) ?? 0;
}
/// <summary>
/// Gets the count of the specific chemical element.
/// </summary>
/// <param name="symbol">The chemcial symbol to get count.</param>
/// <returns>The total.</returns>
public int GetCount(string symbol)
{
symbol = symbol?.Trim();
if (string.IsNullOrEmpty(symbol)) return 0;
return list.Where(ele => symbol.Equals(ele.Element?.Symbol, StringComparison.OrdinalIgnoreCase))?.Sum(ele => ele.Count) ?? 0;
}
/// <summary>
/// Peturns a string that represents the current chemical element information.
/// </summary>
/// <returns>A string that represents the current chemical element information.</returns>
public override string ToString()
{
if (s != null) return s;
var sb = new StringBuilder();
foreach (var item in list)
{
sb.Append(item.ToString());
}
if (sb.Length == 0) sb.Append('e');
if (ChargeNumber != 0)
{
if (ChargeNumber > 1 || ChargeNumber < -1) sb.Append(Math.Abs(ChargeNumber)
.ToString("g")
.Replace('0', '⁰')
.Replace('1', '¹')
.Replace('2', '²')
.Replace('3', '³')
.Replace('4', '⁴')
.Replace('5', '⁵')
.Replace('6', '⁶')
.Replace('7', '⁷')
.Replace('8', '⁸')
.Replace('9', '⁹'));
sb.Append(ChargeNumber > 0 ? '﹢' : 'ˉ');
}
return s = sb.ToString();
}
/// <inheritdoc />
public override int GetHashCode()
=> new Tuple<List<Item>, int>(list, ChargeNumber).GetHashCode();
/// <summary>
/// Indicates whether this instance and a specified object are equal.
/// </summary>
/// <param name="other">The object to compare with the current instance.</param>
/// <returns>true if obj and this instance represent the same value; otherwise, false.</returns>
public bool Equals(MolecularFormula other)
{
if (other is null) return false;
if (ReferenceEquals(this, other)) return true;
if (ChargeNumber != other.ChargeNumber) return false;
return Collection.ListExtensions.Equals(list, other.list);
}
/// <summary>
/// Indicates whether this instance and a specified object are equal.
/// </summary>
/// <param name="other">The object to compare with the current instance.</param>
/// <returns>true if obj and this instance represent the same value; otherwise, false.</returns>
public override bool Equals(object other)
{
if (other is null) return false;
if (other is MolecularFormula isotope) return Equals(isotope);
if (other is IEnumerable<Item> col) return ChargeNumber == 0 && Collection.ListExtensions.Equals(list, col.ToList());
return false;
}
/// <summary>
/// Compares two molecular formula instances to indicate if they are same.
/// leftValue == rightValue
/// </summary>
/// <param name="leftValue">The left value to compare.</param>
/// <param name="rightValue">The right value to compare.</param>
/// <returns>true if they are same; otherwise, false.</returns>
public static bool operator ==(MolecularFormula leftValue, MolecularFormula rightValue)
{
if (ReferenceEquals(leftValue, rightValue)) return true;
if (leftValue is null || rightValue is null) return false;
return leftValue.Equals(rightValue);
}
/// <summary>
/// Compares two molecular formula instances to indicate if they are different.
/// leftValue != rightValue
/// </summary>
/// <param name="leftValue">The left value to compare.</param>
/// <param name="rightValue">The right value to compare.</param>
/// <returns>true if they are different; otherwise, false.</returns>
public static bool operator !=(MolecularFormula leftValue, MolecularFormula rightValue)
{
if (ReferenceEquals(leftValue, rightValue)) return false;
if (leftValue is null || rightValue is null) return true;
return !leftValue.Equals(rightValue);
}
/// <summary>
/// Pluses a molecular formula and a chemical element.
/// </summary>
/// <param name="leftValue">The left value for addition operator.</param>
/// <param name="rightValue">The right value for addition operator.</param>
/// <returns>A result after addition.</returns>
public static MolecularFormula operator +(MolecularFormula leftValue, ChemicalElement rightValue)
{
var isRightEmpty = string.IsNullOrEmpty(rightValue?.Symbol);
if (leftValue is null && isRightEmpty) return null;
if (leftValue is null) return new MolecularFormula(rightValue);
if (isRightEmpty) return leftValue;
var col = leftValue.list.ToList();
col.Add(new Item(rightValue, 1));
return new MolecularFormula(col, leftValue.ChargeNumber);
}
/// <summary>
/// Pluses a molecular formula and a chemical element.
/// </summary>
/// <param name="rightValue">The left value for addition operator.</param>
/// <param name="leftValue">The right value for addition operator.</param>
/// <returns>A result after addition.</returns>
public static MolecularFormula operator +(ChemicalElement leftValue, MolecularFormula rightValue)
{
var isLeftEmpty = string.IsNullOrEmpty(leftValue?.Symbol);
if (rightValue is null && isLeftEmpty) return null;
if (rightValue is null) return new MolecularFormula(leftValue);
if (isLeftEmpty) return rightValue;
var col = rightValue.list.ToList();
col.Add(new Item(leftValue, 1));
return new MolecularFormula(col, rightValue.ChargeNumber);
}
/// <summary>
/// Pluses two molecular formula instances.
/// </summary>
/// <param name="rightValue">The left value for addition operator.</param>
/// <param name="leftValue">The right value for addition operator.</param>
/// <returns>A result after addition.</returns>
public static MolecularFormula operator +(MolecularFormula leftValue, MolecularFormula rightValue)
{
if (leftValue is null || leftValue.Count == 0) return rightValue;
if (rightValue is null || rightValue.Count == 0) return leftValue;
var col = leftValue.list.ToList();
col.AddRange(rightValue.list);
return new MolecularFormula(col, leftValue.ChargeNumber + rightValue.ChargeNumber);
}
/// <summary>
/// Converts to a molecular formula instance.
/// </summary>
/// <param name="element">The chemical element to convert.</param>
public static implicit operator MolecularFormula(ChemicalElement element)
{
return new MolecularFormula(element);
}
/// <summary>
/// Parses.
/// </summary>
/// <param name="s">The input.</param>
/// <returns>A molecular formula instance parsed.</returns>
public static MolecularFormula Parse(string s)
{
s = s?.Trim();
if (string.IsNullOrWhiteSpace(s)) return null;
return TryParse(s) ?? throw new FormatException("s is invalid.");
}
/// <summary>
/// Tries to parse a molecular formula string.
/// </summary>
/// <param name="s">The input.</param>
/// <param name="result">The result output.</param>
/// <returns>true if parse succeeded; otherwise, false.</returns>
public static bool TryParse(string s, out MolecularFormula result)
{
result = TryParse(s);
return result != null;
}
/// <summary>
/// Tries to parse a molecular formula string.
/// </summary>
/// <param name="s">The input.</param>
/// <returns>A molecular formula instance parsed.</returns>
public static MolecularFormula TryParse(string s)
{
s = s?.Trim();
if (string.IsNullOrWhiteSpace(s)) return null;
var col = new List<Item>();
var sb = new StringBuilder();
var count = 0;
var hasCount = false;
var sup = 0;
foreach (var c in s)
{
if (c >= 'A' && c <= 'Z')
{
sup = 0;
if (sb.Length > 0)
{
if (!Add(sb, col, hasCount ? count : 1))
return null;
}
count = 0;
hasCount = false;
sb.Clear();
sb.Append(c);
continue;
}
if (c >= 'a' && c <= 'z')
{
sup = 0;
count = 0;
hasCount = false;
sb.Append(c);
continue;
}
var push = false;
switch (c)
{
case '0':
case '₀':
sup = 0;
count *= 10;
break;
case '1':
case '₁':
sup = 0;
count = count * 10 + 1;
hasCount = true;
break;
case '2':
case '₂':
sup = 0;
count = count * 10 + 2;
hasCount = true;
break;
case '3':
case '₃':
sup = 0;
count = count * 10 + 3;
hasCount = true;
break;
case '4':
case '₄':
sup = 0;
count = count * 10 + 4;
hasCount = true;
break;
case '5':
case '₅':
sup = 0;
count = count * 10 + 5;
hasCount = true;
break;
case '6':
case '₆':
sup = 0;
count = count * 10 + 6;
hasCount = true;
break;
case '7':
case '₇':
sup = 0;
count = count * 10 + 7;
hasCount = true;
break;
case '8':
case '₈':
count = count * 10 + 8;
hasCount = true;
break;
case '9':
case '₉':
sup = 0;
count = count * 10 + 9;
hasCount = true;
break;
case ' ':
case '_':
case '·':
case '.':
case ',':
case '~':
sup = 0;
push = true;
break;
case '-':
case '+':
case 'ˉ':
case '﹢':
push = true;
break;
case '⁰':
sup *= 10;
push = true;
break;
case '¹':
sup = sup * 10 + 1;
push = true;
break;
case '²':
sup = sup * 10 + 2;
push = true;
break;
case '³':
sup = sup * 10 + 3;
push = true;
break;
case '⁴':
sup = sup * 10 + 4;
push = true;
break;
case '⁵':
sup = sup * 10 + 5;
push = true;
break;
case '⁶':
sup = sup * 10 + 6;
push = true;
break;
case '⁷':
sup = sup * 10 + 7;
push = true;
break;
case '⁸':
sup = sup * 10 + 8;
push = true;
break;
case '⁹':
sup = sup * 10 + 9;
push = true;
break;
default:
return null;
}
if (push)
{
if (sb.Length > 0)
{
if (!Add(sb, col, hasCount ? count : 1))
return null;
sb.Clear();
}
count = 0;
hasCount = false;
}
}
if (sb.Length > 0)
{
if (!Add(sb, col, hasCount ? count : 1))
return null;
sb.Clear();
}
var ion = 0;
if (s.EndsWith("+") || s.EndsWith("﹢"))
{
ion = sup;
}
else if (s.EndsWith("-") || s.EndsWith("ˉ"))
{
ion = -sup;
}
var result = new MolecularFormula(col, ion);
return result.list.Count > 0 ? result : null;
}
/// <summary>
/// Gets a collection of all elements and their numbers.
/// </summary>
/// <param name="col">The collection.</param>
/// <returns>A collection of all elements and their numbers.</returns>
public static IEnumerable<Item> Zip(IEnumerable<MolecularFormula> col)
{
var list = new List<Item>();
if (col is null) return list;
foreach (var item in col.SelectMany(ele => ele.list))
{
Zip(list, item);
}
return list;
}
/// <summary>
/// Tests the elements in the two molecular formula instances are passed by the law of conservation of mass.
/// </summary>
/// <param name="a">The left collection.</param>
/// <param name="b">The right collection.</param>
/// <returns>true if conservation of mass; otherwise, false.</returns>
public static bool ConservationOfMass(IEnumerable<MolecularFormula> a, IEnumerable<MolecularFormula> b)
{
try
{
var dictA = Zip(a).ToList();
var dictB = Zip(b).ToList();
if (dictA.Count != dictB.Count) return false;
var chargeA = a.Sum(ele => ele.ChargeNumber);
var chargeB = b.Sum(ele => ele.ChargeNumber);
if (chargeA != chargeB) return false;
foreach (var item in dictA)
{
if (item is null) continue;
if (!dictB.Any(ele => item.Equals(ele))) return false;
}
return true;
}
catch (ArgumentException)
{
return false;
}
}
/// <summary>
/// Returns a string that represents the current object.
/// </summary>
/// <param name="formulas">The molecular fomula collection.</param>
/// <returns>A string that represents the current object.</returns>
public static string ToString(IEnumerable<MolecularFormula> formulas)
{
if (formulas is null) return string.Empty;
var dict = new Dictionary<MolecularFormula, int>();
foreach (var item in formulas)
{
if (item is null) continue;
var f = dict.Keys.FirstOrDefault(ele => ele == item);
if (f is null) dict[item] = 1;
else dict[f]++;
}
return string.Join(" + ", dict.Select(ele => {
if (ele.Value > 1) return ele.Value.ToString("g") + ele.Key.ToString();
return ele.Value.ToString();
}));
}
private static bool Add(StringBuilder sb, List<Item> col, int count)
{
var symbol = sb.ToString();
var item = new Item(symbol, count);
if (item.Element is null)
{
switch (symbol)
{
case "R":
col.Add(new Item(ChemicalElement.C, count));
col.Add(new Item(ChemicalElement.H, count * 2 + 1));
break;
case "Ph":
col.Add(new Item(ChemicalElement.C, count * 6));
col.Add(new Item(ChemicalElement.H, count * 5));
break;
case "Bn":
col.Add(new Item(ChemicalElement.C, count * 6));
col.Add(new Item(ChemicalElement.H, count * 5));
col.Add(new Item(ChemicalElement.C, count));
col.Add(new Item(ChemicalElement.H, count * 2));
break;
default:
return false;
}
}
col.Add(item);
return true;
}
private static void Zip(List<Item> list, Item item)
{
if (item?.Element is null || item.Count < 1) return;
var count = list.Where(ele => ele.Element == item.Element).Sum(ele => ele.Count);
list.RemoveAll(ele => ele.Element == item.Element);
list.Add(new Item(item.Element, count + item.Count));
}
}
}
| 44.184332 | 352 | 0.51773 | [
"MIT"
] | nuscien/trivial | Chemistry/Chemistry/MolecularFormula.cs | 38,438 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZSZ.DTO;
using ZSZ.IService;
using ZSZ.Service.Entities;
using System.Data.Entity;
namespace ZSZ.Service
{
public class RegionService : IRegionService
{
private RegionDTO ToDTO(RegionEntity region)
{
RegionDTO dto = new RegionDTO();
dto.CityId = region.CityId;
dto.CityName = region.City.Name;
dto.CreateDateTime = region.CreateDateTime;
dto.Id = region.Id;
dto.Name = region.Name;
return dto;
}
public RegionDTO[] GetAll(long cityId)
{
using (ZSZDbContext ctx = new ZSZDbContext())
{
CommonService<RegionEntity> bs
= new CommonService<RegionEntity>(ctx);
return bs.GetAll().Include(r=>r.City)
.Where(r => r.CityId == cityId)
.Select(r=>ToDTO(r)).ToArray();
}
}
public RegionDTO GetById(long id)
{
using (ZSZDbContext ctx = new ZSZDbContext())
{
CommonService<RegionEntity> bs
= new CommonService<RegionEntity>(ctx);
var region = bs.GetAll().Include(r => r.City)
.SingleOrDefault(r => r.Id == id);
return region == null ? null : ToDTO(region);
}
}
}
}
| 29.96 | 61 | 0.534713 | [
"Apache-2.0"
] | laoshuai/ZSZ | ZSZ.Service/RegionService.cs | 1,500 | C# |
using PC.PowerApps.Common.Entities.Dataverse;
using PC.PowerApps.Common.ScheduledJobs;
namespace PC.PowerApps.Common.Repositories
{
public static class BankAccountRepository
{
public static void SetTransactionImportStatusToPending(pc_BankAccount bankAccount)
{
if (bankAccount.pc_TransactionImportFile == null)
{
return;
}
bankAccount.pc_TransactionImportError = null;
bankAccount.pc_TransactionImportStatus = pc_TransactionImportStatus.Pending;
}
public static void ScheduleImportTransactions(Context context, pc_BankAccount bankAccount)
{
if (bankAccount.pc_TransactionImportFile == null)
{
return;
}
ImportTransactions importSwedbankTransactions = new ImportTransactions
{
BankAccountId = bankAccount.Id,
Context = context,
};
importSwedbankTransactions.Schedule(allowDuplicates: false);
}
}
}
| 30.571429 | 98 | 0.626168 | [
"MIT"
] | Pilseta-cilvekiem/Participant-Management | PC.PowerApps/PC.PowerApps.Common/Repositories/BankAccountRepository.cs | 1,072 | C# |
// Copyright (c) 2016-2020 Alexander Ong
// See LICENSE in project root for license information.
using UnityEngine;
using System.Collections;
using MoonscraperEngine;
using MoonscraperEngine.Audio;
using MoonscraperChartEditor.Song;
public abstract class MovementController : MonoBehaviour {
const float DESYNCLENIENCE = .05f / 1000.0f;
public static bool cancel = false;
public ChartEditor editor;
protected Globals globals;
public Vector3 initPos { get; protected set; }
protected float scrollDelta = 0;
protected bool focused = true;
public static uint? explicitChartPos = null;
protected float lastUpdatedRealTime = 0;
Transform selfTransform;
// Program options
protected float c_mouseScrollSensitivity = 0.2f; // May miss snap gaps if placed too high
// Jump to a chart position
public abstract void SetPosition(uint tick);
public void SetTime(float time)
{
//if (ChartEditor.Instance.currentState == ChartEditor.State.Editor)
{
Vector3 pos = initPos;
pos.y += ChartEditor.TimeToWorldYPosition(time);
transform.position = pos;
}
}
protected void Start()
{
initPos = transform.position;
globals = GameObject.FindGameObjectWithTag("Globals").GetComponent<Globals>();
selfTransform = transform;
}
public void PlayingMovement()
{
float speed = Globals.gameSettings.hyperspeed;
Vector3 pos = transform.position;
float deltaTime = Time.deltaTime;
float positionOffset = initPos.y;
{
float timeBeforeMovement = ChartEditor.WorldYPositionToTime(pos.y - positionOffset);
float timeAfterMovement = timeBeforeMovement + deltaTime * Globals.gameSettings.gameSpeed;
// Make sure we're staying in sync with the audio
{
SongAudioManager songAudioManager = editor.currentSongAudio;
AudioStream stream = null;
for (int i = 0; i < EnumX<Song.AudioInstrument>.Count; ++i)
{
Song.AudioInstrument audio = (Song.AudioInstrument)i;
if (AudioManager.StreamIsValid(songAudioManager.GetAudioStream(audio)))
{
stream = songAudioManager.GetAudioStream(audio);
break;
}
}
if (AudioManager.StreamIsValid(stream) && stream.IsPlaying())
{
float audioTimePosition = stream.CurrentPositionInSeconds() - editor.services.totalSongAudioOffset;
float desyncAmount = audioTimePosition - timeAfterMovement;
if (Mathf.Abs(desyncAmount) > DESYNCLENIENCE)
timeAfterMovement += desyncAmount;
}
}
float maxChangeInTimeAllowed = Application.targetFrameRate > 0 ? 2.0f / Application.targetFrameRate : 1.0f / 120.0f;
float totalChangeInTime = timeAfterMovement - timeBeforeMovement;
float newTimePosition = ChartEditor.TimeToWorldYPosition(timeBeforeMovement + totalChangeInTime);
pos.y = newTimePosition + positionOffset;
}
selfTransform.position = pos;
explicitChartPos = null;
lastUpdatedRealTime = Time.time;
}
void OnGUI()
{
if (focused)
{
if (UnityEngine.Event.current.type == EventType.ScrollWheel)
{
scrollDelta = -UnityEngine.Event.current.delta.y;
}
else
{
scrollDelta = 0;
}
}
else
scrollDelta = 0;
}
}
| 32.194915 | 129 | 0.599105 | [
"BSD-3-Clause"
] | Mario64iscool2/Moonscraper-Chart-Editor | Moonscraper Chart Editor/Assets/Scripts/Game/Controllers/MovementController.cs | 3,801 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
/*
* Do not modify this file. This file is generated from the dynamodb-2012-08-10.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.DynamoDBv2.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.DynamoDBv2.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for DescribeGlobalTableSettings operation
/// </summary>
public class DescribeGlobalTableSettingsResponseUnmarshaller : JsonResponseUnmarshaller
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context)
{
DescribeGlobalTableSettingsResponse response = new DescribeGlobalTableSettingsResponse();
context.Read();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("GlobalTableName", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.GlobalTableName = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("ReplicaSettings", targetDepth))
{
var unmarshaller = new ListUnmarshaller<ReplicaSettingsDescription, ReplicaSettingsDescriptionUnmarshaller>(ReplicaSettingsDescriptionUnmarshaller.Instance);
response.ReplicaSettings = unmarshaller.Unmarshall(context);
continue;
}
}
return response;
}
/// <summary>
/// Unmarshaller error response to exception.
/// </summary>
/// <param name="context"></param>
/// <param name="innerException"></param>
/// <param name="statusCode"></param>
/// <returns></returns>
public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode)
{
ErrorResponse errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context);
if (errorResponse.Code != null && errorResponse.Code.Equals("GlobalTableNotFoundException"))
{
return new GlobalTableNotFoundException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("InternalServerError"))
{
return new InternalServerErrorException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
return new AmazonDynamoDBException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
private static DescribeGlobalTableSettingsResponseUnmarshaller _instance = new DescribeGlobalTableSettingsResponseUnmarshaller();
internal static DescribeGlobalTableSettingsResponseUnmarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static DescribeGlobalTableSettingsResponseUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 40.585586 | 177 | 0.665483 | [
"Apache-2.0"
] | AltairMartinez/aws-sdk-unity-net | src/Services/DynamoDBv2/Generated/Model/Internal/MarshallTransformations/DescribeGlobalTableSettingsResponseUnmarshaller.cs | 4,505 | C# |
using System;
using System.Drawing;
using System.Windows.Forms;
using System.IO;
using System.Threading;
using System.Diagnostics;
namespace Mandelbrot
{
/// <summary>
/// Summary description for ImaginaryPlane.
/// </summary>
public class ImaginaryPlane
{
// private static ImaginaryPlaneRange DefaultImaginaryPlaneRange =
// new ImaginaryPlaneRange(-.1, .1, -.1, .1); // TODO: change back to 2's after refactoring
private static ImaginaryPlaneRange DefaultImaginaryPlaneRange =
new ImaginaryPlaneRange(-2, 2, -2, 2);
private static ClickBehaviourMode DefaultClickBehaviourMode =
ClickBehaviourMode.ZoomIn;
private static int DefaultZoomFactor = 2; // TODO: change back to 10
private Bitmap bmp;
private Graphics g;
private ColorScheme scheme;
private ImaginaryPlaneRange range;
private ProgressBar progressBar;
private ClickBehaviourMode clickBehaviourMode = DefaultClickBehaviourMode;
private int zoomFactor = DefaultZoomFactor;
public ImaginaryPlane(MandelbrotForm mandelbrotForm)
{
g = System.Drawing.Graphics.FromHwnd(mandelbrotForm.PictureBox.Handle);
bmp = new Bitmap(mandelbrotForm.PictureBox.Width, mandelbrotForm.PictureBox.Height);
range = DefaultImaginaryPlaneRange;
scheme = new SmoothFadeToWhite();
progressBar = mandelbrotForm.ProgressBar;
progressBar.Step = 1;
}
public ColorScheme ColorScheme
{
get
{
return scheme;
}
set
{
scheme = value;
}
}
public ClickBehaviourMode ClickBehaviourMode
{
get
{
return clickBehaviourMode;
}
set
{
clickBehaviourMode = value;
}
}
public int ZoomFactor
{
get
{
return zoomFactor;
}
set
{
if (value < 1)
{
throw new Exception("ZoomFactor must be >= 1");
}
zoomFactor = value;
}
}
public void DrawMandelbrot()
{
ThreadStart threadStart = new ThreadStart(DrawMandel);
Thread thread = new Thread(threadStart);
thread.Start();
}
private void DrawMandel()
{
if (progressBar != null)
{
progressBar.Minimum = 0;
progressBar.Maximum = bmp.Height;
progressBar.Value = 0;
}
lock(this)
{
// TODO: remove below
int startTickCount = System.Environment.TickCount;
// TODO: remove above
for (int y = 0; y < bmp.Height; y++)
{
for (int x = 0; x < bmp.Width; x++)
{
ImaginaryNumber C = ConvertToImaginaryNumber(x, y);
//FractalPoint p = Mandelbrot.TestNumber(C);
//FractalPoint p = Mandelbrot.TestNumberUnrollOnce(C);
FractalPoint p = Mandelbrot.TestNumberUnrollTwice(C);
//FractalPoint p = Mandelbrot.TestNumberUnrollThreeTimes(C);
//FractalPoint p = Mandelbrot.TestNumberUnrollFourTimes(C);
//FractalPoint p = Mandelbrot.TryThisOnForSize(C);
//FractalPoint p = Mandelbrot.TryUnrollingOnce(C);
//FractalPoint p = Mandelbrot.TryUnrollingTwice(C);
//FractalPoint p = Mandelbrot.TryUnrolllllling(C);
bmp.SetPixel(x, y, scheme.calculateColor(p));
}
if (progressBar != null)
{
progressBar.PerformStep();
}
}
// TODO: remove below
int endTickCount = System.Environment.TickCount;
int time = endTickCount - startTickCount;
Debug.WriteLine("Time to draw Mandelbrot: " + time.ToString());
// TODO: remove above
}
Paint();
if (progressBar != null)
{
progressBar.Value = 0;
}
}
public void SaveBitmapAs(string fileName)
{
bmp.Save(fileName);
}
public void Resized(Control drawingSurface)
{
lock(this)
{
range = CalculateNewRange(drawingSurface.Size);
g = System.Drawing.Graphics.FromHwnd(drawingSurface.Handle);
bmp = new Bitmap(drawingSurface.Width, drawingSurface.Height);
}
DrawMandelbrot();
}
private ImaginaryPlaneRange CalculateNewRange(Size newSize)
{
/* if newSize bigger
* widthDiff is negative
* heightDiff is negitave
*
* if newSize smaller
* widthDiff is positive
* heightDiff is positive
*/
double centerRangeA = (range.aMin + range.aMax) / 2.0;
double centerRangeBi = (range.biMin + range.biMax) / 2.0;
double oldAMin = range.aMin;
double oldAMax = range.aMax;
double oldBiMin = range.biMin;
double oldBiMax = range.biMax;
double oldRangeWidth = oldAMax - oldAMin;
double oldRangeHeight = oldBiMax - oldBiMin;
int oldWidth = bmp.Width;
int oldHeight = bmp.Height;
double newAMin;
double newAMax;
double newBiMin;
double newBiMax;
double newRangeWidth;
double newRangeHeight;
int newWidth = newSize.Width;
int newHeight = newSize.Height;
newRangeWidth = (oldRangeWidth * newWidth) / oldWidth;
newRangeHeight = (oldRangeHeight * newHeight) / oldHeight;
newAMin = centerRangeA - (newRangeWidth / 2.0);
newAMax = centerRangeA + (newRangeWidth / 2.0);
newBiMin = centerRangeBi - (newRangeHeight / 2.0);
newBiMax = centerRangeBi + (newRangeHeight / 2.0);
ImaginaryPlaneRange newRange = new ImaginaryPlaneRange(
newAMin, newAMax, newBiMin, newBiMax);
return newRange;
}
public void Transform(int x, int y)
{
switch (ClickBehaviourMode)
{
case ClickBehaviourMode.ZoomIn:
Shift(x, y, (1.0 / zoomFactor));
break;
case ClickBehaviourMode.ZoomOut:
Shift(x, y, zoomFactor);
break;
case ClickBehaviourMode.Move:
Shift(x, y, 1);
break;
case ClickBehaviourMode.DoNothing:
break;
}
}
private void Shift(int x, int y, double factor)
{
//do the actual Shift here.
double aDif = range.aMax - range.aMin;
double biDif = range.biMax - range.biMin;
ImaginaryNumber i = ConvertToImaginaryNumber(x, y);
range.aMax = i.a() + (aDif / 2) * factor;
range.aMin = i.a() - (aDif / 2) * factor;
range.biMax = i.bi() + (biDif / 2) * factor;
range.biMin = i.bi() - (biDif / 2) * factor;
DrawMandelbrot();
}
private ImaginaryNumber ConvertToImaginaryNumber(double x, double y)
{
double a = x * ((range.aMax - range.aMin) / bmp.Width) + range.aMin;
double bi = (bmp.Height - y) * ((range.biMax - range.biMin) / bmp.Height) + range.biMin;
return new ImaginaryNumber(a, bi);
}
public void Paint()
{
System.Threading.ThreadStart threadStart = new ThreadStart(this.PaintThread);
Thread thread = new Thread(threadStart);
thread.Start();
}
private void PaintThread()
{
lock(this)
{
g.DrawImage(bmp, new System.Drawing.Point(0, 0));
}
}
}
/*
//public const int MANDELBROT = -99;
//public const int JULIA = -98;
//private int whichFractal = JULIA;
public void DrawJulia(int threadNumber)
{
for (int x = 0; x < threadNumber; x++)
{
ThreadStart threadStart = new ThreadStart(drawJul);
Thread thread = new Thread(threadStart);
//thread.Priority = thread.Priority + 1;
thread.Start();
}
}
internal class JuliaThread : Thread
{
//
}
private void DrawJul()
{
if (progressBar != null)
{
progressBar.Minimum = 0;
progressBar.Maximum = bmp.Height;
progressBar.Value = 0;
}
lock (this)
{
;
}
}
*/
}
| 23.539735 | 93 | 0.664369 | [
"MIT"
] | bfriesen/Mandelbrot | ImaginaryPlane.cs | 7,109 | C# |
using Npgsql;
using Spurious2.Core.LcboImporting.Domain;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
namespace Spurious2.Repositories.LcboImporting.Repositories
{
public class ProductRepository : IProductRepository
{
readonly NpgsqlConnection connection;
public ProductRepository(NpgsqlConnection connection)
{
this.connection = connection;
}
public async Task Import(IEnumerable<Product> products)
{
if (products == null)
{
throw new ArgumentNullException(nameof(products));
}
await this.connection.OpenAsync().ConfigureAwait(false);
try
{
using (var command = this.connection.CreateCommand())
{
command.CommandText = "DELETE FROM product_incoming";
await command.ExecuteNonQueryAsync().ConfigureAwait(false);
}
using (var writer = this.connection.BeginBinaryImport("COPY product_incoming (id, name, category, volume) FROM STDIN (FORMAT BINARY)"))
{
foreach (var product in products)
{
writer.StartRow();
writer.Write(product.ItemNumber, NpgsqlTypes.NpgsqlDbType.Integer);
writer.Write(product.ItemName, NpgsqlTypes.NpgsqlDbType.Text);
writer.Write(product.LiquorType, NpgsqlTypes.NpgsqlDbType.Text);
writer.Write(product.PackageVolume, NpgsqlTypes.NpgsqlDbType.Integer);
}
writer.Complete();
}
// Call sproc to update table and clear incoming table
using (var command = this.connection.CreateCommand())
{
command.CommandText = "call update_products_from_incoming()";
command.CommandType = System.Data.CommandType.Text;
command.CommandTimeout = 60000;
await command.ExecuteNonQueryAsync().ConfigureAwait(false);
}
}
finally
{
this.connection.Close();
}
}
public async Task<IEnumerable<int>> GetProductIds()
{
var result = new List<int>();
await this.connection.OpenAsync().ConfigureAwait(false);
try
{
using (var command = this.connection.CreateCommand())
{
command.CommandText = "select id from products order by id asc";
using (var reader = await command.ExecuteReaderAsync().ConfigureAwait(false))
{
while (await reader.ReadAsync().ConfigureAwait(false))
{
result.Add(Convert.ToInt32(reader["id"], CultureInfo.InvariantCulture));
}
}
}
}
finally
{
this.connection.Close();
}
return result;
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
this.connection?.Dispose();
}
}
public void Dispose()
{
// Do not change this code. Put cleanup code in Dispose(bool disposing) above.
this.Dispose(true);
GC.SuppressFinalize(this);
}
}
}
| 34.271028 | 151 | 0.52168 | [
"MIT"
] | claq2/spurious2 | Spurious2.Repositories/LcboImporting/Repositories/ProductRepository.cs | 3,669 | C# |
// Licensed to Finnovation Labs Limited under one or more agreements.
// Finnovation Labs Limited licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Net.Http;
using System.Reflection;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using FinnovationLabs.OpenBanking.Library.Connector.BankProfiles;
using FinnovationLabs.OpenBanking.Library.Connector.BankTests.Instrumentation;
using FinnovationLabs.OpenBanking.Library.Connector.Configuration;
using FinnovationLabs.OpenBanking.Library.Connector.Fluent;
using FinnovationLabs.OpenBanking.Library.Connector.Http;
using FinnovationLabs.OpenBanking.Library.Connector.Instrumentation;
using FinnovationLabs.OpenBanking.Library.Connector.Mapping;
using FinnovationLabs.OpenBanking.Library.Connector.Models.Configuration;
using FinnovationLabs.OpenBanking.Library.Connector.Models.Persistent;
using FinnovationLabs.OpenBanking.Library.Connector.Models.Public;
using FinnovationLabs.OpenBanking.Library.Connector.Persistence;
using FinnovationLabs.OpenBanking.Library.Connector.Repositories;
using FinnovationLabs.OpenBanking.Library.Connector.Security;
using FinnovationLabs.OpenBanking.Library.Connector.Services;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using NSubstitute;
using RichardSzalay.MockHttp;
using Xunit;
using Xunit.Abstractions;
namespace FinnovationLabs.OpenBanking.Library.Connector.BankTests.BankTests
{
[Collection("App context collection")]
public partial class PlainAppTests : AppTests, IDisposable
{
private readonly SqliteConnection _connection;
private readonly DbContextOptions<SqliteDbContext> _dbContextOptions;
public PlainAppTests(ITestOutputHelper outputHelper, AppContextFixture appContextFixture) : base(
outputHelper,
appContextFixture)
{
TestConfig = new TestConfigurationProvider();
_connection = new SqliteConnection("DataSource=:memory:");
_connection.Open(); // Creates DB
_dbContextOptions = new DbContextOptionsBuilder<SqliteDbContext>()
.UseSqlite(_connection)
.Options;
using var context = new SqliteDbContext(_dbContextOptions);
context.Database.EnsureCreated(); // Initialise DB with schema
}
public ITestConfigurationProvider TestConfig { get; }
public void Dispose()
{
_connection.Close(); // Deletes DB
}
private BaseDbContext GetDbContext() => new SqliteDbContext(_dbContextOptions);
[Theory]
[MemberData(
nameof(TestedSkippedBanksById),
false,
Skip = "Bank skipped due to setting of" +
nameof(BankProfile.ClientRegistrationApiSettings.UseRegistrationScope) + "in bank profile")]
[MemberData(
nameof(TestedUnskippedBanksById),
false)]
public async Task TestAllNoConsentAuth(
BankProfileEnum bank,
SoftwareStatementProfileData softwareStatementProfile,
RegistrationScope registrationScope)
{
// Collect settings from configuration (to ensure common settings with Generic Host tests;
// a "plain app" might get settings from environment variables or a custom system;
// see comment in next section).
IConfigurationRoot configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", false, true)
.AddUserSecrets(typeof(PlainAppTests).GetTypeInfo().Assembly)
.AddEnvironmentVariables()
.Build();
var obcSettings = configuration
.GetSection(new OpenBankingConnectorSettings().SettingsSectionName)
.Get<OpenBankingConnectorSettings>();
var softwareStatementProfilesSettings = configuration
.GetSection(new SoftwareStatementProfilesSettings().SettingsSectionName)
.Get<SoftwareStatementProfilesSettings>();
var obTransportCertificateProfilesSettings = configuration
.GetSection(new TransportCertificateProfilesSettings().SettingsSectionName)
.Get<TransportCertificateProfilesSettings>();
var obSigningCertificateProfilesSettings = configuration
.GetSection(new SigningCertificateProfilesSettings().SettingsSectionName)
.Get<SigningCertificateProfilesSettings>();
// Create providers from settings
// TODO: update to write settings to environment variables and then use EnvironmentVariablesSettingsProvider to get
// settings as might be done in a "plain app".
var obcSettingsProvider =
new DefaultSettingsProvider<OpenBankingConnectorSettings>(obcSettings);
var softwareStatementProfilesSettingsProvider =
new DefaultSettingsProvider<SoftwareStatementProfilesSettings>(softwareStatementProfilesSettings);
var obTransportCertificateProfilesSettingsProvider =
new DefaultSettingsProvider<TransportCertificateProfilesSettings>(
obTransportCertificateProfilesSettings);
var obSigningCertificateProfilesSettingsProvider =
new DefaultSettingsProvider<SigningCertificateProfilesSettings>(obSigningCertificateProfilesSettings);
// Create stores
var timeProvider = new TimeProvider();
var instrumentationClient = new TestInstrumentationClient(_outputHelper, timeProvider);
var processedSoftwareStatementProfileStore = new ProcessedSoftwareStatementProfileStore(
obcSettingsProvider,
softwareStatementProfilesSettingsProvider,
obTransportCertificateProfilesSettingsProvider,
obSigningCertificateProfilesSettingsProvider,
instrumentationClient);
// Run test
var apiVariantMapper = new ApiVariantMapper();
var apiClient = new ApiClient(instrumentationClient, new HttpClient());
await TestAllInner(
bank,
softwareStatementProfile,
registrationScope,
() => new RequestBuilderContainer(
timeProvider,
apiVariantMapper,
instrumentationClient,
apiClient,
processedSoftwareStatementProfileStore,
GetDbContext()),
false);
}
public IApiClient GetApiClient()
{
if (TestConfig.GetBooleanValue("mockHttp").GetValueOrDefault(false))
{
var mockHttp = new MockHttpMessageHandler();
OpenIdConfiguration openIdConfigData = TestConfig.GetOpenBankingOpenIdConfiguration()!;
string openIdConfig = JsonConvert.SerializeObject(openIdConfigData);
mockHttp.When(HttpMethod.Get, "https://issuer.com/.well-known/openid-configuration")
.Respond("application/json", openIdConfig);
mockHttp.When(HttpMethod.Get, "").Respond("application/json", "{}");
mockHttp.When(HttpMethod.Post, "").Respond("application/json", "{}");
var client = mockHttp.ToHttpClient();
return new ApiClient(Substitute.For<IInstrumentationClient>(), client);
}
X509Certificate2 certificate = CertificateFactories.GetCertificate2FromPem(
TestConfig.GetValue("transportcertificatekey")!,
TestConfig.GetValue("transportCertificate")!)!;
HttpMessageHandler handler = new HttpRequestBuilder()
.SetClientCertificate(certificate)
.CreateMessageHandler();
return ApiClientFactory.CreateApiClient(handler);
}
}
}
| 47.22093 | 127 | 0.683822 | [
"MIT"
] | finlabsuk/open-banking-connector | test/OpenBanking.Library.Connector.BankTests/BankTests/PlainAppTests.cs | 8,124 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace Texxtoor.BaseLibrary.Core.Utilities.Imaging.Barcode
{
/// <summary>
/// Barcode interface for symbology layout.
/// Written by: Brad Barnhill
/// </summary>
interface IBarcode
{
string Encoded_Value
{
get;
}//Encoded_Value
string RawData
{
get;
}//Raw_Data
List<string> Errors
{
get;
}//Errors
}//interface
}//namespace
| 17.966667 | 61 | 0.552876 | [
"Apache-2.0"
] | joergkrause/texxtoor | Texxtoor/Solution/Texxtoor.BaseLibrary.Core/Utilities/Imaging/Barcode/IBarcode.cs | 539 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using PluginCore;
namespace ASCompletion.Model
{
/// <summary>
/// Object representation of an ActionScript MemberModel
/// </summary>
[Serializable]
public class MemberModel: ICloneable, IComparable
{
const string TypedCallbackHLStart = "<[BGCOLOR=#2F90:NORMAL]"; // <- with alpha (0x02)
const string TypedCallbackHLEnd = "[/BGCOLOR]>";
public FileModel InFile;
public bool IsPackageLevel;
public FlagType Flags;
public Visibility Access;
public string Namespace;
public string Name;
public List<MemberModel> Parameters;
public string Type;
public string Template;
public string Comments;
public string Value;
public int ValueEndPosition = -1;
public int LineFrom;
public int LineTo;
public List<ASMetaData> MetaDatas;
public int StartPosition = -1;
public MemberModel()
{
}
public MemberModel(string name, string type, FlagType flags, Visibility access)
{
Name = name;
Type = type;
Flags = flags;
Access = access;
}
public virtual string FullName
{
get
{
if (Template is null) return Name;
return Name + Template;
}
}
/// <inheritdoc />
public object Clone()
{
var result = new MemberModel();
result.Name = Name;
result.Template = Template;
result.Flags = Flags;
result.Access = Access;
result.Namespace = Namespace;
result.InFile = InFile;
result.IsPackageLevel = IsPackageLevel;
result.Parameters = Parameters?.Select(it => (MemberModel) it.Clone()).ToList();
result.Type = Type;
result.Comments = Comments;
result.Value = Value;
result.ValueEndPosition = ValueEndPosition;
result.LineFrom = LineFrom;
result.LineTo = LineTo;
result.StartPosition = StartPosition;
return result;
}
public override string ToString()
{
var result = FullName;
var type = !string.IsNullOrEmpty(Type) ? FormatType(Type) : null;
if ((Flags & FlagType.Function) > 0)
{
var declaration = "(" + ParametersString(true) + ")";
if ((Flags & FlagType.Variable) > 0)
{
if (!string.IsNullOrEmpty(type)) declaration += ":" + type;
result += " : Function" + TypedCallbackHLStart + declaration + TypedCallbackHLEnd;
return result;
}
result += " " + declaration;
}
else if ((Flags & (FlagType.Setter | FlagType.Getter)) > 0)
{
if ((Flags & FlagType.Setter) > 0)
{
if (!Parameters.IsNullOrEmpty() && !string.IsNullOrEmpty(Parameters[0].Type))
return result + " : " + FormatType(Parameters[0].Type);
}
}
if ((Flags & FlagType.Constructor) > 0) return result;
if (!string.IsNullOrEmpty(type)) result += " : " + type;
return result;
}
public string ToDeclarationString() => ToDeclarationString(true, false);
public string ToDeclarationString(bool wrapWithSpaces, bool concatValue)
{
string result = FullName;
string colon = wrapWithSpaces ? " : " : ":";
string type = null;
string comment = "";
if ((Flags & (FlagType.Function | FlagType.Setter | FlagType.Getter)) > 0)
{
if ((Flags & FlagType.Function) > 0 && (Flags & FlagType.Getter | Flags & FlagType.Variable) > 0)
{
if ((Flags & FlagType.Variable) == 0)
result += "()";
type = "Function";
if (!Parameters.IsNullOrEmpty())
{
comment = "/*(" + ParametersString(true) + ")";
if (!string.IsNullOrEmpty(Type)) comment += colon + FormatType(Type);
comment += "*/";
}
}
else
{
result += "(" + ParametersString(true) + ")";
}
}
if (string.IsNullOrEmpty(type) && !string.IsNullOrEmpty(Type))
type = FormatType(Type);
if ((Flags & FlagType.Constructor) > 0) return result;
if (!string.IsNullOrEmpty(type)) result += colon + type;
result += comment;
if (concatValue && Value != null)
result += (wrapWithSpaces ? " = " : "=") + Value.Trim();
return result;
}
public string ParametersString() => ParametersString(false);
public string ParametersString(bool formatted)
{
var result = "";
if (!Parameters.IsNullOrEmpty())
{
var addSep = false;
foreach (var param in Parameters)
{
if (addSep) result += ", ";
else addSep = true;
result += param.ToDeclarationString(false, true);
}
}
return result;
}
public override bool Equals(object obj) => obj is MemberModel to && Name == to.Name && Flags == to.Flags;
public override int GetHashCode() => (Name + Flags).GetHashCode();
public int CompareTo(object obj)
{
if (!(obj is MemberModel)) throw new InvalidCastException("This object is not of type MemberModel");
var to = (MemberModel)obj;
if (Name == to.Name) return Flags.CompareTo(to.Flags);
return string.Compare(Name, to.Name, false);
}
public static string FormatType(string type) => FormatType(type, false);
public static string FormatType(string type, bool allowBBCode)
{
if (string.IsNullOrEmpty(type)) return null;
var p = type.IndexOf('@');
if (p == -1) return type;
var bbCodeOpen = allowBBCode ? "[BGCOLOR=#EEE:SUBTRACT]" : "";
var bbCodeClose = allowBBCode ? "[/BGCOLOR]" : "";
if (type.Substring(0, p) == "Array") return $"{type.Substring(0, p)}{bbCodeOpen}/*{type.Substring(p + 1)}*/{bbCodeClose}";
if (type.Contains("<T>", out var p1) && p1 > 0) return $"{type.Substring(0, p1)}{bbCodeOpen}<{type.Substring(p + 1)}>{bbCodeClose}";
return $"{bbCodeOpen}/*{type.Substring(p + 1)}*/{bbCodeClose}{type.Substring(0, p)}";
}
}
/// <summary>
/// Strong-typed MemberModel list with special merging/searching methods
/// </summary>
[Serializable]
public class MemberList: IEnumerable<MemberModel>
{
bool sorted;
public IEnumerator<MemberModel> GetEnumerator() => items.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => items.GetEnumerator();
readonly List<MemberModel> items = new List<MemberModel>();
public List<MemberModel> Items => items;
public int Count => items.Count;
public MemberList()
{
}
public MemberList(IEnumerable<MemberModel> list)
{
Items.AddRange(list);
}
public MemberModel this[int index]
{
get => items[index];
set
{
sorted = false;
items[index] = value;
}
}
public int Add(MemberModel value)
{
sorted = false;
items.Add(value);
return items.Count;
}
public int Add(MemberList list)
{
sorted = false;
items.AddRange(list);
return items.Count;
}
public void Insert(int index, MemberModel value)
{
sorted = false;
items.Insert(index, value);
}
public void Remove(MemberModel value) => items.Remove(value);
public void Remove(string name)
{
var member = Search(name, 0, 0);
if (member != null) items.Remove(member);
}
public void Clear()
{
sorted = true;
items.Clear();
}
public bool Contains(string name, FlagType mask, Visibility access) => Search(name, mask, access) != null;
/// <summary>
/// Return the first MemberModel instance match in the MemberList
/// </summary>
/// <param name="name">Member name to mach</param>
/// <param name="mask">Flags mask</param>
/// <param name="access">Visibility mask</param>
/// <returns>First match</returns>
public MemberModel Search(string name, FlagType mask, Visibility access)
{
var count = items.Count;
for (var i = 0; i < count; i++)
{
var m = items[i];
if (((m.Flags & mask) == mask)
&& (access == 0 || (m.Access & access) > 0)
&& m.Name == name) return m;
}
return null;
}
/// <summary>
/// Return all MemberModel instance matches in the MemberList
/// </summary>
/// <param name="name">Member name to match</param>
/// <param name="mask">Flags mask</param>
/// <param name="access">Visibility mask</param>
/// <returns>All matches</returns>
public MemberList MultipleSearch(string name, FlagType mask, Visibility access)
{
var result = new MemberList();
foreach (var m in items)
if ((m.Flags & mask) == mask
&& (access == 0 || (m.Access & access) > 0)
&& m.Name == name) result.Add(m);
return result;
}
public void Sort() => Sort(null);
public void Sort(IComparer<MemberModel> comparer)
{
if (sorted) return;
items.Sort(comparer);
sorted = true;
}
/// <summary>
/// Merge one item into the list
/// </summary>
/// <param name="item">Item to merge</param>
public void Merge(MemberModel item)
{
if (item != null) Merge(new MemberList {item});
}
/// <summary>
/// Merge SORTED lists without duplicate values
/// </summary>
/// <param name="list">Items to merge</param>
public void Merge(IEnumerable<MemberModel> list)
{
if (list is null) return;
var index = 0;
foreach (var it in list)
{
var added = false;
while (index < items.Count)
{
var item = items[index];
if (it.Name.CompareTo(item.Name) <= 0)
{
if (it.Name != item.Name) items.Insert(index, it);
else if ((item.Flags & FlagType.Setter) > 0)
{
items.RemoveAt(index);
items.Insert(index, it);
}
added = true;
break;
}
index++;
}
if (!added) items.Add(it);
}
}
public void MergeByLine(MemberModel item)
{
if (item is null) return;
var index = 0;
var added = false;
while (index < items.Count)
{
if (item.LineFrom <= items[index].LineFrom)
{
items.Insert(index, item);
added = true;
break;
}
index++;
}
if (!added) items.Add(item);
}
/// <summary>
/// Merge ORDERED (by line) lists
/// </summary>
/// <param name="list">Items to merge</param>
public void MergeByLine(MemberList list)
{
if (list is null) return;
var index = 0;
foreach (MemberModel item in list)
{
var added = false;
while (index < items.Count)
{
if (item.LineFrom <= items[index].LineFrom)
{
items.Insert(index, item);
added = true;
break;
}
index++;
}
if (!added) items.Add(item);
}
}
/// <summary>
/// Merge selected items from the SORTED lists without duplicate values
/// </summary>
/// <param name="list">Items to merge</param>
public void Merge(MemberList list, FlagType mask, Visibility access)
{
if (list is null) return;
int index = 0;
foreach (MemberModel m in list)
if ((m.Flags & mask) == mask && (m.Access & access) > 0)
{
var added = false;
while (index < items.Count)
{
var item = items[index];
if (m.Name.CompareTo(item.Name) <= 0)
{
if (m.Name != item.Name) Items.Insert(index, m);
else if ((item.Flags & FlagType.Setter) > 0)
{
items.RemoveAt(index);
items.Insert(index, m);
}
added = true;
break;
}
index++;
}
if (!added) items.Add(m);
}
}
public void RemoveAllWithFlag(FlagType flag) => Items.RemoveAll(m => (m.Flags & flag) > 0);
public void RemoveAllWithoutFlag(FlagType flag) => Items.RemoveAll(m => (m.Flags & flag) == 0);
}
public class ByKindMemberComparer : IComparer<MemberModel>
{
public int Compare(MemberModel a, MemberModel b) => GetPriority(a.Flags).CompareTo(GetPriority(b.Flags));
static uint GetPriority(FlagType flag)
{
if ((flag & FlagType.Constant) > 0) return 4;
if ((flag & FlagType.Variable) > 0) return 3;
if ((flag & (FlagType.Getter | FlagType.Setter)) > 0) return 2;
return 1;
}
}
public class SmartMemberComparer : IComparer<MemberModel>
{
public int Compare(MemberModel a, MemberModel b)
{
var cmp = GetPriority(a).CompareTo(GetPriority(b));
return cmp != 0 ? cmp : StringComparer.Ordinal.Compare(a.Name,b.Name);
}
static uint GetPriority(MemberModel m)
{
uint visibility_pri;
if ((m.Access & Visibility.Public) > 0) visibility_pri = 1;
else if ((m.Access & Visibility.Protected) > 0) visibility_pri = 2;
else if ((m.Access & Visibility.Private) > 0) visibility_pri = 3;
else visibility_pri = 4;
uint type_pri;
if ((m.Flags & FlagType.Constant) > 0) type_pri = 50;
else if ((m.Flags & FlagType.Variable) > 0) type_pri = 30;
else if ((m.Flags & (FlagType.Getter | FlagType.Setter)) > 0) type_pri = 30;
else if ((m.Flags & FlagType.Constructor) > 0) type_pri = 20;
else type_pri = 10;
return visibility_pri + type_pri;
}
}
public class ByDeclarationPositionMemberComparer : IComparer<MemberModel>
{
public int Compare(MemberModel a, MemberModel b) => a.LineFrom - b.LineFrom;
}
/// <summary>
/// Compare members based on import name
/// </summary>
public class CaseSensitiveImportComparer : IComparer<MemberModel>
{
static int GetPackageTypeSeparation(string import)
{
var dot = import.IndexOf('.');
var lastDot = -1;
var max = import.Length - 1;
while (dot > 0 && dot < max)
{
if (char.IsUpper(import[dot + 1]))
return dot;
lastDot = dot;
dot = import.IndexOf('.', dot + 1);
}
if (dot < 0 || dot >= max) return lastDot;
if (dot == 0) return -1;
return dot;
}
public static int CompareImports(string import1, string import2)
{
IComparer<string> cmp = StringComparer.Ordinal;
var d1 = GetPackageTypeSeparation(import1);
var d2 = GetPackageTypeSeparation(import2);
// one or both imports do not have a package
if (d1 < 0)
{
if (d2 > 0) return -1;
return cmp.Compare(import1, import2);
}
if (d2 < 0)
{
if (d1 > 0) return 1;
return cmp.Compare(import1, import2);
}
// compare package
var pkg1 = import1.Substring(0, d1);
var pkg2 = import2.Substring(0, d2);
var result = cmp.Compare(pkg1, pkg2);
if (result != 0) return result;
// compare type
var tp1 = import1.Substring(d1 + 1);
var tp2 = import2.Substring(d2 + 1);
result = cmp.Compare(tp1, tp2);
return result;
}
#if DEBUG
static void Assert(int res, int expected)
{
System.Diagnostics.Debug.Assert(res == expected, res + " was not expected " + expected);
}
static CaseSensitiveImportComparer()
{
// poor man's unit tests
Assert(GetPackageTypeSeparation("a.b.C"), 3);
Assert(GetPackageTypeSeparation("a.b.c"), 3);
Assert(GetPackageTypeSeparation("a.b.C.D"), 3);
Assert(GetPackageTypeSeparation("a"), -1);
Assert(GetPackageTypeSeparation(".a"), -1);
Assert(GetPackageTypeSeparation("a."), -1);
Assert(GetPackageTypeSeparation("a.b.c."), 3);
Assert(CompareImports("a", "A"), 32);
Assert(CompareImports("a", "b"), -1);
Assert(CompareImports("b", "a"), 1);
Assert(CompareImports("a", "a"), 0);
Assert(CompareImports("a.A", "b"), 1);
Assert(CompareImports("a", "b.B"), -1);
Assert(CompareImports("a.A", "b.A"), -1);
Assert(CompareImports("b.A", "a.A"), 1);
Assert(CompareImports("a.A", "a.A"), 0);
Assert(CompareImports("a.A", "a.B"), -1);
Assert(CompareImports("b.A", "a.A"), 1);
Assert(CompareImports("a.A", "a.a"), -32);
Assert(CompareImports("a.MathReal", "a.Mathematics"), -19);
}
#endif
public int Compare(string import1, string import2) => CompareImports(import1, import2);
public int Compare(MemberModel item1, MemberModel item2) => CompareImports(item1.Type, item2.Type);
}
} | 35.854867 | 145 | 0.474529 | [
"MIT"
] | Acidburn0zzz/flashdevelop | External/Plugins/ASCompletion/Model/MemberModel.cs | 19,694 | C# |
using Content.Shared.Input;
using Robust.Shared.Input;
namespace Content.Client.Input
{
/// <summary>
/// Contains a helper function for setting up all content
/// contexts, and modifying existing engine ones.
/// </summary>
public static class ContentContexts
{
public static void SetupContexts(IInputContextContainer contexts)
{
var common = contexts.GetContext("common");
common.AddFunction(ContentKeyFunctions.FocusChat);
common.AddFunction(ContentKeyFunctions.FocusLocalChat);
common.AddFunction(ContentKeyFunctions.FocusRadio);
common.AddFunction(ContentKeyFunctions.FocusOOC);
common.AddFunction(ContentKeyFunctions.FocusAdminChat);
common.AddFunction(ContentKeyFunctions.FocusConsoleChat);
common.AddFunction(ContentKeyFunctions.FocusDeadChat);
common.AddFunction(ContentKeyFunctions.CycleChatChannelForward);
common.AddFunction(ContentKeyFunctions.CycleChatChannelBackward);
common.AddFunction(ContentKeyFunctions.ExamineEntity);
common.AddFunction(ContentKeyFunctions.OpenInfo);
common.AddFunction(ContentKeyFunctions.TakeScreenshot);
common.AddFunction(ContentKeyFunctions.TakeScreenshotNoUI);
common.AddFunction(ContentKeyFunctions.Point);
var human = contexts.GetContext("human");
human.AddFunction(ContentKeyFunctions.SwapHands);
human.AddFunction(ContentKeyFunctions.Drop);
human.AddFunction(ContentKeyFunctions.ActivateItemInHand);
human.AddFunction(ContentKeyFunctions.OpenCharacterMenu);
human.AddFunction(ContentKeyFunctions.ActivateItemInWorld);
human.AddFunction(ContentKeyFunctions.ThrowItemInHand);
human.AddFunction(ContentKeyFunctions.TryPullObject);
human.AddFunction(ContentKeyFunctions.MovePulledObject);
human.AddFunction(ContentKeyFunctions.ReleasePulledObject);
human.AddFunction(ContentKeyFunctions.OpenContextMenu);
human.AddFunction(ContentKeyFunctions.OpenCraftingMenu);
human.AddFunction(ContentKeyFunctions.OpenInventoryMenu);
human.AddFunction(ContentKeyFunctions.SmartEquipBackpack);
human.AddFunction(ContentKeyFunctions.SmartEquipBelt);
human.AddFunction(ContentKeyFunctions.MouseMiddle);
human.AddFunction(ContentKeyFunctions.WideAttack);
human.AddFunction(ContentKeyFunctions.ArcadeUp);
human.AddFunction(ContentKeyFunctions.ArcadeDown);
human.AddFunction(ContentKeyFunctions.ArcadeLeft);
human.AddFunction(ContentKeyFunctions.ArcadeRight);
human.AddFunction(ContentKeyFunctions.Arcade1);
human.AddFunction(ContentKeyFunctions.Arcade2);
human.AddFunction(ContentKeyFunctions.Arcade3);
// actions should be common (for ghosts, mobs, etc)
common.AddFunction(ContentKeyFunctions.OpenActionsMenu);
common.AddFunction(ContentKeyFunctions.Hotbar0);
common.AddFunction(ContentKeyFunctions.Hotbar1);
common.AddFunction(ContentKeyFunctions.Hotbar2);
common.AddFunction(ContentKeyFunctions.Hotbar3);
common.AddFunction(ContentKeyFunctions.Hotbar4);
common.AddFunction(ContentKeyFunctions.Hotbar5);
common.AddFunction(ContentKeyFunctions.Hotbar6);
common.AddFunction(ContentKeyFunctions.Hotbar7);
common.AddFunction(ContentKeyFunctions.Hotbar8);
common.AddFunction(ContentKeyFunctions.Hotbar9);
common.AddFunction(ContentKeyFunctions.Loadout1);
common.AddFunction(ContentKeyFunctions.Loadout2);
common.AddFunction(ContentKeyFunctions.Loadout3);
common.AddFunction(ContentKeyFunctions.Loadout4);
common.AddFunction(ContentKeyFunctions.Loadout5);
common.AddFunction(ContentKeyFunctions.Loadout6);
common.AddFunction(ContentKeyFunctions.Loadout7);
common.AddFunction(ContentKeyFunctions.Loadout8);
common.AddFunction(ContentKeyFunctions.Loadout9);
var ghost = contexts.New("ghost", "common");
ghost.AddFunction(EngineKeyFunctions.MoveUp);
ghost.AddFunction(EngineKeyFunctions.MoveDown);
ghost.AddFunction(EngineKeyFunctions.MoveLeft);
ghost.AddFunction(EngineKeyFunctions.MoveRight);
ghost.AddFunction(EngineKeyFunctions.Walk);
ghost.AddFunction(ContentKeyFunctions.OpenContextMenu);
common.AddFunction(ContentKeyFunctions.OpenEntitySpawnWindow);
common.AddFunction(ContentKeyFunctions.OpenSandboxWindow);
common.AddFunction(ContentKeyFunctions.OpenTileSpawnWindow);
common.AddFunction(ContentKeyFunctions.OpenAdminMenu);
}
}
}
| 54.065217 | 77 | 0.708886 | [
"MIT"
] | Bokkiewokkie/space-station-14 | Content.Client/Input/ContentContexts.cs | 4,974 | C# |
// Copyright (c) 20016-2018 Peter M.
//
// File: SudnyExekutorOprava_udajov.cs
// Company: MalikP.
//
// 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.Xml.Serialization;
namespace MalikP.BusinessJournal.Models.V1.Drazba
{
[Serializable]
[XmlType(AnonymousType = true)]
public class SudnyExekutorOprava_udajov
{
public string v_casti { get; set; }
public string text_stary { get; set; }
public string text_novy { get; set; }
}
} | 38.325 | 73 | 0.737769 | [
"MIT"
] | peterM/Obchodny-Vestnik-SR | src/MalikP.BusinessJournal.Models.V1/Drazba/SudnyExekutorOprava_udajov.cs | 1,535 | C# |
// 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.ComponentModel.Composition;
using System.Linq;
using System.Windows.Forms;
using DotSpatial.Controls.Header;
using DotSpatial.Extensions;
namespace DotSpatial.Controls.DefaultRequiredImports
{
/// <summary>
/// Default Header control. It will be used when no custom implementation of IHeaderControl can be found.
/// </summary>
[Export(typeof(IHeaderControl))]
[DefaultRequiredImport]
internal class HeaderControl : MenuBarHeaderControl, ISatisfyImportsExtension
{
#region Fields
private bool _isActivated;
#endregion
#region Properties
/// <inheritdoc />
public int Priority => 1;
[Import]
private AppManager App { get; set; }
[Import("Shell", typeof(ContainerControl))]
private ContainerControl Shell { get; set; }
#endregion
#region Methods
/// <inheritdoc />
public void Activate()
{
if (_isActivated) return;
var headerControls = App.CompositionContainer.GetExportedValues<IHeaderControl>().ToList();
// Activate only if there are no other IHeaderControl implementations and
// custom HeaderControl not yet set
if (App.HeaderControl == null && headerControls.Count == 1 && headerControls[0].GetType() == GetType())
{
_isActivated = true;
var container = new ToolStripPanel
{
Dock = DockStyle.Top
};
Shell.Controls.Add(container);
var menuStrip = new MenuStrip
{
Name = DefaultGroupName,
Dock = DockStyle.Top
};
Shell.Controls.Add(menuStrip);
Initialize(container, menuStrip);
App.ExtensionsActivated += (sender, args) => LoadToolstrips();
// Add default buttons
new DefaultMenuBars(App).Initialize(this);
}
}
#endregion
}
} | 30.473684 | 116 | 0.568653 | [
"MIT"
] | AlexanderSemenyak/DotSpatial | Source/DotSpatial.Controls/DefaultRequiredImports/HeaderControl.cs | 2,318 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("MCD.CMD")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MCD.CMD")]
[assembly: AssemblyCopyright("Copyright © Gabriël Konat 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("bb8c57d4-6fa1-4108-a6e9-4b901546af55")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.1.0.0")]
[assembly: AssemblyFileVersion("0.1.0.0")]
| 37.837838 | 84 | 0.743571 | [
"MIT"
] | Gohla/MTGCardDetection | MCD.CMD/Properties/AssemblyInfo.cs | 1,404 | C# |
#pragma warning disable 108 // new keyword hiding
#pragma warning disable 114 // new keyword hiding
namespace Windows.ApplicationModel.DataTransfer
{
#if __ANDROID__ || __IOS__ || NET46 || false || __MACOS__
[global::Uno.NotImplemented]
#endif
public partial class DataPackage
{
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public global::Windows.ApplicationModel.DataTransfer.DataPackageOperation RequestedOperation
{
get
{
throw new global::System.NotImplementedException("The member DataPackageOperation DataPackage.RequestedOperation is not implemented in Uno.");
}
set
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.ApplicationModel.DataTransfer.DataPackage", "DataPackageOperation DataPackage.RequestedOperation");
}
}
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public global::Windows.ApplicationModel.DataTransfer.DataPackagePropertySet Properties
{
get
{
throw new global::System.NotImplementedException("The member DataPackagePropertySet DataPackage.Properties is not implemented in Uno.");
}
}
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public global::System.Collections.Generic.IDictionary<string, global::Windows.Storage.Streams.RandomAccessStreamReference> ResourceMap
{
get
{
throw new global::System.NotImplementedException("The member IDictionary<string, RandomAccessStreamReference> DataPackage.ResourceMap is not implemented in Uno.");
}
}
#endif
#if __ANDROID__ || __IOS__ || NET46 || false || __MACOS__
[global::Uno.NotImplemented]
public DataPackage()
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.ApplicationModel.DataTransfer.DataPackage", "DataPackage.DataPackage()");
}
#endif
// Forced skipping of method Windows.ApplicationModel.DataTransfer.DataPackage.DataPackage()
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public global::Windows.ApplicationModel.DataTransfer.DataPackageView GetView()
{
throw new global::System.NotImplementedException("The member DataPackageView DataPackage.GetView() is not implemented in Uno.");
}
#endif
// Forced skipping of method Windows.ApplicationModel.DataTransfer.DataPackage.Properties.get
// Forced skipping of method Windows.ApplicationModel.DataTransfer.DataPackage.RequestedOperation.get
// Forced skipping of method Windows.ApplicationModel.DataTransfer.DataPackage.RequestedOperation.set
// Forced skipping of method Windows.ApplicationModel.DataTransfer.DataPackage.OperationCompleted.add
// Forced skipping of method Windows.ApplicationModel.DataTransfer.DataPackage.OperationCompleted.remove
// Forced skipping of method Windows.ApplicationModel.DataTransfer.DataPackage.Destroyed.add
// Forced skipping of method Windows.ApplicationModel.DataTransfer.DataPackage.Destroyed.remove
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public void SetData( string formatId, object value)
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.ApplicationModel.DataTransfer.DataPackage", "void DataPackage.SetData(string formatId, object value)");
}
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public void SetDataProvider( string formatId, global::Windows.ApplicationModel.DataTransfer.DataProviderHandler delayRenderer)
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.ApplicationModel.DataTransfer.DataPackage", "void DataPackage.SetDataProvider(string formatId, DataProviderHandler delayRenderer)");
}
#endif
#if __ANDROID__ || __IOS__ || NET46 || false || __MACOS__
[global::Uno.NotImplemented]
public void SetText( string value)
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.ApplicationModel.DataTransfer.DataPackage", "void DataPackage.SetText(string value)");
}
#endif
#if __ANDROID__ || __IOS__ || NET46 || false || __MACOS__
[global::Uno.NotImplemented]
public void SetUri( global::System.Uri value)
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.ApplicationModel.DataTransfer.DataPackage", "void DataPackage.SetUri(Uri value)");
}
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public void SetHtmlFormat( string value)
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.ApplicationModel.DataTransfer.DataPackage", "void DataPackage.SetHtmlFormat(string value)");
}
#endif
// Forced skipping of method Windows.ApplicationModel.DataTransfer.DataPackage.ResourceMap.get
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public void SetRtf( string value)
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.ApplicationModel.DataTransfer.DataPackage", "void DataPackage.SetRtf(string value)");
}
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public void SetBitmap( global::Windows.Storage.Streams.RandomAccessStreamReference value)
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.ApplicationModel.DataTransfer.DataPackage", "void DataPackage.SetBitmap(RandomAccessStreamReference value)");
}
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public void SetStorageItems( global::System.Collections.Generic.IEnumerable<global::Windows.Storage.IStorageItem> value)
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.ApplicationModel.DataTransfer.DataPackage", "void DataPackage.SetStorageItems(IEnumerable<IStorageItem> value)");
}
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public void SetStorageItems( global::System.Collections.Generic.IEnumerable<global::Windows.Storage.IStorageItem> value, bool readOnly)
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.ApplicationModel.DataTransfer.DataPackage", "void DataPackage.SetStorageItems(IEnumerable<IStorageItem> value, bool readOnly)");
}
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public void SetApplicationLink( global::System.Uri value)
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.ApplicationModel.DataTransfer.DataPackage", "void DataPackage.SetApplicationLink(Uri value)");
}
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public void SetWebLink( global::System.Uri value)
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.ApplicationModel.DataTransfer.DataPackage", "void DataPackage.SetWebLink(Uri value)");
}
#endif
// Forced skipping of method Windows.ApplicationModel.DataTransfer.DataPackage.ShareCompleted.add
// Forced skipping of method Windows.ApplicationModel.DataTransfer.DataPackage.ShareCompleted.remove
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public event global::Windows.Foundation.TypedEventHandler<global::Windows.ApplicationModel.DataTransfer.DataPackage, object> Destroyed
{
[global::Uno.NotImplemented]
add
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.ApplicationModel.DataTransfer.DataPackage", "event TypedEventHandler<DataPackage, object> DataPackage.Destroyed");
}
[global::Uno.NotImplemented]
remove
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.ApplicationModel.DataTransfer.DataPackage", "event TypedEventHandler<DataPackage, object> DataPackage.Destroyed");
}
}
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public event global::Windows.Foundation.TypedEventHandler<global::Windows.ApplicationModel.DataTransfer.DataPackage, global::Windows.ApplicationModel.DataTransfer.OperationCompletedEventArgs> OperationCompleted
{
[global::Uno.NotImplemented]
add
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.ApplicationModel.DataTransfer.DataPackage", "event TypedEventHandler<DataPackage, OperationCompletedEventArgs> DataPackage.OperationCompleted");
}
[global::Uno.NotImplemented]
remove
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.ApplicationModel.DataTransfer.DataPackage", "event TypedEventHandler<DataPackage, OperationCompletedEventArgs> DataPackage.OperationCompleted");
}
}
#endif
#if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public event global::Windows.Foundation.TypedEventHandler<global::Windows.ApplicationModel.DataTransfer.DataPackage, global::Windows.ApplicationModel.DataTransfer.ShareCompletedEventArgs> ShareCompleted
{
[global::Uno.NotImplemented]
add
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.ApplicationModel.DataTransfer.DataPackage", "event TypedEventHandler<DataPackage, ShareCompletedEventArgs> DataPackage.ShareCompleted");
}
[global::Uno.NotImplemented]
remove
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.ApplicationModel.DataTransfer.DataPackage", "event TypedEventHandler<DataPackage, ShareCompletedEventArgs> DataPackage.ShareCompleted");
}
}
#endif
}
}
| 51.005102 | 231 | 0.784735 | [
"Apache-2.0"
] | billchungiii/Uno | src/Uno.UWP/Generated/3.0.0.0/Windows.ApplicationModel.DataTransfer/DataPackage.cs | 9,997 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNextGen.Network.V20181001.Outputs
{
[OutputType]
public sealed class ApplicationGatewayHttpListenerResponse
{
/// <summary>
/// Custom error configurations of the HTTP listener.
/// </summary>
public readonly ImmutableArray<Outputs.ApplicationGatewayCustomErrorResponse> CustomErrorConfigurations;
/// <summary>
/// A unique read-only string that changes whenever the resource is updated.
/// </summary>
public readonly string? Etag;
/// <summary>
/// Frontend IP configuration resource of an application gateway.
/// </summary>
public readonly Outputs.SubResourceResponse? FrontendIPConfiguration;
/// <summary>
/// Frontend port resource of an application gateway.
/// </summary>
public readonly Outputs.SubResourceResponse? FrontendPort;
/// <summary>
/// Host name of HTTP listener.
/// </summary>
public readonly string? HostName;
/// <summary>
/// Resource ID.
/// </summary>
public readonly string? Id;
/// <summary>
/// Name of the HTTP listener that is unique within an Application Gateway.
/// </summary>
public readonly string? Name;
/// <summary>
/// Protocol of the HTTP listener. Possible values are 'Http' and 'Https'.
/// </summary>
public readonly string? Protocol;
/// <summary>
/// Provisioning state of the HTTP listener resource. Possible values are: 'Updating', 'Deleting', and 'Failed'.
/// </summary>
public readonly string? ProvisioningState;
/// <summary>
/// Applicable only if protocol is https. Enables SNI for multi-hosting.
/// </summary>
public readonly bool? RequireServerNameIndication;
/// <summary>
/// SSL certificate resource of an application gateway.
/// </summary>
public readonly Outputs.SubResourceResponse? SslCertificate;
/// <summary>
/// Type of the resource.
/// </summary>
public readonly string? Type;
[OutputConstructor]
private ApplicationGatewayHttpListenerResponse(
ImmutableArray<Outputs.ApplicationGatewayCustomErrorResponse> customErrorConfigurations,
string? etag,
Outputs.SubResourceResponse? frontendIPConfiguration,
Outputs.SubResourceResponse? frontendPort,
string? hostName,
string? id,
string? name,
string? protocol,
string? provisioningState,
bool? requireServerNameIndication,
Outputs.SubResourceResponse? sslCertificate,
string? type)
{
CustomErrorConfigurations = customErrorConfigurations;
Etag = etag;
FrontendIPConfiguration = frontendIPConfiguration;
FrontendPort = frontendPort;
HostName = hostName;
Id = id;
Name = name;
Protocol = protocol;
ProvisioningState = provisioningState;
RequireServerNameIndication = requireServerNameIndication;
SslCertificate = sslCertificate;
Type = type;
}
}
}
| 34.160377 | 120 | 0.617785 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/Network/V20181001/Outputs/ApplicationGatewayHttpListenerResponse.cs | 3,621 | C# |
#pragma warning disable CS1591
namespace TheXDS.Triton.Tests
{
public partial class MiddlewareTests : TritonEfTestClass
{
}
}
| 15.555556 | 60 | 0.728571 | [
"MIT"
] | TheXDS/Trit-n | src/Tests/Triton.Tests.EFCore/Tests/MiddlewareTests.cs | 142 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace MVCSharp.Examples.AdvancedCustomization.ApplicationLogic
{
public enum ViewCategory
{
Mail,
Notes,
Tasks,
None
}
}
| 15.866667 | 66 | 0.659664 | [
"MIT"
] | zherar7ordoya/AP3 | (CSharp)/3) MVP Pattern/MVCSharp/Examples/Advanced (Office2007 UI and more)/ApplicationLogic/ViewCategory.cs | 240 | C# |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Linq;
using Framework.EventBus;
using Framework.Events;
using Framework.EventStore;
using Framework.Exceptions;
using Framework.Snapshotting;
namespace Framework.Aggregate
{
public class AggregateRepository : IAggregateRepository
{
private readonly ISnapshotRepository _snapshotRepository;
private readonly IEventRepository _eventRepository;
private readonly IDomainEventBus _bus;
public AggregateRepository(ISnapshotRepository snapshotRepository, IEventRepository eventRepository, IDomainEventBus bus)
{
this._snapshotRepository = snapshotRepository ?? throw new ArgumentNullException(nameof(snapshotRepository));
this._eventRepository = eventRepository ?? throw new ArgumentNullException(nameof(eventRepository));
this._bus = bus ?? throw new ArgumentNullException(nameof(bus));
}
public async Task<T> GetAsync<T>(Guid aggregateId, int? expectedVersion) where T : IAggregateRoot
{
return await LoadAggregate<T>(aggregateId, expectedVersion);
}
public async Task SaveAsync<T>(T aggregate) where T : IAggregateRoot
{
if (aggregate.DomainEvents == null)
{
return;
}
await this._eventRepository.SaveAsync(aggregate);
if (SnapshotStrategy.ShouldMakeSnapshot(aggregate))
{
var snapshot = ((dynamic)aggregate).GetSnapshot();
await this._snapshotRepository.SaveAsync(snapshot);
}
await PublishEvents(aggregate.DomainEvents);
aggregate.ClearDomainEvents();
}
public async Task<bool> ExistAsync(Guid aggregateId)
{
var events = await this._eventRepository.GetEvents(aggregateId);
return events != null ? true : false;
}
#region private methods
private async Task<T> LoadAggregate<T>(Guid aggregateId, int? expectedVersion) where T : IAggregateRoot
{
if (expectedVersion < 1)
{
throw new AggregateVersionIncorrectException();
}
var aggregate = AggregateFactory<T>.CreateAggregate();
int snapshotVersion = await RestoreAggregateFromSnapshot(aggregateId, aggregate);
if (snapshotVersion != -1)
{
var remainingEvents = await this._eventRepository.GetEvents(aggregateId, snapshotVersion + 1);
if (remainingEvents.Any())
{
aggregate.LoadFromHistory(remainingEvents);
}
if (expectedVersion != null && aggregate.Version != expectedVersion)
{
throw new ConcurrencyException(aggregateId);
}
return aggregate;
}
var allEvents = await this._eventRepository.GetEvents(aggregateId);
if (!allEvents.Any())
{
throw new AggregateNotFoundException(typeof(T), aggregateId);
}
aggregate.LoadFromHistory(allEvents);
if (expectedVersion != null && aggregate.Version != expectedVersion)
{
throw new ConcurrencyException(aggregateId);
}
return aggregate;
}
private async Task PublishEvents(IReadOnlyCollection<IEvent> events)
{
foreach (var @event in events)
{
await this._bus.PublishAsync(@event);
}
}
private async Task<int> RestoreAggregateFromSnapshot(Guid aggregateId, IAggregateRoot aggregate)
{
if (!SnapshotStrategy.IsSnapshotable(aggregate.GetType()))
return -1;
var snapshot = await this._snapshotRepository.GetAsync(aggregateId);
if (snapshot == null)
{
return -1;
}
((dynamic)aggregate).Restore((dynamic)snapshot);
return aggregate.Version;
}
#endregion
}
} | 36.631579 | 129 | 0.604885 | [
"MIT"
] | NilavPatel/Todo.CQRS | Framework/Aggregate/AggregateRepository.cs | 4,176 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Domain.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Domain.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized string similar to The To date must be after the From date.
/// </summary>
internal static string TimeSlot_FromDateBeforeToDate {
get {
return ResourceManager.GetString("TimeSlot_FromDateBeforeToDate", resourceCulture);
}
}
}
}
| 42.849315 | 172 | 0.607737 | [
"Apache-2.0"
] | jezzsantos/clinics | src/Domain.Common/Properties/Resources.Designer.cs | 3,130 | C# |
using System.Collections.Generic;
using DSCore;
using Autodesk.DesignScript.Geometry;
using Autodesk.DesignScript.Runtime;
using DynaShape.GeometryBinders;
using HelixToolkit.Wpf.SharpDX.Core;
using Point = Autodesk.DesignScript.Geometry.Point;
namespace DynaShape.ZeroTouch
{
public static class GeometryBinders
{
public static LineBinder LineBinder(
Line line,
[DefaultArgument("null")] Color color)
{
return new LineBinder(
line.StartPoint.ToTriple(),
line.EndPoint.ToTriple(),
color?.ToSharpDXColor() ?? DynaShapeDisplay.DefaultLineColor);
}
public static LineBinder LineBinder(
Point startPoint,
Point endPoint,
[DefaultArgument("null")] Color color)
{
return new LineBinder(
startPoint.ToTriple(),
endPoint.ToTriple(),
color?.ToSharpDXColor() ?? DynaShapeDisplay.DefaultLineColor);
}
public static PolylineBinder PolylineBinder(
List<Point> vertices,
[DefaultArgument("null")] Color color,
[DefaultArgument("false")] bool loop)
{
return new PolylineBinder(
vertices.ToTriples(),
color?.ToSharpDXColor() ?? DynaShapeDisplay.DefaultLineColor,
loop);
}
public static MeshBinder MeshBinder(
Autodesk.DesignScript.Geometry.Mesh mesh,
[DefaultArgument("null")] Color color)
{
return new MeshBinder(
mesh,
color?.ToSharpDXColor() ?? DynaShapeDisplay.DefaultMeshFaceColor);
}
public static MeshBinder MeshBinder(
Autodesk.Dynamo.MeshToolkit.Mesh toolkitMesh,
[DefaultArgument("null")] Color color)
{
return new MeshBinder(
toolkitMesh,
color?.ToSharpDXColor() ?? DynaShapeDisplay.DefaultMeshFaceColor);
}
public static TexturedMeshBinder TexturedMeshBinder(
Autodesk.Dynamo.MeshToolkit.Mesh toolkitMesh,
[DefaultArgument("null")] Color color,
string textureFileName,
TextureCoordinateSet textureCoordinates)
{
return new TexturedMeshBinder(
toolkitMesh,
color?.ToSharpDXColor() ?? DynaShapeDisplay.DefaultMeshFaceColor,
textureFileName,
textureCoordinates.Content);
}
public static GeometryBinder ChangeColor(GeometryBinder geometryBinder, Color color)
{
geometryBinder.Color = color.ToSharpDXColor();
return geometryBinder;
}
}
} | 31.269663 | 92 | 0.593963 | [
"MIT"
] | htlcnn/DynaShape | DynaShape/ZeroTouch/GeometryBinders.cs | 2,785 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.18010
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace LeakBlocker.Server.Installer {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class SQL {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal SQL() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("LeakBlocker.Server.Installer.SQL", typeof(SQL).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized resource of type System.Byte[].
/// </summary>
internal static byte[] manifest_32 {
get {
object obj = ResourceManager.GetObject("manifest_32", resourceCulture);
return ((byte[])(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Byte[].
/// </summary>
internal static byte[] manifest_64 {
get {
object obj = ResourceManager.GetObject("manifest_64", resourceCulture);
return ((byte[])(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Byte[].
/// </summary>
internal static byte[] msvcr90_32 {
get {
object obj = ResourceManager.GetObject("msvcr90_32", resourceCulture);
return ((byte[])(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Byte[].
/// </summary>
internal static byte[] msvcr90_64 {
get {
object obj = ResourceManager.GetObject("msvcr90_64", resourceCulture);
return ((byte[])(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Byte[].
/// </summary>
internal static byte[] sqlceca40_32 {
get {
object obj = ResourceManager.GetObject("sqlceca40_32", resourceCulture);
return ((byte[])(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Byte[].
/// </summary>
internal static byte[] sqlceca40_64 {
get {
object obj = ResourceManager.GetObject("sqlceca40_64", resourceCulture);
return ((byte[])(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Byte[].
/// </summary>
internal static byte[] sqlcecompact40_32 {
get {
object obj = ResourceManager.GetObject("sqlcecompact40_32", resourceCulture);
return ((byte[])(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Byte[].
/// </summary>
internal static byte[] sqlcecompact40_64 {
get {
object obj = ResourceManager.GetObject("sqlcecompact40_64", resourceCulture);
return ((byte[])(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Byte[].
/// </summary>
internal static byte[] sqlceer40EN_32 {
get {
object obj = ResourceManager.GetObject("sqlceer40EN_32", resourceCulture);
return ((byte[])(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Byte[].
/// </summary>
internal static byte[] sqlceer40EN_64 {
get {
object obj = ResourceManager.GetObject("sqlceer40EN_64", resourceCulture);
return ((byte[])(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Byte[].
/// </summary>
internal static byte[] sqlceme40_32 {
get {
object obj = ResourceManager.GetObject("sqlceme40_32", resourceCulture);
return ((byte[])(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Byte[].
/// </summary>
internal static byte[] sqlceme40_64 {
get {
object obj = ResourceManager.GetObject("sqlceme40_64", resourceCulture);
return ((byte[])(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Byte[].
/// </summary>
internal static byte[] sqlceqp40_32 {
get {
object obj = ResourceManager.GetObject("sqlceqp40_32", resourceCulture);
return ((byte[])(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Byte[].
/// </summary>
internal static byte[] sqlceqp40_64 {
get {
object obj = ResourceManager.GetObject("sqlceqp40_64", resourceCulture);
return ((byte[])(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Byte[].
/// </summary>
internal static byte[] sqlcese40_32 {
get {
object obj = ResourceManager.GetObject("sqlcese40_32", resourceCulture);
return ((byte[])(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Byte[].
/// </summary>
internal static byte[] sqlcese40_64 {
get {
object obj = ResourceManager.GetObject("sqlcese40_64", resourceCulture);
return ((byte[])(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Byte[].
/// </summary>
internal static byte[] System_Data_SqlServerCe {
get {
object obj = ResourceManager.GetObject("System_Data_SqlServerCe", resourceCulture);
return ((byte[])(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Byte[].
/// </summary>
internal static byte[] System_Data_SqlServerCe_Entity {
get {
object obj = ResourceManager.GetObject("System_Data_SqlServerCe_Entity", resourceCulture);
return ((byte[])(obj));
}
}
}
}
| 36.602459 | 171 | 0.52245 | [
"MIT"
] | imanushin/leak-blocker | Projects/LeakBlocker.Server.Installer/SQL.Designer.cs | 8,933 | C# |
namespace Serilog.Exceptions.Destructurers
{
using System;
using System.Collections.Generic;
using Serilog.Exceptions.Core;
/// <summary>
/// Base class for more specific destructurers.
/// It destructures all the standard properties that every <see cref="Exception"/> has.
/// </summary>
public class ExceptionDestructurer : IExceptionDestructurer
{
/// <summary>
/// Gets a collection of exceptions types from standard library that do not have any custom property,
/// so they can be destructured using generic exception destructurer.
/// </summary>
#pragma warning disable CA1819 // Properties should not return arrays
public virtual Type[] TargetTypes
#pragma warning restore CA1819 // Properties should not return arrays
{
get
{
var targetTypes = new List<Type>
{
#pragma warning disable IDE0001 // Simplify Names
#if NET461 || NET472
typeof(Microsoft.SqlServer.Server.InvalidUdtException),
typeof(System.AccessViolationException),
typeof(System.AppDomainUnloadedException),
typeof(System.ApplicationException),
#endif
typeof(System.ArithmeticException),
typeof(System.ArrayTypeMismatchException),
#if NET461 || NET472
typeof(System.CannotUnloadAppDomainException),
#endif
typeof(System.Collections.Generic.KeyNotFoundException),
#if NET461 || NET472
typeof(System.ComponentModel.Design.CheckoutException),
typeof(System.ComponentModel.InvalidAsynchronousStateException),
typeof(System.ComponentModel.InvalidEnumArgumentException),
typeof(System.Configuration.SettingsPropertyIsReadOnlyException),
typeof(System.Configuration.SettingsPropertyNotFoundException),
typeof(System.Configuration.SettingsPropertyWrongTypeException),
typeof(System.ContextMarshalException),
#endif
#if NET461 || NET472
typeof(System.Data.ConstraintException),
typeof(System.Data.DataException),
typeof(System.Data.DeletedRowInaccessibleException),
typeof(System.Data.DuplicateNameException),
typeof(System.Data.EvaluateException),
typeof(System.Data.InRowChangingEventException),
typeof(System.Data.InvalidConstraintException),
typeof(System.Data.InvalidExpressionException),
typeof(System.Data.MissingPrimaryKeyException),
typeof(System.Data.NoNullAllowedException),
typeof(System.Data.OperationAbortedException),
typeof(System.Data.ReadOnlyException),
typeof(System.Data.RowNotInTableException),
typeof(System.Data.SqlTypes.SqlAlreadyFilledException),
typeof(System.Data.SqlTypes.SqlNotFilledException),
#endif
#if NET461 || NET472
typeof(System.Data.StrongTypingException),
typeof(System.Data.SyntaxErrorException),
typeof(System.Data.VersionNotFoundException),
#endif
typeof(System.DataMisalignedException),
typeof(System.DivideByZeroException),
typeof(System.DllNotFoundException),
#if NET461 || NET472
typeof(System.DuplicateWaitObjectException),
typeof(System.EntryPointNotFoundException),
#endif
typeof(System.Exception),
typeof(System.FieldAccessException),
typeof(System.FormatException),
typeof(System.IndexOutOfRangeException),
typeof(System.InsufficientExecutionStackException),
#if NET461 || NET472
typeof(System.InsufficientMemoryException),
#endif
typeof(System.InvalidCastException),
typeof(System.InvalidOperationException),
typeof(System.InvalidProgramException),
typeof(System.InvalidTimeZoneException),
typeof(System.IO.DirectoryNotFoundException),
#if NET461 || NET472
typeof(System.IO.DriveNotFoundException),
#endif
typeof(System.IO.EndOfStreamException),
#if NET461 || NET472
typeof(System.IO.InternalBufferOverflowException),
#endif
typeof(System.IO.InvalidDataException),
typeof(System.IO.IOException),
#if NET461 || NET472
typeof(System.IO.IsolatedStorage.IsolatedStorageException),
#endif
typeof(System.IO.PathTooLongException),
typeof(System.MemberAccessException),
typeof(System.MethodAccessException),
#if NET461 || NET472
typeof(System.MulticastNotSupportedException),
#endif
typeof(System.Net.CookieException),
#if NET461 || NET472
typeof(System.Net.NetworkInformation.PingException),
typeof(System.Net.ProtocolViolationException),
#endif
typeof(System.NotImplementedException),
typeof(System.NotSupportedException),
typeof(System.NullReferenceException),
typeof(System.OutOfMemoryException),
typeof(System.OverflowException),
typeof(System.PlatformNotSupportedException),
typeof(System.RankException),
typeof(System.Reflection.AmbiguousMatchException),
#if NET461 || NET472
typeof(System.Reflection.CustomAttributeFormatException),
#endif
#if !NETSTANDARD1_3
typeof(System.Reflection.InvalidFilterCriteriaException),
typeof(System.Reflection.TargetException),
#endif
typeof(System.Reflection.TargetInvocationException),
typeof(System.Reflection.TargetParameterCountException),
typeof(System.Resources.MissingManifestResourceException),
typeof(System.Runtime.InteropServices.COMException),
typeof(System.Runtime.InteropServices.InvalidComObjectException),
typeof(System.Runtime.InteropServices.InvalidOleVariantTypeException),
typeof(System.Runtime.InteropServices.MarshalDirectiveException),
typeof(System.Runtime.InteropServices.SafeArrayRankMismatchException),
typeof(System.Runtime.InteropServices.SafeArrayTypeMismatchException),
typeof(System.Runtime.InteropServices.SEHException),
#if NET461 || NET472
typeof(System.Runtime.Remoting.RemotingException),
typeof(System.Runtime.Remoting.RemotingTimeoutException),
typeof(System.Runtime.Remoting.ServerException),
typeof(System.Runtime.Serialization.SerializationException),
typeof(System.Security.Authentication.AuthenticationException),
typeof(System.Security.Authentication.InvalidCredentialException),
#endif
typeof(System.Security.Cryptography.CryptographicException),
#if NET461 || NET472
typeof(System.Security.Cryptography.CryptographicUnexpectedOperationException),
typeof(System.Security.Policy.PolicyException),
#endif
typeof(System.Security.VerificationException),
#if NET461 || NET472
typeof(System.Security.XmlSyntaxException),
typeof(System.StackOverflowException),
typeof(System.SystemException),
#endif
typeof(System.Threading.BarrierPostPhaseException),
typeof(System.Threading.LockRecursionException),
typeof(System.Threading.SemaphoreFullException),
typeof(System.Threading.SynchronizationLockException),
typeof(System.Threading.Tasks.TaskSchedulerException),
#if NET461 || NET472
typeof(System.Threading.ThreadInterruptedException),
typeof(System.Threading.ThreadStartException),
typeof(System.Threading.ThreadStateException),
#endif
typeof(System.Threading.WaitHandleCannotBeOpenedException),
typeof(System.TimeoutException),
#if NET461 || NET472
typeof(System.TimeZoneNotFoundException),
#endif
typeof(System.TypeAccessException),
#if NET461 || NET472
typeof(System.TypeUnloadedException),
#endif
typeof(System.UnauthorizedAccessException),
typeof(System.UriFormatException),
};
#pragma warning restore IDE0001 // Simplify Names
#if NET461 || NET472
foreach (var dangerousType in GetNotHandledByMonoTypes())
{
var type = Type.GetType(dangerousType);
if (type is not null)
{
targetTypes.Add(type);
}
}
#endif
return targetTypes.ToArray();
}
}
/// <inheritdoc cref="IExceptionDestructurer.Destructure"/>
public virtual void Destructure(
Exception exception,
IExceptionPropertiesBag propertiesBag,
Func<Exception, IReadOnlyDictionary<string, object?>?> destructureException)
{
if (exception is null)
{
throw new ArgumentNullException(nameof(propertiesBag));
}
if (propertiesBag is null)
{
throw new ArgumentNullException(nameof(propertiesBag));
}
if (destructureException is null)
{
throw new ArgumentNullException(nameof(destructureException));
}
propertiesBag.AddProperty("Type", exception.GetType().FullName);
DestructureCommonExceptionProperties(
exception,
propertiesBag,
destructureException,
data => data.ToStringObjectDictionary());
}
/// <summary>
/// Destructures public properties of <see cref="Exception"/>.
/// Omits less frequently used ones if they are null.
/// </summary>
/// <param name="exception">The exception that will be destructured.</param>
/// <param name="propertiesBag">The bag when destructured properties will be put.</param>
/// <param name="innerDestructure">Function that can be used to destructure inner exceptions if there are any.</param>
/// <param name="destructureDataProperty">Injected function for destructuring <see cref="Exception.Data"/>.</param>
internal static void DestructureCommonExceptionProperties(
Exception exception,
IExceptionPropertiesBag propertiesBag,
Func<Exception, IReadOnlyDictionary<string, object?>?> innerDestructure,
Func<System.Collections.IDictionary, object> destructureDataProperty)
{
if (exception.Data.Count != 0)
{
propertiesBag.AddProperty(nameof(Exception.Data), destructureDataProperty(exception.Data));
}
if (!string.IsNullOrEmpty(exception.HelpLink))
{
propertiesBag.AddProperty(nameof(Exception.HelpLink), exception.HelpLink);
}
if (exception.HResult != 0)
{
propertiesBag.AddProperty(nameof(Exception.HResult), exception.HResult);
}
propertiesBag.AddProperty(nameof(Exception.Message), exception.Message);
propertiesBag.AddProperty(nameof(Exception.Source), exception.Source);
propertiesBag.AddProperty(nameof(Exception.StackTrace), exception.StackTrace);
#if NET461 || NET472
if (exception.TargetSite is not null)
{
propertiesBag.AddProperty(nameof(Exception.TargetSite), exception.TargetSite.ToString());
}
#endif
if (exception.InnerException is not null)
{
propertiesBag.AddProperty(nameof(Exception.InnerException), innerDestructure(exception.InnerException));
}
}
#if NET461 || NET472
/// <summary>
/// Get types that are currently not handled by mono and could raise a LoadTypeException.
/// </summary>
/// <returns>List of type names.</returns>
private static string[] GetNotHandledByMonoTypes() =>
new string[]
{
"System.Diagnostics.Eventing.Reader.EventLogInvalidDataException, System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089",
"System.Diagnostics.Eventing.Reader.EventLogNotFoundException, System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089",
"System.Diagnostics.Eventing.Reader.EventLogProviderDisabledException, System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089",
"System.Diagnostics.Eventing.Reader.EventLogReadingException, System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089",
"System.Diagnostics.Tracing.EventSourceException, mscorlib, Version=4.0.0.0, PublicKeyToken=b77a5c561934e089",
"System.Management.Instrumentation.InstanceNotFoundException, System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089",
"System.Management.Instrumentation.InstrumentationBaseException, System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089",
"System.Management.Instrumentation.InstrumentationException, System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089",
};
#endif
}
}
| 51.731034 | 168 | 0.594721 | [
"MIT"
] | RehanSaeed/Serilog.Exceptions | Source/Serilog.Exceptions/Destructurers/ExceptionDestructurer.cs | 15,002 | C# |
using System;
using System.Collections.Generic;
using System.Xml.Linq;
using Engine.Model;
namespace Engine.Data
{
public static class FromDataFactory
{
public static T Get<T>(string name) where T: class
{
string typestring = typeof(T).Name;
return GetFromXmlFile<T>(name, $@"Data\{typestring}.xml");
}
private static T GetFromXmlFile<T>(string name, string filename) where T: class
{
XDocument xml = XDocument.Load(filename);
foreach (XElement element in xml.Root.Elements())
{
if (element.Attribute("Name")?.Value == name)
{
return (T) Activator.CreateInstance(typeof(T), element);
}
}
return default(T);
}
public static List<T> GetAll<T>() where T : class
{
string typestring = typeof(T).Name;
XDocument xml = XDocument.Load($@"Data\{typestring}.xml");
List<T> list = new List<T>();
foreach (XElement element in xml.Root.Elements())
{
T result = (T) Activator.CreateInstance(typeof(T), element);
list.Add(result);
}
return list;
}
}
} | 29.431818 | 87 | 0.528958 | [
"MIT"
] | isonym/MalifauxCharSheet | MalifauxCharSheet/Engine/Data/FromDataFactory.cs | 1,297 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace IceTube.DataModels
{
public class YoutubeVideo
{
public int Id { get; set; }
public string ActivityId { get; set; }
public string VideoId { get; set; }
public DateTime? PublishedAt { get; set; }
public DateTime AddedAt { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string ThumbnailUrl { get; set; }
public VideoDownloadState DownloadState { get; set; }
public DateTime? StartedDownloadAt { get; set; }
public DateTime? FinishedDownloadAt { get; set; }
public bool DownloadError { get; set; }
public string DownloadErrorDetails { get; set; }
public string ChannelId { get; set; }
public YoutubeChannel Channel { get; set; }
}
} | 25.054054 | 61 | 0.629989 | [
"MIT"
] | watermelonpizza/icetube | IceTube/DataModels/YoutubeVideo.cs | 929 | C# |
/*
* Ory Kratos API
*
* Documentation for all public and administrative Ory Kratos APIs. Public and administrative APIs are exposed on different ports. Public APIs can face the public internet without any protection while administrative APIs should never be exposed without prior authorization. To protect the administative API port you should use something like Nginx, Ory Oathkeeper, or any other technology capable of authorizing incoming requests.
*
* The version of the OpenAPI document: v0.8.0-alpha.2
* Contact: hi@ory.sh
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using Xunit;
using System;
using System.Linq;
using System.IO;
using System.Collections.Generic;
using Ory.Kratos.Client.Api;
using Ory.Kratos.Client.Model;
using Ory.Kratos.Client.Client;
using System.Reflection;
using Newtonsoft.Json;
namespace Ory.Kratos.Client.Test.Model
{
/// <summary>
/// Class for testing KratosSubmitSelfServiceSettingsFlowWithWebAuthnMethodBody
/// </summary>
/// <remarks>
/// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech).
/// Please update the test case below to test the model.
/// </remarks>
public class KratosSubmitSelfServiceSettingsFlowWithWebAuthnMethodBodyTests : IDisposable
{
// TODO uncomment below to declare an instance variable for KratosSubmitSelfServiceSettingsFlowWithWebAuthnMethodBody
//private KratosSubmitSelfServiceSettingsFlowWithWebAuthnMethodBody instance;
public KratosSubmitSelfServiceSettingsFlowWithWebAuthnMethodBodyTests()
{
// TODO uncomment below to create an instance of KratosSubmitSelfServiceSettingsFlowWithWebAuthnMethodBody
//instance = new KratosSubmitSelfServiceSettingsFlowWithWebAuthnMethodBody();
}
public void Dispose()
{
// Cleanup when everything is done.
}
/// <summary>
/// Test an instance of KratosSubmitSelfServiceSettingsFlowWithWebAuthnMethodBody
/// </summary>
[Fact]
public void KratosSubmitSelfServiceSettingsFlowWithWebAuthnMethodBodyInstanceTest()
{
// TODO uncomment below to test "IsType" KratosSubmitSelfServiceSettingsFlowWithWebAuthnMethodBody
//Assert.IsType<KratosSubmitSelfServiceSettingsFlowWithWebAuthnMethodBody>(instance);
}
/// <summary>
/// Test the property 'CsrfToken'
/// </summary>
[Fact]
public void CsrfTokenTest()
{
// TODO unit test for the property 'CsrfToken'
}
/// <summary>
/// Test the property 'Method'
/// </summary>
[Fact]
public void MethodTest()
{
// TODO unit test for the property 'Method'
}
/// <summary>
/// Test the property 'WebauthnRegister'
/// </summary>
[Fact]
public void WebauthnRegisterTest()
{
// TODO unit test for the property 'WebauthnRegister'
}
/// <summary>
/// Test the property 'WebauthnRegisterDisplayname'
/// </summary>
[Fact]
public void WebauthnRegisterDisplaynameTest()
{
// TODO unit test for the property 'WebauthnRegisterDisplayname'
}
/// <summary>
/// Test the property 'WebauthnRemove'
/// </summary>
[Fact]
public void WebauthnRemoveTest()
{
// TODO unit test for the property 'WebauthnRemove'
}
}
}
| 34.461538 | 431 | 0.662946 | [
"Apache-2.0"
] | vinckr/sdk | clients/kratos/dotnet/src/Ory.Kratos.Client.Test/Model/KratosSubmitSelfServiceSettingsFlowWithWebAuthnMethodBodyTests.cs | 3,584 | C# |
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Manatee.Json.Internal;
using Manatee.Json.Patch;
using Manatee.Json.Schema;
using Manatee.Json.Serialization;
using Manatee.Json.Tests.Schema.TestSuite;
using Manatee.Json.Tests.Test_References;
using NUnit.Framework;
namespace Manatee.Json.Tests
{
[TestFixture]
// TODO: Add categories to exclude this test.
[Ignore("This test fixture for development purposes only.")]
public class DevTest
{
[Test]
public void Test()
{
}
}
} | 22.62069 | 62 | 0.742378 | [
"MIT"
] | jinhong-/Manatee.Json | Manatee.Json.Tests/DevTest.cs | 658 | C# |
/*
Copyright © 2015 Intel Corporation
This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0,
which accompanies this distribution, and is available at http://www.eclipse.org/legal/epl-v10.html . https://github.com/viqet
* Contributors:
* Intel Corporation - initial API and implementation and/or initial documentation
*/
using System.Windows;
using System.Windows.Controls;
namespace ViqetDesktop
{
/// <summary>
/// Interaction logic for SettingsPage.xaml
/// </summary>
public partial class Setting : UserControl
{
public Setting()
{
InitializeComponent();
LoadSettings();
}
private void OKButton_Click(object sender, RoutedEventArgs e)
{
SaveSettings();
GoBack();
}
private void CancelButton_Click(object sender, RoutedEventArgs e)
{
GoBack();
}
private void GoBack()
{
LoadSettings();
this.Visibility = Visibility.Collapsed;
}
private void SaveSettings()
{
Properties.Settings.Default.CheckPhotoCount = (bool)this.CheckPhotoCount.IsChecked;
Properties.Settings.Default.DisplayPhotoMOS = (bool)this.DisplayPhotoMOS.IsChecked;
Properties.Settings.Default.Save();
}
private void LoadSettings()
{
this.CheckPhotoCount.IsChecked = Properties.Settings.Default.CheckPhotoCount;
this.DisplayPhotoMOS.IsChecked = Properties.Settings.Default.DisplayPhotoMOS;
}
}
} | 30.425926 | 126 | 0.637858 | [
"EPL-1.0"
] | VIQET/VIQET-Desktop | VIQET-UI/ViqetDesktop/Pages/Common/Setting.xaml.cs | 1,646 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ArrowSpawner : MonoBehaviour {
[Header("Objects")]
public GameObject Arrow;
[Header("State")]
public bool ShootLeft;
[Header("Private")]
private float shootSpeed = 0.5f;
private float shootTimer = 0.5f;
private float xPosition = 30;
void Start() {
Vector3 currentPosition = transform.position;
if(ShootLeft) {
currentPosition.x = xPosition;
} else {
currentPosition.x = -xPosition;
}
transform.position = currentPosition;
}
void Shoot() {
GameObject arrow = Instantiate(Arrow, transform.position, Quaternion.identity);
if(ShootLeft) {
arrow.GetComponent<Arrow>().Direction = -1; // Go left
} else {
arrow.GetComponent<SpriteRenderer>().flipX = true;
arrow.GetComponent<Arrow>().Direction = 1; // Go right
}
}
void Update() {
if(shootTimer <= 0) {
Shoot();
shootTimer = shootSpeed;
} else {
shootTimer -= Time.deltaTime;
}
}
}
| 25.170213 | 87 | 0.57481 | [
"MIT"
] | claby2/tower-scaling | Assets/Scripts/ArrowSpawner.cs | 1,185 | C# |
// <copyright file="ExpandableDictionaryConverter.cs" company="Shkyrockett" >
// Copyright © 2017 - 2020 Shkyrockett. All rights reserved.
// </copyright>
// <author id="shkyrockett">Shkyrockett</author>
// <license>
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
// </license>
// <summary></summary>
// <remarks></remarks>
using System;
using System.Collections;
using System.ComponentModel;
using System.Globalization;
namespace Engine
{
/// <summary>
/// The expandable dictionary converter class.
/// </summary>
/// <seealso cref="System.ComponentModel.CollectionConverter" />
/// <acknowledgment>
/// http://stackoverflow.com/questions/32582504/propertygrid-expandable-collection
/// </acknowledgment>
public class ExpandableDictionaryConverter
: CollectionConverter
{
#region Methods
/// <summary>
/// Convert the to.
/// </summary>
/// <param name="context">The context.</param>
/// <param name="culture">The culture.</param>
/// <param name="value">The value.</param>
/// <param name="destType">The destType.</param>
/// <returns>
/// The <see cref="object" />.
/// </returns>
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destType)
{
if (destType == typeof(string))
{
return "[Key, Value]";
}
return base.ConvertTo(context, culture, value, destType);
}
/// <summary>
/// Get the properties supported.
/// </summary>
/// <param name="context">The context.</param>
/// <returns>
/// The <see cref="bool" />.
/// </returns>
public override bool GetPropertiesSupported(ITypeDescriptorContext context) => true;
/// <summary>
/// Get the properties.
/// </summary>
/// <param name="context">The context.</param>
/// <param name="value">The value.</param>
/// <param name="attributes">The attributes.</param>
/// <returns>
/// The <see cref="PropertyDescriptorCollection" />.
/// </returns>
public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes)
{
if (!(value is IDictionary dictionary) || dictionary.Count == 0)
{
return base.GetProperties(context, value, attributes);
}
var items = new PropertyDescriptorCollection(null);
foreach (var key in dictionary.Keys)
{
items.Add(new ExpandableDictionaryPropertyDescriptor(dictionary, key));
}
return items;
}
#endregion Methods
}
}
| 33.755814 | 136 | 0.590768 | [
"MIT"
] | Shkyrockett/engine | Engine.Base/Converters/ExpandableDictionaryConverter.cs | 2,906 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Christoc.Modules.BattleFrameworkModule
{
public partial class View
{
}
}
| 25.333333 | 81 | 0.432018 | [
"Apache-2.0",
"BSD-3-Clause"
] | alexrogier/RPGFL | DesktopModules/BattleFrameworkModule/View.ascx.designer.cs | 458 | C# |
// 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.
namespace Microsoft.Azure.PowerShell.Cmdlets.VMware.Models.Api20211201
{
using static Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Extensions;
/// <summary>A vSphere Distributed Resource Scheduler (DRS) placement policy</summary>
public partial class PlacementPolicy
{
/// <summary>
/// <c>AfterFromJson</c> will be called after the json deserialization has finished, allowing customization of the object
/// before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="json">The JsonNode that should be deserialized into this object.</param>
partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Json.JsonObject json);
/// <summary>
/// <c>AfterToJson</c> will be called after the json erialization has finished, allowing customization of the <see cref="Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Json.JsonObject"
/// /> before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="container">The JSON container that the serialization result will be placed in.</param>
partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Json.JsonObject container);
/// <summary>
/// <c>BeforeFromJson</c> will be called before the json deserialization has commenced, allowing complete customization of
/// the object before it is deserialized.
/// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="json">The JsonNode that should be deserialized into this object.</param>
/// <param name="returnNow">Determines if the rest of the deserialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Json.JsonObject json, ref bool returnNow);
/// <summary>
/// <c>BeforeToJson</c> will be called before the json serialization has commenced, allowing complete customization of the
/// object before it is serialized.
/// If you wish to disable the default serialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="container">The JSON container that the serialization result will be placed in.</param>
/// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Json.JsonObject container, ref bool returnNow);
/// <summary>
/// Deserializes a <see cref="Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Json.JsonNode"/> into an instance of Microsoft.Azure.PowerShell.Cmdlets.VMware.Models.Api20211201.IPlacementPolicy.
/// </summary>
/// <param name="node">a <see cref="Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Json.JsonNode" /> to deserialize from.</param>
/// <returns>
/// an instance of Microsoft.Azure.PowerShell.Cmdlets.VMware.Models.Api20211201.IPlacementPolicy.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.VMware.Models.Api20211201.IPlacementPolicy FromJson(Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Json.JsonNode node)
{
return node is Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Json.JsonObject json ? new PlacementPolicy(json) : null;
}
/// <summary>
/// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Json.JsonObject into a new instance of <see cref="PlacementPolicy" />.
/// </summary>
/// <param name="json">A Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Json.JsonObject instance to deserialize from.</param>
internal PlacementPolicy(Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Json.JsonObject json)
{
bool returnNow = false;
BeforeFromJson(json, ref returnNow);
if (returnNow)
{
return;
}
__resource = new Microsoft.Azure.PowerShell.Cmdlets.VMware.Models.Api20211201.Resource(json);
{_property = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Json.JsonObject>("properties"), out var __jsonProperties) ? Microsoft.Azure.PowerShell.Cmdlets.VMware.Models.Api20211201.PlacementPolicyProperties.FromJson(__jsonProperties) : Property;}
AfterFromJson(json);
}
/// <summary>
/// Serializes this instance of <see cref="PlacementPolicy" /> into a <see cref="Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Json.JsonNode" />.
/// </summary>
/// <param name="container">The <see cref="Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Json.JsonObject"/> container to serialize this object into. If the caller
/// passes in <c>null</c>, a new instance will be created and returned to the caller.</param>
/// <param name="serializationMode">Allows the caller to choose the depth of the serialization. See <see cref="Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.SerializationMode"/>.</param>
/// <returns>
/// a serialized instance of <see cref="PlacementPolicy" /> as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Json.JsonNode" />.
/// </returns>
public Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.SerializationMode serializationMode)
{
container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Json.JsonObject();
bool returnNow = false;
BeforeToJson(ref container, ref returnNow);
if (returnNow)
{
return container;
}
__resource?.ToJson(container, serializationMode);
AddIf( null != this._property ? (Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Json.JsonNode) this._property.ToJson(null,serializationMode) : null, "properties" ,container.Add );
AfterToJson(ref container);
return container;
}
}
} | 66 | 282 | 0.685045 | [
"MIT"
] | Agazoth/azure-powershell | src/VMware/generated/api/Models/Api20211201/PlacementPolicy.json.cs | 7,021 | C# |
using System.Collections.Generic;
using Horizon.Payment.Alipay.Response;
using Horizon.Payment.Alipay.Utility;
namespace Horizon.Payment.Alipay.Request
{
/// <summary>
/// ant.merchant.expand.indirect.image.upload
/// </summary>
public class AntMerchantExpandIndirectImageUploadRequest : IAlipayUploadRequest<AntMerchantExpandIndirectImageUploadResponse>
{
/// <summary>
/// 图片二进制字节流,最大为10M
/// </summary>
public FileItem ImageContent { get; set; }
/// <summary>
/// 图片格式,支持格式:bmp、jpg、jpeg、png、gif.
/// </summary>
public string ImageType { get; set; }
#region IAlipayRequest Members
private bool needEncrypt = false;
private string apiVersion = "1.0";
private string terminalType;
private string terminalInfo;
private string prodCode;
private string notifyUrl;
private string returnUrl;
private AlipayObject bizModel;
public void SetNeedEncrypt(bool needEncrypt)
{
this.needEncrypt = needEncrypt;
}
public bool GetNeedEncrypt()
{
return needEncrypt;
}
public void SetNotifyUrl(string notifyUrl)
{
this.notifyUrl = notifyUrl;
}
public string GetNotifyUrl()
{
return notifyUrl;
}
public void SetReturnUrl(string returnUrl)
{
this.returnUrl = returnUrl;
}
public string GetReturnUrl()
{
return returnUrl;
}
public void SetTerminalType(string terminalType)
{
this.terminalType = terminalType;
}
public string GetTerminalType()
{
return terminalType;
}
public void SetTerminalInfo(string terminalInfo)
{
this.terminalInfo = terminalInfo;
}
public string GetTerminalInfo()
{
return terminalInfo;
}
public void SetProdCode(string prodCode)
{
this.prodCode = prodCode;
}
public string GetProdCode()
{
return prodCode;
}
public void SetApiVersion(string apiVersion)
{
this.apiVersion = apiVersion;
}
public string GetApiVersion()
{
return apiVersion;
}
public string GetApiName()
{
return "ant.merchant.expand.indirect.image.upload";
}
public IDictionary<string, string> GetParameters()
{
var parameters = new AlipayDictionary
{
{ "image_type", ImageType }
};
return parameters;
}
public AlipayObject GetBizModel()
{
return bizModel;
}
public void SetBizModel(AlipayObject bizModel)
{
this.bizModel = bizModel;
}
#endregion
#region IAlipayUploadRequest Members
public IDictionary<string, FileItem> GetFileParameters()
{
IDictionary<string, FileItem> parameters = new Dictionary<string, FileItem>
{
{ "image_content", ImageContent }
};
return parameters;
}
#endregion
}
}
| 23.503497 | 129 | 0.551324 | [
"Apache-2.0"
] | bluexray/Horizon.Sample | Horizon.Payment.Alipay/Request/AntMerchantExpandIndirectImageUploadRequest.cs | 3,415 | C# |
using Content.Server.GameObjects.Components.Damage;
using Content.Server.GameObjects.Components.Interactable.Tools;
using Content.Server.GameObjects.Components.Power;
using Content.Server.GameObjects.EntitySystems;
using Content.Server.Interfaces;
using Content.Shared.GameObjects.Components.Gravity;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Robust.Server.GameObjects;
using Robust.Server.GameObjects.Components.UserInterface;
using Robust.Server.GameObjects.EntitySystems;
using Robust.Server.Interfaces.GameObjects;
using Robust.Server.Interfaces.Player;
using Robust.Shared.GameObjects;
using Robust.Shared.Interfaces.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.Localization;
using Robust.Shared.Serialization;
namespace Content.Server.GameObjects.Components.Gravity
{
[RegisterComponent]
public class GravityGeneratorComponent: SharedGravityGeneratorComponent, IAttackBy, IBreakAct, IAttackHand
{
private BoundUserInterface _userInterface;
private PowerDeviceComponent _powerDevice;
private SpriteComponent _sprite;
private bool _switchedOn;
private bool _intact;
private GravityGeneratorStatus _status;
public bool Powered => _powerDevice.Powered;
public bool SwitchedOn => _switchedOn;
public bool Intact => _intact;
public GravityGeneratorStatus Status => _status;
public bool NeedsUpdate
{
get
{
switch (_status)
{
case GravityGeneratorStatus.On:
return !(Powered && SwitchedOn && Intact);
case GravityGeneratorStatus.Off:
return SwitchedOn || !(Powered && Intact);
case GravityGeneratorStatus.Unpowered:
return SwitchedOn || Powered || !Intact;
case GravityGeneratorStatus.Broken:
return SwitchedOn || Powered || Intact;
default:
return true; // This _should_ be unreachable
}
}
}
public override string Name => "GravityGenerator";
public override void Initialize()
{
base.Initialize();
_userInterface = Owner.GetComponent<ServerUserInterfaceComponent>()
.GetBoundUserInterface(GravityGeneratorUiKey.Key);
_userInterface.OnReceiveMessage += HandleUIMessage;
_powerDevice = Owner.GetComponent<PowerDeviceComponent>();
_sprite = Owner.GetComponent<SpriteComponent>();
_switchedOn = true;
_intact = true;
_status = GravityGeneratorStatus.On;
UpdateState();
}
public override void ExposeData(ObjectSerializer serializer)
{
base.ExposeData(serializer);
serializer.DataField(ref _switchedOn, "switched_on", true);
serializer.DataField(ref _intact, "intact", true);
}
bool IAttackHand.AttackHand(AttackHandEventArgs eventArgs)
{
if (!eventArgs.User.TryGetComponent<IActorComponent>(out var actor))
return false;
if (Status != GravityGeneratorStatus.Off && Status != GravityGeneratorStatus.On)
{
return false;
}
OpenUserInterface(actor.playerSession);
return true;
}
public bool AttackBy(AttackByEventArgs eventArgs)
{
if (!eventArgs.AttackWith.TryGetComponent<WelderComponent>(out var welder)) return false;
if (welder.TryUse(5.0f))
{
// Repair generator
var damagable = Owner.GetComponent<DamageableComponent>();
var breakable = Owner.GetComponent<BreakableComponent>();
damagable.HealAllDamage();
breakable.broken = false;
_intact = true;
var entitySystemManager = IoCManager.Resolve<IEntitySystemManager>();
var notifyManager = IoCManager.Resolve<IServerNotifyManager>();
entitySystemManager.GetEntitySystem<AudioSystem>().Play("/Audio/items/welder2.ogg", Owner);
notifyManager.PopupMessage(Owner, eventArgs.User, Loc.GetString("You repair the gravity generator with the welder"));
return true;
} else
{
return false;
}
}
public void OnBreak(BreakageEventArgs eventArgs)
{
_intact = false;
_switchedOn = false;
}
public void UpdateState()
{
if (!Intact)
{
MakeBroken();
} else if (!Powered)
{
MakeUnpowered();
} else if (!SwitchedOn)
{
MakeOff();
} else
{
MakeOn();
}
}
private void HandleUIMessage(ServerBoundUserInterfaceMessage message)
{
switch (message.Message)
{
case GeneratorStatusRequestMessage _:
_userInterface.SetState(new GeneratorState(Status == GravityGeneratorStatus.On));
break;
case SwitchGeneratorMessage msg:
_switchedOn = msg.On;
UpdateState();
break;
default:
break;
}
}
private void OpenUserInterface(IPlayerSession playerSession)
{
_userInterface.Open(playerSession);
}
private void MakeBroken()
{
_status = GravityGeneratorStatus.Broken;
_sprite.LayerSetState(0, "broken");
_sprite.LayerSetVisible(1, false);
}
private void MakeUnpowered()
{
_status = GravityGeneratorStatus.Unpowered;
_sprite.LayerSetState(0, "off");
_sprite.LayerSetVisible(1, false);
}
private void MakeOff()
{
_status = GravityGeneratorStatus.Off;
_sprite.LayerSetState(0, "off");
_sprite.LayerSetVisible(1, false);
}
private void MakeOn()
{
_status = GravityGeneratorStatus.On;
_sprite.LayerSetState(0, "on");
_sprite.LayerSetVisible(1, true);
}
}
public enum GravityGeneratorStatus
{
Broken,
Unpowered,
Off,
On
}
}
| 32.028986 | 133 | 0.578431 | [
"MIT"
] | ComicIronic/space-station-14 | Content.Server/GameObjects/Components/Gravity/GravityGeneratorComponent.cs | 6,630 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Compuertas")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Compuertas")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("2a4b40fb-0cfe-4a19-a3f6-7bc75230fff3")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.513514 | 84 | 0.747118 | [
"MIT"
] | ANamelessWolf/AutoCADAPI2018-1 | Compuertas/Properties/AssemblyInfo.cs | 1,391 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FunctionManager : MonoBehaviour
{
//public or private void function's name
// Start is called before the first frame update
public Game Object[] player ;
private void Start()
{
player = GetAllThePlayers();
}
void Update()
{
}
GameObject [] GetAllThePlayers()
{
GameObject [] AllThePlayer = GameObject.FindGamesWithTag("Player");
foreach (var p in AllThePlayer)
{
p.GetComponent<MeshRenderer>().material.color = new Color (Random.value , Random.value , Random.value);
}
return AllThePlayer;
}
}
| 19.657895 | 116 | 0.599732 | [
"Apache-2.0"
] | senauust/Unity | Return.cs | 749 | C# |
// Port to MongoDB of MySql Connector by Adrian Lanning <adrian@nimblejump.com>
// Copyright (c) 2011 Adrian Lanning <adrian@nimblejump.com>
//
// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc.
//
// MySQL Connector/NET is licensed under the terms of the GPLv2
// <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most
// MySQL Connectors. There are special exceptions to the terms and
// conditions of the GPLv2 as it is applied to this software, see the
// FLOSS License Exception
// <http://www.mysql.com/about/legal/licensing/foss-exception.html>.
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published
// by the Free Software Foundation; version 2 of the License.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
// for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
// This code was contributed by Sean Wright (srwright@alcor.concordia.ca) on 2007-01-12
// The copyright was assigned and transferred under the terms of
// the MySQL Contributor License Agreement (CLA)
using NUnit.Framework;
using System.Web.Security;
using System.Collections.Specialized;
using System;
using System.Linq;
using System.Configuration.Provider;
using MongoDB.Driver.Builders;
using MongoDB.Bson.Serialization;
namespace MongoProviders.UnitTests
{
[TestFixture]
public class MembershipProviderTest : BaseTest
{
protected MembershipProvider provider;
[SetUp]
public override void Setup()
{
base.Setup();
provider = new MembershipProvider();
}
private void CreateUserWithFormat(MembershipPasswordFormat format)
{
NameValueCollection config = new NameValueCollection();
config.Add("connectionStringName", _connStrName);
config.Add("applicationName", _applicationName);
config.Add("passwordStrengthRegularExpression", "bar.*");
config.Add("passwordFormat", format.ToString());
provider.Initialize(null, config);
// create the user
MembershipCreateStatus status;
provider.CreateUser("foo", "barbar!", "foo@bar.com", null, null, true, null, out status);
Assert.AreEqual(MembershipCreateStatus.Success, status);
// verify that the password format was saved
var user = _db.GetCollection<User>(provider.CollectionName).FindOne(Query.EQ(provider.ElementNames.LowercaseUsername, "foo"));
MembershipPasswordFormat rowFormat = user.PasswordFormat;
Assert.AreEqual(format, rowFormat);
// then attempt to verify the user
Assert.IsTrue(provider.ValidateUser("foo", "barbar!"));
}
[Test]
public void CreateUserWithHashedPassword()
{
CreateUserWithFormat(MembershipPasswordFormat.Hashed);
}
[Test]
public void CreateUserWithEncryptedPassword()
{
CreateUserWithFormat(MembershipPasswordFormat.Encrypted);
}
[Test]
public void CreateUserWithClearPassword()
{
CreateUserWithFormat(MembershipPasswordFormat.Clear);
}
/// <summary>
/// MySQL Bug #34792 New User/Changing Password Validation Not working.
/// </summary>
[Test]
public void ChangePassword()
{
CreateUserWithHashedPassword();
try
{
provider.ChangePassword("foo", "barbar!", "bar2");
Assert.Fail();
}
catch (ArgumentException ae1)
{
Assert.AreEqual("newPassword", ae1.ParamName);
Assert.IsTrue(ae1.Message.Contains("length of parameter"));
}
try
{
provider.ChangePassword("foo", "barbar!", "barbar2");
Assert.Fail();
}
catch (ArgumentException ae1)
{
Assert.AreEqual("newPassword", ae1.ParamName);
Assert.IsTrue(ae1.Message.Contains("alpha numeric"));
}
try
{
// now test regex strength testing
provider.ChangePassword("foo", "barbar!", "zzzxxx!");
Assert.Fail();
}
catch (ArgumentException ae1)
{
Assert.AreEqual("newPassword", ae1.ParamName);
Assert.IsTrue(ae1.Message.Contains("regular expression"));
}
// now do one that should work
bool result = provider.ChangePassword("foo", "barbar!", "barfoo!");
Assert.IsTrue(result);
provider.ValidateUser("foo", "barfoo!");
}
/// <summary>
/// MySQL Bug #34792 New User/Changing Password Validation Not working.
/// </summary>
[Test]
public void CreateUserWithErrors()
{
NameValueCollection config = new NameValueCollection();
config.Add("connectionStringName", _connStrName);
config.Add("applicationName", _applicationName);
config.Add("passwordStrengthRegularExpression", "bar.*");
config.Add("passwordFormat", "Hashed");
provider.Initialize(null, config);
// first try to create a user with a password not long enough
MembershipCreateStatus status;
MembershipUser user = provider.CreateUser("foo", "xyz",
"foo@bar.com", null, null, true, null, out status);
Assert.IsNull(user);
Assert.AreEqual(MembershipCreateStatus.InvalidPassword, status);
// now with not enough non-alphas
user = provider.CreateUser("foo", "xyz1234",
"foo@bar.com", null, null, true, null, out status);
Assert.IsNull(user);
Assert.AreEqual(MembershipCreateStatus.InvalidPassword, status);
// now one that doesn't pass the regex test
user = provider.CreateUser("foo", "xyzxyz!",
"foo@bar.com", null, null, true, null, out status);
Assert.IsNull(user);
Assert.AreEqual(MembershipCreateStatus.InvalidPassword, status);
// now one that works
user = provider.CreateUser("foo", "barbar!",
"foo@bar.com", null, null, true, null, out status);
Assert.IsNotNull(user);
Assert.AreEqual(MembershipCreateStatus.Success, status);
}
[Test]
public void CreateUserWithDefaultInvalidCharacters()
{
// test default invalid characters
// Username
MembershipCreateStatus status;
MembershipUser user = Membership.CreateUser("foo,","xyz",
"foo@bar.com", null, null, true, null, out status);
Assert.IsNull(user);
Assert.AreEqual(MembershipCreateStatus.InvalidUserName, status);
user = Membership.CreateUser("foo%", "xyz",
"foo@bar.com", null, null, true, null, out status);
Assert.IsNull(user);
Assert.AreEqual(MembershipCreateStatus.InvalidUserName, status);
// Email
user = Membership.CreateUser("foo", "xyz",
"foo,@bar.com", null, null, true, null, out status);
Assert.IsNull(user);
Assert.AreEqual(MembershipCreateStatus.InvalidEmail, status);
user = Membership.CreateUser("foo", "xyz",
"foo%@bar.com", null, null, true, null, out status);
Assert.IsNull(user);
Assert.AreEqual(MembershipCreateStatus.InvalidEmail, status);
}
[Test]
public void CreateUserWithCustomInvalidCharacters()
{
var invalidUserChars = "()-#";
var invalidEmailChars = "^/`";
NameValueCollection config = new NameValueCollection();
config.Add("connectionStringName", _connStrName);
config.Add("applicationName", _applicationName);
config.Add("passwordStrengthRegularExpression", "bar.*");
config.Add("passwordFormat", "Hashed");
config.Add("invalidUsernameCharacters", invalidUserChars);
config.Add("invalidEmailCharacters", invalidEmailChars);
provider.Initialize(null, config);
// Username
MembershipCreateStatus status;
var username = "foo{0}";
foreach (var c in invalidUserChars.Split())
{
MembershipUser user = provider.CreateUser(
String.Format(username, c),
"xyz",
"foo@bar.com", null, null, true, null, out status);
Assert.IsNull(user);
Assert.AreEqual(MembershipCreateStatus.InvalidUserName, status);
}
// Email
var email = "foo{0}@bar.com";
foreach (var c in invalidEmailChars.Split())
{
MembershipUser user = provider.CreateUser(
"foo",
"xyz",
String.Format(email, c),
null, null, true, null, out status);
Assert.IsNull(user);
Assert.AreEqual(MembershipCreateStatus.InvalidEmail, status);
}
}
[Test]
public void DeleteUser()
{
CreateUserWithHashedPassword();
Assert.IsTrue(provider.DeleteUser("foo", true));
var count = _db.GetCollection<User>(provider.CollectionName).Count();
Assert.AreEqual(0, count);
provider = new MembershipProvider();
CreateUserWithHashedPassword();
// in Mongo, all associated data is stored in same document so
// passing true or false to DeleteUser will be the same.
Assert.IsTrue(provider.DeleteUser("foo", deleteAllRelatedData: true));
count = _db.GetCollection<User>(provider.CollectionName).Count();
Assert.AreEqual(0, count);
//Assert.IsTrue(Membership.DeleteUser("foo", false));
//table = FillTable("SELECT * FROM my_aspnet_Membership");
//Assert.AreEqual(0, table.Rows.Count);
//table = FillTable("SELECT * FROM my_aspnet_Users");
//Assert.AreEqual(1, table.Rows.Count);
}
[Test]
public void FindUsersByName()
{
CreateUserWithHashedPassword();
int records;
MembershipUserCollection users = provider.FindUsersByName("F%", 0, 10, out records);
Assert.AreEqual(1, records);
Assert.AreEqual("foo", users["foo"].UserName);
}
[Test]
public void FindUsersByEmail()
{
CreateUserWithHashedPassword();
int records;
MembershipUserCollection users = provider.FindUsersByEmail("foo@bar.com", 0, 10, out records);
Assert.AreEqual(1, records);
Assert.AreEqual("foo", users["foo"].UserName);
}
[Test]
public void TestCreateUserOverrides()
{
try
{
MembershipCreateStatus status;
Membership.CreateUser("foo", "barbar!", "foo@bar.com", "question", "answer", true, out status);
int records;
MembershipUserCollection users = Membership.FindUsersByName("F%", 0, 10, out records);
Assert.AreEqual(1, records);
Assert.AreEqual("foo", users["foo"].UserName);
Membership.CreateUser("test", "barbar!", "myemail@host.com",
"question", "answer", true, out status);
users = Membership.FindUsersByName("T%", 0, 10, out records);
Assert.AreEqual(1, records);
Assert.AreEqual("test", users["test"].UserName);
}
catch (Exception ex)
{
Assert.Fail(ex.Message);
}
}
[Test]
public void NumberOfUsersOnline()
{
int numOnline = Membership.GetNumberOfUsersOnline();
Assert.AreEqual(0, numOnline);
MembershipCreateStatus status;
Membership.CreateUser("foo", "barbar!", "foo@bar.com", "question", "answer", true, out status);
Membership.CreateUser("foo2", "barbar!", "foo2@bar.com", "question", "answer", true, out status);
numOnline = Membership.GetNumberOfUsersOnline();
Assert.AreEqual(2, numOnline);
}
[Test]
public void UnlockUser()
{
MembershipCreateStatus status;
Membership.CreateUser("foo", "barbar!", "foo@bar.com", "question", "answer", true, out status);
Assert.IsFalse(Membership.ValidateUser("foo", "bar2"));
Assert.IsFalse(Membership.ValidateUser("foo", "bar3"));
Assert.IsFalse(Membership.ValidateUser("foo", "bar3"));
Assert.IsFalse(Membership.ValidateUser("foo", "bar3"));
Assert.IsFalse(Membership.ValidateUser("foo", "bar3"));
// the user should be locked now so the right password should fail
Assert.IsFalse(Membership.ValidateUser("foo", "barbar!"));
MembershipUser user = Membership.GetUser("foo");
Assert.IsTrue(user.IsLockedOut);
Assert.IsTrue(user.UnlockUser());
user = Membership.GetUser("foo");
Assert.IsFalse(user.IsLockedOut);
Assert.IsTrue(Membership.ValidateUser("foo", "barbar!"));
}
[Test]
public void GetUsernameByEmail()
{
MembershipCreateStatus status;
Membership.CreateUser("foo", "barbar!", "foo@bar.com", "question", "answer", true, out status);
string username = Membership.GetUserNameByEmail("foo@bar.com");
Assert.AreEqual("foo", username);
username = Membership.GetUserNameByEmail("foo@b.com");
Assert.IsNull(username);
username = Membership.GetUserNameByEmail(" foo@bar.com ");
Assert.AreEqual("foo", username);
}
[Test]
public void UpdateUser()
{
MembershipCreateStatus status;
Membership.CreateUser("foo", "barbar!", "foo@bar.com", "color", "blue", true, out status);
Assert.AreEqual(MembershipCreateStatus.Success, status);
MembershipUser user = Membership.GetUser("foo");
user.Comment = "my comment";
user.Email = "my email";
user.IsApproved = false;
user.LastActivityDate = new DateTime(2008, 1, 1);
user.LastLoginDate = new DateTime(2008, 2, 1);
Membership.UpdateUser(user);
MembershipUser newUser = Membership.GetUser("foo");
Assert.AreEqual(user.Comment, newUser.Comment);
Assert.AreEqual(user.Email, newUser.Email);
Assert.AreEqual(user.IsApproved, newUser.IsApproved);
Assert.AreEqual(user.LastActivityDate, newUser.LastActivityDate);
Assert.AreEqual(user.LastLoginDate, newUser.LastLoginDate);
}
private void ChangePasswordQAHelper(MembershipUser user, string pw, string newQ, string newA)
{
try
{
user.ChangePasswordQuestionAndAnswer(pw, newQ, newA);
Assert.Fail("This should not work.");
}
catch (ArgumentNullException ane)
{
Assert.AreEqual("password", ane.ParamName);
}
catch (ArgumentException)
{
Assert.IsNotNull(pw);
}
}
[Test]
public void ChangePasswordQuestionAndAnswer()
{
MembershipCreateStatus status;
Membership.CreateUser("foo", "barbar!", "foo@bar.com", "color", "blue", true, out status);
Assert.AreEqual(MembershipCreateStatus.Success, status);
MembershipUser user = Membership.GetUser("foo");
ChangePasswordQAHelper(user, "", "newQ", "newA");
ChangePasswordQAHelper(user, "barbar!", "", "newA");
ChangePasswordQAHelper(user, "barbar!", "newQ", "");
ChangePasswordQAHelper(user, null, "newQ", "newA");
bool result = user.ChangePasswordQuestionAndAnswer("barbar!", "newQ", "newA");
Assert.IsTrue(result);
user = Membership.GetUser("foo");
Assert.AreEqual("newQ", user.PasswordQuestion);
}
[Test]
public void GetAllUsers()
{
MembershipCreateStatus status;
// first create a bunch of users
for (int i = 0; i < 100; i++)
{
var user = String.Format("foo{0}", i);
Membership.CreateUser(user, "barbar!", user + "@bar.com",
"question", "answer", true, out status);
}
MembershipUserCollection users = Membership.GetAllUsers();
Assert.AreEqual(100, users.Count);
int index = 0;
foreach (MembershipUser user in users)
Assert.AreEqual(String.Format("foo{0}", index++), user.UserName);
int total;
users = Membership.GetAllUsers(2, 10, out total);
Assert.AreEqual(10, users.Count);
Assert.AreEqual(100, total);
index = 0;
foreach (MembershipUser user in users)
Assert.AreEqual(String.Format("foo2{0}", index++), user.UserName);
}
private void GetPasswordHelper(bool requireQA, bool enablePasswordRetrieval, string answer)
{
MembershipCreateStatus status;
provider = new MembershipProvider();
NameValueCollection config = new NameValueCollection();
config.Add("connectionStringName", _connStrName);
config.Add("requiresQuestionAndAnswer", requireQA ? "true" : "false");
config.Add("enablePasswordRetrieval", enablePasswordRetrieval ? "true" : "false");
config.Add("passwordFormat", "clear");
config.Add("applicationName", _applicationName);
config.Add("writeExceptionsToEventLog", "false");
provider.Initialize(null, config);
provider.CreateUser("foo", "barbar!", "foo@bar.com", "color", "blue", true, null, out status);
try
{
string password = provider.GetPassword("foo", answer);
if (!enablePasswordRetrieval)
Assert.Fail("This should have thrown an exception");
Assert.AreEqual("barbar!", password);
}
catch (MembershipPasswordException)
{
if (requireQA && answer != null)
Assert.Fail("This should not have thrown an exception");
}
catch (ProviderException)
{
if (requireQA && answer != null)
Assert.Fail("This should not have thrown an exception");
}
}
[Test]
public void GetPassword()
{
GetPasswordHelper(false, false, null);
GetPasswordHelper(false, true, null);
GetPasswordHelper(true, true, null);
GetPasswordHelper(true, true, "blue");
}
/// <summary>
/// MySQL Bug #38939 MembershipUser.GetPassword(string answer) fails when incorrect answer is passed.
/// </summary>
[Test]
public void GetPasswordWithWrongAnswer()
{
MembershipCreateStatus status;
NameValueCollection config = new NameValueCollection();
config.Add("connectionStringName", _connStrName);
config.Add("requiresQuestionAndAnswer", "true");
config.Add("enablePasswordRetrieval", "true");
config.Add("passwordFormat", "Encrypted");
config.Add("applicationName", _applicationName);
provider.Initialize(null, config);
provider.CreateUser("foo", "barbar!", "foo@bar.com", "color", "blue", true, null, out status);
MongoProviders.MembershipProvider provider2 = new MongoProviders.MembershipProvider();
NameValueCollection config2 = new NameValueCollection();
config2.Add("connectionStringName", _connStrName);
config2.Add("requiresQuestionAndAnswer", "true");
config2.Add("enablePasswordRetrieval", "true");
config2.Add("passwordFormat", "Encrypted");
config2.Add("applicationName", _applicationName);
provider2.Initialize(null, config2);
try
{
string pw = provider2.GetPassword("foo", "wrong");
Assert.Fail("Should have failed");
}
catch (MembershipPasswordException)
{
}
}
[Test]
public void GetUser()
{
MembershipCreateStatus status;
var guid = Guid.NewGuid();
Membership.CreateUser("foo", "barbar!", "foo@bar.com", "question", "answer", true, guid, out status);
MembershipUser user = Membership.GetUser(guid);
Assert.AreEqual("foo", user.UserName);
// now move the activity date back outside the login
// window
user.LastActivityDate = new DateTime(2008, 1, 1);
Membership.UpdateUser(user);
user = Membership.GetUser("foo");
Assert.IsFalse(user.IsOnline);
user = Membership.GetUser("foo", true);
Assert.IsTrue(user.IsOnline);
// now move the activity date back outside the login
// window again so we can test with providerUserKey
user.LastActivityDate = new DateTime(2008, 1, 1);
Membership.UpdateUser(user);
user = Membership.GetUser(guid);
Assert.IsFalse(user.IsOnline);
user = Membership.GetUser(guid, true);
Assert.IsTrue(user.IsOnline);
}
[Test]
public void FindUsers()
{
MembershipCreateStatus status;
for (int i = 0; i < 100; i++)
{
var user = String.Format("boo{0}", i);
Membership.CreateUser(user, "barbar!", user + "@bar.com",
"question", "answer", true, out status);
Assert.AreEqual(MembershipCreateStatus.Success, status);
}
for (int i = 0; i < 100; i++)
{
var user = String.Format("foo{0}", i);
Membership.CreateUser(user, "barbar!", user + "@bar.com",
"question", "answer", true, null, out status);
Assert.AreEqual(MembershipCreateStatus.Success, status);
}
for (int i = 0; i < 100; i++)
{
var user = String.Format("schmoo{0}", i);
Membership.CreateUser(user, "barbar!", user + "@bar.com",
"question", "answer", true, null, out status);
Assert.AreEqual(MembershipCreateStatus.Success, status);
}
int total = 0;
MembershipUserCollection users = Membership.FindUsersByName("fo%");
Assert.AreEqual(100, users.Count);
users = Membership.FindUsersByName("fo%", 2, 10, out total);
Assert.AreEqual(10, users.Count);
Assert.AreEqual(100, total);
int index = 0;
foreach (MembershipUser user in users)
Assert.AreEqual(String.Format("foo2{0}", index++), user.UserName);
}
[Test]
public void CreateUserWithNoQA()
{
MembershipCreateStatus status;
NameValueCollection config = new NameValueCollection();
config.Add("connectionStringName", _connStrName);
config.Add("requiresQuestionAndAnswer", "true");
config.Add("passwordFormat", "clear");
config.Add("applicationName", _applicationName);
provider.Initialize(null, config);
provider.CreateUser("foo", "barbar!", "foo@bar.com", "color", null, true, null, out status);
Assert.AreEqual(MembershipCreateStatus.InvalidAnswer, status);
provider.CreateUser("foo", "barbar!", "foo@bar.com", "", "blue", true, null, out status);
Assert.AreEqual(MembershipCreateStatus.InvalidQuestion, status);
}
[Test]
public void MinRequiredAlpha()
{
NameValueCollection config = new NameValueCollection();
config.Add("connectionStringName", _connStrName);
config.Add("applicationName", _applicationName);
config.Add("minRequiredNonalphanumericCharacters", "3");
provider.Initialize(null, config);
MembershipCreateStatus status;
MembershipUser user = provider.CreateUser("foo", "pw!pass", "email", null, null, true, null, out status);
Assert.IsNull(user);
Assert.AreEqual(MembershipCreateStatus.InvalidPassword, status);
user = provider.CreateUser("foo", "pw!pa!!", "email", null, null, true, null, out status);
Assert.IsNotNull(user);
Assert.AreEqual(MembershipCreateStatus.Success, status);
}
/// <summary>
/// MySQL Bug #35332 GetPassword() don't working (when PasswordAnswer is NULL)
/// </summary>
[Test]
public void GetPasswordWithNullValues()
{
MembershipCreateStatus status;
NameValueCollection config = new NameValueCollection();
config.Add("connectionStringName", _connStrName);
config.Add("requiresQuestionAndAnswer", "false");
config.Add("enablePasswordRetrieval", "true");
config.Add("passwordFormat", "clear");
config.Add("applicationName", _applicationName);
provider.Initialize(null, config);
MembershipUser user = provider.CreateUser("foo", "barbar!", "foo@bar.com", null, null, true, null, out status);
Assert.IsNotNull(user);
string pw = provider.GetPassword("foo", null);
Assert.AreEqual("barbar!", pw);
}
/// <summary>
/// MySQL Bug #35336 GetPassword() return wrong password (when format is encrypted)
/// </summary>
[Test]
public void GetEncryptedPassword()
{
MembershipCreateStatus status;
NameValueCollection config = new NameValueCollection();
config.Add("connectionStringName", _connStrName);
config.Add("requiresQuestionAndAnswer", "false");
config.Add("enablePasswordRetrieval", "true");
config.Add("passwordFormat", "encrypted");
config.Add("applicationName", _applicationName);
provider.Initialize(null, config);
MembershipUser user = provider.CreateUser("foo", "barbar!", "foo@bar.com", null, null, true, null, out status);
Assert.IsNotNull(user);
string pw = provider.GetPassword("foo", null);
Assert.AreEqual("barbar!", pw);
}
/// <summary>
/// MySQL Bug #42574 ValidateUser does not use the application id, allowing cross application login
/// </summary>
[Test]
public void CrossAppLogin()
{
NameValueCollection config = new NameValueCollection();
config.Add("connectionStringName", _connStrName);
config.Add("applicationName", _applicationName);
config.Add("passwordStrengthRegularExpression", "bar.*");
config.Add("passwordFormat", "Clear");
provider.Initialize(null, config);
MembershipCreateStatus status;
provider.CreateUser("foo", "bar!bar", null, null, null, true, null, out status);
MongoProviders.MembershipProvider provider2 = new MongoProviders.MembershipProvider();
NameValueCollection config2 = new NameValueCollection();
config2.Add("connectionStringName", _connStrName);
config2.Add("applicationName", _appName2);
config2.Add("passwordStrengthRegularExpression", ".*");
config2.Add("passwordFormat", "Clear");
provider2.Initialize(null, config2);
bool worked = provider2.ValidateUser("foo", "bar!bar");
Assert.AreEqual(false, worked);
_db.DropCollection(provider2.CollectionName);
}
/// <summary>
/// MySQL Bug #41408 PasswordReset not possible when requiresQuestionAndAnswer="false"
/// </summary>
[Test]
public void ResetPasswordWorksWhenRequiresQuestionAndAnswerIsFalse()
{
NameValueCollection config = new NameValueCollection();
config.Add("connectionStringName", _connStrName);
config.Add("applicationName", _applicationName);
config.Add("passwordStrengthRegularExpression", "bar.*");
config.Add("passwordFormat", "Clear");
config.Add("requiresQuestionAndAnswer", "false");
provider.Initialize(null, config);
MembershipCreateStatus status;
provider.CreateUser("foo", "bar!bar", "foo@bar.com", null, null, true, null, out status);
MembershipUser u = provider.GetUser("foo", false);
string newpw = provider.ResetPassword("foo", null);
}
[Test]
public void CanResetPasswordForHashedAndSaltedPasswords()
{
NameValueCollection config = new NameValueCollection();
config.Add("connectionStringName", _connStrName);
config.Add("applicationName", _applicationName);
//config.Add("passwordStrengthRegularExpression", "bar.*");
config.Add("passwordFormat", "Hashed");
config.Add("requiresQuestionAndAnswer", "false");
provider.Initialize(null, config);
MembershipCreateStatus status;
provider.CreateUser("foo", "bar!bar", "foo@bar.com", null, null, true, null, out status);
MembershipUser u = provider.GetUser("foo", false);
string newpw = provider.ResetPassword("foo", null);
var result = provider.ValidateUser("foo", newpw);
Assert.AreEqual(true, result);
}
/// <summary>
/// MySQL Bug #59438 setting Membership.ApplicationName has no effect
/// </summary>
[Test]
public void ChangeAppName()
{
NameValueCollection config = new NameValueCollection();
config.Add("connectionStringName", _connStrName);
config.Add("applicationName", _applicationName);
config.Add("requiresUniqueEmail", "false");
config.Add("passwordStrengthRegularExpression", "bar.*");
config.Add("passwordFormat", "Clear");
provider.Initialize(null, config);
MembershipCreateStatus status;
provider.CreateUser("foo", "bar!bar", null, null, null, true, null, out status);
Assert.AreEqual(MembershipCreateStatus.Success, status);
MongoProviders.MembershipProvider provider2 = new MongoProviders.MembershipProvider();
NameValueCollection config2 = new NameValueCollection();
config2.Add("connectionStringName", _connStrName);
config2.Add("applicationName", _appName2);
config2.Add("requiresUniqueEmail", "false");
config2.Add("passwordStrengthRegularExpression", "foo.*");
config2.Add("passwordFormat", "Clear");
provider2.Initialize(null, config2);
provider2.CreateUser("foo2", "foo!foo", null, null, null, true, null, out status);
Assert.AreEqual(MembershipCreateStatus.Success, status);
provider.ApplicationName = "/myapp";
Assert.IsFalse(provider.ValidateUser("foo", "bar!bar"));
Assert.IsTrue(provider.ValidateUser("foo2", "foo!foo"));
}
[Test]
public void GetUserLooksForExactUsername()
{
MembershipCreateStatus status;
Membership.CreateUser("code", "thecode!", "code@example.com", "question", "answer", true, out status);
MembershipUser user = Membership.GetUser("code");
Assert.AreEqual("code", user.UserName);
user = Membership.GetUser("co_e");
Assert.IsNull(user);
}
[Test]
public void GetUserNameByEmailLooksForExactEmail()
{
MembershipCreateStatus status;
Membership.CreateUser("code", "thecode!", "code@mysql.com", "question", "answer", true, out status);
string username = Membership.GetUserNameByEmail("code@mysql.com");
Assert.AreEqual("code", username);
username = Membership.GetUserNameByEmail("co_e@mysql.com");
Assert.IsNull(username);
}
protected class Profile : User
{
public string FirstName { get; set; }
}
[Test]
public void UserUpdateDoesNotWipeOutIgnoredFields()
{
if (!BsonClassMap.IsClassMapRegistered(typeof(Profile)))
{
BsonClassMap.RegisterClassMap<Profile>();
}
NameValueCollection config = new NameValueCollection();
config.Add("connectionStringName", _connStrName);
config.Add("applicationName", _applicationName);
config.Add("requiresUniqueEmail", "false");
config.Add("passwordFormat", "Clear");
config.Add("enablePasswordRetrieval", "true");
provider.Initialize(null, config);
MembershipCreateStatus status;
Membership.CreateUser("foo", "bar!bar", "foo@bar.com", "question", "answer", true, out status);
// ensure user created correctly
MembershipUser user = Membership.GetUser("foo");
Assert.AreEqual("question", user.PasswordQuestion);
// save Profile over User
var mongoProvider = (MongoProviders.MembershipProvider)Membership.Provider;
var profiles = mongoProvider.Database.GetCollection<Profile>(mongoProvider.CollectionName);
var profile = profiles.FindOne(Query.EQ("lname", "foo"));
profile.FirstName = "Neo";
profiles.Save(profile);
// ensure profile saved correctly
profile = profiles.FindOne(Query.EQ("lname", "foo"));
Assert.AreEqual("Neo", profile.FirstName);
Assert.AreEqual("question", profile.PasswordQuestion);
// validate User
var valid = Membership.ValidateUser("foo", "bar!bar");
Assert.AreEqual(true, valid);
// ensure profile fields still in database
profile = profiles.FindOne(Query.EQ("lname", "foo"));
Assert.AreEqual("Neo", profile.FirstName);
Assert.AreEqual("question", profile.PasswordQuestion);
// update User
user.ChangePassword("bar!bar","foo!foo");
// ensure profile fields still in database
profile = profiles.FindOne(Query.EQ("lname", "foo"));
Assert.AreEqual("Neo", profile.FirstName);
Assert.AreEqual("question", profile.PasswordQuestion);
}
}
} | 40.593468 | 138 | 0.583544 | [
"MIT"
] | foxsofter/MongoProviders | MongoProviders.UnitTests/MembershipProviderTest.cs | 36,049 | C# |
// Copyright (c) Josef Pihrt. All rights reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Roslynator.CodeAnalysis.CSharp;
using Roslynator.Testing.CSharp;
using Xunit;
namespace Roslynator.CSharp.Analysis.Tests
{
public class RCS9004CallAnyInsteadOfAccessingCountTests : AbstractCSharpDiagnosticVerifier<SimpleMemberAccessExpressionAnalyzer, BinaryExpressionCodeFixProvider>
{
public override DiagnosticDescriptor Descriptor { get; } = DiagnosticRules.CallAnyInsteadOfAccessingCount;
[Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.CallAnyInsteadOfAccessingCount)]
public async Task Test_SyntaxList_Equals()
{
await VerifyDiagnosticAndFixAsync(@"
using Microsoft.CodeAnalysis;
class C
{
void M()
{
SyntaxList<SyntaxNode> list = default;
if (list.[|Count == 0|]) { }
}
}
", @"
using Microsoft.CodeAnalysis;
class C
{
void M()
{
SyntaxList<SyntaxNode> list = default;
if (!list.Any()) { }
}
}
");
}
[Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.CallAnyInsteadOfAccessingCount)]
public async Task Test_SyntaxList_Equals2()
{
await VerifyDiagnosticAndFixAsync(@"
using Microsoft.CodeAnalysis;
class C
{
void M()
{
SyntaxList<SyntaxNode> list = default;
if ([|0 == list.Count|]) { }
}
}
", @"
using Microsoft.CodeAnalysis;
class C
{
void M()
{
SyntaxList<SyntaxNode> list = default;
if (!list.Any()) { }
}
}
");
}
[Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.CallAnyInsteadOfAccessingCount)]
public async Task Test_SyntaxList_NotEquals()
{
await VerifyDiagnosticAndFixAsync(@"
using Microsoft.CodeAnalysis;
class C
{
void M()
{
SyntaxList<SyntaxNode> list = default;
if (list.[|Count != 0|]) { }
}
}
", @"
using Microsoft.CodeAnalysis;
class C
{
void M()
{
SyntaxList<SyntaxNode> list = default;
if (list.Any()) { }
}
}
");
}
[Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.CallAnyInsteadOfAccessingCount)]
public async Task Test_SyntaxList_GreaterThan()
{
await VerifyDiagnosticAndFixAsync(@"
using Microsoft.CodeAnalysis;
class C
{
void M()
{
SyntaxList<SyntaxNode> list = default;
if (list.[|Count > 0|]) { }
}
}
", @"
using Microsoft.CodeAnalysis;
class C
{
void M()
{
SyntaxList<SyntaxNode> list = default;
if (list.Any()) { }
}
}
");
}
[Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.CallAnyInsteadOfAccessingCount)]
public async Task Test_SeparatedSyntaxList_GreaterThan()
{
await VerifyDiagnosticAndFixAsync(@"
using Microsoft.CodeAnalysis;
class C
{
void M()
{
SeparatedSyntaxList<SyntaxNode> list = default;
if (list.[|Count > 0|]) { }
}
}
", @"
using Microsoft.CodeAnalysis;
class C
{
void M()
{
SeparatedSyntaxList<SyntaxNode> list = default;
if (list.Any()) { }
}
}
");
}
[Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.CallAnyInsteadOfAccessingCount)]
public async Task Test_SyntaxTokenList_GreaterThan()
{
await VerifyDiagnosticAndFixAsync(@"
using Microsoft.CodeAnalysis;
class C
{
void M()
{
SyntaxTokenList list = default;
if (list.[|Count > 0|]) { }
}
}
", @"
using Microsoft.CodeAnalysis;
class C
{
void M()
{
SyntaxTokenList list = default;
if (list.Any()) { }
}
}
");
}
[Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.CallAnyInsteadOfAccessingCount)]
public async Task Test_SyntaxTriviaList_GreaterThan()
{
await VerifyDiagnosticAndFixAsync(@"
using Microsoft.CodeAnalysis;
class C
{
void M()
{
SyntaxTriviaList list = default;
if (list.[|Count > 0|]) { }
}
}
", @"
using Microsoft.CodeAnalysis;
class C
{
void M()
{
SyntaxTriviaList list = default;
if (list.Any()) { }
}
}
");
}
[Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.CallAnyInsteadOfAccessingCount)]
public async Task Test_ChildSyntaxList_GreaterThan()
{
await VerifyDiagnosticAndFixAsync(@"
using Microsoft.CodeAnalysis;
class C
{
void M()
{
ChildSyntaxList list = default;
if (list.[|Count > 0|]) { }
}
}
", @"
using Microsoft.CodeAnalysis;
class C
{
void M()
{
ChildSyntaxList list = default;
if (list.Any()) { }
}
}
");
}
[Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.CallAnyInsteadOfAccessingCount)]
public async Task Test_SyntaxNodeOrTokenList_GreaterThan()
{
await VerifyDiagnosticAndFixAsync(@"
using Microsoft.CodeAnalysis;
class C
{
void M()
{
SyntaxNodeOrTokenList list = default;
if (list.[|Count > 0|]) { }
}
}
", @"
using Microsoft.CodeAnalysis;
class C
{
void M()
{
SyntaxNodeOrTokenList list = default;
if (list.Any()) { }
}
}
");
}
[Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.CallAnyInsteadOfAccessingCount)]
public async Task TestNoDiagnostic_LessThanExpression()
{
await VerifyNoDiagnosticAsync(@"
using Microsoft.CodeAnalysis;
class C
{
void M()
{
SyntaxList<SyntaxNode> list = default;
if (list.Count < 0) { }
}
}
");
}
[Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.CallAnyInsteadOfAccessingCount)]
public async Task TestNoDiagnostic_NotNumericLiteralExpression()
{
await VerifyNoDiagnosticAsync(@"
using Microsoft.CodeAnalysis;
class C
{
void M()
{
SyntaxList<SyntaxNode> list = default;
int count = 0;
if (list.Count > count) { }
}
}
");
}
[Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.CallAnyInsteadOfAccessingCount)]
public async Task TestNoDiagnostic_NotZeroNumericLiteralExpression()
{
await VerifyNoDiagnosticAsync(@"
using Microsoft.CodeAnalysis;
class C
{
void M()
{
SyntaxList<SyntaxNode> list = default;
if (list.Count > 1) { }
}
}
");
}
[Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.CallAnyInsteadOfAccessingCount)]
public async Task TestNoDiagnostic_NotSyntaxList()
{
await VerifyNoDiagnosticAsync(@"
using System.Collections.Generic;
using Microsoft.CodeAnalysis;
class C
{
void M()
{
List<SyntaxNode> list = default;
if (list.Count > 0) { }
}
}
");
}
}
}
| 19.305556 | 165 | 0.614676 | [
"Apache-2.0"
] | JosefPihrt/Roslynator | src/Tests/CodeAnalysis.Analyzers.Tests/RCS9004CallAnyInsteadOfAccessingCountTests.cs | 6,952 | C# |
using RememBeer.Business.Logic.Account.Confirm.Contracts;
namespace RememBeer.Business.Logic.Account.Confirm
{
public class ConfirmEventArgs : IConfirmEventArgs
{
public ConfirmEventArgs(string userId, string code)
{
this.UserId = userId;
this.Code = code;
}
public string UserId { get; set; }
public string Code { get; set; }
}
}
| 22.833333 | 59 | 0.625304 | [
"MIT"
] | J0hnyBG/RememBeerMe | src/RememBeer.Business/Logic/Account/Confirm/ConfirmEventArgs.cs | 413 | C# |
using System.Net;
using System.Threading.Tasks;
using FluentAssertions;
using JsonApiDotNetCore.Serialization.Objects;
using JsonApiDotNetCoreExampleTests.Startups;
using TestBuildingBlocks;
using Xunit;
namespace JsonApiDotNetCoreExampleTests.IntegrationTests.CustomRoutes
{
public sealed class ApiControllerAttributeTests
: IClassFixture<ExampleIntegrationTestContext<TestableStartup<CustomRouteDbContext>, CustomRouteDbContext>>
{
private readonly ExampleIntegrationTestContext<TestableStartup<CustomRouteDbContext>, CustomRouteDbContext> _testContext;
public ApiControllerAttributeTests(ExampleIntegrationTestContext<TestableStartup<CustomRouteDbContext>, CustomRouteDbContext> testContext)
{
_testContext = testContext;
}
[Fact]
public async Task ApiController_attribute_transforms_NotFound_action_result_without_arguments_into_ProblemDetails()
{
// Arrange
const string route = "/world-civilians/missing";
// Act
var (httpResponse, responseDocument) = await _testContext.ExecuteGetAsync<ErrorDocument>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound);
responseDocument.Errors.Should().HaveCount(1);
var error = responseDocument.Errors[0];
error.Links.About.Should().Be("https://tools.ietf.org/html/rfc7231#section-6.5.4");
}
}
}
| 36.925 | 146 | 0.729858 | [
"MIT"
] | jlits/JsonApiDotNetCore | test/JsonApiDotNetCoreExampleTests/IntegrationTests/CustomRoutes/ApiControllerAttributeTests.cs | 1,477 | C# |
using System;
using UnityEngine;
namespace KontrolSystem.KSP.Runtime.KSPVessel {
public partial class KSPVesselModule {
public class SimulatedParachute : SimulatedPart {
private ModuleParachute para;
private ModuleParachute.deploymentStates state;
private double openningTime;
private float deployLevel = 0;
public bool deploying = false;
private bool willDeploy = false;
public SimulatedParachute(ModuleParachute mp, SimCurves simCurve, double startTime, int limitChutesStage) : base(mp.part, simCurve) {
this.para = mp;
this.state = mp.deploymentState;
willDeploy = limitChutesStage != -1 && para.part.inverseStage >= limitChutesStage;
// Work out when the chute was put into its current state based on the current drag as compared to the stowed, semi deployed and fully deployed drag
double timeSinceDeployment = 0;
switch (mp.deploymentState) {
case ModuleParachute.deploymentStates.SEMIDEPLOYED:
if (mp.Anim.isPlaying)
timeSinceDeployment = mp.Anim[mp.semiDeployedAnimation].time;
else
timeSinceDeployment = 10000000;
break;
case ModuleParachute.deploymentStates.DEPLOYED:
if (mp.Anim.isPlaying)
timeSinceDeployment = mp.Anim[mp.fullyDeployedAnimation].time;
else
timeSinceDeployment = 10000000;
break;
case ModuleParachute.deploymentStates.STOWED:
case ModuleParachute.deploymentStates.ACTIVE:
// If the parachute is stowed then for some reason para.parachuteDrag does not reflect the stowed drag. set this up by hand.
timeSinceDeployment = 10000000;
break;
default:
// otherwise set the time since deployment to be a very large number to indcate that it has been in that state for a long time (although we do not know how long!
timeSinceDeployment = 10000000;
break;
}
this.openningTime = startTime - timeSinceDeployment;
}
public override Vector3d Drag(Vector3d vesselVelocity, double dragFactor, float mach) {
if (state != ModuleParachute.deploymentStates.SEMIDEPLOYED && state != ModuleParachute.deploymentStates.DEPLOYED)
return base.Drag(vesselVelocity, dragFactor, mach);
return Vector3d.zero;
}
// Consider activating, semi deploying or deploying a parachute, but do not actually make any changes. returns true if the state has changed
public override bool SimulateAndRollback(double altATGL, double altASL, double endASL, double pressure, double shockTemp, double time, double semiDeployMultiplier) {
if (!willDeploy)
return false;
bool stateChanged = false;
switch (state) {
case ModuleParachute.deploymentStates.STOWED:
if (altATGL < semiDeployMultiplier * para.deployAltitude && shockTemp * para.machHeatMult < para.chuteMaxTemp * para.safeMult) {
stateChanged = true;
}
break;
case ModuleParachute.deploymentStates.ACTIVE:
if (pressure >= para.minAirPressureToOpen) {
stateChanged = true;
}
break;
case ModuleParachute.deploymentStates.SEMIDEPLOYED:
if (altATGL < para.deployAltitude) {
stateChanged = true;
}
break;
}
return (stateChanged);
}
// Consider activating, semi deploying or deploying a parachute. returns true if the state has changed
public override bool Simulate(double altATGL, double altASL, double endASL, double pressure, double shockTemp, double time, double semiDeployMultiplier) {
if (!willDeploy)
return false;
switch (state) {
case ModuleParachute.deploymentStates.STOWED:
if (altATGL < semiDeployMultiplier * para.deployAltitude && shockTemp * para.machHeatMult < para.chuteMaxTemp * para.safeMult) {
state = ModuleParachute.deploymentStates.ACTIVE;
//activatedAGL = altATGL;
//activatedASL = altASL;
// Immediately check to see if the parachute should be semi deployed, rather than waiting for another iteration.
if (pressure >= para.minAirPressureToOpen) {
state = ModuleParachute.deploymentStates.SEMIDEPLOYED;
openningTime = time;
//semiDeployAGL = altATGL;
//semiDeployASL = altASL;
//targetASLAtSemiDeploy = endASL;
}
}
break;
case ModuleParachute.deploymentStates.ACTIVE:
if (pressure >= para.minAirPressureToOpen) {
state = ModuleParachute.deploymentStates.SEMIDEPLOYED;
openningTime = time;
//semiDeployAGL = altATGL;
//semiDeployASL = altASL;
//targetASLAtSemiDeploy = endASL;
}
break;
case ModuleParachute.deploymentStates.SEMIDEPLOYED:
if (altATGL < para.deployAltitude) {
state = ModuleParachute.deploymentStates.DEPLOYED;
openningTime = time;
//fullDeployAGL = altATGL;
//fullDeployASL = altASL;
//targetASLAtFullDeploy = endASL;
}
break;
}
// Now that we have potentially changed states calculate the current drag or the parachute in whatever state (or transition to a state) that it is in.
float normalizedTime;
// Depending on the state that we are in consider if we are part way through a deployment.
if (state == ModuleParachute.deploymentStates.SEMIDEPLOYED) {
normalizedTime = (float)Math.Min((time - openningTime) / para.semiDeploymentSpeed, 1);
} else if (state == ModuleParachute.deploymentStates.DEPLOYED) {
normalizedTime = (float)Math.Min((time - openningTime) / para.deploymentSpeed, 1);
} else {
normalizedTime = 1;
}
// Are we deploying in any way? We know if we are deploying or not if normalized time is less than 1
if (normalizedTime < 1) {
this.deploying = true;
} else {
this.deploying = false;
}
// If we are deploying or semi deploying then use Lerp to replicate the way the game increases the drag as we deploy.
if (deploying && (state == ModuleParachute.deploymentStates.SEMIDEPLOYED || state == ModuleParachute.deploymentStates.DEPLOYED)) {
this.deployLevel = Mathf.Pow(normalizedTime, para.deploymentCurve);
} else {
this.deployLevel = 1;
}
switch (state) {
case ModuleParachute.deploymentStates.STOWED:
case ModuleParachute.deploymentStates.ACTIVE:
case ModuleParachute.deploymentStates.CUT:
SetCubeWeight("PACKED", 1f);
SetCubeWeight("SEMIDEPLOYED", 0f);
SetCubeWeight("DEPLOYED", 0f);
break;
case ModuleParachute.deploymentStates.SEMIDEPLOYED:
SetCubeWeight("PACKED", 1f - deployLevel);
SetCubeWeight("SEMIDEPLOYED", deployLevel);
SetCubeWeight("DEPLOYED", 0f);
break;
case ModuleParachute.deploymentStates.DEPLOYED:
SetCubeWeight("PACKED", 0f);
SetCubeWeight("SEMIDEPLOYED", 1f - deployLevel);
SetCubeWeight("DEPLOYED", deployLevel);
break;
}
return deploying;
}
}
}
}
| 46.141304 | 181 | 0.567138 | [
"MIT"
] | untoldwind/KontrolSystem | KSPRuntime/KSPVessel/KSPVesselModule.SimulatedParachute.cs | 8,492 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
/*
* Do not modify this file. This file is generated from the glue-2017-03-31.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.Glue.Model
{
/// <summary>
/// Container for the parameters to the GetUserDefinedFunction operation.
/// Retrieves a specified function definition from the Data Catalog.
/// </summary>
public partial class GetUserDefinedFunctionRequest : AmazonGlueRequest
{
private string _catalogId;
private string _databaseName;
private string _functionName;
/// <summary>
/// Gets and sets the property CatalogId.
/// <para>
/// The ID of the Data Catalog where the function to be retrieved is located. If none
/// is provided, the AWS account ID is used by default.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=255)]
public string CatalogId
{
get { return this._catalogId; }
set { this._catalogId = value; }
}
// Check to see if CatalogId property is set
internal bool IsSetCatalogId()
{
return this._catalogId != null;
}
/// <summary>
/// Gets and sets the property DatabaseName.
/// <para>
/// The name of the catalog database where the function is located.
/// </para>
/// </summary>
[AWSProperty(Required=true, Min=1, Max=255)]
public string DatabaseName
{
get { return this._databaseName; }
set { this._databaseName = value; }
}
// Check to see if DatabaseName property is set
internal bool IsSetDatabaseName()
{
return this._databaseName != null;
}
/// <summary>
/// Gets and sets the property FunctionName.
/// <para>
/// The name of the function.
/// </para>
/// </summary>
[AWSProperty(Required=true, Min=1, Max=255)]
public string FunctionName
{
get { return this._functionName; }
set { this._functionName = value; }
}
// Check to see if FunctionName property is set
internal bool IsSetFunctionName()
{
return this._functionName != null;
}
}
} | 30.56 | 102 | 0.608966 | [
"Apache-2.0"
] | KenHundley/aws-sdk-net | sdk/src/Services/Glue/Generated/Model/GetUserDefinedFunctionRequest.cs | 3,056 | C# |
// Copyright (c) Umbraco.
// See LICENSE for more details.
namespace Umbraco.Cms.Tests.Common.Builders.Interfaces
{
public interface IWithNameBuilder
{
string Name { get; set; }
}
}
| 18.454545 | 54 | 0.669951 | [
"MIT"
] | Ambertvu/Umbraco-CMS | tests/Umbraco.Tests.Common/Builders/Interfaces/IWithNameBuilder.cs | 203 | C# |
using Orleans;
using Orleans.Providers;
using SimpleGrainInterfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SimpleGrains
{
[StorageProvider(ProviderName="basic")]
public class MyGrain : Grain<MyGrainState>, IMyGrain
{
public Task<int> GetThing1()
{
this.ReadStateAsync();
return Task.FromResult(this.State.Thing1);
}
public Task<string> GetThing2()
{
this.ReadStateAsync();
return Task.FromResult(this.State.Thing2);
}
public Task<Guid> GetThing3()
{
this.ReadStateAsync();
return Task.FromResult(this.State.Thing3);
}
public Task<DateTime> GetThing4()
{
this.ReadStateAsync();
return Task.FromResult(this.State.Thing4);
}
public Task<IEnumerable<int>> GetThings1()
{
this.ReadStateAsync();
return Task.FromResult(this.State.Things1);
}
public Task SaveSomething(int thing1, string thing2, Guid thing3, DateTime thing4, IEnumerable<int> things1)
{
State.Thing1 = thing1;
State.Thing2 = thing2;
State.Thing3 = thing3;
State.Thing4 = thing4;
State.Things1 = things1;
return this.WriteStateAsync();
}
public Task SetThing1(int v)
{
State.Thing1 = v;
return this.WriteStateAsync();
}
public Task SetThing2(string v)
{
State.Thing2 = v;
return this.WriteStateAsync();
}
public Task SetThing3(Guid v)
{
State.Thing3 = v;
return this.WriteStateAsync();
}
public Task SetThings1(IEnumerable<int> v)
{
State.Things1 = v;
return this.WriteStateAsync();
}
public Task<string> GetEtag()
{
return Task.FromResult(State.Etag);
}
public Task ReadSomething()
{
return this.ReadStateAsync();
}
public Task BreakEtagForUnitTestPurposes()
{
State.Etag = Guid.NewGuid().ToString();
return Task.CompletedTask;
}
}
}
| 23.381443 | 116 | 0.570106 | [
"MIT"
] | OrleansContrib/Orleans.StorageProviders.SimpleSQLServerStorage | Tests/SimpleGrains/MyGrain.cs | 2,270 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System.Collections.Generic;
using Azure.Core;
using Azure.ResourceManager.Models;
using Azure.ResourceManager.WebPubSub.Models;
namespace Azure.ResourceManager.WebPubSub
{
/// <summary> A class representing the WebPubSub data model. </summary>
public partial class WebPubSubData : TrackedResourceData
{
/// <summary> Initializes a new instance of WebPubSubData. </summary>
/// <param name="location"> The location. </param>
public WebPubSubData(AzureLocation location) : base(location)
{
PrivateEndpointConnections = new ChangeTrackingList<PrivateEndpointConnectionData>();
SharedPrivateLinkResources = new ChangeTrackingList<SharedPrivateLinkData>();
}
/// <summary> Initializes a new instance of WebPubSubData. </summary>
/// <param name="id"> The id. </param>
/// <param name="name"> The name. </param>
/// <param name="type"> The type. </param>
/// <param name="systemData"> The systemData. </param>
/// <param name="tags"> The tags. </param>
/// <param name="location"> The location. </param>
/// <param name="sku"> The billing information of the resource.(e.g. Free, Standard). </param>
/// <param name="identity"> The managed identity response. </param>
/// <param name="provisioningState"> Provisioning state of the resource. </param>
/// <param name="externalIP"> The publicly accessible IP of the resource. </param>
/// <param name="hostName"> FQDN of the service instance. </param>
/// <param name="publicPort"> The publicly accessible port of the resource which is designed for browser/client side usage. </param>
/// <param name="serverPort"> The publicly accessible port of the resource which is designed for customer server side usage. </param>
/// <param name="version"> Version of the resource. Probably you need the same or higher version of client SDKs. </param>
/// <param name="privateEndpointConnections"> Private endpoint connections to the resource. </param>
/// <param name="sharedPrivateLinkResources"> The list of shared private link resources. </param>
/// <param name="tls"> TLS settings. </param>
/// <param name="hostNamePrefix"> Deprecated. </param>
/// <param name="liveTraceConfiguration"> Live trace configuration of a Microsoft.SignalRService resource. </param>
/// <param name="resourceLogConfiguration">
/// Resource log configuration of a Microsoft.SignalRService resource.
/// If resourceLogConfiguration isn't null or empty, it will override options "EnableConnectivityLog" and "EnableMessagingLogs" in features.
/// Otherwise, use options "EnableConnectivityLog" and "EnableMessagingLogs" in features.
/// </param>
/// <param name="networkAcls"> Network Acls. </param>
/// <param name="publicNetworkAccess">
/// Enable or disable public network access. Default to "Enabled".
/// When it's Enabled, network ACLs still apply.
/// When it's Disabled, public network access is always disabled no matter what you set in network ACLs.
/// </param>
/// <param name="disableLocalAuth">
/// DisableLocalAuth
/// Enable or disable local auth with AccessKey
/// When set as true, connection with AccessKey=xxx won't work.
/// </param>
/// <param name="disableAadAuth">
/// DisableLocalAuth
/// Enable or disable aad auth
/// When set as true, connection with AuthType=aad won't work.
/// </param>
internal WebPubSubData(ResourceIdentifier id, string name, ResourceType type, SystemData systemData, IDictionary<string, string> tags, AzureLocation location, WebPubSubSku sku, ManagedIdentity identity, ProvisioningState? provisioningState, string externalIP, string hostName, int? publicPort, int? serverPort, string version, IReadOnlyList<PrivateEndpointConnectionData> privateEndpointConnections, IReadOnlyList<SharedPrivateLinkData> sharedPrivateLinkResources, WebPubSubTlsSettings tls, string hostNamePrefix, LiveTraceConfiguration liveTraceConfiguration, ResourceLogConfiguration resourceLogConfiguration, WebPubSubNetworkAcls networkAcls, string publicNetworkAccess, bool? disableLocalAuth, bool? disableAadAuth) : base(id, name, type, systemData, tags, location)
{
Sku = sku;
Identity = identity;
ProvisioningState = provisioningState;
ExternalIP = externalIP;
HostName = hostName;
PublicPort = publicPort;
ServerPort = serverPort;
Version = version;
PrivateEndpointConnections = privateEndpointConnections;
SharedPrivateLinkResources = sharedPrivateLinkResources;
Tls = tls;
HostNamePrefix = hostNamePrefix;
LiveTraceConfiguration = liveTraceConfiguration;
ResourceLogConfiguration = resourceLogConfiguration;
NetworkAcls = networkAcls;
PublicNetworkAccess = publicNetworkAccess;
DisableLocalAuth = disableLocalAuth;
DisableAadAuth = disableAadAuth;
}
/// <summary> The billing information of the resource.(e.g. Free, Standard). </summary>
public WebPubSubSku Sku { get; set; }
/// <summary> The managed identity response. </summary>
public ManagedIdentity Identity { get; set; }
/// <summary> Provisioning state of the resource. </summary>
public ProvisioningState? ProvisioningState { get; }
/// <summary> The publicly accessible IP of the resource. </summary>
public string ExternalIP { get; }
/// <summary> FQDN of the service instance. </summary>
public string HostName { get; }
/// <summary> The publicly accessible port of the resource which is designed for browser/client side usage. </summary>
public int? PublicPort { get; }
/// <summary> The publicly accessible port of the resource which is designed for customer server side usage. </summary>
public int? ServerPort { get; }
/// <summary> Version of the resource. Probably you need the same or higher version of client SDKs. </summary>
public string Version { get; }
/// <summary> Private endpoint connections to the resource. </summary>
public IReadOnlyList<PrivateEndpointConnectionData> PrivateEndpointConnections { get; }
/// <summary> The list of shared private link resources. </summary>
public IReadOnlyList<SharedPrivateLinkData> SharedPrivateLinkResources { get; }
/// <summary> TLS settings. </summary>
public WebPubSubTlsSettings Tls { get; set; }
/// <summary> Deprecated. </summary>
public string HostNamePrefix { get; }
/// <summary> Live trace configuration of a Microsoft.SignalRService resource. </summary>
public LiveTraceConfiguration LiveTraceConfiguration { get; set; }
/// <summary>
/// Resource log configuration of a Microsoft.SignalRService resource.
/// If resourceLogConfiguration isn't null or empty, it will override options "EnableConnectivityLog" and "EnableMessagingLogs" in features.
/// Otherwise, use options "EnableConnectivityLog" and "EnableMessagingLogs" in features.
/// </summary>
public ResourceLogConfiguration ResourceLogConfiguration { get; set; }
/// <summary> Network Acls. </summary>
public WebPubSubNetworkAcls NetworkAcls { get; set; }
/// <summary>
/// Enable or disable public network access. Default to "Enabled".
/// When it's Enabled, network ACLs still apply.
/// When it's Disabled, public network access is always disabled no matter what you set in network ACLs.
/// </summary>
public string PublicNetworkAccess { get; set; }
/// <summary>
/// DisableLocalAuth
/// Enable or disable local auth with AccessKey
/// When set as true, connection with AccessKey=xxx won't work.
/// </summary>
public bool? DisableLocalAuth { get; set; }
/// <summary>
/// DisableLocalAuth
/// Enable or disable aad auth
/// When set as true, connection with AuthType=aad won't work.
/// </summary>
public bool? DisableAadAuth { get; set; }
}
}
| 61.118881 | 778 | 0.671968 | [
"MIT"
] | AntonioVT/azure-sdk-for-net | sdk/webpubsub/Azure.ResourceManager.WebPubSub/src/Generated/WebPubSubData.cs | 8,740 | C# |
using System.Collections.Generic;
using System.Net.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Moq;
using NUnit.Framework;
using ViennaNET.CallContext;
namespace ViennaNET.WebApi.Configurators.HttpClients.Basic.Tests
{
[TestFixture]
[Category("Unit")]
[TestOf(typeof(BasicHttpClientsConfigurator))]
public class BasicHttpClientsConfiguratorTests
{
private static ServiceCollection GetServiceCollection()
{
var serviceCollection = new ServiceCollection();
var callContextFactory = new Mock<ICallContextFactory>();
callContextFactory
.Setup(c => c.Create())
.Returns(new EmptyCallContext());
serviceCollection.AddSingleton(callContextFactory.Object);
return serviceCollection;
}
[TestCase(TestName = "Try create client with basic auth")]
public void RegisterHttpClients_ShouldRegisterHttpClient()
{
// Arrange
const string userName = "testUser";
const string password = "testPassword";
var serviceCollection = GetServiceCollection();
var configurationSection =
new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string>
{
{"webApiEndpoints:0:Name", "basicHttpClient"},
{"webApiEndpoints:0:Url", "http://localhost"},
{"webApiEndpoints:0:Timeout", "123"},
{"webApiEndpoints:0:UserName", userName},
{"webApiEndpoints:0:Password", password},
{"webApiEndpoints:0:AuthType", "basic"}
})
.Build();
// Act
serviceCollection.RegisterHttpClients(configurationSection);
// Assert
var buildServiceProvider = serviceCollection.BuildServiceProvider();
var httpClientFactory = (IHttpClientFactory) buildServiceProvider.GetService(typeof(IHttpClientFactory));
var httpClient = httpClientFactory.CreateClient("basicHttpClient");
Assert.IsNotNull(httpClient);
}
[TestCase(TestName = "Try create client with default settings")]
public void RegisterHttpClients_WhenNoEndpoints_ShouldAddDefaultHttpClient()
{
// Arrange
var serviceCollection = GetServiceCollection();
var configurationSection =
new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string>())
.Build();
// Act
serviceCollection.RegisterHttpClients(configurationSection);
// Assert
var buildServiceProvider = serviceCollection.BuildServiceProvider();
var httpClientFactory = (IHttpClientFactory)buildServiceProvider.GetService(typeof(IHttpClientFactory));
var httpClient = httpClientFactory.CreateClient("someHttpClient");
const int defaultTimeoutValue = 100;
Assert.AreEqual(defaultTimeoutValue, httpClient.Timeout.TotalSeconds);
}
[TestCase("ntlm", TestName = "Try register client(ntlm)")]
[TestCase("jwt", TestName = "Try register client(jwt)")]
[TestCase("noauth", TestName = "Try register client(noauth)")]
public void RegisterHttpClients_ShouldNotRegisterHttpClient(string authType)
{
// Arrange
var serviceCollection = GetServiceCollection();
var configurationSection =
new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string>
{
{"webApiEndpoints:0:Name", "someHttpClient"},
{"webApiEndpoints:0:Url", "http://localhost"},
{"webApiEndpoints:0:Timeout", "1"},
{"webApiEndpoints:0:AuthType", authType}
})
.Build();
// Act
serviceCollection.RegisterHttpClients(configurationSection);
// Assert
var buildServiceProvider = serviceCollection.BuildServiceProvider();
var httpClientFactory = (IHttpClientFactory)buildServiceProvider.GetService(typeof(IHttpClientFactory));
Assert.IsNull(httpClientFactory);
}
}
} | 35.044643 | 111 | 0.69758 | [
"MIT"
] | Magicianred/ViennaNET | ViennaNET.WebApi.Configurators.HttpClients.Basic.Tests/BasicHttpClientsConfiguratorTests.cs | 3,925 | C# |
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
namespace UIElements.CounterElements
{
public class LevelCounterElement : CounterElementAbstract
{
[SerializeField] private Sprite _level1;
[SerializeField] private Sprite _level5;
protected override IEnumerable<Sprite> SelectSprites(int count)
{
var level5count = count / 5;
var level1count = count % 5;
return Enumerable.Repeat(_level5, level5count)
.Concat(Enumerable.Repeat(_level1, level1count));
}
}
} | 29.65 | 71 | 0.655987 | [
"MIT"
] | Volodej/GalagaTestProject | Assets/Scripts/UIElements/CounterElements/LevelCounterElement.cs | 593 | C# |
/* Copyright 2013 Daikon Forge */
using UnityEngine;
using UnityEditor;
using System;
using System.Linq;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
[CanEditMultipleObjects]
[CustomEditor( typeof( dfButton ), true )]
public class dfButtonInspector : dfControlInspector
{
private static Dictionary<int, bool> foldouts = new Dictionary<int, bool>();
protected override bool OnCustomInspector()
{
var control = target as dfButton;
if( control == null )
return false;
dfEditorUtil.DrawSeparator();
if( !isFoldoutExpanded( foldouts, "Button Properties", true ) )
return false;
dfEditorUtil.LabelWidth = 100f;
using( dfEditorUtil.BeginGroup( "Data" ) )
{
var text = EditorGUILayout.TextField( "Text", control.Text );
if( text != control.Text )
{
dfEditorUtil.MarkUndo( control, "Change Text" );
control.Text = text;
}
}
using( dfEditorUtil.BeginGroup( "Behavior" ) )
{
var autoSize = EditorGUILayout.Toggle( "Auto size", control.AutoSize );
if( autoSize != control.AutoSize )
{
dfEditorUtil.MarkUndo( control, "Change Auto-size property" );
control.AutoSize = autoSize;
var setDefaultPadding =
autoSize &&
control.Padding.horizontal == 0 &&
control.Padding.vertical == 0 &&
control.Atlas != null &&
!string.IsNullOrEmpty( control.BackgroundSprite );
if( setDefaultPadding )
{
var sprite = control.Atlas[ control.BackgroundSprite ];
control.Padding = new RectOffset
(
sprite.border.left,
sprite.border.right,
sprite.border.top,
sprite.border.bottom
);
}
}
var group = EditorGUILayout.ObjectField( "Group", control.ButtonGroup, typeof( dfControl ), true ) as dfControl;
if( group != control.ButtonGroup )
{
dfEditorUtil.MarkUndo( control, "Assign Button Group" );
control.ButtonGroup = group;
}
}
using( dfEditorUtil.BeginGroup( "Text Appearance" ) )
{
SelectFontDefinition( "Font", control.Atlas, control, "Font", true, true );
if( control.Font == null )
return false;
var align = (TextAlignment)EditorGUILayout.EnumPopup( "Text Align", control.TextAlignment );
if( align != control.TextAlignment )
{
dfEditorUtil.MarkUndo( control, "Change control Text Alignment" );
control.TextAlignment = align;
}
var vertAlign = (dfVerticalAlignment)EditorGUILayout.EnumPopup( "Vert Align", control.VerticalAlignment );
if( vertAlign != control.VerticalAlignment )
{
dfEditorUtil.MarkUndo( control, "Change Vertical Alignment" );
control.VerticalAlignment = vertAlign;
}
var textScale = EditorGUILayout.FloatField( "Text Scale", control.TextScale );
if( textScale != control.TextScale )
{
dfEditorUtil.MarkUndo( control, "Change Text Scale" );
control.TextScale = textScale;
}
var scaleMode = (dfTextScaleMode)EditorGUILayout.EnumPopup( "Auto Scale", control.TextScaleMode );
if( scaleMode != control.TextScaleMode )
{
dfEditorUtil.MarkUndo( control, "Change Text Scale Mode" );
control.TextScaleMode = scaleMode;
}
var wordwrap = EditorGUILayout.Toggle( "Word Wrap", control.WordWrap );
if( wordwrap != control.WordWrap )
{
dfEditorUtil.MarkUndo( control, "Toggle Word Wrap" );
control.WordWrap = wordwrap;
}
var padding = dfEditorUtil.EditPadding( "Padding", control.Padding );
if( padding != control.Padding )
{
dfEditorUtil.MarkUndo( control, "Change Textbox Padding" );
control.Padding = padding;
}
var shadow = EditorGUILayout.Toggle( "Shadow Effect", control.Shadow );
if( shadow != control.Shadow )
{
dfEditorUtil.MarkUndo( control, "Change Shadow Effect" );
control.Shadow = shadow;
}
if( shadow )
{
var shadowColor = EditorGUILayout.ColorField( "Shadow Color", control.ShadowColor );
if( shadowColor != control.ShadowColor )
{
dfEditorUtil.MarkUndo( control, "Change Shadow Color" );
control.ShadowColor = shadowColor;
}
var shadowOffset = dfEditorUtil.EditInt2( "Shadow Offset", "X", "Y", control.ShadowOffset );
if( shadowOffset != control.ShadowOffset )
{
dfEditorUtil.MarkUndo( control, "Change Shadow Color" );
control.ShadowOffset = shadowOffset;
}
dfEditorUtil.LabelWidth = 120f;
}
}
using( dfEditorUtil.BeginGroup( "Images" ) )
{
SelectTextureAtlas( "Atlas", control, "Atlas", false, true );
if( control.GUIManager != null && !dfAtlas.Equals( control.Atlas, control.GUIManager.DefaultAtlas ) )
{
EditorGUILayout.HelpBox( "This control does not use the same Texture Atlas as the View, which will result in an additional draw call.", MessageType.Info );
}
var buttonState = (dfButton.ButtonState)EditorGUILayout.EnumPopup( "Button State", control.State );
if( buttonState != control.State )
{
dfEditorUtil.MarkUndo( control, "Change Button State" );
control.State = buttonState;
}
SelectSprite( "Normal", control.Atlas, control, "BackgroundSprite" );
SelectSprite( "Focus", control.Atlas, control, "FocusSprite", false );
SelectSprite( "Hover", control.Atlas, control, "HoverSprite", false );
SelectSprite( "Pressed", control.Atlas, control, "PressedSprite", false );
SelectSprite( "Disabled", control.Atlas, control, "DisabledSprite", false );
}
using( dfEditorUtil.BeginGroup( "Image Colors" ) )
{
var backColor = EditorGUILayout.ColorField( "Normal", control.Color );
if( backColor != control.Color )
{
dfEditorUtil.MarkUndo( control, "Change Background Color" );
control.Color = backColor;
}
backColor = EditorGUILayout.ColorField( "Hover", control.HoverBackgroundColor );
if( backColor != control.HoverBackgroundColor )
{
dfEditorUtil.MarkUndo( control, "Change Background Color" );
control.HoverBackgroundColor = backColor;
}
backColor = EditorGUILayout.ColorField( "Pressed", control.PressedBackgroundColor );
if( backColor != control.PressedBackgroundColor )
{
dfEditorUtil.MarkUndo( control, "Change Background Color" );
control.PressedBackgroundColor = backColor;
}
backColor = EditorGUILayout.ColorField( "Focused", control.FocusBackgroundColor );
if( backColor != control.FocusBackgroundColor )
{
dfEditorUtil.MarkUndo( control, "Change Background Color" );
control.FocusBackgroundColor = backColor;
}
backColor = EditorGUILayout.ColorField( "Disabled", control.DisabledColor );
if( backColor != control.DisabledColor )
{
dfEditorUtil.MarkUndo( control, "Change Background Color" );
control.DisabledColor = backColor;
}
}
using( dfEditorUtil.BeginGroup( "Text Colors" ) )
{
var textColor = EditorGUILayout.ColorField( "Normal", control.TextColor );
if( textColor != control.TextColor )
{
dfEditorUtil.MarkUndo( control, "Change Text Color" );
control.TextColor = textColor;
}
textColor = EditorGUILayout.ColorField( "Hover", control.HoverTextColor );
if( textColor != control.HoverTextColor )
{
dfEditorUtil.MarkUndo( control, "Change Text Color" );
control.HoverTextColor = textColor;
}
textColor = EditorGUILayout.ColorField( "Pressed", control.PressedTextColor );
if( textColor != control.PressedTextColor )
{
dfEditorUtil.MarkUndo( control, "Change Text Color" );
control.PressedTextColor = textColor;
}
textColor = EditorGUILayout.ColorField( "Focused", control.FocusTextColor );
if( textColor != control.FocusTextColor )
{
dfEditorUtil.MarkUndo( control, "Change Text Color" );
control.FocusTextColor = textColor;
}
textColor = EditorGUILayout.ColorField( "Disabled", control.DisabledTextColor );
if( textColor != control.DisabledTextColor )
{
dfEditorUtil.MarkUndo( control, "Change Text Color" );
control.DisabledTextColor = textColor;
}
}
return true;
}
protected override bool OnControlDoubleClick( dfControl control, Event evt )
{
// HACK: Horribly hacky way to add better workflow for Tab controls
// Double-click will select the tab corresponding to the double-clicked
// button and make it visible so that the user can edit the tab page.
if( control.Parent is dfTabstrip )
{
var tabStrip = control.Parent as dfTabstrip;
tabStrip.SelectedIndex = control.ZOrder;
SceneView.lastActiveSceneView.Repaint();
dfGUIManager.RefreshAll();
return true;
}
return base.OnControlDoubleClick( control, evt );
}
}
| 28.727273 | 159 | 0.69503 | [
"Apache-2.0"
] | takemurakimio/missing-part-1 | Assets/Daikon Forge/DFGUI/Editor/dfButtonInspector.cs | 8,534 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Xamarin.Forms.Labs
{
public static class BindableObjectExtensions
{
public static T GetValue<T>(this BindableObject bindableObject, BindableProperty property)
{
return (T)bindableObject.GetValue(property);
}
}
}
| 23.764706 | 99 | 0.683168 | [
"Apache-2.0"
] | Applifting/Xamarin-Forms-Labs | src/Xamarin.Forms.Labs/Xamarin.Forms.Labs/Extensions/BindableObjectExtensions.cs | 406 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(fileName = "EnemyInfo", menuName = "BiuBiuBoom/EnemyInfo", order = 0)]
public class EnemyInfo : ScriptableObject
{
[Header("瘫痪时长")]
public float fallDownTime;
[Header("瘫痪延长时长")]
public float plusFallDownTime;
[Header("瘫痪最大时长")]
public float maxFallDownTime;
[Header("重启恢复血量百分比")]
public float resumePercent;
[Header("重启血量减少百分比")]
public float plusResumePercent;
[Header("重启最低生命百分比")]
public float minResumePercent;
[Header("怪物感知玩家的范围")]
public float perceptionDis;
}
| 20.933333 | 87 | 0.702229 | [
"MIT"
] | Vinkle-hzt/BiuBiuBoom | Assets/Scripts/Info/EnemyInfo.cs | 734 | C# |
// Copyright (c) Six Labors and contributors.
// Licensed under the Apache License, Version 2.0.
using System;
using System.Linq;
namespace SixLabors.ImageSharp.MetaData.Profiles.Icc
{
/// <summary>
/// The purpose of this tag type is to provide a mechanism to relate physical
/// colorant amounts with the normalized device codes produced by lut8Type, lut16Type,
/// lutAToBType, lutBToAType or multiProcessElementsType tags so that corrections can
/// be made for variation in the device without having to produce a new profile.
/// </summary>
internal sealed class IccResponseCurveSet16TagDataEntry : IccTagDataEntry, IEquatable<IccResponseCurveSet16TagDataEntry>
{
/// <summary>
/// Initializes a new instance of the <see cref="IccResponseCurveSet16TagDataEntry"/> class.
/// </summary>
/// <param name="curves">The Curves</param>
public IccResponseCurveSet16TagDataEntry(IccResponseCurve[] curves)
: this(curves, IccProfileTag.Unknown)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="IccResponseCurveSet16TagDataEntry"/> class.
/// </summary>
/// <param name="curves">The Curves</param>
/// <param name="tagSignature">Tag Signature</param>
public IccResponseCurveSet16TagDataEntry(IccResponseCurve[] curves, IccProfileTag tagSignature)
: base(IccTypeSignature.ResponseCurveSet16, tagSignature)
{
Guard.NotNull(curves, nameof(curves));
Guard.IsTrue(curves.Length > 0, nameof(curves), $"{nameof(curves)} needs at least one element");
this.Curves = curves;
this.ChannelCount = (ushort)curves[0].ResponseArrays.Length;
Guard.IsFalse(curves.Any(t => t.ResponseArrays.Length != this.ChannelCount), nameof(curves), "All curves need to have the same number of channels");
}
/// <summary>
/// Gets the number of channels
/// </summary>
public ushort ChannelCount { get; }
/// <summary>
/// Gets the curves
/// </summary>
public IccResponseCurve[] Curves { get; }
/// <inheritdoc/>
public override bool Equals(IccTagDataEntry other)
{
return other is IccResponseCurveSet16TagDataEntry entry && this.Equals(entry);
}
/// <inheritdoc />
public bool Equals(IccResponseCurveSet16TagDataEntry other)
{
if (other is null)
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
return base.Equals(other)
&& this.ChannelCount == other.ChannelCount
&& this.Curves.SequenceEqual(other.Curves);
}
/// <inheritdoc />
public override bool Equals(object obj)
{
return obj is IccResponseCurveSet16TagDataEntry other && this.Equals(other);
}
/// <inheritdoc />
public override int GetHashCode()
{
return HashCode.Combine(
this.Signature,
this.ChannelCount,
this.Curves);
}
}
} | 35.5 | 160 | 0.602266 | [
"Apache-2.0"
] | HighEndGuy/ImageSharp | src/ImageSharp/MetaData/Profiles/ICC/TagDataEntries/IccResponseCurveSet16TagDataEntry.cs | 3,268 | C# |
// 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.Threading.Tasks;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations
{
public class WhereKeywordRecommenderTests : KeywordRecommenderTests
{
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAtRoot_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterClass_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"class C { }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterGlobalStatement_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"System.Console.WriteLine();
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterGlobalVariableDeclaration_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"int i = 0;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInUsingAlias()
{
await VerifyAbsenceAsync(
@"using Goo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInEmptyStatement()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNewClause()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var q = from x in y
$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterPreviousClause()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var v = from x in y
where x > y
$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterPreviousContinuationClause()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var v = from x in y
group x by y into g
$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAtEndOfPreviousClause()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"var q = from x in y$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestBetweenClauses()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var q = from x in y
$$
from z in w"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterWhere()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"var q = from x in y
where $$
from z in w"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterClass()
{
await VerifyAbsenceAsync(
@"class C $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGenericClass()
{
await VerifyKeywordAsync(
@"class C<T> $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterClassBaseList()
{
await VerifyAbsenceAsync(
@"class C : IGoo $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGenericClassBaseList()
{
await VerifyKeywordAsync(
@"class C<T> : IGoo $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterDelegate()
{
await VerifyAbsenceAsync(
@"delegate void D() $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGenericDelegate()
{
await VerifyKeywordAsync(
@"delegate void D<T>() $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterPreviousClassConstraint()
{
await VerifyKeywordAsync(
@"class C<T> where T : class $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterPreviousStructConstraint()
{
await VerifyKeywordAsync(
@"class C<T> where T : struct $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterPreviousNewConstraint()
{
await VerifyKeywordAsync(
@"class C<T> where T : new() $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterPreviousConstraint()
{
await VerifyKeywordAsync(
@"class C<T> where T : IList<T> $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterPreviousDelegateClassConstraint()
{
await VerifyKeywordAsync(
@"delegate void D<T>() where T : class $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterPreviousDelegateStructConstraint()
{
await VerifyKeywordAsync(
@"delegate void D<T>() where T : struct $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterPreviousDelegateNewConstraint()
{
await VerifyKeywordAsync(
@"delegate void D<T>() where T : new() $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterPreviousDelegateConstraint()
{
await VerifyKeywordAsync(
@"delegate void D<T>() where T : IList<T> $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterMethod()
{
await VerifyAbsenceAsync(
@"class C {
void D() $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGenericMethod()
{
await VerifyKeywordAsync(
@"class C {
void D<T>() $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterPreviousMethodClassConstraint()
{
await VerifyKeywordAsync(
@"class C {
void D<T>() where T : class $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterPreviousMethodStructConstraint()
{
await VerifyKeywordAsync(
@"class C {
void D<T>() where T : struct $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterPreviousMethodNewConstraint()
{
await VerifyKeywordAsync(
@"class C {
void D<T>() where T : new() $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterPreviousMethodConstraint()
{
await VerifyKeywordAsync(
@"class C {
void D<T>() where T : IList<T> $$");
}
[WorkItem(550715, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/550715")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterWhereTypeConstraint()
{
await VerifyAbsenceAsync(
@"public class Goo<T> : System.Object where $$
{
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterWhereWhere()
{
await VerifyAbsenceAsync(
@"public class Goo<T> : System.Object where where $$
{
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterWhereWhereWhere()
{
await VerifyAbsenceAsync(
@"public class Goo<T> : System.Object where where where $$
{
}");
}
[WorkItem(550720, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/550720")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNoWhereAfterDot()
{
await VerifyAbsenceAsync(
@"public class Goo<where> : System.$$
{
}");
}
}
}
| 31.037543 | 161 | 0.622168 | [
"Apache-2.0"
] | ElanHasson/roslyn | src/EditorFeatures/CSharpTest2/Recommendations/WhereKeywordRecommenderTests.cs | 9,096 | C# |
using System;
using System.ComponentModel;
using System.Threading;
using System.Threading.Tasks;
using Android.Animation;
using Android.Content.Res;
using Android.Graphics.Drawables;
using Android.OS;
using Android.Views;
using Android.Widget;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
using XamEffects;
using XamEffects.Droid;
using XamEffects.Droid.GestureCollectors;
using Color = Android.Graphics.Color;
using ListView = Android.Widget.ListView;
using ScrollView = Android.Widget.ScrollView;
using View = Android.Views.View;
[assembly: ExportEffect(typeof(TouchEffectPlatform), nameof(TouchEffect))]
namespace XamEffects.Droid {
public class TouchEffectPlatform : PlatformEffect {
public bool EnableRipple => Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop;
public bool IsDisposed => (Container as IVisualElementRenderer)?.Element == null;
public View View => Control ?? Container;
Color _color;
byte _alpha;
RippleDrawable _ripple;
FrameLayout _viewOverlay;
ObjectAnimator _animator;
public static void Init() {
}
protected override void OnAttached() {
if (Control is ListView || Control is ScrollView) {
return;
}
View.Clickable = true;
View.LongClickable = true;
_viewOverlay = new FrameLayout(Container.Context) {
LayoutParameters = new ViewGroup.LayoutParams(-1, -1),
Clickable = false,
Focusable = false,
};
Container.LayoutChange += ViewOnLayoutChange;
if (EnableRipple)
_viewOverlay.Background = CreateRipple(_color);
SetEffectColor();
TouchCollector.Add(View, OnTouch);
Container.AddView(_viewOverlay);
_viewOverlay.BringToFront();
}
protected override void OnDetached() {
if (IsDisposed) return;
Container.RemoveView(_viewOverlay);
_viewOverlay.Pressed = false;
_viewOverlay.Foreground = null;
_viewOverlay.Dispose();
Container.LayoutChange -= ViewOnLayoutChange;
if (EnableRipple)
_ripple?.Dispose();
TouchCollector.Delete(View, OnTouch);
}
protected override void OnElementPropertyChanged(PropertyChangedEventArgs e) {
base.OnElementPropertyChanged(e);
if (e.PropertyName == TouchEffect.ColorProperty.PropertyName) {
SetEffectColor();
}
}
void SetEffectColor() {
var color = TouchEffect.GetColor(Element);
if (color == Xamarin.Forms.Color.Default) {
return;
}
_color = color.ToAndroid();
_alpha = _color.A == 255 ? (byte)80 : _color.A;
if (EnableRipple) {
_ripple.SetColor(GetPressedColorSelector(_color));
}
}
void OnTouch(View.TouchEventArgs args) {
switch (args.Event.Action) {
case MotionEventActions.Down:
if (EnableRipple)
ForceStartRipple(args.Event.GetX(), args.Event.GetY());
else
BringLayer();
break;
case MotionEventActions.Up:
case MotionEventActions.Cancel:
if (IsDisposed) return;
if (EnableRipple)
ForceEndRipple();
else
TapAnimation(250, _alpha, 0);
break;
}
}
void ViewOnLayoutChange(object sender, View.LayoutChangeEventArgs layoutChangeEventArgs) {
var group = (ViewGroup)sender;
if (group == null || IsDisposed) return;
_viewOverlay.Right = group.Width;
_viewOverlay.Bottom = group.Height;
}
#region Ripple
RippleDrawable CreateRipple(Color color) {
if (Element is Layout) {
var mask = new ColorDrawable(Color.White);
return _ripple = new RippleDrawable(GetPressedColorSelector(color), null, mask);
}
var back = View.Background;
if (back == null) {
var mask = new ColorDrawable(Color.White);
return _ripple = new RippleDrawable(GetPressedColorSelector(color), null, mask);
}
if (back is RippleDrawable) {
_ripple = (RippleDrawable)back.GetConstantState().NewDrawable();
_ripple.SetColor(GetPressedColorSelector(color));
return _ripple;
}
return _ripple = new RippleDrawable(GetPressedColorSelector(color), back, null);
}
static ColorStateList GetPressedColorSelector(int pressedColor) {
return new ColorStateList(
new[] { new int[] { } },
new[] { pressedColor, });
}
void ForceStartRipple(float x, float y) {
if (IsDisposed || !(_viewOverlay.Background is RippleDrawable bc)) return;
_viewOverlay.BringToFront();
bc.SetHotspot(x, y);
_viewOverlay.Pressed = true;
}
void ForceEndRipple() {
if (IsDisposed) return;
_viewOverlay.Pressed = false;
}
#endregion
#region Overlay
void BringLayer() {
if (IsDisposed)
return;
ClearAnimation();
_viewOverlay.BringToFront();
var color = _color;
color.A = _alpha;
_viewOverlay.SetBackgroundColor(color);
}
void TapAnimation(long duration, byte startAlpha, byte endAlpha) {
if (IsDisposed)
return;
_viewOverlay.BringToFront();
var start = _color;
var end = _color;
start.A = startAlpha;
end.A = endAlpha;
ClearAnimation();
_animator = ObjectAnimator.OfObject(_viewOverlay,
"BackgroundColor",
new ArgbEvaluator(),
start.ToArgb(),
end.ToArgb());
_animator.SetDuration(duration);
_animator.RepeatCount = 0;
_animator.RepeatMode = ValueAnimatorRepeatMode.Restart;
_animator.Start();
_animator.AnimationEnd += AnimationOnAnimationEnd;
}
void AnimationOnAnimationEnd(object sender, EventArgs eventArgs) {
if (IsDisposed) return;
ClearAnimation();
}
void ClearAnimation() {
if (_animator == null) return;
_animator.AnimationEnd -= AnimationOnAnimationEnd;
_animator.Cancel();
_animator.Dispose();
_animator = null;
}
#endregion
}
}
| 30.443478 | 98 | 0.561839 | [
"MIT"
] | michaelkollmann/XamEffects | src/XamEffects.Droid/TouchEffectPlatform.cs | 7,004 | C# |
using Sdk.Application.Common.Interfaces;
using Sdk.Application.TodoLists.Queries.ExportTodos;
using Sdk.Infrastructure.Files.Maps;
using CsvHelper;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
namespace Sdk.Infrastructure.Files
{
public class CsvFileBuilder : ICsvFileBuilder
{
public byte[] BuildTodoItemsFile(IEnumerable<TodoItemRecord> records)
{
using var memoryStream = new MemoryStream();
using (var streamWriter = new StreamWriter(memoryStream))
{
using var csvWriter = new CsvWriter(streamWriter, CultureInfo.InvariantCulture);
csvWriter.Configuration.RegisterClassMap<TodoItemRecordMap>();
csvWriter.WriteRecords(records);
}
return memoryStream.ToArray();
}
}
}
| 30.464286 | 96 | 0.681125 | [
"MIT"
] | ronhowe/CleanArchitecture | src/Sdk.Infrastructure/Files/CsvFileBuilder.cs | 855 | C# |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Windows.Input;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using MvvmCross.Binding.BindingContext;
using MvvmCross.Navigation;
using MvvmCross.ViewModels;
namespace ElementPlayer.Android
{
// This class is never actually executed, but when Xamarin linking is enabled it does how to ensure types and properties
// are preserved in the deployed app
[global::Android.Runtime.Preserve(AllMembers = true)]
public class LinkerPleaseInclude
{
public void Include(Button button)
{
button.Click += (s, e) => button.Text = button.Text + "";
}
public void Include(CheckBox checkBox)
{
checkBox.CheckedChange += (sender, args) => checkBox.Checked = !checkBox.Checked;
}
public void Include(Switch @switch)
{
@switch.CheckedChange += (sender, args) => @switch.Checked = !@switch.Checked;
}
public void Include(View view)
{
view.Click += (s, e) => view.ContentDescription = view.ContentDescription + "";
}
public void Include(TextView text)
{
text.AfterTextChanged += (sender, args) => text.Text = "" + text.Text;
text.Hint = "" + text.Hint;
}
public void Include(CheckedTextView text)
{
text.AfterTextChanged += (sender, args) => text.Text = "" + text.Text;
text.Hint = "" + text.Hint;
}
public void Include(CompoundButton cb)
{
cb.CheckedChange += (sender, args) => cb.Checked = !cb.Checked;
}
public void Include(SeekBar sb)
{
sb.ProgressChanged += (sender, args) => sb.Progress = sb.Progress + 1;
}
public void Include(RadioGroup radioGroup)
{
radioGroup.CheckedChange += (sender, args) => radioGroup.Check(args.CheckedId);
}
public void Include(RadioButton radioButton)
{
radioButton.CheckedChange += (sender, args) => radioButton.Checked = args.IsChecked;
}
public void Include(RatingBar ratingBar)
{
ratingBar.RatingBarChange += (sender, args) => ratingBar.Rating = 0 + ratingBar.Rating;
}
public void Include(Activity act)
{
act.Title = act.Title + "";
}
public void Include(INotifyCollectionChanged changed)
{
changed.CollectionChanged += (s, e) => { var test = $"{e.Action}{e.NewItems}{e.NewStartingIndex}{e.OldItems}{e.OldStartingIndex}"; };
}
public void Include(ICommand command)
{
command.CanExecuteChanged += (s, e) => { if (command.CanExecute(null)) command.Execute(null); };
}
public void Include(MvvmCross.IoC.MvxPropertyInjector injector)
{
injector = new MvvmCross.IoC.MvxPropertyInjector();
}
public void Include(System.ComponentModel.INotifyPropertyChanged changed)
{
changed.PropertyChanged += (sender, e) =>
{
var test = e.PropertyName;
};
}
public void Include(MvxTaskBasedBindingContext context)
{
context.Dispose();
var context2 = new MvxTaskBasedBindingContext();
context2.Dispose();
}
public void Include(MvxNavigationService service, IMvxViewModelLoader loader)
{
service = new MvxNavigationService(null, loader);
}
public void Include(ConsoleColor color)
{
Console.Write("");
Console.WriteLine("");
color = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.Red;
Console.ForegroundColor = ConsoleColor.Yellow;
Console.ForegroundColor = ConsoleColor.Magenta;
Console.ForegroundColor = ConsoleColor.White;
Console.ForegroundColor = ConsoleColor.Gray;
Console.ForegroundColor = ConsoleColor.DarkGray;
}
public void Include(MvvmCross.Plugin.Json.Plugin plugin)
{
plugin.Load();
}
}
}
| 31.271429 | 145 | 0.595249 | [
"MIT"
] | ZeProgFactory/XamarinMediaManager | Samples/ElementPlayer.Android/LinkerPleaseInclude.cs | 4,380 | C# |
// -----------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// -----------------------------------------------------------------------
using System;
using System.ComponentModel.Composition.Factories;
using System.ComponentModel.Composition.Hosting;
using System.ComponentModel.Composition.Primitives;
using System.Reflection;
using Microsoft.Internal;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;
using System.Linq;
using System.UnitTesting;
using System.Threading;
namespace System.ComponentModel.Composition.ReflectionModel
{
[TestClass]
public class ReflectionModelServicesTests
{
[TestMethod]
public void CreatePartDefinition()
{
Type expectedType = typeof(TestPart);
Lazy<Type> expectedLazyType = expectedType.AsLazy();
IDictionary<string, object> expectedMetadata = new Dictionary<string, object>();
expectedMetadata["Key1"] = 1;
expectedMetadata["Key2"] = "Value2";
IEnumerable<ImportDefinition> expectedImports = CreateImports(expectedType);
IEnumerable<ExportDefinition> expectedExports = CreateExports(expectedType);
ICompositionElement expectedOrigin = new MockOrigin();
ComposablePartDefinition partDefinition = ReflectionModelServices.CreatePartDefinition(expectedLazyType, false,
new Lazy<IEnumerable<ImportDefinition>>(() => expectedImports),
new Lazy<IEnumerable<ExportDefinition>>(() => expectedExports),
expectedMetadata.AsLazy(), expectedOrigin);
Assert.IsNotNull(partDefinition);
ReflectionComposablePartDefinition definition = partDefinition as ReflectionComposablePartDefinition;
Assert.IsNotNull(definition);
Assert.AreSame(expectedType, definition.GetPartType());
Assert.IsTrue(definition.Metadata.Keys.SequenceEqual(expectedMetadata.Keys));
Assert.IsTrue(definition.Metadata.Values.SequenceEqual(expectedMetadata.Values));
Assert.IsTrue(definition.ExportDefinitions.SequenceEqual(expectedExports.Cast<ExportDefinition>()));
Assert.IsTrue(definition.ImportDefinitions.SequenceEqual(expectedImports.Cast<ImportDefinition>()));
Assert.AreSame(expectedOrigin, ((ICompositionElement)definition).Origin);
Assert.IsNotNull(((ICompositionElement)definition).DisplayName);
Assert.IsFalse(definition.IsDisposalRequired);
}
[TestMethod]
public void CreatePartDefinition_Disposable()
{
Type expectedType = typeof(TestPart);
Lazy<Type> expectedLazyType = expectedType.AsLazy();
IDictionary<string, object> expectedMetadata = new Dictionary<string, object>();
expectedMetadata["Key1"] = 1;
expectedMetadata["Key2"] = "Value2";
IEnumerable<ImportDefinition> expectedImports = CreateImports(expectedType);
IEnumerable<ExportDefinition> expectedExports = CreateExports(expectedType);
ICompositionElement expectedOrigin = new MockOrigin();
ComposablePartDefinition partDefinition = ReflectionModelServices.CreatePartDefinition(expectedLazyType, true,
new Lazy<IEnumerable<ImportDefinition>>(() => expectedImports),
new Lazy<IEnumerable<ExportDefinition>>(() => expectedExports),
expectedMetadata.AsLazy(), expectedOrigin);
Assert.IsNotNull(partDefinition);
ReflectionComposablePartDefinition definition = partDefinition as ReflectionComposablePartDefinition;
Assert.IsNotNull(definition);
Assert.AreSame(expectedType, definition.GetPartType());
Assert.IsTrue(definition.Metadata.Keys.SequenceEqual(expectedMetadata.Keys));
Assert.IsTrue(definition.Metadata.Values.SequenceEqual(expectedMetadata.Values));
Assert.IsTrue(definition.ExportDefinitions.SequenceEqual(expectedExports.Cast<ExportDefinition>()));
Assert.IsTrue(definition.ImportDefinitions.SequenceEqual(expectedImports.Cast<ImportDefinition>()));
Assert.AreSame(expectedOrigin, ((ICompositionElement)definition).Origin);
Assert.IsNotNull(((ICompositionElement)definition).DisplayName);
Assert.IsTrue(definition.IsDisposalRequired);
}
[TestMethod]
public void CreatePartDefinition_NullMetadataAllowed()
{
Type expectedType = typeof(TestPart);
Lazy<Type> expectedLazyType = expectedType.AsLazy();
IEnumerable<ImportDefinition> expectedImports = CreateImports(expectedType);
IEnumerable<ExportDefinition> expectedExports = CreateExports(expectedType);
ICompositionElement expectedOrigin = new MockOrigin();
ComposablePartDefinition partDefinition = ReflectionModelServices.CreatePartDefinition(expectedLazyType, false,
new Lazy<IEnumerable<ImportDefinition>>(() => expectedImports),
new Lazy<IEnumerable<ExportDefinition>>(() => expectedExports),
null, expectedOrigin);
Assert.IsNotNull(partDefinition);
ReflectionComposablePartDefinition definition = partDefinition as ReflectionComposablePartDefinition;
Assert.IsNotNull(definition);
Assert.IsNotNull(definition.Metadata);
Assert.AreEqual(0, definition.Metadata.Count);
}
[TestMethod]
public void CreatePartDefinition_EvaluatedNullMetadataAllowed()
{
Type expectedType = typeof(TestPart);
Lazy<Type> expectedLazyType = expectedType.AsLazy();
IDictionary<string, object> expectedMetadata = null;
IEnumerable<ImportDefinition> expectedImports = CreateImports(expectedType);
IEnumerable<ExportDefinition> expectedExports = CreateExports(expectedType);
ICompositionElement expectedOrigin = new MockOrigin();
ComposablePartDefinition partDefinition = ReflectionModelServices.CreatePartDefinition(expectedLazyType, false,
new Lazy<IEnumerable<ImportDefinition>>(() => expectedImports),
new Lazy<IEnumerable<ExportDefinition>>(() => expectedExports),
expectedMetadata.AsLazy(), expectedOrigin);
Assert.IsNotNull(partDefinition);
ReflectionComposablePartDefinition definition = partDefinition as ReflectionComposablePartDefinition;
Assert.IsNotNull(definition);
Assert.IsNotNull(definition.Metadata);
Assert.AreEqual(0, definition.Metadata.Count);
}
[TestMethod]
public void CreatePartDefinition_NullExportsAllowed()
{
Type expectedType = typeof(TestPart);
Lazy<Type> expectedLazyType = expectedType.AsLazy();
IEnumerable<ImportDefinition> expectedImports = CreateImports(expectedType);
IEnumerable<ExportDefinition> expectedExports = CreateExports(expectedType);
IDictionary<string, object> expectedMetadata = new Dictionary<string, object>();
ICompositionElement expectedOrigin = new MockOrigin();
ComposablePartDefinition partDefinition = ReflectionModelServices.CreatePartDefinition(expectedLazyType, false,
new Lazy<IEnumerable<ImportDefinition>>(() => expectedImports),
null,
expectedMetadata.AsLazy(), expectedOrigin);
Assert.IsNotNull(partDefinition);
ReflectionComposablePartDefinition definition = partDefinition as ReflectionComposablePartDefinition;
Assert.IsNotNull(definition);
Assert.IsNotNull(definition.ExportDefinitions);
Assert.AreEqual(0, definition.ExportDefinitions.Count());
}
[TestMethod]
public void CreatePartDefinition_EvaluatedNullExportsAllowed()
{
Type expectedType = typeof(TestPart);
Lazy<Type> expectedLazyType = expectedType.AsLazy();
IEnumerable<ImportDefinition> expectedImports = CreateImports(expectedType);
IEnumerable<ExportDefinition> expectedExports = CreateExports(expectedType);
IDictionary<string, object> expectedMetadata = new Dictionary<string, object>();
ICompositionElement expectedOrigin = new MockOrigin();
ComposablePartDefinition partDefinition = ReflectionModelServices.CreatePartDefinition(expectedLazyType, false,
new Lazy<IEnumerable<ImportDefinition>>(() => expectedImports),
new Lazy<IEnumerable<ExportDefinition>>(() => null),
expectedMetadata.AsLazy(), expectedOrigin);
Assert.IsNotNull(partDefinition);
ReflectionComposablePartDefinition definition = partDefinition as ReflectionComposablePartDefinition;
Assert.IsNotNull(definition);
Assert.IsNotNull(definition.ExportDefinitions);
Assert.AreEqual(0, definition.ExportDefinitions.Count());
}
[TestMethod]
public void CreatePartDefinition_ExportsMustBeOfRightType()
{
Type expectedType = typeof(TestPart);
Lazy<Type> expectedLazyType = expectedType.AsLazy();
IEnumerable<ImportDefinition> expectedImports = CreateImports(expectedType);
IEnumerable<ExportDefinition> expectedExports = CreateExports(expectedType);
IDictionary<string, object> expectedMetadata = new Dictionary<string, object>();
ICompositionElement expectedOrigin = new MockOrigin();
ComposablePartDefinition partDefinition = ReflectionModelServices.CreatePartDefinition(expectedLazyType, false,
new Lazy<IEnumerable<ImportDefinition>>(() => expectedImports),
new Lazy<IEnumerable<ExportDefinition>>(() => CreateInvalidExports()),
expectedMetadata.AsLazy(), expectedOrigin);
Assert.IsNotNull(partDefinition);
ReflectionComposablePartDefinition definition = partDefinition as ReflectionComposablePartDefinition;
Assert.IsNotNull(definition);
ExceptionAssert.Throws<InvalidOperationException>(() =>
{
definition.ExportDefinitions.Count();
});
}
[TestMethod]
public void CreatePartDefinition_NullImportsAllowed()
{
Type expectedType = typeof(TestPart);
Lazy<Type> expectedLazyType = expectedType.AsLazy();
IEnumerable<ImportDefinition> expectedImports = CreateImports(expectedType);
IEnumerable<ExportDefinition> expectedExports = CreateExports(expectedType);
IDictionary<string, object> expectedMetadata = new Dictionary<string, object>();
ICompositionElement expectedOrigin = new MockOrigin();
ComposablePartDefinition partDefinition = ReflectionModelServices.CreatePartDefinition(expectedLazyType, false,
null,
new Lazy<IEnumerable<ExportDefinition>>(() => expectedExports),
expectedMetadata.AsLazy(), expectedOrigin);
Assert.IsNotNull(partDefinition);
ReflectionComposablePartDefinition definition = partDefinition as ReflectionComposablePartDefinition;
Assert.IsNotNull(definition);
Assert.IsNotNull(definition.ImportDefinitions);
Assert.AreEqual(0, definition.ImportDefinitions.Count());
}
[TestMethod]
public void CreatePartDefinition_EvaluatedNullImportsAllowed()
{
Type expectedType = typeof(TestPart);
Lazy<Type> expectedLazyType = expectedType.AsLazy();
IEnumerable<ImportDefinition> expectedImports = CreateImports(expectedType);
IEnumerable<ExportDefinition> expectedExports = CreateExports(expectedType);
IDictionary<string, object> expectedMetadata = new Dictionary<string, object>();
ICompositionElement expectedOrigin = new MockOrigin();
ComposablePartDefinition partDefinition = ReflectionModelServices.CreatePartDefinition(expectedLazyType, false,
new Lazy<IEnumerable<ImportDefinition>>(() => null),
new Lazy<IEnumerable<ExportDefinition>>(() => expectedExports),
expectedMetadata.AsLazy(), expectedOrigin);
Assert.IsNotNull(partDefinition);
ReflectionComposablePartDefinition definition = partDefinition as ReflectionComposablePartDefinition;
Assert.IsNotNull(definition);
Assert.IsNotNull(definition.ImportDefinitions);
Assert.AreEqual(0, definition.ImportDefinitions.Count());
}
[TestMethod]
public void CreatePartDefinition_ImportsMustBeOfRightType()
{
Type expectedType = typeof(TestPart);
Lazy<Type> expectedLazyType = expectedType.AsLazy();
IEnumerable<ImportDefinition> expectedImports = CreateImports(expectedType);
IEnumerable<ExportDefinition> expectedExports = CreateExports(expectedType);
IDictionary<string, object> expectedMetadata = new Dictionary<string, object>();
ICompositionElement expectedOrigin = new MockOrigin();
ComposablePartDefinition partDefinition = ReflectionModelServices.CreatePartDefinition(expectedLazyType, false,
new Lazy<IEnumerable<ImportDefinition>>(() => CreateInvalidImports()),
new Lazy<IEnumerable<ExportDefinition>>(() => expectedExports),
expectedMetadata.AsLazy(), expectedOrigin);
Assert.IsNotNull(partDefinition);
ReflectionComposablePartDefinition definition = partDefinition as ReflectionComposablePartDefinition;
Assert.IsNotNull(definition);
ExceptionAssert.Throws<InvalidOperationException>(() =>
{
definition.ImportDefinitions.Count();
});
}
[TestMethod]
public void CreatePartDefinition_NullTypeNotAllowed()
{
Type expectedType = typeof(TestPart);
Lazy<Type> expectedLazyType = expectedType.AsLazy();
IDictionary<string, object> expectedMetadata = new Dictionary<string, object>();
expectedMetadata["Key1"] = 1;
expectedMetadata["Key2"] = "Value2";
IEnumerable<ImportDefinition> expectedImports = CreateImports(expectedType);
IEnumerable<ExportDefinition> expectedExports = CreateExports(expectedType);
ICompositionElement expectedOrigin = new MockOrigin();
ExceptionAssert.ThrowsArgument<ArgumentNullException>("partType", () =>
{
ComposablePartDefinition partDefinition = ReflectionModelServices.CreatePartDefinition(null, false,
new Lazy<IEnumerable<ImportDefinition>>(() => expectedImports),
new Lazy<IEnumerable<ExportDefinition>>(() => expectedExports),
expectedMetadata.AsLazy(), expectedOrigin);
});
}
[TestMethod]
public void CreatePartDefinition_NullEvaluatedTypeNotAllowed()
{
Type expectedType = typeof(TestPart);
Lazy<Type> expectedLazyType = expectedType.AsLazy();
IDictionary<string, object> expectedMetadata = new Dictionary<string, object>();
expectedMetadata["Key1"] = 1;
expectedMetadata["Key2"] = "Value2";
IEnumerable<ImportDefinition> expectedImports = CreateImports(expectedType);
IEnumerable<ExportDefinition> expectedExports = CreateExports(expectedType);
ICompositionElement expectedOrigin = new MockOrigin();
ComposablePartDefinition partDefinition = ReflectionModelServices.CreatePartDefinition(new Lazy<Type>(() => null), false,
new Lazy<IEnumerable<ImportDefinition>>(() => expectedImports),
new Lazy<IEnumerable<ExportDefinition>>(() => expectedExports),
expectedMetadata.AsLazy(), expectedOrigin);
ReflectionComposablePartDefinition definition = partDefinition as ReflectionComposablePartDefinition;
Assert.IsNotNull(definition);
ExceptionAssert.Throws<InvalidOperationException>(() =>
{
definition.GetPartType();
});
}
[TestMethod]
public void GetPartType()
{
Type expectedType = typeof(TestPart);
Lazy<Type> expectedLazyType = expectedType.AsLazy();
IDictionary<string, object> expectedMetadata = new Dictionary<string, object>();
expectedMetadata["Key1"] = 1;
expectedMetadata["Key2"] = "Value2";
IEnumerable<ImportDefinition> expectedImports = CreateImports(expectedType);
IEnumerable<ExportDefinition> expectedExports = CreateExports(expectedType);
ICompositionElement expectedOrigin = new MockOrigin();
ComposablePartDefinition partDefinition = ReflectionModelServices.CreatePartDefinition(expectedLazyType, false,
new Lazy<IEnumerable<ImportDefinition>>(() => expectedImports),
new Lazy<IEnumerable<ExportDefinition>>(() => expectedExports),
expectedMetadata.AsLazy(), expectedOrigin);
Assert.IsNotNull(partDefinition);
Lazy<Type> lazyPartType = ReflectionModelServices.GetPartType(partDefinition);
Assert.AreEqual(expectedLazyType, lazyPartType);
}
[TestMethod]
public void GetPartType_NullAsPart_ShouldThrowArgumentNull()
{
ExceptionAssert.ThrowsArgument<ArgumentNullException>("partDefinition", () =>
{
ReflectionModelServices.GetPartType(null);
});
}
[TestMethod]
public void GetPartType_InvalidPart_ShouldThrowArgument()
{
ExceptionAssert.ThrowsArgument<ArgumentException>("partDefinition", () =>
{
ReflectionModelServices.GetPartType(new InvalidPartDefinition());
});
}
[TestMethod]
public void IsDisposalRequired_ForNonDisposable()
{
Type expectedType = typeof(TestPart);
Lazy<Type> expectedLazyType = expectedType.AsLazy();
IDictionary<string, object> expectedMetadata = new Dictionary<string, object>();
expectedMetadata["Key1"] = 1;
expectedMetadata["Key2"] = "Value2";
IEnumerable<ImportDefinition> expectedImports = CreateImports(expectedType);
IEnumerable<ExportDefinition> expectedExports = CreateExports(expectedType);
ICompositionElement expectedOrigin = new MockOrigin();
ComposablePartDefinition partDefinition = ReflectionModelServices.CreatePartDefinition(expectedLazyType, false,
new Lazy<IEnumerable<ImportDefinition>>(() => expectedImports),
new Lazy<IEnumerable<ExportDefinition>>(() => expectedExports),
expectedMetadata.AsLazy(), expectedOrigin);
Assert.IsNotNull(partDefinition);
bool isDisposalRequired = ReflectionModelServices.IsDisposalRequired(partDefinition);
Assert.IsFalse(isDisposalRequired);
}
[TestMethod]
public void IsDisposalRequired_ForDisposable()
{
Type expectedType = typeof(TestPart);
Lazy<Type> expectedLazyType = expectedType.AsLazy();
IDictionary<string, object> expectedMetadata = new Dictionary<string, object>();
expectedMetadata["Key1"] = 1;
expectedMetadata["Key2"] = "Value2";
IEnumerable<ImportDefinition> expectedImports = CreateImports(expectedType);
IEnumerable<ExportDefinition> expectedExports = CreateExports(expectedType);
ICompositionElement expectedOrigin = new MockOrigin();
ComposablePartDefinition partDefinition = ReflectionModelServices.CreatePartDefinition(expectedLazyType, true,
new Lazy<IEnumerable<ImportDefinition>>(() => expectedImports),
new Lazy<IEnumerable<ExportDefinition>>(() => expectedExports),
expectedMetadata.AsLazy(), expectedOrigin);
Assert.IsNotNull(partDefinition);
bool isDisposalRequired = ReflectionModelServices.IsDisposalRequired(partDefinition);
Assert.IsTrue(isDisposalRequired);
}
[TestMethod]
public void IsDisposalRequired_NullAsPart_ShouldThrowArgumentNull()
{
ExceptionAssert.ThrowsArgument<ArgumentNullException>("partDefinition", () =>
{
ReflectionModelServices.IsDisposalRequired(null);
});
}
[TestMethod]
public void IsDisposalRequired_InvalidPart_ShouldThrowArgument()
{
ExceptionAssert.ThrowsArgument<ArgumentException>("partDefinition", () =>
{
ReflectionModelServices.IsDisposalRequired(new InvalidPartDefinition());
});
}
[TestMethod]
public void CreateExportDefinition()
{
PropertyInfo property = typeof(TestPart).GetProperties().First();
LazyMemberInfo expectedLazyMember = new LazyMemberInfo(property);
IDictionary<string, object> expectedMetadata = new Dictionary<string, object>();
expectedMetadata["Key1"] = 1;
expectedMetadata["Key2"] = "Value2";
string expectedContractName = "Foo";
ICompositionElement expectedOrigin = new MockOrigin();
ExportDefinition exportDefinition = ReflectionModelServices.CreateExportDefinition(expectedLazyMember, expectedContractName, expectedMetadata.AsLazy(), expectedOrigin);
Assert.IsNotNull(exportDefinition);
ReflectionMemberExportDefinition definition = exportDefinition as ReflectionMemberExportDefinition;
Assert.IsNotNull(definition);
Assert.AreEqual(expectedContractName, definition.ContractName);
Assert.IsTrue(definition.Metadata.Keys.SequenceEqual(expectedMetadata.Keys));
Assert.IsTrue(definition.Metadata.Values.SequenceEqual(expectedMetadata.Values));
Assert.AreEqual(expectedOrigin, ((ICompositionElement)definition).Origin);
Assert.AreEqual(expectedLazyMember, definition.ExportingLazyMember);
}
[TestMethod]
public void CreateExportDefinition_NullAsContractName_ThrowsNullArgument()
{
PropertyInfo property = typeof(TestPart).GetProperties().First();
LazyMemberInfo expectedLazyMember = new LazyMemberInfo(property);
IDictionary<string, object> expectedMetadata = new Dictionary<string, object>();
expectedMetadata["Key1"] = 1;
expectedMetadata["Key2"] = "Value2";
ICompositionElement expectedOrigin = new MockOrigin();
ExceptionAssert.ThrowsArgument<ArgumentNullException>("contractName", () =>
{
ReflectionModelServices.CreateExportDefinition(expectedLazyMember, null, expectedMetadata.AsLazy(), expectedOrigin);
});
}
public void CreateExportDefinition_NullAsMetadata_Allowed()
{
PropertyInfo property = typeof(TestPart).GetProperties().First();
LazyMemberInfo expectedLazyMember = new LazyMemberInfo(property);
IDictionary<string, object> expectedMetadata = new Dictionary<string, object>();
expectedMetadata["Key1"] = 1;
expectedMetadata["Key2"] = "Value2";
string expectedContractName = "Foo";
ICompositionElement expectedOrigin = new MockOrigin();
ExportDefinition definition = ReflectionModelServices.CreateExportDefinition(expectedLazyMember, expectedContractName, expectedMetadata.AsLazy(), expectedOrigin);
Assert.IsNotNull(definition.Metadata);
Assert.AreEqual(0, definition.Metadata.Count);
}
[TestMethod]
public void CreateExportDefinition_InvalidLazymemberInfo_ShouldThrowArtument()
{
EventInfo _event = typeof(TestPart).GetEvents().First();
LazyMemberInfo expectedLazyMember = new LazyMemberInfo(_event);
IDictionary<string, object> expectedMetadata = new Dictionary<string, object>();
expectedMetadata["Key1"] = 1;
expectedMetadata["Key2"] = "Value2";
string expectedContractName = "Foo";
ICompositionElement expectedOrigin = new MockOrigin();
ExceptionAssert.ThrowsArgument<ArgumentException>("exportingMember", () =>
{
ReflectionModelServices.CreateExportDefinition(expectedLazyMember, expectedContractName, expectedMetadata.AsLazy(), expectedOrigin);
});
}
[TestMethod]
public void GetExportingMember()
{
PropertyInfo property = typeof(TestPart).GetProperties().First();
LazyMemberInfo expectedLazyMember = new LazyMemberInfo(property);
IDictionary<string, object> expectedMetadata = new Dictionary<string, object>();
expectedMetadata["Key1"] = 1;
expectedMetadata["Key2"] = "Value2";
string expectedContractName = "Foo";
ICompositionElement expectedOrigin = new MockOrigin();
ExportDefinition exportDefinition = ReflectionModelServices.CreateExportDefinition(expectedLazyMember, expectedContractName, expectedMetadata.AsLazy(), expectedOrigin);
Assert.IsNotNull(exportDefinition);
LazyMemberInfo lazyMember = ReflectionModelServices.GetExportingMember(exportDefinition);
Assert.AreEqual(expectedLazyMember, lazyMember);
}
[TestMethod]
public void GetExportingMember_NullAsExportDefinition_ShouldThrowArhumentNull()
{
ExceptionAssert.ThrowsArgument<ArgumentNullException>("exportDefinition", () =>
{
ReflectionModelServices.GetExportingMember(null);
});
}
[TestMethod]
public void GetExportingMember_InvalidExportDefinition_ShouldThrowArhumentNull()
{
ExceptionAssert.ThrowsArgument<ArgumentException>("exportDefinition", () =>
{
ReflectionModelServices.GetExportingMember(new ExportDefinition("Foo", null));
});
}
[TestMethod]
public void CreateImportDefinition_Member()
{
PropertyInfo property = typeof(TestPart).GetProperties().First();
LazyMemberInfo expectedLazyMember = new LazyMemberInfo(property);
string expectedContractName = "Foo";
string expectedRequiredTypeIdentity = "Bar";
KeyValuePair<string, Type>[] expectedRequiredMetadata = new KeyValuePair<string, Type>[] { new KeyValuePair<string, Type>("Key1", typeof(string)), new KeyValuePair<string, Type>("Key2", typeof(int)) };
ImportCardinality expectedCardinality = ImportCardinality.ExactlyOne;
CreationPolicy expectedCreationPolicy = CreationPolicy.NonShared;
bool expectedRecomposable = true;
ICompositionElement expectedOrigin = new MockOrigin();
ImportDefinition importDefinition = ReflectionModelServices.CreateImportDefinition(
expectedLazyMember,
expectedContractName,
expectedRequiredTypeIdentity,
expectedRequiredMetadata,
expectedCardinality,
expectedRecomposable,
expectedCreationPolicy,
expectedOrigin);
Assert.IsNotNull(importDefinition);
ReflectionMemberImportDefinition definition = importDefinition as ReflectionMemberImportDefinition;
Assert.IsNotNull(definition);
Assert.AreEqual(expectedLazyMember, definition.ImportingLazyMember);
Assert.AreEqual(definition.ContractName, expectedContractName);
Assert.AreEqual(definition.RequiredTypeIdentity, expectedRequiredTypeIdentity);
Assert.IsTrue(definition.RequiredMetadata.SequenceEqual(expectedRequiredMetadata));
Assert.AreEqual(definition.Cardinality, expectedCardinality);
Assert.AreEqual(definition.RequiredCreationPolicy, expectedCreationPolicy);
Assert.AreEqual(definition.IsRecomposable, expectedRecomposable);
Assert.AreSame(expectedOrigin, ((ICompositionElement)definition).Origin);
Assert.IsFalse(definition.IsPrerequisite);
}
[TestMethod]
public void CreateImportDefinition_Member_InvalidMember_ShouldThrowArgument()
{
MethodInfo method = typeof(TestPart).GetMethods().First();
LazyMemberInfo expectedLazyMember = new LazyMemberInfo(method);
string expectedContractName = "Foo";
string expectedRequiredTypeIdentity = "Bar";
KeyValuePair<string, Type>[] expectedRequiredMetadata = new KeyValuePair<string, Type>[] { new KeyValuePair<string, Type>("Key1", typeof(string)), new KeyValuePair<string, Type>("Key2", typeof(int)) };
ImportCardinality expectedCardinality = ImportCardinality.ExactlyOne;
CreationPolicy expectedCreationPolicy = CreationPolicy.NonShared;
bool expectedRecomposable = true;
ICompositionElement expectedOrigin = new MockOrigin();
ExceptionAssert.ThrowsArgument<ArgumentException>("importingMember", () =>
{
ReflectionModelServices.CreateImportDefinition(
expectedLazyMember,
expectedContractName,
expectedRequiredTypeIdentity,
expectedRequiredMetadata,
expectedCardinality,
expectedRecomposable,
expectedCreationPolicy,
expectedOrigin);
});
}
[TestMethod]
public void GetImporingMember()
{
PropertyInfo property = typeof(TestPart).GetProperties().First();
LazyMemberInfo expectedLazyMember = new LazyMemberInfo(property);
string expectedContractName = "Foo";
string expectedRequiredTypeIdentity = "Bar";
KeyValuePair<string, Type>[] expectedRequiredMetadata = new KeyValuePair<string, Type>[] { new KeyValuePair<string, Type>("Key1", typeof(string)), new KeyValuePair<string, Type>("Key2", typeof(int)) };
ImportCardinality expectedCardinality = ImportCardinality.ExactlyOne;
CreationPolicy expectedCreationPolicy = CreationPolicy.NonShared;
bool expectedRecomposable = true;
ICompositionElement expectedOrigin = new MockOrigin();
ImportDefinition importDefinition = ReflectionModelServices.CreateImportDefinition(
expectedLazyMember,
expectedContractName,
expectedRequiredTypeIdentity,
expectedRequiredMetadata,
expectedCardinality,
expectedRecomposable,
expectedCreationPolicy,
expectedOrigin);
Assert.IsNotNull(importDefinition);
LazyMemberInfo lazyMember = ReflectionModelServices.GetImportingMember(importDefinition);
Assert.AreEqual(expectedLazyMember, lazyMember);
}
[TestMethod]
public void GetImporingMember_NullAsImport_ShouldThrowArgumentNull()
{
ExceptionAssert.ThrowsArgument<ArgumentNullException>("importDefinition", () =>
{
ReflectionModelServices.GetImportingMember(null);
});
}
[TestMethod]
public void GetImporingMember_InvalidImport_ShouldThrowArgument()
{
ExceptionAssert.ThrowsArgument<ArgumentException>("importDefinition", () =>
{
ReflectionModelServices.GetImportingMember(new ContractBasedImportDefinition("Foo", "Foo", null, ImportCardinality.ZeroOrMore, false, false, CreationPolicy.Any));
});
}
[TestMethod]
public void CreateImportDefinition_Parameter()
{
ParameterInfo parameter = typeof(TestPart).GetConstructor(new Type[] { typeof(int) }).GetParameters()[0];
Lazy<ParameterInfo> expectedLazyParameter = parameter.AsLazy();
string expectedContractName = "Foo";
string expectedRequiredTypeIdentity = "Bar";
KeyValuePair<string, Type>[] expectedRequiredMetadata = new KeyValuePair<string, Type>[] { new KeyValuePair<string, Type>("Key1", typeof(string)), new KeyValuePair<string, Type>("Key2", typeof(int)) };
ImportCardinality expectedCardinality = ImportCardinality.ExactlyOne;
CreationPolicy expectedCreationPolicy = CreationPolicy.NonShared;
ICompositionElement expectedOrigin = new MockOrigin();
ImportDefinition importDefinition = ReflectionModelServices.CreateImportDefinition(
expectedLazyParameter,
expectedContractName,
expectedRequiredTypeIdentity,
expectedRequiredMetadata,
expectedCardinality,
expectedCreationPolicy,
expectedOrigin);
Assert.IsNotNull(importDefinition);
ReflectionParameterImportDefinition definition = importDefinition as ReflectionParameterImportDefinition;
Assert.IsNotNull(definition);
Assert.AreEqual(expectedLazyParameter, definition.ImportingLazyParameter);
Assert.AreEqual(definition.ContractName, expectedContractName);
Assert.AreEqual(definition.RequiredTypeIdentity, expectedRequiredTypeIdentity);
Assert.IsTrue(definition.RequiredMetadata.SequenceEqual(expectedRequiredMetadata));
Assert.AreEqual(definition.Cardinality, expectedCardinality);
Assert.AreEqual(definition.RequiredCreationPolicy, expectedCreationPolicy);
Assert.IsFalse(definition.IsRecomposable);
Assert.AreSame(expectedOrigin, ((ICompositionElement)definition).Origin);
Assert.IsTrue(definition.IsPrerequisite);
}
[TestMethod]
public void CreateImportDefinition_Parameter_NullAsParamater_ShouldThrowArgumentNull()
{
ParameterInfo parameter = typeof(TestPart).GetConstructor(new Type[] { typeof(int) }).GetParameters()[0];
Lazy<ParameterInfo> expectedLazyParameter = parameter.AsLazy();
string expectedContractName = "Foo";
string expectedRequiredTypeIdentity = "Bar";
KeyValuePair<string, Type>[] expectedRequiredMetadata = new KeyValuePair<string, Type>[] { new KeyValuePair<string, Type>("Key1", typeof(string)), new KeyValuePair<string, Type>("Key2", typeof(int)) };
ImportCardinality expectedCardinality = ImportCardinality.ExactlyOne;
CreationPolicy expectedCreationPolicy = CreationPolicy.NonShared;
ICompositionElement expectedOrigin = new MockOrigin();
ExceptionAssert.ThrowsArgument<ArgumentNullException>("parameter", () =>
{
ReflectionModelServices.CreateImportDefinition(
null,
expectedContractName,
expectedRequiredTypeIdentity,
expectedRequiredMetadata,
expectedCardinality,
expectedCreationPolicy,
expectedOrigin);
});
}
[TestMethod]
public void GetImportingParameter()
{
ParameterInfo parameter = typeof(TestPart).GetConstructor(new Type[] { typeof(int) }).GetParameters()[0];
Lazy<ParameterInfo> expectedLazyParameter = parameter.AsLazy();
string expectedContractName = "Foo";
string expectedRequiredTypeIdentity = "Bar";
KeyValuePair<string, Type>[] expectedRequiredMetadata = new KeyValuePair<string, Type>[] { new KeyValuePair<string, Type>("Key1", typeof(string)), new KeyValuePair<string, Type>("Key2", typeof(int)) };
ImportCardinality expectedCardinality = ImportCardinality.ExactlyOne;
CreationPolicy expectedCreationPolicy = CreationPolicy.NonShared;
ICompositionElement expectedOrigin = new MockOrigin();
ImportDefinition importDefinition = ReflectionModelServices.CreateImportDefinition(
expectedLazyParameter,
expectedContractName,
expectedRequiredTypeIdentity,
expectedRequiredMetadata,
expectedCardinality,
expectedCreationPolicy,
expectedOrigin);
Assert.IsNotNull(importDefinition);
Lazy<ParameterInfo> lazyParameter = ReflectionModelServices.GetImportingParameter(importDefinition);
Assert.AreEqual(expectedLazyParameter, lazyParameter);
}
[TestMethod]
public void GetImportingParameter_NullAsImport_ShouldThrowArgumentNull()
{
ExceptionAssert.ThrowsArgument<ArgumentNullException>("importDefinition", () =>
{
ReflectionModelServices.GetImportingParameter(null);
});
}
[TestMethod]
public void GetImportingParameter_InvalidImport_ShouldThrowArgument()
{
ExceptionAssert.ThrowsArgument<ArgumentException>("importDefinition", () =>
{
ReflectionModelServices.GetImportingParameter(new ContractBasedImportDefinition("Foo", "Foo", null, ImportCardinality.ZeroOrMore, false, false, CreationPolicy.Any));
});
}
[TestMethod]
public void IsImportingParameter_OnParameterImport()
{
ParameterInfo parameter = typeof(TestPart).GetConstructor(new Type[] { typeof(int) }).GetParameters()[0];
Lazy<ParameterInfo> expectedLazyParameter = parameter.AsLazy();
string expectedContractName = "Foo";
string expectedRequiredTypeIdentity = "Bar";
KeyValuePair<string, Type>[] expectedRequiredMetadata = new KeyValuePair<string, Type>[] { new KeyValuePair<string, Type>("Key1", typeof(string)), new KeyValuePair<string, Type>("Key2", typeof(int)) };
ImportCardinality expectedCardinality = ImportCardinality.ExactlyOne;
CreationPolicy expectedCreationPolicy = CreationPolicy.NonShared;
ICompositionElement expectedOrigin = new MockOrigin();
ImportDefinition importDefinition = ReflectionModelServices.CreateImportDefinition(
expectedLazyParameter,
expectedContractName,
expectedRequiredTypeIdentity,
expectedRequiredMetadata,
expectedCardinality,
expectedCreationPolicy,
expectedOrigin);
Assert.IsNotNull(importDefinition);
Assert.IsTrue(ReflectionModelServices.IsImportingParameter(importDefinition));
}
[TestMethod]
public void IsImportingParameter_OnMemberImport()
{
PropertyInfo property = typeof(TestPart).GetProperties().First();
LazyMemberInfo expectedLazyMember = new LazyMemberInfo(property);
string expectedContractName = "Foo";
string expectedRequiredTypeIdentity = "Bar";
KeyValuePair<string, Type>[] expectedRequiredMetadata = new KeyValuePair<string, Type>[] { new KeyValuePair<string, Type>("Key1", typeof(string)), new KeyValuePair<string, Type>("Key2", typeof(int)) };
ImportCardinality expectedCardinality = ImportCardinality.ExactlyOne;
CreationPolicy expectedCreationPolicy = CreationPolicy.NonShared;
bool expectedRecomposable = true;
ICompositionElement expectedOrigin = new MockOrigin();
ImportDefinition importDefinition = ReflectionModelServices.CreateImportDefinition(
expectedLazyMember,
expectedContractName,
expectedRequiredTypeIdentity,
expectedRequiredMetadata,
expectedCardinality,
expectedRecomposable,
expectedCreationPolicy,
expectedOrigin);
Assert.IsNotNull(importDefinition);
Assert.IsFalse(ReflectionModelServices.IsImportingParameter(importDefinition));
}
[TestMethod]
public void IsImportingParameter_NullAsImport_ShouldThrowArgumentNull()
{
ExceptionAssert.ThrowsArgument<ArgumentNullException>("importDefinition", () =>
{
ReflectionModelServices.IsImportingParameter(null);
});
}
[TestMethod]
public void IsImportingParameter_InvalidImport_ShouldThrowArgument()
{
ExceptionAssert.ThrowsArgument<ArgumentException>("importDefinition", () =>
{
ReflectionModelServices.IsImportingParameter(new ContractBasedImportDefinition("Foo", "Foo", null, ImportCardinality.ZeroOrMore, false, false, CreationPolicy.Any));
});
}
[TestMethod]
public void IsExportFactoryImportDefinition_NullImport_ShouldThrowArgumentNull()
{
ExceptionAssert.ThrowsArgumentNull("importDefinition", () =>
ReflectionModelServices.IsExportFactoryImportDefinition(null));
}
[TestMethod]
public void IsExportFactoryImportDefinition_InvalidImport_ShouldThrowArgument()
{
ExceptionAssert.ThrowsArgument("importDefinition", () =>
ReflectionModelServices.IsExportFactoryImportDefinition(CreateInvalidImport()));
}
[TestMethod]
public void IsExportFactoryImportDefinition_NonPartCreatorImport_ShouldReturnFalse()
{
var import = ReflectionModelServices.CreateImportDefinition(
new LazyMemberInfo(MemberTypes.Field, () => new MemberInfo[] { typeof(ReflectionModelServicesTests) }), // bogus member
"Foo",
"Foo",
Enumerable.Empty<KeyValuePair<string, Type>>(),
ImportCardinality.ZeroOrMore,
false,
CreationPolicy.Any,
null);
Assert.IsFalse(ReflectionModelServices.IsExportFactoryImportDefinition(import));
}
[TestMethod]
public void IsExportFactoryImportDefinition_PartCreatorImport_ShouldReturnTrue()
{
var import = ReflectionModelServices.CreateImportDefinition(
new LazyMemberInfo(MemberTypes.Field, () => new MemberInfo[] { typeof(ReflectionModelServicesTests) }), // bogus member
"Foo",
"Foo",
Enumerable.Empty<KeyValuePair<string, Type>>(),
ImportCardinality.ZeroOrMore,
false,
CreationPolicy.Any,
MetadataServices.EmptyMetadata,
true, //isPartCreator
null);
Assert.IsTrue(ReflectionModelServices.IsExportFactoryImportDefinition(import));
}
[TestMethod]
public void GetExportFactoryProductImportDefinition_NullImport_ShouldThrowArgumentNull()
{
ExceptionAssert.ThrowsArgumentNull("importDefinition", () =>
ReflectionModelServices.GetExportFactoryProductImportDefinition(null));
}
[TestMethod]
public void GetExportFactoryProductImportDefinition_InvalidImport_ShouldThrowArgument()
{
ExceptionAssert.ThrowsArgument("importDefinition", () =>
ReflectionModelServices.GetExportFactoryProductImportDefinition(CreateInvalidImport()));
}
[TestMethod]
public void GetExportFactoryProductImportDefinition_()
{
}
[TestMethod]
public void GetExportFactoryProductImportDefinition_PartCreatorImport_()
{
LazyMemberInfo bogusMember = new LazyMemberInfo(MemberTypes.Field, () => new MemberInfo[] { typeof(ReflectionModelServicesTests) });
var import = ReflectionModelServices.CreateImportDefinition(
bogusMember,
"Foo",
"Foo",
Enumerable.Empty<KeyValuePair<string, Type>>(),
ImportCardinality.ZeroOrMore,
false,
CreationPolicy.Any,
null,
true, //isPartCreator
null);
var productImport = ReflectionModelServices.GetExportFactoryProductImportDefinition(import);
var import2 = ReflectionModelServices.CreateImportDefinition(
bogusMember,
productImport.ContractName,
productImport.RequiredTypeIdentity,
productImport.RequiredMetadata,
productImport.Cardinality,
productImport.IsRecomposable,
productImport.RequiredCreationPolicy,
productImport.Metadata,
true, //isPartCreator
null);
Assert.AreEqual(import.ContractName, import2.ContractName);
Assert.AreEqual(import.Cardinality, import2.Cardinality);
Assert.AreEqual(import.IsRecomposable, import2.IsRecomposable);
Assert.AreEqual(import.RequiredCreationPolicy, import2.RequiredCreationPolicy);
Assert.AreEqual(import.RequiredTypeIdentity, import2.RequiredTypeIdentity);
EnumerableAssert.AreEqual(import.RequiredMetadata, import2.RequiredMetadata);
}
private static IEnumerable<ImportDefinition> CreateInvalidImports()
{
yield return new ContractBasedImportDefinition("Foo", "Foo", null, ImportCardinality.ZeroOrMore, false, false, CreationPolicy.Any);
}
private static ImportDefinition CreateInvalidImport()
{
return new ContractBasedImportDefinition("Foo", "Foo", null, ImportCardinality.ZeroOrMore, false, false, CreationPolicy.Any);
}
private static IEnumerable<ExportDefinition> CreateInvalidExports()
{
yield return new ExportDefinition("Foo", null);
}
class InvalidPartDefinition : ComposablePartDefinition
{
public override ComposablePart CreatePart()
{
throw new NotImplementedException();
}
public override IEnumerable<ExportDefinition> ExportDefinitions
{
get { throw new NotImplementedException(); }
}
public override IEnumerable<ImportDefinition> ImportDefinitions
{
get { throw new NotImplementedException(); }
}
}
private static List<ImportDefinition> CreateImports(Type type)
{
List<ImportDefinition> imports = new List<ImportDefinition>();
foreach (PropertyInfo property in type.GetProperties())
{
imports.Add(new ReflectionMemberImportDefinition(new LazyMemberInfo(property), "Contract", (string)null, new KeyValuePair<string, Type>[] { new KeyValuePair<string, Type>("Key1", typeof(string)), new KeyValuePair<string, Type>("Key2", typeof(int)) }, ImportCardinality.ZeroOrOne, true, false, CreationPolicy.Any, MetadataServices.EmptyMetadata, new TypeOrigin(type)));
}
return imports;
}
private static List<ExportDefinition> CreateExports(Type type)
{
List<ExportDefinition> exports = new List<ExportDefinition>();
foreach (PropertyInfo property in type.GetProperties())
{
exports.Add(ReflectionModelServices.CreateExportDefinition(new LazyMemberInfo(property), "Contract", new Lazy<IDictionary<string, object>>(() => null), new TypeOrigin(type)));
}
return exports;
}
public class TestPart
{
public TestPart(int arg1)
{
}
public int field1;
public string field2;
public int Property1 { get; set; }
public string Property2
{
get { return null; }
set
{
this.Event.Invoke(this, null);
}
}
public event EventHandler Event;
}
private class TypeOrigin : ICompositionElement
{
private readonly Type _type;
private readonly ICompositionElement _orgin;
public TypeOrigin(Type type)
: this(type, null)
{
}
public TypeOrigin(Type type, ICompositionElement origin)
{
this._type = type;
this._orgin = origin;
}
public string DisplayName
{
get
{
return this._type.GetDisplayName();
}
}
public ICompositionElement Origin
{
get
{
return this._orgin;
}
}
}
private class MockOrigin : ICompositionElement
{
public string DisplayName
{
get { throw new NotImplementedException(); }
}
public ICompositionElement Origin
{
get { throw new NotImplementedException(); }
}
}
}
}
| 45.512704 | 384 | 0.65154 | [
"MIT"
] | zhy29563/MyMEF | redist/test/ComponentModelUnitTest/System/ComponentModel/Composition/ReflectionModel/ReflectionModelServicesTests.cs | 50,155 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Globalization;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using PasswordVault.Models;
using PasswordVault.Data;
using PasswordVault.Services;
using Microsoft.Extensions.Options;
using System.Text;
using Microsoft.IdentityModel.Tokens;
namespace PasswordVault.WebApi
{
public class WebAuthenticationService
{
//private IDatabase _dbContext;
//private IMasterPassword _masterPassword;
//private IEncryptionService _encryptionService;
//private readonly AppSettings _appsettings;
//public UserService(IOptions<AppSettings> appSettings, IDatabase dbContext, IMasterPassword masterPassword, IEncryptionService encryptionService)
//{
// _dbContext = dbContext;
// _masterPassword = masterPassword;
// _encryptionService = encryptionService;
// _appsettings = appSettings.Value;
//}
//public User Authenticate(string username, string password)
//{
// User result = new User(false);
// if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
// {
// return result;
// }
// if (!_dbContext.UserExistsByUsername(username))
// {
// return result;
// }
// else
// {
// User user = _dbContext.GetUserByUsername(username);
// bool valid = _masterPassword.VerifyPassword(password, user.Salt, user.Hash, Convert.ToInt32(user.Iterations, CultureInfo.CurrentCulture));
// if (valid)
// {
// string tempKey = _encryptionService.Decrypt(user.EncryptedKey, password);
// result = new User(user.GUID,
// user.Username,
// tempKey,
// _encryptionService.Decrypt(user.FirstName, tempKey),
// _encryptionService.Decrypt(user.LastName, tempKey),
// _encryptionService.Decrypt(user.PhoneNumber, tempKey),
// _encryptionService.Decrypt(user.Email, tempKey),
// true);
// var tokenHandler = new JwtSecurityTokenHandler();
// var key = Encoding.ASCII.GetBytes(_appsettings.Secret);
// var tokenDescriptor = new SecurityTokenDescriptor
// {
// Subject = new ClaimsIdentity(new Claim[]
// {
// new Claim(ClaimTypes.Name, user.GUID.ToString())
// }),
// Expires = DateTime.UtcNow.AddDays(7),
// SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
// };
// var token = tokenHandler.CreateToken(tokenDescriptor);
// result.Token = tokenHandler.WriteToken(token);
// }
// }
// return result;
//}
}
}
| 40.380952 | 156 | 0.5398 | [
"Apache-2.0"
] | willem445/PasswordVault | PasswordVault.WebApi/Services/Authentication/WebAuthenticationService.cs | 3,394 | C# |
namespace TestApp
{
partial class FormMain
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form 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.odAnyFile = new System.Windows.Forms.OpenFileDialog();
this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
this.tbMain = new System.Windows.Forms.TextBox();
this.tbSearchString = new System.Windows.Forms.TextBox();
this.btWholeWordForward = new System.Windows.Forms.Button();
this.menuStrip1 = new System.Windows.Forms.MenuStrip();
this.mnuFile = new System.Windows.Forms.ToolStripMenuItem();
this.mnuOpen = new System.Windows.Forms.ToolStripMenuItem();
this.btWholeWordBackward = new System.Windows.Forms.Button();
this.btTestSomething = new System.Windows.Forms.Button();
this.menuStrip1.SuspendLayout();
this.SuspendLayout();
//
// odAnyFile
//
this.odAnyFile.Filter = "All files|*.*";
//
// openFileDialog1
//
this.openFileDialog1.FileName = "openFileDialog1";
//
// tbMain
//
this.tbMain.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.tbMain.HideSelection = false;
this.tbMain.Location = new System.Drawing.Point(12, 27);
this.tbMain.Multiline = true;
this.tbMain.Name = "tbMain";
this.tbMain.ScrollBars = System.Windows.Forms.ScrollBars.Both;
this.tbMain.Size = new System.Drawing.Size(776, 369);
this.tbMain.TabIndex = 0;
this.tbMain.WordWrap = false;
this.tbMain.TextChanged += new System.EventHandler(this.TbMain_TextChanged);
//
// tbSearchString
//
this.tbSearchString.Location = new System.Drawing.Point(12, 418);
this.tbSearchString.Name = "tbSearchString";
this.tbSearchString.Size = new System.Drawing.Size(321, 20);
this.tbSearchString.TabIndex = 1;
this.tbSearchString.TextChanged += new System.EventHandler(this.TbMain_TextChanged);
//
// btWholeWordForward
//
this.btWholeWordForward.Location = new System.Drawing.Point(659, 415);
this.btWholeWordForward.Name = "btWholeWordForward";
this.btWholeWordForward.Size = new System.Drawing.Size(129, 23);
this.btWholeWordForward.TabIndex = 2;
this.btWholeWordForward.Text = "Whole word test >>";
this.btWholeWordForward.UseVisualStyleBackColor = true;
this.btWholeWordForward.Click += new System.EventHandler(this.BtWholeWordForward_Click);
//
// menuStrip1
//
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.mnuFile});
this.menuStrip1.Location = new System.Drawing.Point(0, 0);
this.menuStrip1.Name = "menuStrip1";
this.menuStrip1.Size = new System.Drawing.Size(800, 24);
this.menuStrip1.TabIndex = 3;
this.menuStrip1.Text = "menuStrip1";
//
// mnuFile
//
this.mnuFile.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.mnuOpen});
this.mnuFile.Name = "mnuFile";
this.mnuFile.Size = new System.Drawing.Size(37, 20);
this.mnuFile.Text = "File";
//
// mnuOpen
//
this.mnuOpen.Name = "mnuOpen";
this.mnuOpen.Size = new System.Drawing.Size(103, 22);
this.mnuOpen.Text = "Open";
this.mnuOpen.Click += new System.EventHandler(this.MnuOpen_Click);
//
// btWholeWordBackward
//
this.btWholeWordBackward.Location = new System.Drawing.Point(524, 415);
this.btWholeWordBackward.Name = "btWholeWordBackward";
this.btWholeWordBackward.Size = new System.Drawing.Size(129, 23);
this.btWholeWordBackward.TabIndex = 4;
this.btWholeWordBackward.Text = "<< Whole word test";
this.btWholeWordBackward.UseVisualStyleBackColor = true;
this.btWholeWordBackward.Click += new System.EventHandler(this.BtWholeWordBackward_Click);
//
// btTestSomething
//
this.btTestSomething.Location = new System.Drawing.Point(389, 415);
this.btTestSomething.Name = "btTestSomething";
this.btTestSomething.Size = new System.Drawing.Size(129, 23);
this.btTestSomething.TabIndex = 5;
this.btTestSomething.Text = "Test something";
this.btTestSomething.UseVisualStyleBackColor = true;
this.btTestSomething.Click += new System.EventHandler(this.BtTestSomething_Click);
//
// FormMain
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Controls.Add(this.btTestSomething);
this.Controls.Add(this.btWholeWordBackward);
this.Controls.Add(this.btWholeWordForward);
this.Controls.Add(this.tbSearchString);
this.Controls.Add(this.tbMain);
this.Controls.Add(this.menuStrip1);
this.MainMenuStrip = this.menuStrip1;
this.Name = "FormMain";
this.Text = "FormMain";
this.menuStrip1.ResumeLayout(false);
this.menuStrip1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.OpenFileDialog odAnyFile;
private System.Windows.Forms.OpenFileDialog openFileDialog1;
private System.Windows.Forms.TextBox tbMain;
private System.Windows.Forms.TextBox tbSearchString;
private System.Windows.Forms.Button btWholeWordForward;
private System.Windows.Forms.MenuStrip menuStrip1;
private System.Windows.Forms.ToolStripMenuItem mnuFile;
private System.Windows.Forms.ToolStripMenuItem mnuOpen;
private System.Windows.Forms.Button btWholeWordBackward;
private System.Windows.Forms.Button btTestSomething;
}
}
| 46.054217 | 156 | 0.586789 | [
"MIT"
] | VPKSoft/VPKSoft.SearchText | TestApp/FormMain.Designer.cs | 7,647 | C# |
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
using System;
namespace Microsoft.Azure.PowerShell.Cmdlets.DigitalTwins.Runtime.Json
{
internal sealed partial class JsonDate : JsonNode, IEquatable<JsonDate>, IComparable<JsonDate>
{
internal static bool AssumeUtcWhenKindIsUnspecified = true;
private readonly DateTimeOffset value;
internal JsonDate(DateTime value)
{
if (value.Kind == DateTimeKind.Unspecified && AssumeUtcWhenKindIsUnspecified)
{
value = DateTime.SpecifyKind(value, DateTimeKind.Utc);
}
this.value = value;
}
internal JsonDate(DateTimeOffset value)
{
this.value = value;
}
internal override JsonType Type => JsonType.Date;
#region Helpers
internal DateTimeOffset ToDateTimeOffset()
{
return value;
}
internal DateTime ToDateTime()
{
if (value.Offset == TimeSpan.Zero)
{
return value.UtcDateTime;
}
return value.DateTime;
}
internal DateTime ToUtcDateTime() => value.UtcDateTime;
internal int ToUnixTimeSeconds()
{
return (int)value.ToUnixTimeSeconds();
}
internal long ToUnixTimeMilliseconds()
{
return (int)value.ToUnixTimeMilliseconds();
}
internal string ToIsoString()
{
return IsoDate.FromDateTimeOffset(value).ToString();
}
#endregion
public override string ToString()
{
return ToIsoString();
}
internal static new JsonDate Parse(string text)
{
if (text == null) throw new ArgumentNullException(nameof(text));
// TODO support: unixtimeseconds.partialseconds
if (text.Length > 4 && _IsNumber(text)) // UnixTime
{
var date = DateTimeOffset.FromUnixTimeSeconds(long.Parse(text));
return new JsonDate(date);
}
else if (text.Length <= 4 || text[4] == '-') // ISO: 2012-
{
return new JsonDate(IsoDate.Parse(text).ToDateTimeOffset());
}
else
{
// NOT ISO ENCODED
// "Thu, 5 Apr 2012 16:59:01 +0200",
return new JsonDate(DateTimeOffset.Parse(text));
}
}
private static bool _IsNumber(string text)
{
foreach (var c in text)
{
if (!char.IsDigit(c)) return false;
}
return true;
}
internal static JsonDate FromUnixTime(int seconds)
{
return new JsonDate(DateTimeOffset.FromUnixTimeSeconds(seconds));
}
internal static JsonDate FromUnixTime(double seconds)
{
var milliseconds = (long)(seconds * 1000d);
return new JsonDate(DateTimeOffset.FromUnixTimeMilliseconds(milliseconds));
}
#region Implicit Casts
public static implicit operator DateTimeOffset(JsonDate value)
=> value.ToDateTimeOffset();
public static implicit operator DateTime(JsonDate value)
=> value.ToDateTime();
// From Date
public static implicit operator JsonDate(DateTimeOffset value)
{
return new JsonDate(value);
}
public static implicit operator JsonDate(DateTime value)
{
return new JsonDate(value);
}
// From String
public static implicit operator JsonDate(string value)
{
return Parse(value);
}
#endregion
#region Equality
public override bool Equals(object obj)
{
return obj is JsonDate date && date.value == this.value;
}
public bool Equals(JsonDate other)
{
return this.value == other.value;
}
public override int GetHashCode() => value.GetHashCode();
#endregion
#region IComparable<XDate> Members
int IComparable<JsonDate>.CompareTo(JsonDate other)
{
return value.CompareTo(other.value);
}
#endregion
}
} | 27.895954 | 99 | 0.514712 | [
"MIT"
] | 3quanfeng/azure-powershell | src/DigitalTwins/generated/runtime/Nodes/JsonDate.cs | 4,656 | C# |
//-----------------------------------------------------------------------
// <copyright file="FrameApi.cs" company="Google">
//
// Copyright 2017 Google Inc. All Rights Reserved.
//
// 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.
//
// </copyright>
//-----------------------------------------------------------------------
namespace GoogleARCoreInternal
{
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using GoogleARCore;
using UnityEngine;
#if UNITY_IOS && !UNITY_EDITOR
using AndroidImport = GoogleARCoreInternal.DllImportNoop;
using IOSImport = System.Runtime.InteropServices.DllImportAttribute;
#else
using AndroidImport = System.Runtime.InteropServices.DllImportAttribute;
using IOSImport = GoogleARCoreInternal.DllImportNoop;
#endif
internal class FrameApi
{
private NativeSession m_NativeSession;
// Throttle warnings to at most once every N seconds.
private ThrottledLogMessage m_FailedToAcquireWarning = new ThrottledLogMessage(5f);
public FrameApi(NativeSession nativeSession)
{
m_NativeSession = nativeSession;
}
public void Release(IntPtr frameHandle)
{
ExternApi.ArFrame_release(frameHandle);
}
public long GetTimestamp()
{
long timestamp = 0;
ExternApi.ArFrame_getTimestamp(m_NativeSession.SessionHandle, m_NativeSession.FrameHandle,
ref timestamp);
return timestamp;
}
public IntPtr AcquireCamera()
{
IntPtr cameraHandle = IntPtr.Zero;
ExternApi.ArFrame_acquireCamera(m_NativeSession.SessionHandle, m_NativeSession.FrameHandle,
ref cameraHandle);
return cameraHandle;
}
public CameraImageBytes AcquireCameraImageBytes()
{
IntPtr cameraImageHandle = IntPtr.Zero;
ApiArStatus status = ExternApi.ArFrame_acquireCameraImage(m_NativeSession.SessionHandle,
m_NativeSession.FrameHandle, ref cameraImageHandle);
if (status != ApiArStatus.Success)
{
m_FailedToAcquireWarning.ThrottledLogWarningFormat(
"Failed to acquire camera image with status {0}.\n" +
"Will continue to retry.", status);
return new CameraImageBytes(IntPtr.Zero);
}
m_NativeSession.MarkHandleAcquired(cameraImageHandle);
return new CameraImageBytes(cameraImageHandle);
}
public bool TryAcquirePointCloudHandle(out IntPtr pointCloudHandle)
{
pointCloudHandle = IntPtr.Zero;
ApiArStatus status = ExternApi.ArFrame_acquirePointCloud(m_NativeSession.SessionHandle,
m_NativeSession.FrameHandle, ref pointCloudHandle);
if (status != ApiArStatus.Success)
{
Debug.LogWarningFormat("Failed to acquire point cloud with status {0}", status);
return false;
}
return true;
}
public bool AcquireImageMetadata(ref IntPtr imageMetadataHandle)
{
var status = ExternApi.ArFrame_acquireImageMetadata(m_NativeSession.SessionHandle,
m_NativeSession.FrameHandle, ref imageMetadataHandle);
if (status != ApiArStatus.Success)
{
Debug.LogErrorFormat("Failed to aquire camera image metadata with status {0}", status);
return false;
}
return true;
}
public LightEstimate GetLightEstimate()
{
IntPtr lightEstimateHandle = m_NativeSession.LightEstimateApi.Create();
ExternApi.ArFrame_getLightEstimate(m_NativeSession.SessionHandle, m_NativeSession.FrameHandle,
lightEstimateHandle);
LightEstimateState state = m_NativeSession.LightEstimateApi.GetState(lightEstimateHandle);
Color colorCorrection = m_NativeSession.LightEstimateApi.GetColorCorrection(lightEstimateHandle);
m_NativeSession.LightEstimateApi.Destroy(lightEstimateHandle);
return new LightEstimate(state, colorCorrection.a,
new Color(colorCorrection.r, colorCorrection.g, colorCorrection.b, 1f));
}
public void TransformDisplayUvCoords(ref ApiDisplayUvCoords uv)
{
ApiDisplayUvCoords uvOut = new ApiDisplayUvCoords();
ExternApi.ArFrame_transformDisplayUvCoords(m_NativeSession.SessionHandle, m_NativeSession.FrameHandle,
ApiDisplayUvCoords.NumFloats, ref uv, ref uvOut);
uv = uvOut;
}
public void GetUpdatedTrackables(List<Trackable> trackables)
{
IntPtr listHandle = m_NativeSession.TrackableListApi.Create();
ExternApi.ArFrame_getUpdatedTrackables(m_NativeSession.SessionHandle, m_NativeSession.FrameHandle,
ApiTrackableType.BaseTrackable, listHandle);
trackables.Clear();
int count = m_NativeSession.TrackableListApi.GetCount(listHandle);
for (int i = 0; i < count; i++)
{
IntPtr trackableHandle = m_NativeSession.TrackableListApi.AcquireItem(listHandle, i);
// TODO:: Remove conditional when b/75291352 is fixed.
ApiTrackableType trackableType = m_NativeSession.TrackableApi.GetType(trackableHandle);
if ((int)trackableType == 0x41520105)
{
m_NativeSession.TrackableApi.Release(trackableHandle);
continue;
}
Trackable trackable = m_NativeSession.TrackableFactory(trackableHandle);
if (trackable != null)
{
trackables.Add(trackable);
}
else
{
m_NativeSession.TrackableApi.Release(trackableHandle);
}
}
m_NativeSession.TrackableListApi.Destroy(listHandle);
}
private struct ExternApi
{
[DllImport(ApiConstants.ARCoreNativeApi)]
public static extern void ArFrame_release(IntPtr frame);
[DllImport(ApiConstants.ARCoreNativeApi)]
public static extern void ArFrame_getTimestamp(IntPtr sessionHandle,
IntPtr frame, ref long timestamp);
#pragma warning disable 626
[AndroidImport(ApiConstants.ARCoreNativeApi)]
public static extern void ArFrame_acquireCamera(IntPtr sessionHandle, IntPtr frameHandle,
ref IntPtr cameraHandle);
[AndroidImport(ApiConstants.ARCoreNativeApi)]
public static extern ApiArStatus ArFrame_acquireCameraImage(IntPtr sessionHandle, IntPtr frameHandle,
ref IntPtr imageHandle);
[AndroidImport(ApiConstants.ARCoreNativeApi)]
public static extern ApiArStatus ArFrame_acquirePointCloud(IntPtr sessionHandle, IntPtr frameHandle,
ref IntPtr pointCloudHandle);
[AndroidImport(ApiConstants.ARCoreNativeApi)]
public static extern void ArFrame_transformDisplayUvCoords(IntPtr session, IntPtr frame,
int numElements, ref ApiDisplayUvCoords uvsIn, ref ApiDisplayUvCoords uvsOut);
[AndroidImport(ApiConstants.ARCoreNativeApi)]
public static extern void ArFrame_getUpdatedTrackables(IntPtr sessionHandle, IntPtr frameHandle,
ApiTrackableType filterType, IntPtr outTrackableList);
[AndroidImport(ApiConstants.ARCoreNativeApi)]
public static extern void ArFrame_getLightEstimate(IntPtr sessionHandle, IntPtr frameHandle,
IntPtr lightEstimateHandle);
[AndroidImport(ApiConstants.ARCoreNativeApi)]
public static extern ApiArStatus ArFrame_acquireImageMetadata(IntPtr sessionHandle, IntPtr frameHandle,
ref IntPtr outMetadata);
#pragma warning restore 626
}
}
}
| 40.431925 | 115 | 0.645146 | [
"Apache-2.0"
] | BSAA0203/AR_Paint | AR/Assets/GoogleARCore/SDK/Scripts/Api/Wrappers/FrameApi.cs | 8,612 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Sets.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Sets.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap venn_intersect {
get {
object obj = ResourceManager.GetObject("venn-intersect", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap venn_not_intersect {
get {
object obj = ResourceManager.GetObject("venn-not-intersect", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap venn_not_subset {
get {
object obj = ResourceManager.GetObject("venn-not-subset", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap venn_union {
get {
object obj = ResourceManager.GetObject("venn-union", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
}
}
| 41.278846 | 170 | 0.583741 | [
"MIT"
] | jakesee/excel-sets | Sets/Properties/Resources.Designer.cs | 4,295 | C# |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.IO;
using BankLedger;
namespace BankLedgerTests
{
[TestClass]
public class AccountTests
{
[TestMethod]
public void Menu_NumberInput_ValidNumberOutput()
{
//Arrange
Account test = new Account();
string input = "0{0}-5{0}100{0}6{0}5{0}"; //Each part of the string represents user input and the {0} represent newlines
using (var sw = new StringWriter())
{
using (var sr = new StringReader(string.Format(input, Environment.NewLine)))
{
Console.SetOut(sw);
Console.SetIn(sr);
//Act
int result = test.Menu();
//Assert
Assert.IsTrue(result == 5);
}
}
}
[TestMethod]
public void TransactionHistory_ValidInput_CountChanges()
{
//Arrange
Account test = new Account();
string input = "1{0}100{0}1{0}400{0}2{0}100{0}2{0}200{0}5{0}";
using (var sw = new StringWriter())
{
using (var sr = new StringReader(string.Format(input, Environment.NewLine)))
{
Console.SetOut(sw);
Console.SetIn(sr);
//Act
test.AccountWorkflow();
//Assert
Assert.IsTrue(test.TransactionHistory.Count == 4);
}
}
}
[TestMethod]
public void Deposit_ValidInput_BalanceChanges()
{
//Arrange
Account test = new Account();
string input = "1{0}100{0}5{0}";
using (var sw = new StringWriter())
{
using (var sr = new StringReader(string.Format(input, Environment.NewLine)))
{
Console.SetOut(sw);
Console.SetIn(sr);
//Act
test.AccountWorkflow();
//Assert
Assert.IsTrue(test.Balance == 100);
}
}
}
[TestMethod]
public void Withdraw_ValidInput_BalanceChanges()
{
//Arrange
Account test = new Account();
string input = "1{0}200{0}2{0}100{0}5{0}";
using (var sw = new StringWriter())
{
using (var sr = new StringReader(string.Format(input, Environment.NewLine)))
{
Console.SetOut(sw);
Console.SetIn(sr);
//Act
test.AccountWorkflow();
//Assert
Assert.IsTrue(test.Balance == 100);
}
}
}
[TestMethod]
public void Withdraw_InvalidOverdraft_NoBalanceChange()
{
//Arrange
Account test = new Account();
string input = "1{0}100{0}2{0}200{0}5{0}";
using (var sw = new StringWriter())
{
using (var sr = new StringReader(string.Format(input, Environment.NewLine)))
{
Console.SetOut(sw);
Console.SetIn(sr);
//Act
test.AccountWorkflow();
//Assert
Assert.IsTrue(test.Balance == 100);
}
}
}
}
}
| 26.181159 | 133 | 0.443122 | [
"MIT"
] | Herberholz/BankLedger | BankLedger/BankLedgerTests/AccountTests.cs | 3,615 | C# |
using System;
using System.Collections.Generic;
using CoreGraphics;
using MapKit;
using MapsDemo.Controls;
using MapsDemo.iOS.Renderer;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Maps.iOS;
using Xamarin.Forms.Platform.iOS;
[assembly: ExportRenderer(typeof(CustomMap), typeof(CustomMapRenderer))]
namespace MapsDemo.iOS.Renderer
{
public class CustomMapRenderer : MapRenderer
{
UIView customPinView;
List<CustomPin> customPins;
protected override void OnElementChanged(ElementChangedEventArgs<View> e)
{
base.OnElementChanged(e);
if (e.OldElement != null)
{
var nativeMap = Control as MKMapView;
if (nativeMap != null)
{
nativeMap.RemoveAnnotations(nativeMap.Annotations);
nativeMap.GetViewForAnnotation = null;
nativeMap.CalloutAccessoryControlTapped -= OnCalloutAccessoryControlTapped;
nativeMap.DidSelectAnnotationView -= OnDidSelectAnnotationView;
nativeMap.DidDeselectAnnotationView -= OnDidDeselectAnnotationView;
}
}
if (e.NewElement != null)
{
var formsMap = (CustomMap)e.NewElement;
var nativeMap = Control as MKMapView;
customPins = formsMap.CustomPins;
nativeMap.GetViewForAnnotation = GetViewForAnnotation;
nativeMap.CalloutAccessoryControlTapped += OnCalloutAccessoryControlTapped;
nativeMap.DidSelectAnnotationView += OnDidSelectAnnotationView;
nativeMap.DidDeselectAnnotationView += OnDidDeselectAnnotationView;
}
}
MKAnnotationView GetViewForAnnotation(MKMapView mapView, IMKAnnotation annotation)
{
MKAnnotationView annotationView = null;
if (annotation is MKUserLocation)
return null;
var customPin = GetCustomPin(annotation as MKPointAnnotation);
if (customPin == null)
{
throw new Exception("Custom pin not found");
}
annotationView = mapView.DequeueReusableAnnotation(customPin.Id.ToString());
if (annotationView == null)
{
annotationView = new CustomMKAnnotationView(annotation, customPin.Id.ToString());
annotationView.Image = UIImage.FromFile("pin.png");
annotationView.CalloutOffset = new CGPoint(0, 0);
annotationView.LeftCalloutAccessoryView = new UIImageView(UIImage.FromFile("monkey.png"));
annotationView.RightCalloutAccessoryView = UIButton.FromType(UIButtonType.DetailDisclosure);
((CustomMKAnnotationView)annotationView).Id = customPin.Id.ToString();
((CustomMKAnnotationView)annotationView).Url = customPin.Url;
}
annotationView.CanShowCallout = true;
return annotationView;
}
void OnDidSelectAnnotationView(object sender, MKAnnotationViewEventArgs e)
{
var customView = e.View as CustomMKAnnotationView;
customPinView = new UIView();
if (customView.Id == "Xamarin")
{
customPinView.Frame = new CGRect(0, 0, 200, 84);
var image = new UIImageView(new CGRect(0, 0, 200, 84));
image.Image = UIImage.FromFile("xamarin.png");
customPinView.AddSubview(image);
customPinView.Center = new CGPoint(0, -(e.View.Frame.Height + 75));
e.View.AddSubview(customPinView);
}
}
void OnCalloutAccessoryControlTapped(object sender, MKMapViewAccessoryTappedEventArgs e)
{
var customView = e.View as CustomMKAnnotationView;
if (!string.IsNullOrWhiteSpace(customView.Url))
{
UIApplication.SharedApplication.OpenUrl(new Foundation.NSUrl(customView.Url));
}
}
void OnDidDeselectAnnotationView(object sender, MKAnnotationViewEventArgs e)
{
if (!e.View.Selected)
{
customPinView.RemoveFromSuperview();
customPinView.Dispose();
customPinView = null;
}
}
}
} | 38.165217 | 108 | 0.606744 | [
"MIT"
] | jorgemht/Xamarin-3.0 | MapsDemo/MapsDemo/MapsDemo.iOS/Renderer/CustomMapRenderer.cs | 4,391 | C# |
using KeyPay.DomainModels.V2.PayRun;
namespace KeyPay.ApiFunctions.V2
{
public class SuperAdjustmentsFunction : BaseFunction
{
public SuperAdjustmentsFunction(ApiRequestExecutor api) : base(api)
{
}
public SuperAdjustmentResponse List(int businessId, int payRunId)
{
return ApiRequest<SuperAdjustmentResponse>("/business/" + businessId + "/payrun/" + payRunId + "/superadjustments");
}
}
} | 28.9375 | 128 | 0.667387 | [
"MIT"
] | KeyPay/keypay-dotnet | src/keypay-dotnet/ApiFunctions/V2/SuperAdjustmentsFunction.cs | 463 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("RenCShapBot")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("RenCShapBot")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("8139603d-4c8a-499b-a12a-0b2aa9843306")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.567568 | 84 | 0.747482 | [
"MIT"
] | Iran/RenCSharpBot | RenCShapBot/Properties/AssemblyInfo.cs | 1,393 | C# |
using BeatSaberMarkupLanguage.Components;
using BeatSaberMarkupLanguage.Parser;
using HMUI;
using IPA.Utilities;
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using static BeatSaberMarkupLanguage.BSMLParser;
using static BeatSaberMarkupLanguage.Components.CustomListTableData;
using static HMUI.TableView;
namespace BeatSaberMarkupLanguage.TypeHandlers
{
[ComponentHandler(typeof(CustomListTableData))]
public class CustomListTableDataHandler : TypeHandler
{
public override Dictionary<string, string[]> Props => new Dictionary<string, string[]>()
{
{ "selectCell", new[]{ "select-cell" } },
{ "visibleCells", new[]{ "visible-cells"} },
{ "cellSize", new[]{ "cell-size"} },
{ "id", new[]{ "id" } },
{ "data", new[] { "data", "content" } },
{ "listWidth", new[] { "list-width" } },
{ "listHeight", new[] { "list-height" } },
{ "expandCell", new[] { "expand-cell" } },
{ "listStyle", new[] { "list-style" } },
{ "listDirection", new[] { "list-direction" } },
{ "alignCenter", new[] { "align-to-center" } }
};
public override void HandleType(ComponentTypeWithData componentType, BSMLParserParams parserParams)
{
CustomListTableData tableData = componentType.component as CustomListTableData;
if (componentType.data.TryGetValue("selectCell", out string selectCell))
{
tableData.tableView.didSelectCellWithIdxEvent += delegate (TableView table, int index)
{
if (!parserParams.actions.TryGetValue(selectCell, out BSMLAction action))
throw new Exception("select-cell action '" + componentType.data["onClick"] + "' not found");
action.Invoke(table, index);
};
}
if (componentType.data.TryGetValue("listDirection", out string listDirection))
tableData.tableView.SetField<TableView, TableType>("_tableType", (TableType)Enum.Parse(typeof(TableType), listDirection));
if (componentType.data.TryGetValue("listStyle", out string listStyle))
tableData.Style = (ListStyle)Enum.Parse(typeof(ListStyle), listStyle);
if (componentType.data.TryGetValue("cellSize", out string cellSize))
tableData.cellSize = Parse.Float(cellSize);
if (componentType.data.TryGetValue("expandCell", out string expandCell))
tableData.expandCell = Parse.Bool(expandCell);
if (componentType.data.TryGetValue("alignCenter", out string alignCenter))
tableData.tableView.SetField<TableView, bool>("_alignToCenter", Parse.Bool(alignCenter));
if (componentType.data.TryGetValue("data", out string value))
{
if (!parserParams.values.TryGetValue(value, out BSMLValue contents))
throw new Exception("value '" + value + "' not found");
tableData.data = contents.GetValue() as List<CustomCellInfo>;
tableData.tableView.ReloadData();
}
switch (tableData.tableView.tableType)
{
case TableType.Vertical:
(componentType.component.gameObject.transform as RectTransform).sizeDelta = new Vector2(componentType.data.TryGetValue("listWidth", out string vListWidth) ? Parse.Float(vListWidth) : 60, tableData.cellSize * (componentType.data.TryGetValue("visibleCells", out string vVisibleCells) ? Parse.Float(vVisibleCells) : 7));
tableData.tableView.contentTransform.anchorMin = new Vector2(0, 1);
break;
case TableType.Horizontal:
(componentType.component.gameObject.transform as RectTransform).sizeDelta = new Vector2(tableData.cellSize * (componentType.data.TryGetValue("visibleCells", out string hVisibleCells) ? Parse.Float(hVisibleCells) : 4), componentType.data.TryGetValue("listHeight", out string hListHeight) ? Parse.Float(hListHeight) : 40);
break;
}
componentType.component.gameObject.GetComponent<LayoutElement>().preferredHeight = (componentType.component.gameObject.transform as RectTransform).sizeDelta.y;
componentType.component.gameObject.GetComponent<LayoutElement>().preferredWidth = (componentType.component.gameObject.transform as RectTransform).sizeDelta.x;
tableData.tableView.gameObject.SetActive(true);
if (componentType.data.TryGetValue("id", out string id))
{
TableViewScroller scroller = tableData.tableView.GetField<TableViewScroller, TableView>("_scroller");
parserParams.AddEvent(id + "#PageUp", scroller.PageScrollUp);
parserParams.AddEvent(id + "#PageDown", scroller.PageScrollDown);
}
}
}
}
| 52.715789 | 340 | 0.638578 | [
"MIT"
] | Pespiri/BeatSaberMarkupLanguage | BeatSaberMarkupLanguage/TypeHandlers/CustomListTableDataHandler.cs | 5,010 | C# |
using System;
using System.Reflection;
namespace WebAPI_Learning1.Areas.HelpPage.ModelDescriptions
{
public interface IModelDocumentationProvider
{
string GetDocumentation(MemberInfo member);
string GetDocumentation(Type type);
}
} | 21.75 | 59 | 0.754789 | [
"Apache-2.0"
] | davidbull931997/asp.net | WebAPI_Buoi2/WebAPI_Learning1/Areas/HelpPage/ModelDescriptions/IModelDocumentationProvider.cs | 261 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("gabriel-client")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("gabriel-client")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: ComVisible(false)] | 36.034483 | 84 | 0.74067 | [
"MIT"
] | buaafw/6d-pose-estimation-with-ml-in-ar | gabriel/client/legacy-windows-client/gabriel-client/Properties/AssemblyInfo.cs | 1,048 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public static class Noise
{
public static float[,] GenerateNoiseMap(int mapWidth, int mapHeight, int seed, float scale, int octaves, float persistance, float lacunarity, Vector2 offset)
{
float[,] noiseMap = new float[mapWidth, mapHeight];
System.Random prng = new System.Random(seed);
Vector2[] octaveOffsets = new Vector2[octaves];
for (int i = 0; i < octaves; i++) {
float offsetX = prng.Next(-100000, 100000) + offset.x;
float offsetY = prng.Next(-100000, 100000) + offset.y;
octaveOffsets[i] = new Vector2(offsetX, offsetY);
}
if(scale <= 0)
{
scale = 0.0001f;
}
float maxNoiseHeight = float.MinValue;
float minNoiseHeight = float.MaxValue;
float halfWidth = mapWidth / 2f;
float halfHeight = mapHeight / 2f;
for(int y = 0; y < mapHeight; y++)
{
for (int x = 0; x < mapWidth; x++)
{
float amplitude = 1;
float frequency = 1;
float noiseHeight = 0;
for(int i = 0; i< octaves; i++)
{
float sampleX = (x - halfWidth) / scale * frequency + octaveOffsets[i].x;
float sampleY = (y - halfHeight) / scale * frequency + octaveOffsets[i].y;
// mulitply by 2 then subtract 1 = turns from range 0,1 to range -1,1
float perlinValue = Mathf.PerlinNoise(sampleX, sampleY) * 2 -1;
noiseHeight += perlinValue * amplitude;
amplitude *= persistance;
frequency *= lacunarity;
}
if(noiseHeight > maxNoiseHeight)
{
maxNoiseHeight = noiseHeight;
}
else if(noiseHeight< minNoiseHeight)
{
minNoiseHeight = noiseHeight;
}
noiseMap[x, y] = noiseHeight;
}
}
for (int y = 0; y < mapHeight; y++)
{
for (int x = 0; x < mapWidth; x++)
{
noiseMap[x, y] = Mathf.InverseLerp(minNoiseHeight, maxNoiseHeight, noiseMap[x, y]);
}
}
return noiseMap;
}
}
| 31.973684 | 161 | 0.496708 | [
"MIT"
] | igodsmark/MapGen-Unity | Assets/Scripts/Noise.cs | 2,432 | C# |
/*
* 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.Collections.Generic;
using Aliyun.Acs.Core;
namespace Aliyun.Acs.Rds.Model.V20140815
{
public class ModifyDTCSecurityIpHostsForSQLServerResponse : AcsResponse
{
private string requestId;
private string dBInstanceId;
private string dTCSetResult;
private string taskId;
public string RequestId
{
get
{
return requestId;
}
set
{
requestId = value;
}
}
public string DBInstanceId
{
get
{
return dBInstanceId;
}
set
{
dBInstanceId = value;
}
}
public string DTCSetResult
{
get
{
return dTCSetResult;
}
set
{
dTCSetResult = value;
}
}
public string TaskId
{
get
{
return taskId;
}
set
{
taskId = value;
}
}
}
}
| 19.588235 | 73 | 0.648048 | [
"Apache-2.0"
] | sdk-team/aliyun-openapi-net-sdk | aliyun-net-sdk-rds/Rds/Model/V20140815/ModifyDTCSecurityIpHostsForSQLServerResponse.cs | 1,665 | C# |
using Dapper;
using ModelCreater.DbHelper;
using ModelCreater.Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ModelCreater
{
public partial class FrmMain : Form
{
private readonly string _ModelsPath = ConfigurationManager.AppSettings["ModelsPath"];
private IDbHelper dbHelper;
private int _Num = 0;
public FrmMain()
{
InitializeComponent();
}
private void FrmMain_Load(object sender, EventArgs e)
{
tbNameSpace.Text = ConfigurationManager.AppSettings["NameSpace"];
tbClassSuffix.Text = ConfigurationManager.AppSettings["ClassSuffix"];
progressBar1.Minimum = 0;
progressBar1.Step = 1;
Dictionary<string, string> dicDatabaseType = new Dictionary<string, string>();
dicDatabaseType.Add("MSSqlServer", ConfigurationManager.ConnectionStrings["MSSqlServer"].ToString());
dicDatabaseType.Add("MySql", ConfigurationManager.ConnectionStrings["MySql"].ToString());
dicDatabaseType.Add("Oracle", ConfigurationManager.ConnectionStrings["Oracle"].ToString());
dicDatabaseType.Add("SQLite", ConfigurationManager.ConnectionStrings["SQLite"].ToString());
cbDatabaseType.DropDownStyle = ComboBoxStyle.DropDownList;
cbDatabaseType.DataSource = dicDatabaseType.ToList();
cbDatabaseType.DisplayMember = "Key";
cbDatabaseType.ValueMember = "Value";
cbDatabaseType.SelectedIndex = -1;
cbDatabaseType.SelectedIndexChanged += new EventHandler(cbDatabaseType_SelectedIndexChanged);
dgTables.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dgTables.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
timer1.Enabled = true;
}
private void cbDatabaseType_SelectedIndexChanged(object sender, EventArgs e)
{
tbConnectString.Text = cbDatabaseType.SelectedValue.ToString();
}
private void btnConnect_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(cbDatabaseType.Text)) return;
switch (cbDatabaseType.Text)
{
case "MSSqlServer":
dbHelper = new MSSqlServerHelper(tbConnectString.Text);
break;
//case "MySql":
// dbHelper = new MySqlHelper(tbConnectString.Text);
// break;
default:
return;
}
dgTables.DataSource = dbHelper.GetTableInfo();
}
private void BtnCreateModel_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(tbNameSpace.Text))
{
MessageBox.Show("必须填写命名空间");
return;
}
if (dgTables.SelectedRows.Count == 0)
{
MessageBox.Show("请选择要生成Model的表");
return;
}
Thread myThread = new Thread(new ThreadStart(() =>
{
string appStartupPath = Application.StartupPath;
string strNamespace = tbNameSpace.Text;
string strClassTemplate;
string strFieldTemplate = string.Empty;
Regex regField = new Regex(@"[ \t]*#field start([\s\S]*)#field end", RegexOptions.IgnoreCase);
try
{
//读模板
strClassTemplate = FileHelper.ReadFile(appStartupPath + "\\ModelTemplate.txt");
Match matchField = regField.Match(strClassTemplate);
if (matchField.Success)
{
strFieldTemplate = matchField.Groups[1].Value.TrimEnd(' ');
}
//获取选中表
List<TableInfo> tableInfos = new List<TableInfo>();
foreach (DataGridViewRow item in dgTables.SelectedRows)
{
tableInfos.Add(new TableInfo()
{
RowNum = int.Parse(item.Cells[0].Value.ToString()),
TableName = item.Cells[1].Value.ToString(),
Comment = item.Cells[2].Value.ToString(),
});
}
//初始化进度条
progressBar1.Invoke(new Action(() =>
{
progressBar1.Value = 0;
progressBar1.Maximum = tableInfos.Count;
}));
_Num = 0;
//遍历表
foreach (var item in tableInfos)
{
string tableComments = item.Comment; //表注释
string strClass = strClassTemplate.Replace("#table_comments", tableComments.Replace("\r\n", "\r\n /// ").Replace("\n", "\r\n /// "));
strClass = strClass.Replace("#name_space", strNamespace);
strClass = strClass.Replace("#table_name", item.TableName);
string strClassName = item.TableName + tbClassSuffix.Text; //类名
strClass = strClass.Replace("#class_name", strClassName);
//获取表字段
StringBuilder sbFields = new StringBuilder();
var tableColumns = dbHelper.GetTableColumns(item.TableName, cbUseNullNumberType.Checked, cbUseNullDateType.Checked, cbGuidConvertString.Checked);
foreach (var column in tableColumns)
{
string strField = strFieldTemplate.Replace("#field_comments", column.Comment.Replace("\r\n", "\r\n /// ").Replace("\n", "\r\n /// "));
strField = strField.Replace("#data_type", column.DataType);
strField = strField.Replace("#field_name", column.ColumnName);
sbFields.Append(strField);
}
strClass = regField.Replace(strClass, sbFields.ToString());
//生成model
FileHelper.WriteFile($"{appStartupPath}\\{_ModelsPath}", strClass, strClassName);
//增加进度
_Num++;
}
MessageBox.Show($"Model生成完毕,请查看{_ModelsPath}目录");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}));
myThread.IsBackground = true;
myThread.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
progressBar1.Invoke(new Action(() => progressBar1.Value = _Num));
}
}
}
| 39.911602 | 176 | 0.53696 | [
"MIT"
] | asfuyao/ModelCreater | ModelCreater/FrmMain.cs | 7,344 | C# |
using UISleuth.Widgets;
namespace UISleuth.Messages
{
internal class CallConstructorRequest : Request
{
public UIConstructor Constructor { get; set; }
public UIProperty Property { get; set; }
public string WidgetId { get; set; }
}
internal class CallConstructorResponse : Response
{
public string ErrorMessage { get; set; }
public bool Successful { get; set; }
}
} | 25.352941 | 54 | 0.647332 | [
"MIT"
] | michaeled/uisleuth | Mobile/Source/UISleuth/Messages/CallConstructorRequest.cs | 433 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/d3dcommon.h in the Windows SDK for Windows 10.0.20348.0
// Original source is Copyright © Microsoft. All rights reserved.
namespace TerraFX.Interop.DirectX;
/// <include file='D3D_CBUFFER_TYPE.xml' path='doc/member[@name="D3D_CBUFFER_TYPE"]/*' />
public enum D3D_CBUFFER_TYPE
{
/// <include file='D3D_CBUFFER_TYPE.xml' path='doc/member[@name="D3D_CBUFFER_TYPE.D3D_CT_CBUFFER"]/*' />
D3D_CT_CBUFFER = 0,
/// <include file='D3D_CBUFFER_TYPE.xml' path='doc/member[@name="D3D_CBUFFER_TYPE.D3D_CT_TBUFFER"]/*' />
D3D_CT_TBUFFER = (D3D_CT_CBUFFER + 1),
/// <include file='D3D_CBUFFER_TYPE.xml' path='doc/member[@name="D3D_CBUFFER_TYPE.D3D_CT_INTERFACE_POINTERS"]/*' />
D3D_CT_INTERFACE_POINTERS = (D3D_CT_TBUFFER + 1),
/// <include file='D3D_CBUFFER_TYPE.xml' path='doc/member[@name="D3D_CBUFFER_TYPE.D3D_CT_RESOURCE_BIND_INFO"]/*' />
D3D_CT_RESOURCE_BIND_INFO = (D3D_CT_INTERFACE_POINTERS + 1),
/// <include file='D3D_CBUFFER_TYPE.xml' path='doc/member[@name="D3D_CBUFFER_TYPE.D3D10_CT_CBUFFER"]/*' />
D3D10_CT_CBUFFER = D3D_CT_CBUFFER,
/// <include file='D3D_CBUFFER_TYPE.xml' path='doc/member[@name="D3D_CBUFFER_TYPE.D3D10_CT_TBUFFER"]/*' />
D3D10_CT_TBUFFER = D3D_CT_TBUFFER,
/// <include file='D3D_CBUFFER_TYPE.xml' path='doc/member[@name="D3D_CBUFFER_TYPE.D3D11_CT_CBUFFER"]/*' />
D3D11_CT_CBUFFER = D3D_CT_CBUFFER,
/// <include file='D3D_CBUFFER_TYPE.xml' path='doc/member[@name="D3D_CBUFFER_TYPE.D3D11_CT_TBUFFER"]/*' />
D3D11_CT_TBUFFER = D3D_CT_TBUFFER,
/// <include file='D3D_CBUFFER_TYPE.xml' path='doc/member[@name="D3D_CBUFFER_TYPE.D3D11_CT_INTERFACE_POINTERS"]/*' />
D3D11_CT_INTERFACE_POINTERS = D3D_CT_INTERFACE_POINTERS,
/// <include file='D3D_CBUFFER_TYPE.xml' path='doc/member[@name="D3D_CBUFFER_TYPE.D3D11_CT_RESOURCE_BIND_INFO"]/*' />
D3D11_CT_RESOURCE_BIND_INFO = D3D_CT_RESOURCE_BIND_INFO,
}
| 50.390244 | 145 | 0.738625 | [
"MIT"
] | IngmarBitter/terrafx.interop.windows | sources/Interop/Windows/DirectX/um/d3dcommon/D3D_CBUFFER_TYPE.cs | 2,068 | C# |
// <auto-generated>
// 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.
// </auto-generated>
namespace Microsoft.Azure.Management.ApplicationInsights.Management.Models
{
using Microsoft.Rest;
/// <summary>
/// Exception thrown for an invalid response with ErrorResponse
/// information.
/// </summary>
public partial class ErrorResponseException : RestException
{
/// <summary>
/// Gets information about the associated HTTP request.
/// </summary>
public HttpRequestMessageWrapper Request { get; set; }
/// <summary>
/// Gets information about the associated HTTP response.
/// </summary>
public HttpResponseMessageWrapper Response { get; set; }
/// <summary>
/// Gets or sets the body object.
/// </summary>
public ErrorResponse Body { get; set; }
/// <summary>
/// Initializes a new instance of the ErrorResponseException class.
/// </summary>
public ErrorResponseException()
{
}
/// <summary>
/// Initializes a new instance of the ErrorResponseException class.
/// </summary>
/// <param name="message">The exception message.</param>
public ErrorResponseException(string message)
: this(message, null)
{
}
/// <summary>
/// Initializes a new instance of the ErrorResponseException class.
/// </summary>
/// <param name="message">The exception message.</param>
/// <param name="innerException">Inner exception.</param>
public ErrorResponseException(string message, System.Exception innerException)
: base(message, innerException)
{
}
}
}
| 32.15873 | 86 | 0.621422 | [
"MIT"
] | 0rland0Wats0n/azure-sdk-for-net | sdk/applicationinsights/Microsoft.Azure.Management.ApplicationInsights/src/Generated/Models/ErrorResponseException.cs | 2,026 | C# |
using System.AddIn.Pipeline;
namespace MK6.GameKeeper.AddIns
{
[AddInBase]
public interface GameKeeperAddIn
{
void Start();
void Stop();
AddInStatus Status { get; }
}
}
| 16.230769 | 36 | 0.606635 | [
"MIT"
] | market6/MK6.GameKeeper.AddInBase | MK6.GameKeeper.AddIns/GameKeeperAddIn.cs | 213 | C# |
using NUnit.Framework;
using PrototypeApp;
using PrototypeApp.AOP;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security;
using System.Text;
using System.Threading.Tasks;
namespace UnitTests
{
[TestFixture]
public class Class1
{
//[Test]
//public void Test()
//{
// Startup startup = new Startup();
// startup.Start();
//}
//[Test]
//public void GetTodaysTrades_UserIsPermittedToViewTrades_TradesAreReturned()
//{
// PermissionsStub.IsUserPermittedToContinue = true;
// Startup startup = new Startup();
// startup.Start();
// startup.Login();
//}
[Test]
public void GetTodaysTrades_UserIsNotPermittedToViewTrades_SecurityExceptionThrown()
{
PermissionsStub.IsUserPermittedToContinue = false;
Startup startup = new Startup();
startup.Start();
Assert.Throws<SecurityException>(() => startup.Login());
}
}
}
| 23.608696 | 92 | 0.592081 | [
"MIT"
] | bobbyache/CsPrototypes | CastleWindsor/CastleWindsorPrototype/UnitTests/Class1.cs | 1,088 | C# |
//
// NeuroLoopGain Library
// Library containing helper classes used to implement the NeuroLoopGain analysis.
//
// Copyright 2012 Marco Roessen
//
// 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 NeuroLoopGainLibrary.Edf
{
public enum PrereadTALs
{
None,
OnOpenFile,
UseThread
}
} | 30.962963 | 82 | 0.72488 | [
"MIT"
] | UiL-OTS-labs/EDFPlusChecker | Source/NeuroLoogGainLibrary/Edf/PrereadTALs.cs | 838 | C# |
/* Copyright (c) 2010 Michael Lidgren
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.
*/
#define IS_STOPWATCH_AVAILABLE
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
namespace Lidgren.Network
{
/// <summary>
/// Time service
/// </summary>
public static class NetTime
{
#if IS_STOPWATCH_AVAILABLE
private static readonly long s_timeInitialized = Stopwatch.GetTimestamp();
private static readonly double s_dInvFreq = 1.0 / (double)Stopwatch.Frequency;
/// <summary>
/// Get number of seconds since the application started
/// </summary>
public static double Now { get { return (double)(Stopwatch.GetTimestamp() - s_timeInitialized) * s_dInvFreq; } }
#else
/// <summary>
/// Get number of seconds since the application started
/// </summary>
public static double Now { get { return (double)Environment.TickCount / 1000.0; } }
#endif
/// <summary>
/// Given seconds it will output a human friendly readable string (milliseconds if less than 60 seconds)
/// </summary>
public static string ToReadable(double seconds)
{
if (seconds > 60)
return TimeSpan.FromSeconds(seconds).ToString();
return (seconds * 1000.0).ToString("N2") + " ms";
}
}
} | 38.508475 | 115 | 0.735035 | [
"Unlicense"
] | CaptainSandman/DarkHavoc | Dependencies/MonoGame/ThirdParty/Lidgren.Network/NetTime.cs | 2,274 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace Microsoft.AspNetCore.Http.Result
{
/// <summary>
/// Implements an interface for registering external methods that provide
/// custom IResult instances.
/// </summary>
internal class ResultExtensions : IResultExtensions { }
} | 35.727273 | 77 | 0.727735 | [
"MIT"
] | TechnicalConsultant123/aspnetcore | src/Http/Http.Results/src/ResultExtensions.cs | 393 | C# |
//------------------------------------------------------------
// Game Framework
// Copyright © 2013-2019 Jiang Yin. All rights reserved.
// Homepage: http://gameframework.cn/
// Feedback: mailto:jiangyin@gameframework.cn
//------------------------------------------------------------
namespace GameFramework.Sound
{
/// <summary>
/// 声音组辅助器接口。
/// </summary>
public interface ISoundGroupHelper
{
}
}
| 25.117647 | 63 | 0.468384 | [
"MIT"
] | ElPsyCongree/GameFramework | GameFramework/Sound/ISoundGroupHelper.cs | 448 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
namespace Transfusion.Pages
{
public class IndexModel : PageModel
{
private readonly ILogger<IndexModel> _logger;
public IndexModel(ILogger<IndexModel> logger)
{
_logger = logger;
}
public void OnGet()
{
}
}
}
| 19.346154 | 53 | 0.667992 | [
"MIT"
] | sbannikov/csharpcroc | 2020-Spring/Transfusion/Pages/Index.cshtml.cs | 505 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WebMVC.Application.Services.Scraper.Models.Dto
{
public class OccurenceDto
{
public int No { get; set; }
public string Word { get; set; }
public int Occurence { get; set; }
}
}
| 20.117647 | 56 | 0.675439 | [
"MIT"
] | kelvint96/Sitecore.Analyzer.Seo | src/Web/WebMVC/Application/Services/Scraper/Models/Dto/OccurenceDto.cs | 344 | C# |
#pragma warning disable 108 // new keyword hiding
#pragma warning disable 114 // new keyword hiding
namespace Windows.ApplicationModel.VoiceCommands
{
#if __ANDROID__ || __IOS__ || NET46 || __WASM__
[global::Uno.NotImplemented]
#endif
public partial class VoiceCommandConfirmationResult
{
#if __ANDROID__ || __IOS__ || NET46 || __WASM__
[global::Uno.NotImplemented]
public bool Confirmed
{
get
{
throw new global::System.NotImplementedException("The member bool VoiceCommandConfirmationResult.Confirmed is not implemented in Uno.");
}
}
#endif
// Forced skipping of method Windows.ApplicationModel.VoiceCommands.VoiceCommandConfirmationResult.Confirmed.get
}
}
| 30.304348 | 140 | 0.761836 | [
"Apache-2.0"
] | nv-ksavaria/Uno | src/Uno.UWP/Generated/3.0.0.0/Windows.ApplicationModel.VoiceCommands/VoiceCommandConfirmationResult.cs | 697 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Les informations générales relatives à un assembly dépendent de
// l'ensemble d'attributs suivant. Changez les valeurs de ces attributs pour modifier les informations
// associées à un assembly.
[assembly: AssemblyTitle("Server")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Server")]
[assembly: AssemblyCopyright("Copyright © 2021")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// L'affectation de la valeur false à ComVisible rend les types invisibles dans cet assembly
// aux composants COM. Si vous devez accéder à un type dans cet assembly à partir de
// COM, affectez la valeur true à l'attribut ComVisible sur ce type.
[assembly: ComVisible(false)]
// Le GUID suivant est pour l'ID de la typelib si ce projet est exposé à COM
[assembly: Guid("d6ebd0b6-381a-47ce-8add-6c1d5bce2d58")]
// Les informations de version pour un assembly se composent des quatre valeurs suivantes :
//
// Version principale
// Version secondaire
// Numéro de build
// Révision
//
// Vous pouvez spécifier toutes les valeurs ou indiquer les numéros de build et de révision par défaut
// en utilisant '*', comme indiqué ci-dessous :
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 41.108108 | 104 | 0.73044 | [
"MIT"
] | tbenoist1/eiin839 | ProjetBiking/Server/Properties/AssemblyInfo.cs | 1,546 | C# |
//Copyright (C) Microsoft Corporation. All rights reserved.
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
// See the ReadMe.html for additional information
public class ObjectDumper {
public static void Write(object element)
{
Write(element, 0);
}
public static void Write(object element, int depth)
{
Write(element, depth, Console.Out);
}
public static void Write(object element, int depth, TextWriter log)
{
ObjectDumper dumper = new ObjectDumper(depth);
dumper.writer = log;
dumper.WriteObject(null, element);
log.WriteLine(new string('-', 20));
}
TextWriter writer;
int pos;
int level;
int depth;
private ObjectDumper(int depth)
{
this.depth = depth;
}
private void Write(string s)
{
if (s != null) {
writer.Write(s);
pos += s.Length;
}
}
private void WriteIndent()
{
for (int i = 0; i < level; i++) writer.Write(" ");
}
private void WriteLine()
{
writer.WriteLine();
pos = 0;
}
private void WriteTab()
{
Write(" ");
while (pos % 8 != 0) Write(" ");
}
private void WriteObject(string prefix, object element)
{
if (element == null || element is ValueType || element is string) {
WriteIndent();
Write(prefix);
WriteValue(element);
WriteLine();
}
else {
IEnumerable enumerableElement = element as IEnumerable;
if (enumerableElement != null) {
foreach (object item in enumerableElement) {
if (item is IEnumerable && !(item is string)) {
WriteIndent();
Write(prefix);
Write("...");
WriteLine();
if (level < depth) {
level++;
WriteObject(prefix, item);
level--;
}
}
else {
WriteObject(prefix, item);
}
}
}
else {
MemberInfo[] members = element.GetType().GetMembers(BindingFlags.Public | BindingFlags.Instance);
WriteIndent();
Write(prefix);
bool propWritten = false;
foreach (MemberInfo m in members) {
FieldInfo f = m as FieldInfo;
PropertyInfo p = m as PropertyInfo;
if (f != null || p != null) {
if (propWritten) {
WriteTab();
}
else {
propWritten = true;
}
Write(m.Name);
Write("=");
Type t = f != null ? f.FieldType : p.PropertyType;
if (t.IsValueType || t == typeof(string)) {
WriteValue(f != null ? f.GetValue(element) : p.GetValue(element, null));
}
else {
if (typeof(IEnumerable).IsAssignableFrom(t)) {
Write("...");
}
else {
Write("{ }");
}
}
}
}
if (propWritten) WriteLine();
if (level < depth) {
foreach (MemberInfo m in members) {
FieldInfo f = m as FieldInfo;
PropertyInfo p = m as PropertyInfo;
if (f != null || p != null) {
Type t = f != null ? f.FieldType : p.PropertyType;
if (!(t.IsValueType || t == typeof(string))) {
object value = f != null ? f.GetValue(element) : p.GetValue(element, null);
if (value != null) {
level++;
WriteObject(m.Name + ": ", value);
level--;
}
}
}
}
}
}
}
}
private void WriteValue(object o)
{
if (o == null) {
Write("null");
}
else if (o is DateTime) {
Write(((DateTime)o).ToShortDateString());
}
else if (o is ValueType || o is string) {
Write(o.ToString());
}
else if (o is IEnumerable) {
Write("...");
}
else {
Write("{ }");
}
}
}
| 30.630303 | 113 | 0.39632 | [
"MIT"
] | coojee2012/pm3 | Tools/ObjectDumper.cs | 5,056 | C# |
using EdityMcEditface.HtmlRenderer;
using EdityMcEditface.HtmlRenderer.FileInfo;
using HtmlAgilityPack;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace EdityMcEditface.HtmlRenderer.Compiler
{
public class JsonCompiler : IContentCompiler
{
private IFileFinder fileFinder;
private String outDir;
private ITargetFileInfoProvider fileInfoProvider;
private IOverrideValuesProvider overrideValuesProvider;
public JsonCompiler(IFileFinder fileFinder, String outDir, ITargetFileInfoProvider fileInfoProvider, IOverrideValuesProvider overrideValuesProvider)
{
this.fileFinder = fileFinder;
this.outDir = outDir;
this.fileInfoProvider = fileInfoProvider;
this.overrideValuesProvider = overrideValuesProvider;
}
public void buildPage(string relativeFile)
{
relativeFile = relativeFile.TrimStartingPathChars();
var outFile = Path.Combine(this.outDir, relativeFile);
var extension = "json";
if (OutputExtension != null)
{
extension = OutputExtension;
}
outFile = Path.ChangeExtension(outFile, extension);
var fileInfo = fileInfoProvider.GetFileInfo(relativeFile, null);
TemplateEnvironment environment = new TemplateEnvironment(fileInfo.FileNoExtension, fileFinder, overrideValuesProvider.OverrideVars, null, true);
PageStack pageStack = new PageStack(environment, fileFinder);
pageStack.ContentFile = fileInfo.HtmlFile;
if (pageStack.Visible)
{
pageStack.ContentTransformer = (content) =>
{
//This removes all html elements and formatting and cleans up the whitespace
HtmlDocument htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(content);
var escaped = HtmlEntity.DeEntitize(htmlDoc.DocumentNode.InnerText);
escaped = escaped.SingleSpaceWhitespace();
return escaped.JsonEscape();
};
var pageSettings = fileFinder.GetProjectPageDefinition(fileInfo);
var layout = pageSettings.Layout;
if (OutputExtension != null)
{
layout = Path.ChangeExtension(layout, OutputExtension);
}
pageStack.pushLayout(layout);
var dr = new PlainTextRenderer(environment, StringExtensions.JsonEscape);
var document = dr.getDocument(pageStack.Pages);
var outDir = Path.GetDirectoryName(outFile);
if (!Directory.Exists(outDir))
{
Directory.CreateDirectory(outDir);
}
using (var writer = new StreamWriter(File.Open(outFile, FileMode.Create, FileAccess.Write, FileShare.None), Encoding.UTF8))
{
writer.Write(document);
}
}
}
public void copyProjectContent()
{
}
/// <summary>
/// Change the extension for the output file, by default the extension is .json.
/// </summary>
public String OutputExtension { get; set; } = null;
}
}
| 38.285714 | 157 | 0.609931 | [
"MIT"
] | threax/EdityMcEditface | EdityMcEditface.HtmlRenderer/Compiler/JsonCompiler.cs | 3,486 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//
// Push a new high score
public class NewHighScorePanel : MonoBehaviour {
// input field for player's name
public UnityEngine.UI.InputField nameInput;
// server connection for high score
public HighScoreClient highScoreClient;
// Panel to show all high scores
public HighScorePanel highScorePanel;
//
// Submit button
public void Submit()
{
int score = GameScore.GetScore();
// post high score
string name = nameInput.text;
HighScoreClient.ScorePair pair = new HighScoreClient.ScorePair();
pair.Name = name;
pair.Score = score;
highScoreClient.PostNewHighScore(pair, OnComplete);
}
//
// When we've completed the process reshow high scores
private void OnComplete()
{
highScorePanel.LoadHighScores();
gameObject.SetActive(false);
GameScore.ClearScore();
}
}
| 21.782609 | 73 | 0.657685 | [
"MIT"
] | UNEW-INFT3050/INFT3050_19Sem2 | Week11_Stroids/Assets/Scripts/Menus/NewHighScorePanel.cs | 1,004 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Cumulocity.SDK.Client.Rest.API.Cep.Notification;
using Cumulocity.SDK.Client.Rest.Representation.Cep;
namespace Cumulocity.SDK.Client.Rest.API.Cep
{
/// <summary>
/// API for integration with Custom Event Processing modules from the platform.
///
/// </summary>
public interface ICepApi
{
/// <summary>
/// Gets the notifications subscriber, which allows to receive notifications sent from cep.
/// <pre>
/// <code>
/// Example:
///
/// Subscriber<String, Object> subscriber = deviceControlApi.getNotificationsSubscriber();
///
/// subscriber.subscirbe( "channelId" , new SubscriptionListener<String, Object>() {
///
/// {@literal @}Override
/// public void OnNotification(Subscription<GId> subscription, Object operation) {
/// //Process notification from cep module
/// }
///
/// {@literal @}Override
/// public void OnError(Subscription<GId> subscription, Throwable ex) {
/// // handle Subscribe error
/// }
/// });
/// </code>
/// </pre>
/// </summary>
/// <returns> subscriber </returns>
/// <exception cref="SDKException"> </exception>
CepCustomNotificationsSubscriber CustomNotificationsSubscriber { get; }
/// <summary>
/// Gets an cep module by id
/// </summary>
/// <param name="id"> of the cep module to search for </param>
/// <returns> the cep module with the given id </returns>
/// <exception cref="SDKException"> if the cep module is not found or if the query failed </exception>
CepModuleRepresentation Get(string id);
/// <summary>
/// Gets a cep module text by id
/// </summary>
/// <param name="id"> of the cep module to search for </param>
/// <returns> the cep module text </returns>
/// <exception cref="SDKException"> if the cep module is not found or if the query failed </exception>
string GetText(string id);
/// <summary>
/// Creates an cep module in the platform.
/// </summary>
/// <param name="content"> input stream to resource with cep module definition </param>
/// <returns> the created cep module with the generated id </returns>
/// <exception cref="SDKException"> if the cep module could not be created </exception>
[Obsolete]
CepModuleRepresentation Create(Stream content);
/// <summary>
/// Creates an cep module in the platform.
/// </summary>
/// <param name="content"> of cep module definition </param>
/// <returns> the created cep module with the generated id </returns>
/// <exception cref="SDKException"> if the cep module could not be created </exception>
CepModuleRepresentation Create(string content);
/// <summary>
/// Updates an cep module in the platform.
/// The cep module to be updated is identified by the id.
/// </summary>
/// <param name="id"> of cep module to Update </param>
/// <param name="content"> input stream to resource with cep module definition </param>
/// <returns> the updated cep module </returns>
/// <exception cref="SDKException"> if the cep module could not be updated </exception>
CepModuleRepresentation Update(string id, Stream content);
CepModuleRepresentation Update(string id, string content);
CepModuleRepresentation Update(CepModuleRepresentation module);
/// <summary>
/// Gets all cep modules from the platform
/// </summary>
/// <returns> collection of cep modules with paging functionality </returns>
/// <exception cref="SDKException"> if the query failed </exception>
ICepModuleCollection Modules { get; }
/// <summary>
/// Deletes the cep module from the platform.
/// </summary>
/// <exception cref="SDKException"> </exception>
void Delete(CepModuleRepresentation module);
/// <summary>
/// Deletes the cep module from the platform.
/// </summary>
/// <exception cref="SDKException"> </exception>
void Delete(string id);
/// <summary>
/// Checks state of cep microservice.
/// </summary>
T Health<T>(Type clazz);
}
}
| 35.269565 | 104 | 0.671844 | [
"MIT"
] | SoftwareAG/cumulocity-sdk-cs | REST-SDK/src/Cumulocity.SDK.Client/Rest/API/Cep/ICepApi.cs | 4,058 | C# |
namespace Fonet
{
using System.Collections;
using Fonet.Apps;
using Fonet.DataTypes;
using Fonet.Fo.Flow;
using Fonet.Fo.Pagination;
using Fonet.Layout;
using Fonet.Render.Pdf;
/// <summary>
/// This class acts as a bridge between the XML:FO parser and the
/// formatting/rendering classes. It will queue PageSequences up until
/// all the IDs required by them are satisfied, at which time it will
/// render the pages.
/// StreamRenderer is created by Driver and called from FOTreeBuilder
/// when a PageSequence is created, and AreaTree when a Page is formatted.
/// </summary>
internal class StreamRenderer
{
/// <summary>
/// Keep track of the number of pages rendered.
/// </summary>
private int pageCount = 0;
/// <summary>
/// The renderer being used.
/// </summary>
private PdfRenderer renderer;
/// <summary>
/// The formatting results to be handed back to the caller.
/// </summary>
private FormattingResults results = new FormattingResults();
/// <summary>
/// The FontInfo for this renderer.
/// </summary>
private FontInfo fontInfo = new FontInfo();
/// <summary>
/// The list of pages waiting to be renderered.
/// </summary>
private ArrayList renderQueue = new ArrayList();
/// <summary>
/// The current set of IDReferences, passed to the areatrees
/// and pages. This is used by the AreaTree as a single map of
/// all IDs.
/// </summary>
private IDReferences idReferences = new IDReferences();
/// <summary>
/// The list of markers.
/// </summary>
private ArrayList documentMarkers;
private ArrayList currentPageSequenceMarkers;
private PageSequence currentPageSequence;
public StreamRenderer(PdfRenderer renderer)
{
this.renderer = renderer;
}
public IDReferences GetIDReferences()
{
return idReferences;
}
public FormattingResults getResults()
{
return this.results;
}
public void StartRenderer()
{
pageCount = 0;
renderer.SetupFontInfo(fontInfo);
renderer.StartRenderer();
}
public void StopRenderer()
{
// Force the processing of any more queue elements, even if they
// are not resolved.
ProcessQueue(true);
renderer.StopRenderer();
}
/// <summary>
/// Format the PageSequence. The PageSequence formats Pages and adds
/// them to the AreaTree, which subsequently calls the StreamRenderer
/// instance (this) again to render the page. At this time the page
/// might be printed or it might be queued. A page might not be
/// renderable immediately if the IDReferences are not all valid. In
/// this case we defer the rendering until they are all valid.
/// </summary>
/// <param name="pageSequence"></param>
public void Render(PageSequence pageSequence)
{
AreaTree a = new AreaTree(this);
a.setFontInfo(fontInfo);
var sw = System.Diagnostics.Stopwatch.StartNew();
pageSequence.Format(a);
FonetDriver.ActiveDriver.FireFonetInfo(string.Format("Rendered Page Sequence Output in [{0}] seconds.", sw.Elapsed.TotalSeconds));
this.results.HaveFormattedPageSequence(pageSequence);
FonetDriver.ActiveDriver.FireFonetInfo(
"Last page-sequence produced " + pageSequence.PageCount + " page(s).");
}
public void QueuePage(Page page)
{
// Process markers
PageSequence pageSequence = page.getPageSequence();
if (pageSequence != currentPageSequence)
{
currentPageSequence = pageSequence;
currentPageSequenceMarkers = null;
}
ArrayList markers = page.getMarkers();
if (markers != null)
{
if (documentMarkers == null)
{
documentMarkers = new ArrayList();
}
if (currentPageSequenceMarkers == null)
{
currentPageSequenceMarkers = new ArrayList();
}
for (int i = 0; i < markers.Count; i++)
{
Marker marker = (Marker)markers[i];
marker.releaseRegistryArea();
currentPageSequenceMarkers.Add(marker);
documentMarkers.Add(marker);
}
}
// Try to optimise on the common case that there are no pages pending
// and that all ID references are valid on the current pages. This
// short-cuts the pipeline and renders the area immediately.
if ((renderQueue.Count == 0) && idReferences.IsEveryIdValid())
{
renderer.Render(page);
}
else
{
AddToRenderQueue(page);
}
pageCount++;
}
private void AddToRenderQueue(Page page)
{
RenderQueueEntry entry = new RenderQueueEntry(this, page);
renderQueue.Add(entry);
// The just-added entry could (possibly) resolve the waiting entries,
// so we try to process the queue now to see.
ProcessQueue(false);
}
/// <summary>
/// Try to process the queue from the first entry forward. If an
/// entry can't be processed, then the queue can't move forward,
/// so return.
/// </summary>
/// <param name="force"></param>
private void ProcessQueue(bool force)
{
while (renderQueue.Count > 0)
{
RenderQueueEntry entry = (RenderQueueEntry)renderQueue[0];
if ((!force) && (!entry.isResolved()))
{
break;
}
renderer.Render(entry.getPage());
renderQueue.RemoveAt(0);
}
}
/// <summary>
/// A RenderQueueEntry consists of the Page to be queued, plus a list
/// of outstanding ID references that need to be resolved before the
/// Page can be renderered.
/// </summary>
private class RenderQueueEntry
{
/// <summary>
/// The Page that has outstanding ID references.
/// </summary>
private Page page;
private StreamRenderer outer;
/// <summary>
/// A list of ID references (names).
/// </summary>
private ArrayList unresolvedIdReferences = new ArrayList();
public RenderQueueEntry(StreamRenderer outer, Page page)
{
this.outer = outer;
this.page = page;
foreach (object o in outer.idReferences.getInvalidElements())
{
unresolvedIdReferences.Add(o);
}
}
public Page getPage()
{
return page;
}
/// <summary>
/// See if the outstanding references are resolved in the current
/// copy of IDReferences.
/// </summary>
/// <returns></returns>
public bool isResolved()
{
if ((unresolvedIdReferences.Count == 0) || outer.idReferences.IsEveryIdValid())
{
return true;
}
// See if any of the unresolved references are still unresolved.
foreach (string s in unresolvedIdReferences)
{
if (!outer.idReferences.doesIDExist(s))
{
return false;
}
}
unresolvedIdReferences.RemoveRange(0, unresolvedIdReferences.Count);
return true;
}
}
/// <summary>
/// Auxillary function for retrieving markers.
/// </summary>
/// <returns></returns>
public ArrayList GetDocumentMarkers()
{
return documentMarkers;
}
/// <summary>
/// Auxillary function for retrieving markers.
/// </summary>
/// <returns></returns>
public PageSequence GetCurrentPageSequence()
{
return currentPageSequence;
}
/// <summary>
/// Auxillary function for retrieving markers.
/// </summary>
/// <returns></returns>
public ArrayList GetCurrentPageSequenceMarkers()
{
return currentPageSequenceMarkers;
}
}
} | 32.464789 | 142 | 0.521367 | [
"Apache-2.0"
] | Genocs/PdfTemplating.XslFO | OpenSource.FONet.NetFramework/Core/StreamRenderer.cs | 9,220 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using Infosys.Solutions.CodeGeneration.Framework;
namespace Infosys.Lif.LegacyWorkbench.CodeProviders.HostCallers
{
internal class WCFHostCP : ContentProvider
{
Entities.GenericCollection<ContractModuleMapping> contractsMapping;
string projPrefix = string.Empty;
string hostNamespace = string.Empty;
[PlaceHolder("ServiceContractNamespace")]
string ServiceContractNamespace
{
get
{
if (projPrefix != null || projPrefix != string.Empty)
{
return projPrefix.Trim() + hostNamespace + ".ServiceContract";
}
else
{
return hostNamespace + ".ServiceContract";
}
}
}
[PlaceHolder("ServiceImplementationNamespace")]
string ServiceImplementationNamespace
{
get
{
if (projPrefix != null || projPrefix != string.Empty)
{
return projPrefix.Trim() + hostNamespace + ".ServiceImplementation";
}
else
{
return hostNamespace + ".ServiceImplementation";
}
}
}
[PlaceHolder("MethodBodies")]
string MethodBodies
{
get
{
StringBuilder sb = new StringBuilder();
int counter = 0;
int listCounter = 0;
foreach (string strKey in contractsMappingHashTable.Keys)
{
Entities.GenericCollection<HostCallers.ContractModuleMapping> contractMapping =
(Entities.GenericCollection<HostCallers.ContractModuleMapping>)contractsMappingHashTable[strKey];
string templateName = "MethodTemplate";
switch (contractMapping[counter].Contract.MethodType)
{
case Entities.Contract.ContractMethodType.Insert:
if (contractMapping[counter].Contract.MethodName == null
|| contractMapping[counter].Contract.MethodName.Length == 0)
{
contractMapping[counter].Contract.MethodName = "Insert";
}
break;
case Entities.Contract.ContractMethodType.Update:
if (contractMapping[counter].Contract.MethodName == null
|| contractMapping[counter].Contract.MethodName.Length == 0)
{
contractMapping[counter].Contract.MethodName = "Update";
}
break;
case Entities.Contract.ContractMethodType.Delete:
if (contractMapping[counter].Contract.MethodName == null
|| contractMapping[counter].Contract.MethodName.Length == 0)
{
contractMapping[counter].Contract.MethodName = "Delete";
}
break;
default:
if (contractMapping[counter].Contract.MethodName == null
|| contractMapping[counter].Contract.MethodName.Length == 0)
{
contractMapping[counter].Contract.MethodName = "Select";
}
break;
}
Template template = ContentTemplate.RepeatingTemplate(templateName);
MethodTemplateCp codeProvider = new MethodTemplateCp(contractMapping[counter].Module,
contractMapping[counter].Contract, template, projPrefix,
hostNamespaceList[listCounter++].ToString());
sb.Append(codeProvider.GenerateContent());
}
return sb.ToString();
}
}
Hashtable contractsMappingHashTable;
ArrayList hostNamespaceList;
internal WCFHostCP(Hashtable contractModuleMappings, Template contentTemplate,
string _projPrefix, ArrayList _hostNamespace)
{
contractsMappingHashTable = contractModuleMappings;
ContentTemplate = contentTemplate;
projPrefix = _projPrefix;
hostNamespaceList = _hostNamespace;
}
}
class MethodTemplateCp : ContentProvider
{
Entities.Contract contractForGeneration;
Entities.ContractModule moduleForGeneration;
string projectPrefix;
string hostNamespace;
internal MethodTemplateCp(Entities.ContractModule contractModule,
Entities.Contract contract, Template contentTemplate, string projPrefix, string hostAccessNamespace)
{
this.ContentTemplate = contentTemplate;
this.contractForGeneration = contract;
this.moduleForGeneration = contractModule;
this.projectPrefix = projPrefix;
this.hostNamespace = hostAccessNamespace;
}
[PlaceHolder("ServiceContractNamespace")]
string ServiceContractNamespace
{
get
{
if (projectPrefix != null || projectPrefix != string.Empty)
{
return projectPrefix.Trim() + hostNamespace + ".ServiceContract";
}
else
{
return hostNamespace + ".ServiceContract";
}
}
}
[PlaceHolder("ServiceImplementationNamespace")]
string ServiceImplementationNamespace
{
get
{
if (projectPrefix != null || projectPrefix != string.Empty)
{
return projectPrefix.Trim() + hostNamespace + ".ServiceImplementation";
}
else
{
return hostNamespace + ".ServiceImplementation";
}
}
}
[PlaceHolder("ServiceName")]
string ServiceName
{
get
{
if (contractForGeneration.ServiceName == null || contractForGeneration.ServiceName.Length == 0)
{
return contractForGeneration.ContractName;
}
else
{
return contractForGeneration.ServiceName;
}
}
}
[PlaceHolder("TransacID")]
string TransacID
{
get
{
if (contractForGeneration.TransactionId == null || contractForGeneration.TransactionId.Length == 0)
{
return contractForGeneration.ContractName;
}
else
{
return contractForGeneration.TransactionId;
}
}
}
[PlaceHolder("OperType")]
string OperType
{
get
{
if (contractForGeneration.MethodType.ToString().Length == 0)
{
return contractForGeneration.ContractName;
}
else
{
return contractForGeneration.MethodType.ToString().Substring(0, 1);
}
}
}
[PlaceHolder("ContractEntityName")]
string ContractEntityName
{
get
{
return contractForGeneration.ContractName;
}
}
[PlaceHolder("MethodName")]
string MethodName
{
get
{
return contractForGeneration.MethodName;
}
}
[PlaceHolder("ContractName")]
string ContractName
{
get
{
//use full contract name
return contractForGeneration.ContractName;//.Substring(0,4);
}
}
}
}
| 32.401515 | 141 | 0.488193 | [
"Apache-2.0"
] | Infosys/Intelligent-Bot-Management- | Data Integration Framework/Legacy Workbench/LegacyParserComponents/CodeProviders/HostCallers/WCFHostCP.cs | 8,554 | C# |
using NUnit.Framework;
using static NSelene.Selene;
namespace NSelene.Tests.Integration.SharedDriver.SeleneSpec
{
using System;
using System.Linq;
using System.Reflection;
using Harness;
using OpenQA.Selenium;
[TestFixture]
public class SeleneElement_Should_Specs : BaseTest
{
// TODO: imrove coverage and consider breaking down into separate test classes
[Test]
public void Should_HaveValue_WaitsForPresenceInDom_OfInitiialyAbsent()
{
Configuration.Timeout = 0.6;
Configuration.PollDuringWaits = 0.1;
Given.OpenedEmptyPage();
var beforeCall = DateTime.Now;
Given.OpenedPageWithBodyTimedOut(
@"
<input value='initial' style='display:none'></input>
",
300
);
S("input").Should(Have.Value("initial"));
var afterCall = DateTime.Now;
Assert.Greater(afterCall, beforeCall.AddSeconds(0.3));
Assert.Less(afterCall, beforeCall.AddSeconds(0.6));
}
[Test]
public void Should_HaveNoValue_WaitsForAbsenceInDom_OfInitiialyPresent()
{
Configuration.Timeout = 0.6;
Configuration.PollDuringWaits = 0.1;
Given.OpenedPageWithBody(
@"
<input value='initial' style='display:none'></input>
"
);
var beforeCall = DateTime.Now;
Given.WithBodyTimedOut(
@"
",
300
);
S("input").Should(Have.No.Value("initial"));
var afterCall = DateTime.Now;
Assert.Greater(afterCall, beforeCall.AddSeconds(0.3));
Assert.Less(afterCall, beforeCall.AddSeconds(0.6));
try
{
Configuration.Driver
.FindElement(By.TagName("input")).GetAttribute("value");
Assert.Fail("should fail because the element should be already absent");
}
catch (WebDriverException error)
{
StringAssert.Contains(
"no such element: Unable to locate element: ", error.Message
);
}
}
[Test]
public void Should_HaveValue_IsRenderedInError_OnAbsentElementTimeoutFailure()
{
Configuration.Timeout = 0.25;
Configuration.PollDuringWaits = 0.1;
Given.OpenedEmptyPage();
var beforeCall = DateTime.Now;
try
{
S("input").Should(Have.Value("initial"));
}
catch (TimeoutException error)
{
var afterCall = DateTime.Now;
Assert.Greater(afterCall, beforeCall.AddSeconds(0.25));
var accuracyDelta = 0.2;
Assert.Less(afterCall, beforeCall.AddSeconds(0.25 + 0.1 + accuracyDelta));
// TODO: shoud we check timing here too?
var lines = error.Message.Split("\n").Select(
item => item.Trim()
).ToList();
Assert.Contains("Timed out after 0.25s, while waiting for:", lines);
Assert.Contains("Browser.Element(input).Attribute(value = «initial»)", lines);
Assert.Contains("Reason:", lines);
Assert.Contains(
"no such element: Unable to locate element: "
+ "{\"method\":\"css selector\",\"selector\":\"input\"}"
,
lines
);
}
}
[Test]
public void Should_HaveValue_IsRenderedInError_OnAbsentValueAttributeTimeoutFailure()
{
Configuration.Timeout = 0.25;
Configuration.PollDuringWaits = 0.1;
Given.OpenedPageWithBody(
@"
<label style='display:none'></label>
"
);
var beforeCall = DateTime.Now;
try
{
S("label").Should(Have.Value("initial"));
}
catch (TimeoutException error)
{
var afterCall = DateTime.Now;
Assert.Greater(afterCall, beforeCall.AddSeconds(0.25));
var accuracyDelta = 0.2;
Assert.Less(afterCall, beforeCall.AddSeconds(0.25 + 0.1 + accuracyDelta));
// TODO: shoud we check timing here too?
var lines = error.Message.Split("\n").Select(
item => item.Trim()
).ToList();
Assert.Contains("Timed out after 0.25s, while waiting for:", lines);
Assert.Contains("Browser.Element(label).Attribute(value = «initial»)", lines);
Assert.Contains("Reason:", lines);
Assert.Contains("Actual value: Null (attribute is absent)", lines);
Assert.Contains(
"Actual webelement: <label style=\"display:none\"></label>",
lines
);
}
}
[Test]
public void Should_HaveValue_IsRenderedInError_OnDifferentActualAsEmptyFailure()
{
Configuration.Timeout = 0.25;
Configuration.PollDuringWaits = 0.1;
Given.OpenedPageWithBody(
@"
<input value='' style='display:none'></input>
"
);
var beforeCall = DateTime.Now;
try
{
S("input").Should(Have.Value("some"));
}
catch (TimeoutException error)
{
var afterCall = DateTime.Now;
Assert.Greater(afterCall, beforeCall.AddSeconds(0.25));
var accuracyDelta = 0.2;
Assert.Less(afterCall, beforeCall.AddSeconds(0.25 + 0.1 + accuracyDelta));
// TODO: shoud we check timing here too?
var lines = error.Message.Split("\n").Select(
item => item.Trim()
).ToList();
Assert.Contains("Timed out after 0.25s, while waiting for:", lines);
Assert.Contains("Browser.Element(input).Attribute(value = «some»)", lines);
Assert.Contains("Reason:", lines);
Assert.Contains("Actual value: «»", lines);
Assert.Contains(
"Actual webelement: <input value=\"\" style=\"display:none\">",
lines
);
}
}
[Test]
public void Should_HaveValue_Or_HaveText_IsRenderedInError_OnDifferentActualAsEmptyFailure()
{
Configuration.Timeout = 0.25;
Configuration.PollDuringWaits = 0.1;
Given.OpenedPageWithBody(
@"
<label value='some'>thing</label>
"
);
var beforeCall = DateTime.Now;
try
{
S("label").Should(Have.Value("").Or(Have.ExactText("")));
}
catch (TimeoutException error)
{
var afterCall = DateTime.Now;
Assert.Greater(afterCall, beforeCall.AddSeconds(0.25));
var accuracyDelta = 0.2;
Assert.Less(afterCall, beforeCall.AddSeconds(0.25 + 0.1 + accuracyDelta));
// TODO: shoud we check timing here too?
var lines = error.Message.Split("\n").Select(
item => item.Trim()
).ToList();
Assert.Contains("Timed out after 0.25s, while waiting for:", lines);
Assert.Contains("Browser.Element(label).Attribute(value = «») OR ExactText(«»)", lines);
Assert.Contains("Reason:", lines);
Assert.Contains("Actual value: «some»", lines);
Assert.Contains(
"Actual webelement: <label value=\"some\">thing</label>",
lines
);
Assert.Contains("Actual text: «thing»", lines);
Assert.Contains( // this line will be repeated twice; we mention it here just to remember to refactor in future
"Actual webelement: <label value=\"some\">thing</label>",
lines
);
}
}
[Test]
public void Should_HaveValue_And_HaveText_IsRenderedInError_OnDifferentActualAsEmptyFailure()
{
Configuration.Timeout = 0.25;
Configuration.PollDuringWaits = 0.1;
Given.OpenedPageWithBody(
@"
<label value='some'></label>
"
);
var beforeCall = DateTime.Now;
try
{
S("label").Should(Have.Value("some").And(Have.ExactText("thing")));
}
catch (TimeoutException error)
{
var afterCall = DateTime.Now;
Assert.Greater(afterCall, beforeCall.AddSeconds(0.25));
var accuracyDelta = 0.2;
Assert.Less(afterCall, beforeCall.AddSeconds(0.25 + 0.1 + accuracyDelta));
// TODO: shoud we check timing here too?
var lines = error.Message.Split("\n").Select(
item => item.Trim()
).ToList();
Assert.Contains("Timed out after 0.25s, while waiting for:", lines);
Assert.Contains("Browser.Element(label).Attribute(value = «some») AND ExactText(«thing»)", lines);
Assert.Contains("Reason:", lines);
Assert.Contains("Actual text: «»", lines);
Assert.Contains( // this line will be repeated twice; we mention it here just to remember to refactor in future
"Actual webelement: <label value=\"some\"></label>",
lines
);
}
}
[Test]
public void Should_HaveNoValue_IsRenderedInError_OnInDomElementTimeoutFailure()
{
Configuration.Timeout = 0.25;
Configuration.PollDuringWaits = 0.1;
Given.OpenedPageWithBody(
@"
<input value='initial' style='display:none'></input>
"
);
var beforeCall = DateTime.Now;
try
{
S("input").Should(Have.No.Value("initial"));
}
catch (TimeoutException error)
{
var afterCall = DateTime.Now;
Assert.Greater(afterCall, beforeCall.AddSeconds(0.25));
var accuracyDelta = 0.2;
Assert.Less(afterCall, beforeCall.AddSeconds(0.25 + 0.1 + accuracyDelta));
// TODO: shoud we check timing here too?
var lines = error.Message.Split("\n").Select(
item => item.Trim()
).ToList();
Assert.Contains("Timed out after 0.25s, while waiting for:", lines);
Assert.Contains("Browser.Element(input).not Attribute(value = «initial»)", lines);
Assert.Contains("Reason:", lines);
Assert.Contains("condition not matched", lines);
}
}
[Test]
public void Should_HaveText_WaitsForVisibility_OfInitialyHidden()
{
Configuration.Timeout = 0.6;
Configuration.PollDuringWaits = 0.1;
Given.OpenedPageWithBody(
@"
<label style='display:none'>initial</label>
"
);
var beforeCall = DateTime.Now;
Given.ExecuteScriptWithTimeout(
@"
document.getElementsByTagName('label')[0].style.display = 'block';
",
300
);
S("label").Should(Have.Text("initial"));
var afterCall = DateTime.Now;
Assert.Greater(afterCall, beforeCall.AddSeconds(0.3));
Assert.Less(afterCall, beforeCall.AddSeconds(0.6));
Assert.AreEqual(
"initial",
Configuration.Driver
.FindElement(By.TagName("label")).Text
);
}
[Test]
public void Should_HaveText_WaitsForAskedText_OfInitialyOtherText()
{
Configuration.Timeout = 0.6;
Configuration.PollDuringWaits = 0.1;
Given.OpenedPageWithBody(
@"
<label>initial</label>
"
);
var beforeCall = DateTime.Now;
Given.OpenedPageWithBodyTimedOut(
@"
<label>new</label>
"
,
300
);
S("label").Should(Have.Text("new"));
var afterCall = DateTime.Now;
Assert.Greater(afterCall, beforeCall.AddSeconds(0.3));
Assert.Less(afterCall, beforeCall.AddSeconds(0.6));
Assert.AreEqual(
"new",
Configuration.Driver
.FindElement(By.TagName("label")).Text
);
Assert.AreEqual(
"new",
Configuration.Driver
.FindElement(By.TagName("label")).Text
);
}
[Test]
public void Should_HaveText_IsRenderedInError_OnHiddenElementFailure()
{
Configuration.Timeout = 0.25;
Configuration.PollDuringWaits = 0.1;
Given.OpenedPageWithBody(
@"
<label style='display:none'>initial</label>
"
);
try
{
S("label").Should(Have.Text("initial"));
}
catch (TimeoutException error)
{
var lines = error.Message.Split("\n").Select(
item => item.Trim()
).ToList();
Assert.Contains("Timed out after 0.25s, while waiting for:", lines);
Assert.Contains("Browser.Element(label).TextContaining(«initial»)", lines);
Assert.Contains("Reason:", lines);
Assert.Contains("Actual text: «»", lines);
Assert.Contains(
"Actual webelement: <label style=\"display:none\">initial</label>",
lines
);
Assert.AreEqual(
"", Configuration.Driver.FindElement(By.TagName("label")).Text
);
}
}
[Test]
public void Should_BeVisible_WaitsForVisibility_OfInitiialyHiddenInDom()
{
Configuration.Timeout = 0.6;
Configuration.PollDuringWaits = 0.1;
Given.OpenedPageWithBody(
@"
<label style='display:none'>initial</label>
"
);
var beforeCall = DateTime.Now;
Given.ExecuteScriptWithTimeout(
@"
document.getElementsByTagName('label')[0].style.display = 'block';
",
300
);
S("label").Should(Be.Visible);
var afterCall = DateTime.Now;
Assert.Greater(afterCall, beforeCall.AddSeconds(0.3));
Assert.Less(afterCall, beforeCall.AddSeconds(0.6));
}
[Test]
public void Should_BeNotVisible_WaitsForHiddenInDom_FromInitiialyVisible()
{
Configuration.Timeout = 0.6;
Configuration.PollDuringWaits = 0.1;
Given.OpenedPageWithBody(
@"
<label style='display:block'>initial</label>
"
);
var beforeCall = DateTime.Now;
Given.ExecuteScriptWithTimeout(
@"
document.getElementsByTagName('label')[0].style.display = 'none';
",
300
);
S("label").Should(Be.Not.Visible);
var afterCall = DateTime.Now;
Assert.Greater(afterCall, beforeCall.AddSeconds(0.3));
Assert.Less(afterCall, beforeCall.AddSeconds(0.6));
}
[Test]
public void Should_BeVisible_WaitsForVisibility_OfInitiialyAbsentInDom()
{
Configuration.Timeout = 0.6;
Configuration.PollDuringWaits = 0.1;
Given.OpenedEmptyPage();
var beforeCall = DateTime.Now;
Given.WithBodyTimedOut(
@"
<label>initial</label>
"
,
300
);
S("label").Should(Be.Visible);
var afterCall = DateTime.Now;
Assert.Greater(afterCall, beforeCall.AddSeconds(0.3));
Assert.Less(afterCall, beforeCall.AddSeconds(0.6));
}
[Test]
public void Should_BeNotVisible_WaitsForAbsentInDom_FromInitiallyVisibile()
{
Configuration.Timeout = 0.6;
Configuration.PollDuringWaits = 0.1;
Given.OpenedPageWithBody(
@"
<label>initial</label>
"
);
var beforeCall = DateTime.Now;
Given.WithBodyTimedOut(
@"
"
,
300
);
S("label").Should(Be.Not.Visible);
var afterCall = DateTime.Now;
Assert.Greater(afterCall, beforeCall.AddSeconds(0.3));
Assert.Less(afterCall, beforeCall.AddSeconds(0.6));
}
[Test]
public void Should_BeVisible_IsRenderedInError_OnHiddenInDomElementFailure()
{
Configuration.Timeout = 0.25;
Configuration.PollDuringWaits = 0.1;
Given.OpenedPageWithBody(
@"
<label style='display:none'>initial</label>
"
);
var beforeCall = DateTime.Now;
try
{
S("label").Should(Be.Visible);
}
catch (TimeoutException error)
{
var afterCall = DateTime.Now;
Assert.Greater(afterCall, beforeCall.AddSeconds(0.25));
var accuracyDelta = 0.2;
Assert.Less(afterCall, beforeCall.AddSeconds(0.25 + 0.1 + accuracyDelta));
var lines = error.Message.Split("\n").Select(
item => item.Trim()
).ToList();
Assert.Contains("Timed out after 0.25s, while waiting for:", lines);
Assert.Contains("Browser.Element(label).Visible", lines);
Assert.Contains("Reason:", lines);
Assert.Contains(
"Found element is not visible: "
+ "<label style=\"display:none\">initial</label>"
,
lines
);
Assert.AreEqual(
false, Configuration.Driver.FindElement(By.TagName("label")).Displayed
);
}
}
[Test]
public void Should_BeNotVisible_IsRenderedInError_OnVisibleElementFailure()
{
Configuration.Timeout = 0.25;
Configuration.PollDuringWaits = 0.1;
Given.OpenedPageWithBody(
@"
<label>initial</label>
"
);
try
{
S("label").Should(Be.Not.Visible);
}
catch (TimeoutException error)
{
var lines = error.Message.Split("\n").Select(
item => item.Trim()
).ToList();
Assert.Contains("Timed out after 0.25s, while waiting for:", lines);
Assert.Contains("Browser.Element(label).not Visible", lines);
Assert.Contains("Reason:", lines);
Assert.Contains("condition not matched", lines);
Assert.AreEqual(
true, Configuration.Driver.FindElement(By.TagName("label")).Displayed
);
}
}
[Test]
public void Should_BeVisible_IsRenderedInError_OnAbsentInDomElementFailure()
{
Configuration.Timeout = 0.25;
Configuration.PollDuringWaits = 0.1;
Given.OpenedEmptyPage();
var beforeCall = DateTime.Now;
try
{
S("label").Should(Be.Visible);
}
catch (TimeoutException error)
{
var afterCall = DateTime.Now;
Assert.Greater(afterCall, beforeCall.AddSeconds(0.25));
var accuracyDelta = 0.2;
Assert.Less(afterCall, beforeCall.AddSeconds(0.25 + 0.1 + accuracyDelta));
var lines = error.Message.Split("\n").Select(
item => item.Trim()
).ToList();
Assert.Contains("Timed out after 0.25s, while waiting for:", lines);
Assert.Contains("Browser.Element(label).Visible", lines);
Assert.Contains("Reason:", lines);
Assert.Contains(
"no such element: Unable to locate element: "
+ "{\"method\":\"css selector\",\"selector\":\"label\"}"
,
lines
);
}
}
[Test]
public void Should_HaveText_IsRenderedInError_OnElementDifferentTextFailure()
{
Configuration.Timeout = 0.25;
Configuration.PollDuringWaits = 0.1;
Given.OpenedPageWithBody(
@"
<label>initial</label>
"
);
try
{
S("label").Should(Have.Text("new"));
}
catch (TimeoutException error)
{
var lines = error.Message.Split("\n").Select(
item => item.Trim()
).ToList();
Assert.Contains("Timed out after 0.25s, while waiting for:", lines);
Assert.Contains("Browser.Element(label).TextContaining(«new»)", lines);
Assert.Contains("Reason:", lines);
Assert.Contains("Actual text: «initial»", lines);
Assert.Contains(
"Actual webelement: <label>initial</label>",
lines
);
Assert.AreEqual(
"initial", Configuration.Driver.FindElement(By.TagName("label")).Text
);
}
}
[Test]
public void Should_HaveText_DoesNotWaitForNoOverlay() // TODO: but should it?
{
Configuration.Timeout = 0.6;
Configuration.PollDuringWaits = 0.1;
Given.OpenedPageWithBody(
@"
<div
id='overlay'
style='
display:block;
position: fixed;
display: block;
width: 100%;
height: 100%;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0,0,0,0.1);
z-index: 2;
cursor: pointer;
'
>
</div>
<label>initial</label>
"
);
var beforeCall = DateTime.Now;
Given.ExecuteScriptWithTimeout(
@"
document.getElementById('overlay').style.display = 'none';
",
300
);
S("label").Should(Have.Text("initial"));
var afterCall = DateTime.Now;
Assert.Less(afterCall, beforeCall.AddSeconds(0.3));
Assert.AreEqual(
"initial",
Configuration.Driver
.FindElement(By.TagName("label")).Text
);
// Assert.Greater(afterCall, beforeCall.AddSeconds(0.3));
// Assert.Less(afterCall, beforeCall.AddSeconds(0.6));
}
// [Test]
// public void Should_HaveText_IsRenderedInError_OnOverlappedWithOverlayFailure() // IS NOT RELEVANT
// {
// Configuration.Timeout = 0.25;
// Configuration.PollDuringWaits = 0.1;
// Given.OpenedPageWithBody(
// @"
// <div
// id='overlay'
// style='
// display: block;
// position: fixed;
// display: block;
// width: 100%;
// height: 100%;
// top: 0;
// left: 0;
// right: 0;
// bottom: 0;
// background-color: rgba(0,0,0,0.1);
// z-index: 2;
// cursor: pointer;
// '
// >
// </div>
// <label>initial</label>
// "
// );
// try
// {
// S("label").Should(Have.Text("initial"));
// }
// catch (TimeoutException error)
// {
// var lines = error.Message.Split("\n").Select(
// item => item.Trim()
// ).ToList();
// Assert.Contains("Timed out after 0.25s, while waiting for:", lines);
// Assert.Contains("Browser.Element(label).contains initial", lines);
// Assert.Contains("Reason:", lines);
// Assert.NotNull(lines.Find(item => item.Contains(
// "Element is overlapped by: <div id=\"overlay\" "
// )));
// }
// }
}
}
| 34.51634 | 127 | 0.474266 | [
"MIT"
] | davespoon/NSelene | NSeleneTests/Integration/SharedDriver/SeleneElement_Should_Specs.cs | 26,437 | C# |
// 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 class ToArrayTests
{
[Theory]
[MemberData(nameof(UnorderedSources.Ranges), new[] { 0, 1, 2, 16 }, MemberType = typeof(UnorderedSources))]
public static void ToArray_Unordered(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
IntegerRangeSet seen = new IntegerRangeSet(0, count);
Assert.All(query.ToArray(), x => seen.Add(x));
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData(nameof(UnorderedSources.Ranges), new[] { 1024 * 4, 1024 * 1024 }, MemberType = typeof(UnorderedSources))]
public static void ToArray_Unordered_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
ToArray_Unordered(labeled, count);
}
[Theory]
[MemberData(nameof(Sources.Ranges), new[] { 0, 1, 2, 16 }, MemberType = typeof(Sources))]
public static void ToArray(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
int seen = 0;
Assert.All(query.ToArray(), x => Assert.Equal(seen++, x));
Assert.Equal(count, seen);
}
[Theory]
[OuterLoop]
[MemberData(nameof(Sources.Ranges), new[] { 1024 * 4, 1024 * 1024 }, MemberType = typeof(Sources))]
public static void ToArray_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
ToArray(labeled, count);
}
[Fact]
public static void ToArray_OperationCanceledException_PreCanceled()
{
AssertThrows.AlreadyCanceled(source => source.ToArray());
}
[Fact]
public static void ToArray_ArgumentNullException()
{
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<bool>)null).ToArray());
}
}
}
| 36.233333 | 125 | 0.613615 | [
"MIT"
] | hougongchao/corefx | src/System.Linq.Parallel/tests/QueryOperators/ToArrayTests.cs | 2,174 | C# |
using System.Xml.Serialization;
namespace WarHub.ArmouryModel.Source
{
[WhamNodeCore]
[XmlType("infoLink")]
public sealed partial class InfoLinkCore : EntryBaseCore
{
[XmlAttribute("targetId")]
public string TargetId { get; }
[XmlAttribute("type")]
public InfoLinkKind Type { get; }
}
}
| 21.375 | 60 | 0.643275 | [
"MIT"
] | amis92/wham | src/WarHub.ArmouryModel.Source/InfoLinkCore.cs | 344 | C# |
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Rebus.Forklift.RabbitMq")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Rebus.Forklift.RabbitMq")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("9781c814-18e2-412a-a504-f5572424e0dd")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.333333 | 84 | 0.742754 | [
"MIT"
] | lucasantarelli/rebus | Rebus.Forklift.RabbitMq/Properties/AssemblyInfo.cs | 1,383 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Umbraco.ModelsBuilder v3.0.8.100
//
// Changes to this file will be lost if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Web;
using Umbraco.Core.Models;
using Umbraco.Core.Models.PublishedContent;
using Umbraco.Web;
using Umbraco.ModelsBuilder;
using Umbraco.ModelsBuilder.Umbraco;
namespace Umbraco.Web.PublishedContentModels
{
/// <summary>Module Picker</summary>
[PublishedContentModel("modulePicker")]
public partial class ModulePicker : PublishedContentModel
{
#pragma warning disable 0109 // new is redundant
public new const string ModelTypeAlias = "modulePicker";
public new const PublishedItemType ModelItemType = PublishedItemType.Content;
#pragma warning restore 0109
public ModulePicker(IPublishedContent content)
: base(content)
{ }
#pragma warning disable 0109 // new is redundant
public new static PublishedContentType GetModelContentType()
{
return PublishedContentType.Get(ModelItemType, ModelTypeAlias);
}
#pragma warning restore 0109
public static PublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<ModulePicker, TValue>> selector)
{
return PublishedContentModelUtility.GetModelPropertyType(GetModelContentType(), selector);
}
///<summary>
/// Modules
///</summary>
[ImplementPropertyType("moduleSources")]
public MBran.Modules.PropertyEditors.Modules.ModulePickerValue ModuleSources
{
get { return this.GetPropertyValue<MBran.Modules.PropertyEditors.Modules.ModulePickerValue>("moduleSources"); }
}
}
}
| 31.413793 | 115 | 0.708562 | [
"MIT"
] | markglibres/mbran-umbraco-components | src/MBran.Components.Test/App_Data/Models/ModulePicker.generated.cs | 1,822 | C# |
// 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.DirectoryServices;
using System.Collections.Generic;
using System.Collections;
using System.Diagnostics;
using System.Security.Principal;
namespace System.DirectoryServices.AccountManagement
{
internal class ADDNLinkedAttrSet : BookmarkableResultSet
{
// This class can be used to either enumerate the members of a group, or the groups
// to which a principal belongs. If being used to enumerate the members of a group:
// * groupDN --- the DN of the group we're enumerating
// * members --- array of enumerators containing the DNs of the members of the group we're enumerating (the "member" attribute)
// * primaryGroupDN --- should be null
// * recursive --- whether or not to recursively enumerate group membership
//
// If being used to enumerate the groups to which a principal belongs:
// * groupDN --- the DN of the principal (i.e., the user)
// * members --- the DNs of the groups to which that principal belongs (e.g, the "memberOf" attribute)
// * primaryGroupDN --- the DN of the principal's primary group (constructed from the "primaryGroupID" attribute)
// * recursive --- should be false
//
// Note that the variables in this class are generally named in accord with the "enumerating the members
// of a group" case.
//
// It is assumed that recursive enumeration will only be performed for the "enumerating the members of a group"
// case, not the "groups to which a principal belongs" case, thus, this.recursive == true implies the former
// (but this.recursive == false could imply either case).
internal ADDNLinkedAttrSet(
string groupDN,
IEnumerable[] members,
string primaryGroupDN,
DirectorySearcher primaryGroupMembersSearcher,
bool recursive,
ADStoreCtx storeCtx)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info,
"ADDNLinkedAttrSet",
"ADDNLinkedAttrSet: groupDN={0}, primaryGroupDN={1}, recursive={2}, PG queryFilter={3}, PG queryBase={4}",
groupDN,
(primaryGroupDN != null ? primaryGroupDN : "NULL"),
recursive,
(primaryGroupMembersSearcher != null ? primaryGroupMembersSearcher.Filter : "NULL"),
(primaryGroupMembersSearcher != null ? primaryGroupMembersSearcher.SearchRoot.Path : "NULL"));
_groupsVisited.Add(groupDN); // so we don't revisit it
_recursive = recursive;
_storeCtx = storeCtx;
_originalStoreCtx = storeCtx;
if (null != members)
{
foreach (IEnumerable enumerator in members)
{
_membersQueue.Enqueue(enumerator);
_originalMembers.Enqueue(enumerator);
}
}
_members = null;
_currentMembersSearcher = null;
_primaryGroupDN = primaryGroupDN;
if (primaryGroupDN == null)
_returnedPrimaryGroup = true; // so we don't bother trying to return the primary group
_primaryGroupMembersSearcher = primaryGroupMembersSearcher;
_expansionMode = ExpansionMode.Enum;
_originalExpansionMode = _expansionMode;
}
internal ADDNLinkedAttrSet(
string groupDN,
DirectorySearcher[] membersSearcher,
string primaryGroupDN,
DirectorySearcher primaryGroupMembersSearcher,
bool recursive,
ADStoreCtx storeCtx)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info,
"ADDNLinkedAttrSet",
"ADDNLinkedAttrSet: groupDN={0}, primaryGroupDN={1}, recursive={2}, M queryFilter={3}, M queryBase={4}, PG queryFilter={5}, PG queryBase={6}",
groupDN,
(primaryGroupDN != null ? primaryGroupDN : "NULL"),
recursive,
(membersSearcher != null ? membersSearcher[0].Filter : "NULL"),
(membersSearcher != null ? membersSearcher[0].SearchRoot.Path : "NULL"),
(primaryGroupMembersSearcher != null ? primaryGroupMembersSearcher.Filter : "NULL"),
(primaryGroupMembersSearcher != null ? primaryGroupMembersSearcher.SearchRoot.Path : "NULL"));
_groupsVisited.Add(groupDN); // so we don't revisit it
_recursive = recursive;
_storeCtx = storeCtx;
_originalStoreCtx = storeCtx;
_members = null;
_originalMembers = null;
_membersEnum = null;
_primaryGroupDN = primaryGroupDN;
if (primaryGroupDN == null)
_returnedPrimaryGroup = true; // so we don't bother trying to return the primary group
if (null != membersSearcher)
{
foreach (DirectorySearcher ds in membersSearcher)
{
_memberSearchersQueue.Enqueue(ds);
_memberSearchersQueueOriginal.Enqueue(ds);
}
}
_currentMembersSearcher = null;
_primaryGroupMembersSearcher = primaryGroupMembersSearcher;
_expansionMode = ExpansionMode.ASQ;
_originalExpansionMode = _expansionMode;
}
// Return the principal we're positioned at as a Principal object.
// Need to use our StoreCtx's GetAsPrincipal to convert the native object to a Principal
override internal object CurrentAsPrincipal
{
get
{
if (this.current != null)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "CurrentAsPrincipal: using current");
if (this.current is DirectoryEntry)
return ADUtils.DirectoryEntryAsPrincipal((DirectoryEntry)this.current, _storeCtx);
else
{
return ADUtils.SearchResultAsPrincipal((SearchResult)this.current, _storeCtx, null);
}
}
else
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "CurrentAsPrincipal: using currentForeignPrincipal");
Debug.Assert(_currentForeignPrincipal != null);
return _currentForeignPrincipal;
}
}
}
// Advance the enumerator to the next principal in the result set, pulling in additional pages
// of results (or ranges of attribute values) as needed.
// Returns true if successful, false if no more results to return.
override internal bool MoveNext()
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "Entering MoveNext");
_atBeginning = false;
bool needToRetry;
bool f = false;
do
{
needToRetry = false;
// reset our found state. If we are restarting the loop we don't have a current principal yet.
f = false;
if (!_returnedPrimaryGroup)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNext: trying PrimaryGroup DN");
f = MoveNextPrimaryGroupDN();
}
if (!f)
{
if (_expansionMode == ExpansionMode.ASQ)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNext: trying member searcher");
f = MoveNextMemberSearcher();
}
else
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNext: trying member enum");
f = MoveNextMemberEnum();
}
}
if (!f)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNext: trying foreign");
f = MoveNextForeign(ref needToRetry);
}
if (!f)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNext: trying primary group search");
f = MoveNextQueryPrimaryGroupMember();
}
}
while (needToRetry);
return f;
}
private bool MoveNextPrimaryGroupDN()
{
// Do the special primary group ID processing if we haven't yet returned the primary group.
Debug.Assert(_primaryGroupDN != null);
this.current = SDSUtils.BuildDirectoryEntry(
BuildPathFromDN(_primaryGroupDN),
_storeCtx.Credentials,
_storeCtx.AuthTypes);
_storeCtx.InitializeNewDirectoryOptions((DirectoryEntry)this.current);
GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNextMemberSearcher: returning primary group {0}", ((DirectoryEntry)this.current).Path);
_currentForeignDE = null;
_currentForeignPrincipal = null;
_returnedPrimaryGroup = true;
return true;
}
private bool GetNextSearchResult()
{
bool memberFound = false;
do
{
if (_currentMembersSearcher == null)
{
Debug.Assert(_memberSearchersQueue != null);
if (_memberSearchersQueue.Count == 0)
{
// We are out of searchers in the queue.
return false;
}
else
{
// Remove the next searcher from the queue and place it in the current search variable.
_currentMembersSearcher = _memberSearchersQueue.Dequeue();
_memberSearchResults = _currentMembersSearcher.FindAll();
Debug.Assert(_memberSearchResults != null);
_memberSearchResultsEnumerator = _memberSearchResults.GetEnumerator();
}
}
GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNextQueryMember: have a searcher");
memberFound = _memberSearchResultsEnumerator.MoveNext();
// The search is complete.
// Dipose the searcher and search results.
if (!memberFound)
{
_currentMembersSearcher.Dispose();
_currentMembersSearcher = null;
_memberSearchResults.Dispose();
_memberSearchResults = null;
}
} while (!memberFound);
return memberFound;
}
private bool MoveNextMemberSearcher()
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "Entering MoveNextMemberSearcher");
bool needToRetry = false;
bool f = false;
do
{
f = GetNextSearchResult();
needToRetry = false;
if (f)
{
SearchResult currentSR = (SearchResult)_memberSearchResultsEnumerator.Current;
// Got a member from this group (or, got a group of which we're a member).
// Create a DirectoryEntry for it.
string memberDN = (string)currentSR.Properties["distinguishedName"][0];
GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNextMemberSearcher: got a value from the enumerator: {0}", memberDN);
// Make sure the member is a principal
if ((!ADUtils.IsOfObjectClass(currentSR, "group")) &&
(!ADUtils.IsOfObjectClass(currentSR, "user")) && // includes computer as well
(!ADUtils.IsOfObjectClass(currentSR, "foreignSecurityPrincipal")))
{
// We found a member, but it's not a principal type. Skip it.
GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNextMemberSearcher: not a principal, skipping");
needToRetry = true;
}
// If we're processing recursively, and the member is a group, we DON'T return it,
// but rather treat it as something to recursively visit later
// (unless we've already visited the group previously)
else if (_recursive && ADUtils.IsOfObjectClass(currentSR, "group"))
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNextMemberSearcher: adding to groupsToVisit");
if (!_groupsVisited.Contains(memberDN) && !_groupsToVisit.Contains(memberDN))
_groupsToVisit.Add(memberDN);
// and go on to the next member....
needToRetry = true;
}
else if (_recursive && ADUtils.IsOfObjectClass(currentSR, "foreignSecurityPrincipal"))
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNextMemberSearcher: foreign principal, adding to foreignMembers");
// If we haven't seen this FPO yet then add it to the seen user database.
if (!_usersVisited.ContainsKey(currentSR.Properties["distinguishedName"][0].ToString()))
{
// The FPO might represent a group, in which case we should recursively enumerate its
// membership. So save it off for later processing.
_foreignMembersCurrentGroup.Add(currentSR.GetDirectoryEntry());
_usersVisited.Add(currentSR.Properties["distinguishedName"][0].ToString(), true);
}
// and go on to the next member....
needToRetry = true;
}
else
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNextMemberSearcher: using as current");
// Check to see if we have already seen this user during the enumeration
// If so then move on to the next user. If not then return it as current.
if (!_usersVisited.ContainsKey(currentSR.Properties["distinguishedName"][0].ToString()))
{
this.current = currentSR;
_currentForeignDE = null;
_currentForeignPrincipal = null;
_usersVisited.Add(currentSR.Properties["distinguishedName"][0].ToString(), true);
}
else
{
needToRetry = true;
}
}
}
else
{
// We reached the end of this group's membership. If we're not processing recursively,
// we're done. Otherwise, go on to the next group to visit.
// First create a DE that points to the group we want to expand, Using that as a search root run
// an ASQ search against member and start enumerting those results.
if (_recursive)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info,
"ADDNLinkedAttrSet",
"MoveNextMemberSearcher: recursive processing, groupsToVisit={0}",
_groupsToVisit.Count);
if (_groupsToVisit.Count > 0)
{
// Pull off the next group to visit
string groupDN = _groupsToVisit[0];
_groupsToVisit.RemoveAt(0);
_groupsVisited.Add(groupDN);
GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNextMemberSearcher: recursively processing {0}", groupDN);
// get the membership of this new group
DirectoryEntry groupDE = SDSUtils.BuildDirectoryEntry(BuildPathFromDN(groupDN), _storeCtx.Credentials, _storeCtx.AuthTypes);
_storeCtx.InitializeNewDirectoryOptions(groupDE);
// Queue up a searcher for the new group expansion.
DirectorySearcher ds = SDSUtils.ConstructSearcher(groupDE);
ds.Filter = "(objectClass=*)";
ds.SearchScope = SearchScope.Base;
ds.AttributeScopeQuery = "member";
ds.CacheResults = false;
_memberSearchersQueue.Enqueue(ds);
// and go on to the first member of this new group.
needToRetry = true;
}
}
}
}
while (needToRetry);
return f;
}
private bool GetNextEnum()
{
bool memberFound = false;
do
{
if (null == _members)
{
if (_membersQueue.Count == 0)
{
return false;
}
_members = _membersQueue.Dequeue();
_membersEnum = _members.GetEnumerator();
}
memberFound = _membersEnum.MoveNext();
if (!memberFound)
{
IDisposable disposableMembers = _members as IDisposable;
if (disposableMembers != null)
{
disposableMembers.Dispose();
}
IDisposable disposableMembersEnum = _membersEnum as IDisposable;
if (disposableMembersEnum != null)
{
disposableMembersEnum.Dispose();
}
_members = null;
_membersEnum = null;
}
} while (!memberFound);
return memberFound;
}
private bool MoveNextMemberEnum()
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "Entering MoveNextMemberEnum");
bool needToRetry = false;
bool disposeMemberDE = false;
bool f;
do
{
f = GetNextEnum();
needToRetry = false;
disposeMemberDE = false;
if (f)
{
DirectoryEntry memberDE = null;
try
{
// Got a member from this group (or, got a group of which we're a member).
// Create a DirectoryEntry for it.
string memberDN = (string)_membersEnum.Current;
GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNextMemberEnum: got a value from the enumerator: {0}", memberDN);
memberDE = SDSUtils.BuildDirectoryEntry(
BuildPathFromDN(memberDN),
_storeCtx.Credentials,
_storeCtx.AuthTypes);
_storeCtx.InitializeNewDirectoryOptions(memberDE);
_storeCtx.LoadDirectoryEntryAttributes(memberDE);
// Make sure the member is a principal
if ((!ADUtils.IsOfObjectClass(memberDE, "group")) &&
(!ADUtils.IsOfObjectClass(memberDE, "user")) && // includes computer as well
(!ADUtils.IsOfObjectClass(memberDE, "foreignSecurityPrincipal")))
{
// We found a member, but it's not a principal type. Skip it.
GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNextMemberEnum: not a principal, skipping");
needToRetry = true;
disposeMemberDE = true; //Since member is not principal we don't return it. So mark it for dispose.
}
// If we're processing recursively, and the member is a group, we DON'T return it,
// but rather treat it as something to recursively visit later
// (unless we've already visited the group previously)
else if (_recursive && ADUtils.IsOfObjectClass(memberDE, "group"))
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNextMemberEnum: adding to groupsToVisit");
if (!_groupsVisited.Contains(memberDN) && !_groupsToVisit.Contains(memberDN))
_groupsToVisit.Add(memberDN);
// and go on to the next member....
needToRetry = true;
disposeMemberDE = true; //Since recursive is set to true, we do not return groups. So mark it for dispose.
}
else if (_recursive && ADUtils.IsOfObjectClass(memberDE, "foreignSecurityPrincipal"))
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNextMemberEnum: foreign principal, adding to foreignMembers");
// If we haven't seen this FPO yet then add it to the seen user database.
if (!_usersVisited.ContainsKey(memberDE.Properties["distinguishedName"][0].ToString()))
{
// The FPO might represent a group, in which case we should recursively enumerate its
// membership. So save it off for later processing.
_foreignMembersCurrentGroup.Add(memberDE);
_usersVisited.Add(memberDE.Properties["distinguishedName"][0].ToString(), true);
disposeMemberDE = false; //We store the FPO DirectoryEntry objects for further processing. So do NOT dispose it.
}
// and go on to the next member....
needToRetry = true;
}
else
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNextMemberEnum: using as current");
// Check to see if we have already seen this user during the enumeration
// If so then move on to the next user. If not then return it as current.
if (!_usersVisited.ContainsKey(memberDE.Properties["distinguishedName"][0].ToString()))
{
this.current = memberDE;
_currentForeignDE = null;
_currentForeignPrincipal = null;
_usersVisited.Add(memberDE.Properties["distinguishedName"][0].ToString(), true);
disposeMemberDE = false; //memberDE will be set in the Principal object we return. So do NOT dispose it.
}
else
{
needToRetry = true;
}
}
}
finally
{
if (disposeMemberDE && memberDE != null)
{
//This means the constructed member is not used in the new principal
memberDE.Dispose();
}
}
}
else
{
// We reached the end of this group's membership. If we're not processing recursively,
// we're done. Otherwise, go on to the next group to visit.
if (_recursive)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info,
"ADDNLinkedAttrSet",
"MoveNextLocal: recursive processing, groupsToVisit={0}",
_groupsToVisit.Count);
if (_groupsToVisit.Count > 0)
{
// Pull off the next group to visit
string groupDN = _groupsToVisit[0];
_groupsToVisit.RemoveAt(0);
_groupsVisited.Add(groupDN);
GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNextMemberEnum: recursively processing {0}", groupDN);
// get the membership of this new group
DirectoryEntry groupDE = SDSUtils.BuildDirectoryEntry(
BuildPathFromDN(groupDN),
_storeCtx.Credentials,
_storeCtx.AuthTypes);
_storeCtx.InitializeNewDirectoryOptions(groupDE);
// set up for the next round of enumeration
//Here a new DirectoryEntry object is created and passed
//to RangeRetriever object. Hence, configure
//RangeRetriever to dispose the DirEntry on its dispose.
_membersQueue.Enqueue(new RangeRetriever(groupDE, "member", true));
// and go on to the first member of this new group....
needToRetry = true;
}
}
}
}
while (needToRetry);
return f;
}
private void TranslateForeignMembers()
{
GlobalDebug.WriteLineIf(GlobalDebug.Warn, "ADDNLinkedAttrSet", "TranslateForeignMembers: Translating foreign members");
List<Byte[]> sidList = new List<Byte[]>(_foreignMembersCurrentGroup.Count);
// Foreach foreign principal retrive the sid.
// If the SID is for a fake object we have to track it separately. If we were attempt to translate it
// it would fail and not be returned and we would lose it.
// Once we have a list of sids then translate them against the target store in one call.
foreach (DirectoryEntry de in _foreignMembersCurrentGroup)
{
// Get the SID of the foreign principal
if (de.Properties["objectSid"].Count == 0)
{
throw new PrincipalOperationException(SR.ADStoreCtxCantRetrieveObjectSidForCrossStore);
}
Byte[] sid = (Byte[])de.Properties["objectSid"].Value;
// What type of SID is it?
SidType sidType = Utils.ClassifySID(sid);
if (sidType == SidType.FakeObject)
{
//Add the foreign member DirectoryEntry to fakePrincipalMembers list for further translation
//This de will be disposed after completing the translation by another code block.
_fakePrincipalMembers.Add(de);
// It's a FPO for something like NT AUTHORITY\NETWORK SERVICE.
// There's no real store object corresponding to this FPO, so
// fake a Principal.
GlobalDebug.WriteLineIf(GlobalDebug.Info,
"ADDNLinkedAttrSet",
"TranslateForeignMembers: fake principal, SID={0}",
Utils.ByteArrayToString(sid));
}
else
{
GlobalDebug.WriteLineIf(GlobalDebug.Info,
"ADDNLinkedAttrSet",
"TranslateForeignMembers: standard principal, SID={0}",
Utils.ByteArrayToString(sid));
sidList.Add(sid);
//We do NOT need the Foreign member DirectoryEntry object once it has been translated and added to sidList.
//So disposing it off now
de.Dispose();
}
}
// This call will perform a bulk sid translate to the name + issuer domain.
_foreignMembersToReturn = new SidList(sidList, _storeCtx.DnsHostName, _storeCtx.Credentials);
// We have translated the sids so clear the group now.
_foreignMembersCurrentGroup.Clear();
}
private bool MoveNextForeign(ref bool outerNeedToRetry)
{
outerNeedToRetry = false;
bool needToRetry;
Principal foreignPrincipal;
GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "Entering MoveNextForeign");
do
{
needToRetry = false;
if (_foreignMembersCurrentGroup.Count > 0)
{
TranslateForeignMembers();
}
if (_fakePrincipalMembers.Count > 0)
{
foreignPrincipal = _storeCtx.ConstructFakePrincipalFromSID((Byte[])_fakePrincipalMembers[0].Properties["objectSid"].Value);
_fakePrincipalMembers[0].Dispose();
_fakePrincipalMembers.RemoveAt(0);
}
else if ((_foreignMembersToReturn != null) && (_foreignMembersToReturn.Length > 0))
{
StoreCtx foreignStoreCtx;
SidListEntry foreignSid = _foreignMembersToReturn[0];
// sidIssuerName is null only if SID was not resolved
// return a unknown principal back
if (null == foreignSid.sidIssuerName)
{
// create and return the unknown principal if it is not yet present in usersVisited
if (!_usersVisited.ContainsKey(foreignSid.name))
{
byte[] sid = Utils.ConvertNativeSidToByteArray(foreignSid.pSid);
UnknownPrincipal unknownPrincipal = UnknownPrincipal.CreateUnknownPrincipal(_storeCtx.OwningContext, sid, foreignSid.name);
_usersVisited.Add(foreignSid.name, true);
this.current = null;
_currentForeignDE = null;
_currentForeignPrincipal = unknownPrincipal;
// remove the current member
_foreignMembersToReturn.RemoveAt(0);
return true;
}
// remove the current member
_foreignMembersToReturn.RemoveAt(0);
needToRetry = true;
continue;
}
SidType sidType = Utils.ClassifySID(foreignSid.pSid);
if (sidType == SidType.RealObjectFakeDomain)
{
// This is a BUILTIN object. It's a real object on the store we're connected to, but LookupSid
// will tell us it's a member of the BUILTIN domain. Resolve it as a principal on our store.
GlobalDebug.WriteLineIf(GlobalDebug.Warn, "ADDNLinkedAttrSet", "MoveNextForeign: builtin principal");
foreignStoreCtx = _storeCtx;
}
else
{
ContextOptions remoteOptions = DefaultContextOptions.ADDefaultContextOption;
#if USE_CTX_CACHE
PrincipalContext remoteCtx = SDSCache.Domain.GetContext(foreignSid.sidIssuerName, _storeCtx.Credentials, remoteOptions);
#else
PrincipalContext remoteCtx = new PrincipalContext(
ContextType.Domain,
foreignSid.sidIssuerName,
null,
(this.storeCtx.Credentials != null ? this.storeCtx.Credentials.UserName : null),
(this.storeCtx.Credentials != null ? storeCtx.storeCtx.Credentials.Password : null),
remoteOptions);
#endif
foreignStoreCtx = remoteCtx.QueryCtx;
}
foreignPrincipal = foreignStoreCtx.FindPrincipalByIdentRef(
typeof(Principal),
UrnScheme.SidScheme,
(new SecurityIdentifier(Utils.ConvertNativeSidToByteArray(_foreignMembersToReturn[0].pSid), 0)).ToString(),
DateTime.UtcNow);
if (null == foreignPrincipal)
{
GlobalDebug.WriteLineIf(GlobalDebug.Warn, "ADDNLinkedAttrSet", "MoveNextForeign: no matching principal");
throw new PrincipalOperationException(SR.ADStoreCtxFailedFindCrossStoreTarget);
}
_foreignMembersToReturn.RemoveAt(0);
}
else
{
// We don't have any more foreign principals to return so start with the foreign groups
if (_foreignGroups.Count > 0)
{
outerNeedToRetry = true;
// Determine the domainFunctionalityMode of the foreign domain. If they are W2k or not a global group then we can't use ASQ.
if (_foreignGroups[0].Context.ServerInformation.OsVersion == DomainControllerMode.Win2k ||
_foreignGroups[0].GroupScope != GroupScope.Global)
{
_expansionMode = ExpansionMode.Enum;
return ExpandForeignGroupEnumerator();
}
else
{
_expansionMode = ExpansionMode.ASQ;
return ExpandForeignGroupSearcher();
}
}
else
{
// We are done with foreign principals and groups..
return false;
}
}
if (foreignPrincipal is GroupPrincipal)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNextForeign: foreign member is a group");
// A group, need to recursively expand it (unless it's a fake group,
// in which case it is by definition empty and so contains nothing to expand, or unless
// we've already or will visit it).
// Postpone to later.
if (!foreignPrincipal.fakePrincipal)
{
string groupDN = (string)((DirectoryEntry)foreignPrincipal.UnderlyingObject).Properties["distinguishedName"].Value;
GlobalDebug.WriteLineIf(GlobalDebug.Info,
"ADDNLinkedAttrSet",
"MoveNextForeign: not a fake group, adding {0} to foreignGroups",
groupDN);
if (!_groupsVisited.Contains(groupDN) && !_groupsToVisit.Contains(groupDN))
{
_foreignGroups.Add((GroupPrincipal)foreignPrincipal);
}
else
{
foreignPrincipal.Dispose();
}
}
needToRetry = true;
continue;
}
else
{
// Not a group, nothing to recursively expand, so just return it.
GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNextForeign: using as currentForeignDE/currentForeignPrincipal");
DirectoryEntry foreignDE = (DirectoryEntry)foreignPrincipal.GetUnderlyingObject();
_storeCtx.LoadDirectoryEntryAttributes(foreignDE);
if (!_usersVisited.ContainsKey(foreignDE.Properties["distinguishedName"][0].ToString()))
{
_usersVisited.Add(foreignDE.Properties["distinguishedName"][0].ToString(), true);
this.current = null;
_currentForeignDE = null;
_currentForeignPrincipal = foreignPrincipal;
return true;
}
else
{
foreignPrincipal.Dispose();
}
needToRetry = true;
continue;
}
}
while (needToRetry);
return false;
}
private bool ExpandForeignGroupEnumerator()
{
Debug.Assert(_recursive == true);
GlobalDebug.WriteLineIf(GlobalDebug.Info,
"ADDNLinkedAttrSet",
"ExpandForeignGroupEnumerator: there are {0} foreignGroups",
_foreignGroups.Count);
GroupPrincipal foreignGroup = _foreignGroups[0];
_foreignGroups.RemoveAt(0);
// Since members of AD groups must be AD objects
Debug.Assert(foreignGroup.Context.QueryCtx is ADStoreCtx);
Debug.Assert(foreignGroup.UnderlyingObject is DirectoryEntry);
Debug.Assert(((DirectoryEntry)foreignGroup.UnderlyingObject).Path.StartsWith("LDAP:", StringComparison.Ordinal));
_storeCtx = (ADStoreCtx)foreignGroup.Context.QueryCtx;
//Here the foreignGroup object is removed from the foreignGroups collection.
//and not used anymore. Hence, configure RangeRetriever to dispose the DirEntry on its dispose.
_membersQueue.Enqueue(new RangeRetriever((DirectoryEntry)foreignGroup.UnderlyingObject, "member", true));
string groupDN = (string)((DirectoryEntry)foreignGroup.UnderlyingObject).Properties["distinguishedName"].Value;
_groupsVisited.Add(groupDN);
GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "ExpandForeignGroupEnumerator: recursively processing {0}", groupDN);
return true;
}
private bool ExpandForeignGroupSearcher()
{
Debug.Assert(_recursive == true);
GlobalDebug.WriteLineIf(GlobalDebug.Info,
"ADDNLinkedAttrSet",
"ExpandForeignGroupSearcher: there are {0} foreignGroups",
_foreignGroups.Count);
GroupPrincipal foreignGroup = _foreignGroups[0];
_foreignGroups.RemoveAt(0);
// Since members of AD groups must be AD objects
Debug.Assert(foreignGroup.Context.QueryCtx is ADStoreCtx);
Debug.Assert(foreignGroup.UnderlyingObject is DirectoryEntry);
Debug.Assert(((DirectoryEntry)foreignGroup.UnderlyingObject).Path.StartsWith("LDAP:", StringComparison.Ordinal));
_storeCtx = (ADStoreCtx)foreignGroup.Context.QueryCtx;
// Queue up a searcher for the new group expansion.
DirectorySearcher ds = SDSUtils.ConstructSearcher((DirectoryEntry)foreignGroup.UnderlyingObject);
ds.Filter = "(objectClass=*)";
ds.SearchScope = SearchScope.Base;
ds.AttributeScopeQuery = "member";
ds.CacheResults = false;
_memberSearchersQueue.Enqueue(ds);
string groupDN = (string)((DirectoryEntry)foreignGroup.UnderlyingObject).Properties["distinguishedName"].Value;
_groupsVisited.Add(groupDN);
GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "ExpandForeignGroupSearcher: recursively processing {0}", groupDN);
return true;
}
private bool MoveNextQueryPrimaryGroupMember()
{
bool f = false;
if (_primaryGroupMembersSearcher != null)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNextQueryMember: have a searcher");
if (_queryMembersResults == null)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNextQueryMember: issuing query");
_queryMembersResults = _primaryGroupMembersSearcher.FindAll();
Debug.Assert(_queryMembersResults != null);
_queryMembersResultEnumerator = _queryMembersResults.GetEnumerator();
}
f = _queryMembersResultEnumerator.MoveNext();
if (f)
{
this.current = (SearchResult)_queryMembersResultEnumerator.Current;
Debug.Assert(this.current != null);
_currentForeignDE = null;
_currentForeignPrincipal = null;
GlobalDebug.WriteLineIf(GlobalDebug.Info,
"ADDNLinkedAttrSet",
"MoveNextQueryMember: got a result, using as current {0}",
((SearchResult)this.current).Path);
}
}
return f;
}
// Resets the enumerator to before the first result in the set. This potentially can be an expensive
// operation, e.g., if doing a paged search, may need to re-retrieve the first page of results.
// As a special case, if the ResultSet is already at the very beginning, this is guaranteed to be
// a no-op.
override internal void Reset()
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "Reset");
if (!_atBeginning)
{
_usersVisited.Clear();
_groupsToVisit.Clear();
string originalGroupDN = _groupsVisited[0];
_groupsVisited.Clear();
_groupsVisited.Add(originalGroupDN);
// clear the current enumerator
_members = null;
_membersEnum = null;
// replace all items in the queue with the originals and reset them.
if (null != _originalMembers)
{
_membersQueue.Clear();
foreach (IEnumerable ie in _originalMembers)
{
_membersQueue.Enqueue(ie);
IEnumerator enumerator = ie.GetEnumerator();
enumerator.Reset();
}
}
_expansionMode = _originalExpansionMode;
_storeCtx = _originalStoreCtx;
this.current = null;
if (_primaryGroupDN != null)
_returnedPrimaryGroup = false;
_foreignMembersCurrentGroup.Clear();
_fakePrincipalMembers.Clear();
if (null != _foreignMembersToReturn)
_foreignMembersToReturn.Clear();
_currentForeignPrincipal = null;
_currentForeignDE = null;
_foreignGroups.Clear();
_queryMembersResultEnumerator = null;
if (_queryMembersResults != null)
{
_queryMembersResults.Dispose();
_queryMembersResults = null;
}
if (null != _currentMembersSearcher)
{
_currentMembersSearcher.Dispose();
_currentMembersSearcher = null;
}
_memberSearchResultsEnumerator = null;
if (_memberSearchResults != null)
{
_memberSearchResults.Dispose();
_memberSearchResults = null;
}
if (null != _memberSearchersQueue)
{
foreach (DirectorySearcher ds in _memberSearchersQueue)
{
ds.Dispose();
}
_memberSearchersQueue.Clear();
if (null != _memberSearchersQueueOriginal)
{
foreach (DirectorySearcher ds in _memberSearchersQueueOriginal)
{
_memberSearchersQueue.Enqueue(ds);
}
}
}
_atBeginning = true;
}
}
override internal ResultSetBookmark BookmarkAndReset()
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "Bookmarking");
ADDNLinkedAttrSetBookmark bookmark = new ADDNLinkedAttrSetBookmark();
bookmark.usersVisited = _usersVisited;
_usersVisited = new Dictionary<string, bool>();
bookmark.groupsToVisit = _groupsToVisit;
_groupsToVisit = new List<string>();
string originalGroupDN = _groupsVisited[0];
bookmark.groupsVisited = _groupsVisited;
_groupsVisited = new List<string>();
_groupsVisited.Add(originalGroupDN);
bookmark.expansionMode = _expansionMode;
// bookmark the current enumerators
bookmark.members = _members;
bookmark.membersEnum = _membersEnum;
// Clear the current enumerators for reset
_members = null;
_membersEnum = null;
// Copy all enumerators in the queue over to the bookmark queue.
if (null != _membersQueue)
{
bookmark.membersQueue = new Queue<IEnumerable>(_membersQueue.Count);
foreach (IEnumerable ie in _membersQueue)
{
bookmark.membersQueue.Enqueue(ie);
}
}
// Refill the original queue with the original enumerators and reset them
if (null != _membersQueue)
{
_membersQueue.Clear();
if (_originalMembers != null)
{
foreach (IEnumerable ie in _originalMembers)
{
_membersQueue.Enqueue(ie);
IEnumerator enumerator = ie.GetEnumerator();
enumerator.Reset();
}
}
}
bookmark.storeCtx = _storeCtx;
_expansionMode = _originalExpansionMode;
if (null != _currentMembersSearcher)
{
_currentMembersSearcher.Dispose();
_currentMembersSearcher = null;
}
_storeCtx = _originalStoreCtx;
bookmark.current = this.current;
bookmark.returnedPrimaryGroup = _returnedPrimaryGroup;
this.current = null;
if (_primaryGroupDN != null)
_returnedPrimaryGroup = false;
bookmark.foreignMembersCurrentGroup = _foreignMembersCurrentGroup;
bookmark.fakePrincipalMembers = _fakePrincipalMembers;
bookmark.foreignMembersToReturn = _foreignMembersToReturn;
bookmark.currentForeignPrincipal = _currentForeignPrincipal;
bookmark.currentForeignDE = _currentForeignDE;
_foreignMembersCurrentGroup = new List<DirectoryEntry>();
_fakePrincipalMembers = new List<DirectoryEntry>();
_currentForeignDE = null;
bookmark.foreignGroups = _foreignGroups;
_foreignGroups = new List<GroupPrincipal>();
bookmark.queryMembersResults = _queryMembersResults;
bookmark.queryMembersResultEnumerator = _queryMembersResultEnumerator;
_queryMembersResults = null;
_queryMembersResultEnumerator = null;
bookmark.memberSearchResults = _memberSearchResults;
bookmark.memberSearchResultsEnumerator = _memberSearchResultsEnumerator;
_memberSearchResults = null;
_memberSearchResultsEnumerator = null;
if (null != _memberSearchersQueue)
{
bookmark.memberSearcherQueue = new Queue<DirectorySearcher>(_memberSearchersQueue.Count);
foreach (DirectorySearcher ds in _memberSearchersQueue)
{
bookmark.memberSearcherQueue.Enqueue(ds);
}
}
if (null != _memberSearchersQueueOriginal)
{
_memberSearchersQueue.Clear();
foreach (DirectorySearcher ds in _memberSearchersQueueOriginal)
{
_memberSearchersQueue.Enqueue(ds);
}
}
bookmark.atBeginning = _atBeginning;
_atBeginning = true;
return bookmark;
}
override internal void RestoreBookmark(ResultSetBookmark bookmark)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "Restoring from bookmark");
Debug.Assert(bookmark is ADDNLinkedAttrSetBookmark);
ADDNLinkedAttrSetBookmark adBookmark = (ADDNLinkedAttrSetBookmark)bookmark;
_usersVisited = adBookmark.usersVisited;
_groupsToVisit = adBookmark.groupsToVisit;
_groupsVisited = adBookmark.groupsVisited;
_storeCtx = adBookmark.storeCtx;
this.current = adBookmark.current;
_returnedPrimaryGroup = adBookmark.returnedPrimaryGroup;
_foreignMembersCurrentGroup = adBookmark.foreignMembersCurrentGroup;
_fakePrincipalMembers = adBookmark.fakePrincipalMembers;
_foreignMembersToReturn = adBookmark.foreignMembersToReturn;
_currentForeignPrincipal = adBookmark.currentForeignPrincipal;
_currentForeignDE = adBookmark.currentForeignDE;
_foreignGroups = adBookmark.foreignGroups;
if (_queryMembersResults != null)
_queryMembersResults.Dispose();
_queryMembersResults = adBookmark.queryMembersResults;
_queryMembersResultEnumerator = adBookmark.queryMembersResultEnumerator;
_memberSearchResults = adBookmark.memberSearchResults;
_memberSearchResultsEnumerator = adBookmark.memberSearchResultsEnumerator;
_atBeginning = adBookmark.atBeginning;
_expansionMode = adBookmark.expansionMode;
// Replace enumerators
_members = adBookmark.members;
_membersEnum = adBookmark.membersEnum;
// Replace the enumerator queue elements
if (null != _membersQueue)
{
_membersQueue.Clear();
if (null != adBookmark.membersQueue)
{
foreach (IEnumerable ie in adBookmark.membersQueue)
{
_membersQueue.Enqueue(ie);
}
}
}
if (null != _memberSearchersQueue)
{
foreach (DirectorySearcher ds in _memberSearchersQueue)
{
ds.Dispose();
}
_memberSearchersQueue.Clear();
if (null != adBookmark.memberSearcherQueue)
{
foreach (DirectorySearcher ds in adBookmark.memberSearcherQueue)
{
_memberSearchersQueue.Enqueue(ds);
}
}
}
}
// IDisposable implementation
public override void Dispose()
{
try
{
if (!_disposed)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "Dispose: disposing");
if (_primaryGroupMembersSearcher != null)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "Dispose: disposing primaryGroupMembersSearcher");
_primaryGroupMembersSearcher.Dispose();
}
if (_queryMembersResults != null)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "Dispose: disposing queryMembersResults");
_queryMembersResults.Dispose();
}
if (_currentMembersSearcher != null)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "Dispose: disposing membersSearcher");
_currentMembersSearcher.Dispose();
}
if (_memberSearchResults != null)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "Dispose: disposing memberSearchResults");
_memberSearchResults.Dispose();
}
if (_memberSearchersQueue != null)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "Dispose: disposing memberSearchersQueue");
foreach (DirectorySearcher ds in _memberSearchersQueue)
{
ds.Dispose();
}
_memberSearchersQueue.Clear();
}
IDisposable disposableMembers = _members as IDisposable;
if (disposableMembers != null)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "Dispose: disposing members Enumerable");
disposableMembers.Dispose();
}
IDisposable disposableMembersEnum = _membersEnum as IDisposable;
if (disposableMembersEnum != null)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "Dispose: disposing membersEnum Enumerator");
disposableMembersEnum.Dispose();
}
if (_membersQueue != null)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "Dispose: disposing membersQueue");
foreach (IEnumerable enumerable in _membersQueue)
{
IDisposable disposableEnum = enumerable as IDisposable;
if (disposableEnum != null)
{
disposableEnum.Dispose();
}
}
}
if (_foreignGroups != null)
{
foreach (GroupPrincipal gp in _foreignGroups)
{
gp.Dispose();
}
}
_disposed = true;
}
}
finally
{
base.Dispose();
}
}
//
//
//
private UnsafeNativeMethods.IADsPathname _pathCracker = null;
private object _pathLock = new object();
private Dictionary<string, bool> _usersVisited = new Dictionary<string, bool>();
// The 0th entry in this list is always the DN of the original group/user whose membership we're querying
private List<string> _groupsVisited = new List<string>();
private List<string> _groupsToVisit = new List<string>();
protected Object current = null; // current member of the group (or current group of the user)
private bool _returnedPrimaryGroup = false;
private string _primaryGroupDN; // the DN of the user's PrimaryGroup (not included in this.members/originalMembers)
private bool _recursive;
private Queue<IEnumerable> _membersQueue = new Queue<IEnumerable>();
private IEnumerable _members; // the membership we're currently enumerating over
private Queue<IEnumerable> _originalMembers = new Queue<IEnumerable>(); // the membership we started off with (before recursing)
private IEnumerator _membersEnum = null;
private ADStoreCtx _storeCtx;
private ADStoreCtx _originalStoreCtx;
private bool _atBeginning = true;
private bool _disposed = false;
// foreign
// This contains a list of employees built while enumerating the current group. These are FSP objects in the current domain and need to
// be translated to find out the domain that holds the actual object.
private List<DirectoryEntry> _foreignMembersCurrentGroup = new List<DirectoryEntry>();
// List of objects from the group tha are actual fake group objects.
private List<DirectoryEntry> _fakePrincipalMembers = new List<DirectoryEntry>();
// list of SIDs + store that have been translated. These could be any principal object
private SidList _foreignMembersToReturn = null;
private Principal _currentForeignPrincipal = null;
private DirectoryEntry _currentForeignDE = null;
private List<GroupPrincipal> _foreignGroups = new List<GroupPrincipal>();
// members based on a query (used for users who are group members by virtue of their primaryGroupId pointing to the group)
private DirectorySearcher _primaryGroupMembersSearcher;
private SearchResultCollection _queryMembersResults = null;
private IEnumerator _queryMembersResultEnumerator = null;
private DirectorySearcher _currentMembersSearcher = null;
private Queue<DirectorySearcher> _memberSearchersQueue = new Queue<DirectorySearcher>();
private Queue<DirectorySearcher> _memberSearchersQueueOriginal = new Queue<DirectorySearcher>();
private SearchResultCollection _memberSearchResults = null;
private IEnumerator _memberSearchResultsEnumerator = null;
private ExpansionMode _expansionMode;
private ExpansionMode _originalExpansionMode;
private string BuildPathFromDN(string dn)
{
string userSuppliedServername = _storeCtx.UserSuppliedServerName;
if (null == _pathCracker)
{
lock (_pathLock)
{
if (null == _pathCracker)
{
UnsafeNativeMethods.Pathname pathNameObj = new UnsafeNativeMethods.Pathname();
_pathCracker = (UnsafeNativeMethods.IADsPathname)pathNameObj;
_pathCracker.EscapedMode = 2 /* ADS_ESCAPEDMODE_ON */;
}
}
}
_pathCracker.Set(dn, 4 /* ADS_SETTYPE_DN */);
string escapedDn = _pathCracker.Retrieve(7 /* ADS_FORMAT_X500_DN */);
if (userSuppliedServername.Length > 0)
return "LDAP://" + _storeCtx.UserSuppliedServerName + "/" + escapedDn;
else
return "LDAP://" + escapedDn;
}
}
internal enum ExpansionMode
{
Enum = 0,
ASQ = 1,
}
internal class ADDNLinkedAttrSetBookmark : ResultSetBookmark
{
public Dictionary<string, bool> usersVisited;
public List<string> groupsToVisit;
public List<string> groupsVisited;
public IEnumerable members;
public IEnumerator membersEnum = null;
public Queue<IEnumerable> membersQueue;
public ADStoreCtx storeCtx;
public Object current;
public bool returnedPrimaryGroup;
public List<DirectoryEntry> foreignMembersCurrentGroup;
public List<DirectoryEntry> fakePrincipalMembers;
public SidList foreignMembersToReturn;
public Principal currentForeignPrincipal;
public DirectoryEntry currentForeignDE;
public List<GroupPrincipal> foreignGroups;
public SearchResultCollection queryMembersResults;
public IEnumerator queryMembersResultEnumerator;
public SearchResultCollection memberSearchResults;
public IEnumerator memberSearchResultsEnumerator;
public bool atBeginning;
public ExpansionMode expansionMode;
public Queue<DirectorySearcher> memberSearcherQueue;
}
}
// #endif
| 44.907681 | 178 | 0.523837 | [
"MIT"
] | BigBadBleuCheese/corefx | src/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADDNLinkedAttrSet.cs | 63,724 | C# |
using System;
namespace RestEase
{
/// <summary>
/// Marks a parameter as being a query param
/// </summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property, Inherited = false, AllowMultiple = false)]
public sealed class QueryAttribute : Attribute
{
private string? _name;
/// <summary>
/// Gets or sets the name of the query param. Will use the parameter / property name if unset.
/// </summary>
public string? Name
{
get => this._name;
set
{
this._name = value;
this.HasName = true;
}
}
/// <summary>
/// Gets a value indicating whether the user has set the name attribute
/// </summary>
public bool HasName { get; private set; }
/// <summary>
/// Gets the serialization method to use to serialize the value. Defaults to QuerySerializationMethod.ToString
/// </summary>
public QuerySerializationMethod SerializationMethod { get; set; }
/// <summary>
/// Gets or sets the format string used to format the value
/// </summary>
/// <remarks>
/// If <see cref="SerializationMethod"/> is <see cref="QuerySerializationMethod.Serialized"/>, this is passed to the serializer
/// as <see cref="RequestQueryParamSerializerInfo.Format"/>.
/// Otherwise, if this looks like a format string which can be passed to <see cref="string.Format(IFormatProvider, string, object[])"/>,
/// (i.e. it contains at least one format placeholder), then this happens with the value passed as the first arg.
/// Otherwise, if the value implements <see cref="IFormattable"/>, this is passed to the value's
/// <see cref="IFormattable.ToString(string, IFormatProvider)"/> method. Otherwise this is ignored.
/// Example values: "X2", "{0:X2}", "test{0}".
/// </remarks>
public string? Format { get; set; }
/// <summary>
/// Initialises a new instance of the <see cref="QueryAttribute"/> class
/// </summary>
public QueryAttribute()
: this(QuerySerializationMethod.Default)
{
}
/// <summary>
/// Initialises a new instance of the <see cref="QueryAttribute"/> class, with the given serialization method
/// </summary>
/// <param name="serializationMethod">Serialization method to use to serialize the value</param>
public QueryAttribute(QuerySerializationMethod serializationMethod)
{
// Don't set this.Name
this.SerializationMethod = serializationMethod;
}
/// <summary>
/// Initialises a new instance of the <see cref="QueryAttribute"/> class, with the given name
/// </summary>
/// <param name="name">Name of the query parameter</param>
public QueryAttribute(string? name)
: this(name, QuerySerializationMethod.Default)
{
}
/// <summary>
/// Initialises a new instance of the <see cref="QueryAttribute"/> class, with the given name and serialization method
/// </summary>
/// <param name="name">Name of the query parameter</param>
/// <param name="serializationMethod">Serialization method to use to serialize the value</param>
public QueryAttribute(string? name, QuerySerializationMethod serializationMethod)
{
this.Name = name;
this.SerializationMethod = serializationMethod;
}
}
}
| 41.617978 | 145 | 0.591793 | [
"MIT"
] | Mu-L/RestEase | src/Common/QueryAttribute.cs | 3,618 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.