context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace AppApi.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
private const int DefaultCollectionSize = 3;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="HttpResponseWrapper.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web {
using System;
using System.Collections;
using System.Collections.Specialized;
using System.IO;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Web.Caching;
using System.Web.Routing;
[TypeForwardedFrom("System.Web.Abstractions, Version=3.5.0.0, Culture=Neutral, PublicKeyToken=31bf3856ad364e35")]
public class HttpResponseWrapper : HttpResponseBase {
private HttpResponse _httpResponse;
public HttpResponseWrapper(HttpResponse httpResponse) {
if (httpResponse == null) {
throw new ArgumentNullException("httpResponse");
}
_httpResponse = httpResponse;
}
public override bool Buffer {
get {
return _httpResponse.Buffer;
}
set {
_httpResponse.Buffer = value;
}
}
public override bool BufferOutput {
get {
return _httpResponse.BufferOutput;
}
set {
_httpResponse.BufferOutput = value;
}
}
public override HttpCachePolicyBase Cache {
get {
return new HttpCachePolicyWrapper(_httpResponse.Cache);
}
}
public override string CacheControl {
get {
return _httpResponse.CacheControl;
}
set {
_httpResponse.CacheControl = value;
}
}
public override string Charset {
get {
return _httpResponse.Charset;
}
set {
_httpResponse.Charset = value;
}
}
public override CancellationToken ClientDisconnectedToken {
get {
return _httpResponse.ClientDisconnectedToken;
}
}
public override Encoding ContentEncoding {
get {
return _httpResponse.ContentEncoding;
}
set {
_httpResponse.ContentEncoding = value;
}
}
public override string ContentType {
get {
return _httpResponse.ContentType;
}
set {
_httpResponse.ContentType = value;
}
}
public override HttpCookieCollection Cookies {
get {
return _httpResponse.Cookies;
}
}
public override int Expires {
get {
return _httpResponse.Expires;
}
set {
_httpResponse.Expires = value;
}
}
public override DateTime ExpiresAbsolute {
get {
return _httpResponse.ExpiresAbsolute;
}
set {
_httpResponse.ExpiresAbsolute = value;
}
}
public override Stream Filter {
get {
return _httpResponse.Filter;
}
set {
_httpResponse.Filter = value;
}
}
public override NameValueCollection Headers {
get {
return _httpResponse.Headers;
}
}
public override bool HeadersWritten {
get {
return _httpResponse.HeadersWritten;
}
}
public override Encoding HeaderEncoding {
get {
return _httpResponse.HeaderEncoding;
}
set {
_httpResponse.HeaderEncoding = value;
}
}
public override bool IsClientConnected {
get {
return _httpResponse.IsClientConnected;
}
}
public override bool IsRequestBeingRedirected {
get {
return _httpResponse.IsRequestBeingRedirected;
}
}
public override TextWriter Output {
get {
return _httpResponse.Output;
}
set {
_httpResponse.Output = value;
}
}
public override Stream OutputStream {
get {
return _httpResponse.OutputStream;
}
}
public override string RedirectLocation {
get {
return _httpResponse.RedirectLocation;
}
set {
_httpResponse.RedirectLocation = value;
}
}
public override string Status {
get {
return _httpResponse.Status;
}
set {
_httpResponse.Status = value;
}
}
public override int StatusCode {
get {
return _httpResponse.StatusCode;
}
set {
_httpResponse.StatusCode = value;
}
}
public override string StatusDescription {
get {
return _httpResponse.StatusDescription;
}
set {
_httpResponse.StatusDescription = value;
}
}
public override int SubStatusCode {
get {
return _httpResponse.SubStatusCode;
}
set {
_httpResponse.SubStatusCode = value;
}
}
public override bool SupportsAsyncFlush {
get {
return _httpResponse.SupportsAsyncFlush;
}
}
public override bool SuppressContent {
get {
return _httpResponse.SuppressContent;
}
set {
_httpResponse.SuppressContent = value;
}
}
public override bool SuppressDefaultCacheControlHeader {
get {
return _httpResponse.SuppressDefaultCacheControlHeader;
}
set {
_httpResponse.SuppressDefaultCacheControlHeader = value;
}
}
public override bool SuppressFormsAuthenticationRedirect {
get {
return _httpResponse.SuppressFormsAuthenticationRedirect;
}
set {
_httpResponse.SuppressFormsAuthenticationRedirect = value;
}
}
public override bool TrySkipIisCustomErrors {
get {
return _httpResponse.TrySkipIisCustomErrors;
}
set {
_httpResponse.TrySkipIisCustomErrors = value;
}
}
public override void AddCacheItemDependency(string cacheKey) {
_httpResponse.AddCacheItemDependency(cacheKey);
}
public override void AddCacheItemDependencies(ArrayList cacheKeys) {
_httpResponse.AddCacheItemDependencies(cacheKeys);
}
public override void AddCacheItemDependencies(string[] cacheKeys) {
_httpResponse.AddCacheItemDependencies(cacheKeys);
}
public override void AddCacheDependency(params CacheDependency[] dependencies) {
_httpResponse.AddCacheDependency(dependencies);
}
public override void AddFileDependency(string filename) {
_httpResponse.AddFileDependency(filename);
}
public override ISubscriptionToken AddOnSendingHeaders(Action<HttpContextBase> callback) {
return _httpResponse.AddOnSendingHeaders(HttpContextWrapper.WrapCallback(callback));
}
public override void AddFileDependencies(ArrayList filenames) {
_httpResponse.AddFileDependencies(filenames);
}
public override void AddFileDependencies(string[] filenames) {
_httpResponse.AddFileDependencies(filenames);
}
public override void AddHeader(string name, string value) {
_httpResponse.AddHeader(name, value);
}
public override void AppendCookie(HttpCookie cookie) {
_httpResponse.AppendCookie(cookie);
}
public override void AppendHeader(string name, string value) {
_httpResponse.AppendHeader(name, value);
}
public override void AppendToLog(string param) {
_httpResponse.AppendToLog(param);
}
public override string ApplyAppPathModifier(string virtualPath) {
return _httpResponse.ApplyAppPathModifier(virtualPath);
}
public override IAsyncResult BeginFlush(AsyncCallback callback, Object state) {
return _httpResponse.BeginFlush(callback, state);
}
public override void BinaryWrite(byte[] buffer) {
_httpResponse.BinaryWrite(buffer);
}
public override void Clear() {
_httpResponse.Clear();
}
public override void ClearContent() {
_httpResponse.ClearContent();
}
public override void ClearHeaders() {
_httpResponse.ClearHeaders();
}
public override void Close() {
_httpResponse.Close();
}
public override void DisableKernelCache() {
_httpResponse.DisableKernelCache();
}
public override void DisableUserCache() {
_httpResponse.DisableUserCache();
}
public override void End() {
_httpResponse.End();
}
public override void EndFlush(IAsyncResult asyncResult) {
_httpResponse.EndFlush(asyncResult);
}
public override void Flush() {
_httpResponse.Flush();
}
public override void Pics(string value) {
_httpResponse.Pics(value);
}
public override void Redirect(string url) {
_httpResponse.Redirect(url);
}
public override void Redirect(string url, bool endResponse) {
_httpResponse.Redirect(url, endResponse);
}
public override void RedirectPermanent(String url) {
_httpResponse.RedirectPermanent(url);
}
public override void RedirectPermanent(String url, bool endResponse) {
_httpResponse.RedirectPermanent(url, endResponse);
}
public override void RedirectToRoute(object routeValues) {
_httpResponse.RedirectToRoute(routeValues);
}
public override void RedirectToRoute(string routeName) {
_httpResponse.RedirectToRoute(routeName);
}
public override void RedirectToRoute(RouteValueDictionary routeValues) {
_httpResponse.RedirectToRoute(routeValues);
}
public override void RedirectToRoute(string routeName, object routeValues) {
_httpResponse.RedirectToRoute(routeName, routeValues);
}
public override void RedirectToRoute(string routeName, RouteValueDictionary routeValues) {
_httpResponse.RedirectToRoute(routeName, routeValues);
}
public override void RedirectToRoutePermanent(object routeValues) {
_httpResponse.RedirectToRoutePermanent(routeValues);
}
public override void RedirectToRoutePermanent(string routeName) {
_httpResponse.RedirectToRoutePermanent(routeName);
}
public override void RedirectToRoutePermanent(RouteValueDictionary routeValues) {
_httpResponse.RedirectToRoutePermanent(routeValues);
}
public override void RedirectToRoutePermanent(string routeName, object routeValues) {
_httpResponse.RedirectToRoutePermanent(routeName, routeValues);
}
public override void RedirectToRoutePermanent(string routeName, RouteValueDictionary routeValues) {
_httpResponse.RedirectToRoutePermanent(routeName, routeValues);
}
public override void RemoveOutputCacheItem(string path) {
HttpResponse.RemoveOutputCacheItem(path);
}
public override void RemoveOutputCacheItem(string path, string providerName) {
HttpResponse.RemoveOutputCacheItem(path, providerName);
}
public override void SetCookie(HttpCookie cookie) {
_httpResponse.SetCookie(cookie);
}
public override void TransmitFile(string filename) {
_httpResponse.TransmitFile(filename);
}
public override void TransmitFile(string filename, long offset, long length) {
_httpResponse.TransmitFile(filename, offset, length);
}
public override void Write(string s) {
_httpResponse.Write(s);
}
public override void Write(char ch) {
_httpResponse.Write(ch);
}
public override void Write(char[] buffer, int index, int count) {
_httpResponse.Write(buffer, index, count);
}
public override void Write(object obj) {
_httpResponse.Write(obj);
}
public override void WriteFile(string filename) {
_httpResponse.WriteFile(filename);
}
public override void WriteFile(string filename, bool readIntoMemory) {
_httpResponse.WriteFile(filename, readIntoMemory);
}
public override void WriteFile(string filename, long offset, long size) {
_httpResponse.WriteFile(filename, offset, size);
}
public override void WriteFile(IntPtr fileHandle, long offset, long size) {
_httpResponse.WriteFile(fileHandle, offset, size);
}
public override void WriteSubstitution(HttpResponseSubstitutionCallback callback) {
_httpResponse.WriteSubstitution(callback);
}
}
}
| |
// (c) Copyright Microsoft Corporation.
// This source is subject to the Microsoft Public License (Ms-PL).
// Please see http://go.microsoft.com/fwlink/?LinkID=131993 for details.
// All other rights reserved.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Animation;
namespace MahApps.Metro.Controls
{
/// <summary>
/// enumeration for the different transition types
/// </summary>
public enum TransitionType
{
/// <summary>
/// Use the VisualState DefaultTransition
/// </summary>
Default,
/// <summary>
/// Use the VisualState Normal
/// </summary>
Normal,
/// <summary>
/// Use the VisualState UpTransition
/// </summary>
Up,
/// <summary>
/// Use the VisualState DownTransition
/// </summary>
Down,
/// <summary>
/// Use the VisualState RightTransition
/// </summary>
Right,
/// <summary>
/// Use the VisualState RightReplaceTransition
/// </summary>
RightReplace,
/// <summary>
/// Use the VisualState LeftTransition
/// </summary>
Left,
/// <summary>
/// Use the VisualState LeftReplaceTransition
/// </summary>
LeftReplace,
/// <summary>
/// Use a custom VisualState, the name must be CustomTransition
/// </summary>
Custom
}
/// <summary>
/// A ContentControl that animates content as it loads and unloads.
/// </summary>
public class TransitioningContentControl : ContentControl
{
internal const string PresentationGroup = "PresentationStates";
internal const string NormalState = "Normal";
internal const string PreviousContentPresentationSitePartName = "PreviousContentPresentationSite";
internal const string CurrentContentPresentationSitePartName = "CurrentContentPresentationSite";
private ContentPresenter CurrentContentPresentationSite { get; set; }
private ContentPresenter PreviousContentPresentationSite { get; set; }
private bool _allowIsTransitioningWrite;
private Storyboard _currentTransition;
public event RoutedEventHandler TransitionCompleted;
public const TransitionType DefaultTransitionState = TransitionType.Default;
public static readonly DependencyProperty IsTransitioningProperty = DependencyProperty.Register("IsTransitioning", typeof(bool), typeof(TransitioningContentControl), new PropertyMetadata(OnIsTransitioningPropertyChanged));
public static readonly DependencyProperty TransitionProperty = DependencyProperty.Register("Transition", typeof(TransitionType), typeof(TransitioningContentControl), new FrameworkPropertyMetadata(TransitionType.Default, FrameworkPropertyMetadataOptions.AffectsArrange | FrameworkPropertyMetadataOptions.Inherits, OnTransitionPropertyChanged));
public static readonly DependencyProperty RestartTransitionOnContentChangeProperty = DependencyProperty.Register("RestartTransitionOnContentChange", typeof(bool), typeof(TransitioningContentControl), new PropertyMetadata(false, OnRestartTransitionOnContentChangePropertyChanged));
public static readonly DependencyProperty CustomVisualStatesProperty = DependencyProperty.Register("CustomVisualStates", typeof(ObservableCollection<VisualState>), typeof(TransitioningContentControl), new PropertyMetadata(null));
public ObservableCollection<VisualState> CustomVisualStates {
get { return (ObservableCollection<VisualState>)this.GetValue(CustomVisualStatesProperty); }
set { this.SetValue(CustomVisualStatesProperty, value); }
}
/// <summary>
/// Gets/sets if the content is transitioning.
/// </summary>
public bool IsTransitioning
{
get { return (bool)GetValue(IsTransitioningProperty); }
private set
{
_allowIsTransitioningWrite = true;
SetValue(IsTransitioningProperty, value);
_allowIsTransitioningWrite = false;
}
}
public TransitionType Transition
{
get { return (TransitionType)GetValue(TransitionProperty); }
set { SetValue(TransitionProperty, value); }
}
public bool RestartTransitionOnContentChange
{
get { return (bool)GetValue(RestartTransitionOnContentChangeProperty); }
set { SetValue(RestartTransitionOnContentChangeProperty, value); }
}
private static void OnIsTransitioningPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var source = (TransitioningContentControl)d;
if (!source._allowIsTransitioningWrite)
{
source.IsTransitioning = (bool)e.OldValue;
throw new InvalidOperationException();
}
}
private Storyboard CurrentTransition
{
get { return _currentTransition; }
set
{
// decouple event
if (_currentTransition != null)
{
_currentTransition.Completed -= OnTransitionCompleted;
}
_currentTransition = value;
if (_currentTransition != null)
{
_currentTransition.Completed += OnTransitionCompleted;
}
}
}
private static void OnTransitionPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var source = (TransitioningContentControl)d;
var oldTransition = (TransitionType)e.OldValue;
var newTransition = (TransitionType)e.NewValue;
if (source.IsTransitioning)
{
source.AbortTransition();
}
// find new transition
Storyboard newStoryboard = source.GetStoryboard(newTransition);
// unable to find the transition.
if (newStoryboard == null)
{
// could be during initialization of xaml that presentationgroups was not yet defined
if (VisualStates.TryGetVisualStateGroup(source, PresentationGroup) == null)
{
// will delay check
source.CurrentTransition = null;
}
else
{
// revert to old value
source.SetValue(TransitionProperty, oldTransition);
throw new ArgumentException(
string.Format(CultureInfo.CurrentCulture, "Temporary removed exception message", newTransition));
}
}
else
{
source.CurrentTransition = newStoryboard;
}
}
private static void OnRestartTransitionOnContentChangePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((TransitioningContentControl)d).OnRestartTransitionOnContentChangeChanged((bool)e.OldValue, (bool)e.NewValue);
}
protected virtual void OnRestartTransitionOnContentChangeChanged(bool oldValue, bool newValue)
{
}
public TransitioningContentControl()
{
this.CustomVisualStates = new ObservableCollection<VisualState>();
DefaultStyleKey = typeof(TransitioningContentControl);
}
public override void OnApplyTemplate()
{
if (IsTransitioning)
{
AbortTransition();
}
if (this.CustomVisualStates != null && this.CustomVisualStates.Any()) {
var presentationGroup = VisualStates.TryGetVisualStateGroup(this, PresentationGroup);
if (presentationGroup != null) {
foreach (var state in this.CustomVisualStates) {
presentationGroup.States.Add(state);
}
}
}
base.OnApplyTemplate();
PreviousContentPresentationSite = GetTemplateChild(PreviousContentPresentationSitePartName) as ContentPresenter;
CurrentContentPresentationSite = GetTemplateChild(CurrentContentPresentationSitePartName) as ContentPresenter;
if (CurrentContentPresentationSite != null)
{
CurrentContentPresentationSite.Content = Content;
}
// hookup currenttransition
Storyboard transition = GetStoryboard(Transition);
CurrentTransition = transition;
if (transition == null)
{
var invalidTransition = Transition;
// revert to default
Transition = DefaultTransitionState;
throw new ArgumentException(string.Format("'{0}' Transition could not be found!", invalidTransition), "Transition");
}
VisualStateManager.GoToState(this, NormalState, false);
}
protected override void OnContentChanged(object oldContent, object newContent)
{
base.OnContentChanged(oldContent, newContent);
StartTransition(oldContent, newContent);
}
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "newContent", Justification = "Should be used in the future.")]
private void StartTransition(object oldContent, object newContent)
{
// both presenters must be available, otherwise a transition is useless.
if (CurrentContentPresentationSite != null && PreviousContentPresentationSite != null)
{
if (RestartTransitionOnContentChange)
{
CurrentTransition.Completed -= OnTransitionCompleted;
}
CurrentContentPresentationSite.Content = newContent;
PreviousContentPresentationSite.Content = oldContent;
// and start a new transition
if (!IsTransitioning || RestartTransitionOnContentChange)
{
if (RestartTransitionOnContentChange)
{
CurrentTransition.Completed += OnTransitionCompleted;
}
IsTransitioning = true;
VisualStateManager.GoToState(this, NormalState, false);
VisualStateManager.GoToState(this, GetTransitionName(Transition), true);
}
}
}
/// <summary>
/// Reload the current transition if the content is the same.
/// </summary>
public void ReloadTransition()
{
// both presenters must be available, otherwise a transition is useless.
if (CurrentContentPresentationSite != null && PreviousContentPresentationSite != null)
{
if (RestartTransitionOnContentChange)
{
CurrentTransition.Completed -= OnTransitionCompleted;
}
if (!IsTransitioning || RestartTransitionOnContentChange)
{
if (RestartTransitionOnContentChange)
{
CurrentTransition.Completed += OnTransitionCompleted;
}
IsTransitioning = true;
VisualStateManager.GoToState(this, NormalState, false);
VisualStateManager.GoToState(this, GetTransitionName(Transition), true);
}
}
}
private void OnTransitionCompleted(object sender, EventArgs e)
{
AbortTransition();
RoutedEventHandler handler = TransitionCompleted;
if (handler != null)
{
handler(this, new RoutedEventArgs());
}
}
public void AbortTransition()
{
// go to normal state and release our hold on the old content.
VisualStateManager.GoToState(this, NormalState, false);
IsTransitioning = false;
if (PreviousContentPresentationSite != null)
{
PreviousContentPresentationSite.Content = null;
}
}
private Storyboard GetStoryboard(TransitionType newTransition)
{
VisualStateGroup presentationGroup = VisualStates.TryGetVisualStateGroup(this, PresentationGroup);
Storyboard newStoryboard = null;
if (presentationGroup != null)
{
var transitionName = GetTransitionName(newTransition);
newStoryboard = presentationGroup.States
.OfType<VisualState>()
.Where(state => state.Name == transitionName)
.Select(state => state.Storyboard)
.FirstOrDefault();
}
return newStoryboard;
}
private string GetTransitionName(TransitionType transition)
{
switch (transition) {
default:
case TransitionType.Default:
return "DefaultTransition";
case TransitionType.Normal:
return "Normal";
case TransitionType.Up:
return "UpTransition";
case TransitionType.Down:
return "DownTransition";
case TransitionType.Right:
return "RightTransition";
case TransitionType.RightReplace:
return "RightReplaceTransition";
case TransitionType.Left:
return "LeftTransition";
case TransitionType.LeftReplace:
return "LeftReplaceTransition";
case TransitionType.Custom:
return "CustomTransition";
}
}
}
}
| |
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Data;
using Microsoft.Win32;
using MySql.Data.MySqlClient;
using System.IO;
using WebsitePanel.Server.Utils;
using WebsitePanel.Providers.Utils;
using WebsitePanel.Providers;
using System.Reflection;
using System.Data.Common;
namespace WebsitePanel.Providers.Database
{
public class MySqlServer : HostingServiceProviderBase, IDatabaseServer
{
#region Properties
protected string BackupTempFolder
{
get { return Path.GetTempPath(); }
}
protected string MySqlBinFolder
{
get { return Path.Combine(InstallFolder, "Bin"); }
}
protected int ServerPort
{
get
{
string addr = ProviderSettings["InternalAddress"];
if (String.IsNullOrEmpty(addr))
return 3306;
int idx = addr.IndexOfAny(new char[] { ':', ',' });
if (idx == -1)
return 3306;
return Int32.Parse(addr.Substring(idx + 1));
}
}
protected string ServerName
{
get
{
string addr = ProviderSettings["InternalAddress"];
if (String.IsNullOrEmpty(addr))
return addr;
int idx = addr.IndexOfAny(new char[]{':', ','});
if (idx == -1)
return addr;
return addr.Substring(0, idx);
}
}
protected string InstallFolder
{
get { return FileUtils.EvaluateSystemVariables(ProviderSettings["InstallFolder"]); }
}
protected string RootLogin
{
get { return ProviderSettings["RootLogin"]; }
}
protected string RootPassword
{
get { return ProviderSettings["RootPassword"]; }
}
protected bool OldPassword
{
get { return !String.IsNullOrEmpty(ProviderSettings["OldPassword"])
? Boolean.Parse(ProviderSettings["OldPassword"]) : false; }
}
public string ConnectionString
{
get
{
return String.Format("server={0};port={1};database=mysql;uid={2};password={3}",
ServerName, ServerPort, RootLogin, RootPassword);
}
}
#endregion
#region Static ctor
static MySqlServer()
{
AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
}
static System.Reflection.Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
//
if (!args.Name.Contains("MySql.Data"))
return null;
if (args.Name.Contains("MySql.Data.resources"))
return null;
//
string connectorKeyName = "SOFTWARE\\MySQL AB\\MySQL Connector/Net";
string connectorVersion = String.Empty;
//
if (PInvoke.RegistryHive.HKLM.SubKeyExists_x86(connectorKeyName))
{
connectorVersion = PInvoke.RegistryHive.HKLM.GetSubKeyValue_x86(connectorKeyName, "Version");
}
string assemblyFullName = string.Format("MySql.Data, Version={0}.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d", connectorVersion);
if (assemblyFullName == args.Name)
{
return null; //avoid of stack overflow
}
return Assembly.Load(assemblyFullName);
}
#endregion
#region Databases
private string GetSafeConnectionString(string databaseName, string username, string password)
{
return String.Format("server={0};port={1};database={2};uid={3};password={4}",
ServerName, ServerPort, databaseName, username, password);
}
public virtual bool CheckConnectivity(string databaseName, string username, string password)
{
MySqlConnection conn = new MySqlConnection(
String.Format("server={0};port={1};database={2};uid={3};password={4}",
ServerName,
ServerPort,
databaseName,
username,
password)
);
try
{
conn.Open();
}
catch
{
return false;
}
conn.Close();
return true;
}
public virtual DataSet ExecuteSqlQuery(string databaseName, string commandText)
{
commandText = "USE " + databaseName + "; " + commandText;
return ExecuteQueryDataSet(commandText);
}
public virtual void ExecuteSqlNonQuery(string databaseName, string commandText)
{
commandText = "USE " + databaseName + ";\n" + commandText;
ExecuteNonQuery(commandText);
}
public virtual DataSet ExecuteSqlQuerySafe(string databaseName, string username, string password, string commandText)
{
commandText = "USE " + databaseName + "; " + commandText;
return ExecuteQueryDataSet(commandText, GetSafeConnectionString(databaseName, username, password));
}
public virtual void ExecuteSqlNonQuerySafe(string databaseName, string username, string password, string commandText)
{
commandText = "USE " + databaseName + ";\n" + commandText;
ExecuteNonQuery(commandText, GetSafeConnectionString(databaseName, username, password));
}
public virtual bool DatabaseExists(string databaseName)
{
DataTable dvDatabases = ExecuteQuery("SHOW DATABASES");
DataView dvDatabase = new DataView(dvDatabases, String.Format("Database='{0}'",
databaseName), "", DataViewRowState.CurrentRows);
return (dvDatabase.Count > 0);
}
public virtual string[] GetDatabases()
{
DataTable dt = ExecuteQuery("SHOW DATABASES");
List<string> databases = new List<string>();
foreach (DataRow dr in dt.Rows)
{
if (!Convert.IsDBNull(dr["Database"]))
{
databases.Add(Convert.ToString(dr["Database"]));
}
}
return databases.ToArray();
}
public virtual SqlDatabase GetDatabase(string databaseName)
{
if (!DatabaseExists(databaseName))
return null;
SqlDatabase database = new SqlDatabase();
database.Name = databaseName;
// calculate database size
DataView dvTables = ExecuteQuery(String.Format("SHOW TABLE STATUS FROM {0}", databaseName)).DefaultView;
long data = 0;
long index = 0;
foreach (DataRowView drTable in dvTables)
{
//
if (!Convert.IsDBNull(drTable["Data_length"]))
{
data += Convert.ToInt64(drTable["Data_length"]);
}
//
if (!Convert.IsDBNull(drTable["Index_length"]))
{
index += Convert.ToInt64(drTable["Index_length"]);
}
}
//size in KB
database.DataSize = (int)(data + index) / 1024;
// get database uzers
database.Users = GetDatabaseUsers(databaseName);
return database;
}
public virtual void CreateDatabase(SqlDatabase database)
{
if (database.Users == null)
database.Users = new string[0];
/*if (!((Regex.IsMatch(database.Name, @"[^\w\.-]")) && (database.Name.Length > 40)))
{
Exception ex = new Exception("INVALID_DATABASE_NAME");
throw ex;
}
*/
// create database
ExecuteNonQuery(String.Format("CREATE DATABASE IF NOT EXISTS {0};", database.Name));
// grant users access
foreach (string user in database.Users)
AddUserToDatabase(database.Name, user);
}
public virtual void UpdateDatabase(SqlDatabase database)
{
if (database.Users == null)
database.Users = new string[0];
// remove all users from database
string[] users = GetDatabaseUsers(database.Name);
foreach (string user in users)
RemoveUserFromDatabase(database.Name, user);
// grant users access
foreach (string user in database.Users)
AddUserToDatabase(database.Name, user);
}
public virtual void DeleteDatabase(string databaseName)
{
if (!DatabaseExists(databaseName))
return;
// remove all users from database
string[] users = GetDatabaseUsers(databaseName);
foreach (string user in users)
RemoveUserFromDatabase(databaseName, user);
// close all connection
CloseDatabaseConnections(databaseName);
// drop database
ExecuteNonQuery(String.Format("DROP DATABASE IF EXISTS {0}", databaseName));
}
#endregion
#region Users
public virtual bool UserExists(string username)
{
return (ExecuteQuery(String.Format("SELECT user FROM user WHERE user = '{0}'",
username)).DefaultView.Count > 0);
}
public virtual string[] GetUsers()
{
DataTable dt = ExecuteQuery("select user from user");
List<string> users = new List<string>();
foreach (DataRow dr in dt.Rows)
users.Add(dr["user"].ToString());
return users.ToArray();
}
public virtual SqlUser GetUser(string username, string[] databases)
{
// get user information
SqlUser user = new SqlUser();
user.Name = username;
// get user databases
user.Databases = GetUserDatabases(username);
return user;
}
public virtual void CreateUser(SqlUser user, string password)
{
if (user.Databases == null)
user.Databases = new string[0];
/*if (!((Regex.IsMatch(user.Name, @"[^\w\.-]")) && (user.Name.Length > 16)))
{
Exception ex = new Exception("INVALID_USERNAME");
throw ex;
}
*/
ExecuteNonQuery(String.Format(
"GRANT USAGE ON mysql.* TO '{0}'@'%' IDENTIFIED BY '{1}'",
user.Name, password));
if (OldPassword)
ChangeUserPassword(user.Name, password);
// add access to databases
foreach (string database in user.Databases)
AddUserToDatabase(database, user.Name);
}
public virtual void UpdateUser(SqlUser user, string[] allDatabases)
{
if (user.Databases == null)
user.Databases = new string[0];
// update user databases access
string[] databases = GetUserDatabases(user.Name);
foreach (string database in databases)
RemoveUserFromDatabase(database, user.Name);
foreach (string database in user.Databases)
AddUserToDatabase(database, user.Name);
// change user password if required
if (!String.IsNullOrEmpty(user.Password))
ChangeUserPassword(user.Name, user.Password);
}
public virtual void DeleteUser(string username, string[] databases)
{
ExecuteNonQuery(String.Format(
@"DELETE FROM mysql.user WHERE User='{0}' AND Host = '%';
DELETE FROM mysql.db WHERE User='{0}' AND Host = '%';
DELETE FROM mysql.tables_priv WHERE User='{0}' AND Host = '%';
DELETE FROM mysql.columns_priv WHERE User='{0}' AND Host = '%';
FLUSH PRIVILEGES;", username));
}
public virtual void ChangeUserPassword(string username, string password)
{
string pswMode = OldPassword ? "OLD_" : "";
ExecuteNonQuery(String.Format("SET PASSWORD FOR '{0}'@'%' = {1}PASSWORD('{2}')",
username, pswMode, password));
}
#endregion
#region Backup databases
public virtual byte[] GetTempFileBinaryChunk(string path, int offset, int length)
{
CheckTempPath(path);
byte[] buffer = FileUtils.GetFileBinaryChunk(path, offset, length);
// delete temp file
if (buffer.Length < length)
FileUtils.DeleteFile(path);
return buffer;
}
public virtual string AppendTempFileBinaryChunk(string fileName, string path, byte[] chunk)
{
if (path == null)
{
path = Path.Combine(Path.GetTempPath(), fileName);
if (FileUtils.FileExists(path))
FileUtils.DeleteFile(path);
}
else
{
CheckTempPath(path);
}
FileUtils.AppendFileBinaryContent(path, chunk);
return path;
}
public virtual string BackupDatabase(string databaseName, string backupName, bool zipBackup)
{
string bakFile = BackupDatabase(databaseName, (zipBackup ? null : backupName));
// zip database files
if (zipBackup)
{
string zipFile = Path.Combine(BackupTempFolder, backupName);
FileUtils.ZipFiles(zipFile, Path.GetDirectoryName(bakFile), new string[] { Path.GetFileName(bakFile) });
// delete data files
if (String.Compare(bakFile, zipFile, true) != 0)
FileUtils.DeleteFile(bakFile);
bakFile = zipFile;
}
return bakFile;
}
private string BackupDatabase(string databaseName, string backupName)
{
if (backupName == null)
backupName = databaseName + ".sql";
string cmd = Path.Combine(MySqlBinFolder, "mysqldump.exe");
string bakFile = Path.Combine(BackupTempFolder, backupName);
string args = string.Format(" --host={0} --port={1} --user={2} --password={3} --opt --skip-extended-insert --skip-quick --skip-comments --result-file=\"{4}\" {5}",
ServerName, ServerPort, RootLogin, RootPassword, bakFile, databaseName);
// backup database
FileUtils.ExecuteSystemCommand(cmd, args);
return bakFile;
}
public virtual void TruncateDatabase(string databaseName)
{
string zipPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
FileUtils.CreateDirectory(zipPath);
// create temporary batchfile
string batchfilename = Path.Combine(zipPath, "MySql_Truncate.bat");
StreamWriter file = new StreamWriter(batchfilename);
file.WriteLine("@ECHO OFF");
file.WriteLine("cls");
file.WriteLine("set host=%1%");
file.WriteLine("set port=%2%");
file.WriteLine("set user=%3%");
file.WriteLine("set password=%4%");
file.WriteLine("set dbname=%5%");
file.WriteLine("\"" + Path.Combine(MySqlBinFolder, "mysql") + "\" --host=%host% --port=%port% --user=%user% --password=%password% -N -e \"SELECT CONCAT('OPTIMIZE TABLE ', table_name, ';') FROM information_schema.tables WHERE table_schema = '%dbname%' AND data_free/1024/1024 > 5;\" | mysql --host=%host% --port=%port% --user=%user% --password=%password% %dbname%");
file.Close();
// close current database connections
CloseDatabaseConnections(databaseName);
try
{
string args = string.Format(" {0} {1} {2} {3} {4}",
ServerName, ServerPort,
RootLogin, RootPassword, databaseName);
FileUtils.ExecuteSystemCommand(batchfilename, args);
}
finally
{
FileUtils.DeleteDirectoryAdvanced(zipPath);
}
}
#endregion
#region Restore database
public virtual void RestoreDatabase(string databaseName, string[] files)
{
string tempPath = Path.GetTempPath();
//create folder with unique name to avoid getting all files from temp directory
string zipPath = Path.Combine(tempPath, Guid.NewGuid().ToString());
// store original database information
SqlDatabase database = GetDatabase(databaseName);
// unzip uploaded files if required
List<string> expandedFiles = new List<string>();
foreach (string file in files)
{
if (Path.GetExtension(file).ToLower() == ".zip")
{
// unpack file
expandedFiles.AddRange(FileUtils.UnzipFiles(file, zipPath));
// delete zip archive
FileUtils.DeleteFile(file);
}
else
{
// just add file to the collection
if (!FileUtils.DirectoryExists(zipPath))
FileUtils.CreateDirectory(zipPath);
string newfile = Path.Combine(zipPath, Path.GetFileName(file));
FileUtils.MoveFile(file, newfile);
expandedFiles.Add(newfile);
}
}
files = new string[expandedFiles.Count];
expandedFiles.CopyTo(files, 0);
if (files.Length == 0)
throw new ApplicationException("No backup files were uploaded"); // error: no backup files were uploaded
if (files.Length > 1)
throw new ApplicationException("Too many files were uploaded"); // error: too many files were uploaded
// analyze uploaded files
bool fromDump = true;
foreach (string file in files)
{
if (Path.GetExtension(file).ToLower() != ".sql")
{
fromDump = false;
break;
}
}
if (fromDump)
{
// restore database
// create temporary batchfile
string batchfilename = Path.Combine(zipPath, "MySql_Restore.bat");
StreamWriter file = new StreamWriter(batchfilename);
file.WriteLine("@ECHO OFF");
file.WriteLine("cls");
file.WriteLine("set host=%1%");
file.WriteLine("set port=%2%");
file.WriteLine("set user=%3%");
file.WriteLine("set password=%4%");
file.WriteLine("set dbname=%5%");
file.WriteLine("set dumpfile=%6%");
file.WriteLine("\"" + Path.Combine(MySqlBinFolder, "mysql") + "\" --host=%host% --port=%port% --user=%user% --password=%password% %dbname% < %dumpfile%");
file.Close();
// restore from .SQL file
CloseDatabaseConnections(database.Name);
try
{
string sqlFile = files[0];
string args = string.Format(" {0} {1} {2} {3} {4} {5}",
ServerName, ServerPort,
RootLogin, RootPassword, database.Name, Path.GetFileName(sqlFile));
FileUtils.ExecuteSystemCommand(batchfilename, args);
}
finally
{
// delete uploaded files
FileUtils.DeleteFiles(files);
}
}
else
{
// do nothing
}
//delete temporary folder for zip contents
if (FileUtils.DirectoryExists(zipPath))
{
FileUtils.DeleteDirectoryAdvanced(zipPath);
}
}
#endregion
#region private helper methods
private int ExecuteNonQuery(string commandText)
{
return ExecuteNonQuery(commandText, ConnectionString);
}
private int ExecuteNonQuery(string commandText, string connectionString)
{
MySqlConnection conn = new MySqlConnection(connectionString);
MySqlCommand cmd = new MySqlCommand(commandText, conn);
conn.Open();
int ret = cmd.ExecuteNonQuery();
conn.Close();
return ret;
}
private DataTable ExecuteQuery(string commandText, string connectionString)
{
return ExecuteQueryDataSet(commandText, connectionString).Tables[0];
}
private DataTable ExecuteQuery(string commandText)
{
return ExecuteQueryDataSet(commandText).Tables[0];
}
private DataSet ExecuteQueryDataSet(string commandText)
{
return ExecuteQueryDataSet(commandText, ConnectionString);
}
private DataSet ExecuteQueryDataSet(string commandText, string connectionString)
{
MySqlConnection conn = new MySqlConnection(connectionString);
MySqlDataAdapter adapter = new MySqlDataAdapter(commandText, conn);
DataSet ds = new DataSet();
adapter.Fill(ds);
return ds;
}
private string[] GetDatabaseUsers(string databaseName)
{
DataTable dtResult = ExecuteQuery(String.Format("SELECT User FROM db WHERE Db='{0}' AND Host='%' AND " +
"Select_priv = 'Y' AND " +
"Insert_priv = 'Y' AND " +
"Update_priv = 'Y' AND " +
"Delete_priv = 'Y' AND " +
"Index_priv = 'Y' AND " +
"Alter_priv = 'Y' AND " +
"Create_priv = 'Y' AND " +
"Drop_priv = 'Y' AND " +
"Create_tmp_table_priv = 'Y' AND " +
"Lock_tables_priv = 'Y'", databaseName.ToLower()));
//
List<string> users = new List<string>();
//
if (dtResult != null)
{
if (dtResult.DefaultView != null)
{
DataView dvUsers = dtResult.DefaultView;
//
foreach (DataRowView drUser in dvUsers)
{
if (!Convert.IsDBNull(drUser["user"]))
{
users.Add(Convert.ToString(drUser["user"]));
}
}
}
}
//
return users.ToArray();
}
private string[] GetUserDatabases(string username)
{
DataTable dtResult = ExecuteQuery(String.Format("SELECT Db FROM db WHERE LOWER(User)='{0}' AND Host='%' AND " +
"Select_priv = 'Y' AND " +
"Insert_priv = 'Y' AND " +
"Update_priv = 'Y' AND " +
"Delete_priv = 'Y' AND " +
"Index_priv = 'Y' AND " +
"Alter_priv = 'Y' AND " +
"Create_priv = 'Y' AND " +
"Drop_priv = 'Y' AND " +
"Create_tmp_table_priv = 'Y' AND " +
"Lock_tables_priv = 'Y'", username.ToLower()));
//
List<string> databases = new List<string>();
//
//
if (dtResult != null)
{
if (dtResult.DefaultView != null)
{
DataView dvDatabases = dtResult.DefaultView;
//
foreach (DataRowView drDatabase in dvDatabases)
{
if (!Convert.IsDBNull(drDatabase["db"]))
{
databases.Add(Convert.ToString(drDatabase["db"]));
}
}
}
}
//
return databases.ToArray();
}
private void AddUserToDatabase(string databaseName, string user)
{
// grant database access
ExecuteNonQuery(String.Format("GRANT ALL PRIVILEGES ON {0}.* TO '{1}'@'%'",
databaseName, user));
}
private void RemoveUserFromDatabase(string databaseName, string user)
{
// revoke db access
ExecuteNonQuery(String.Format("REVOKE ALL PRIVILEGES ON {0}.* FROM '{1}'@'%'",
databaseName, user));
}
private void CloseDatabaseConnections(string database)
{
DataTable dtProcesses = ExecuteQuery("SHOW PROCESSLIST");
//
string filter = String.Format("db = '{0}'", database);
//
if (dtProcesses.Columns["db"].DataType == typeof(System.Byte[]))
filter = String.Format("Convert(db, 'System.String') = '{0}'", database);
DataView dvProcesses = new DataView(dtProcesses);
foreach (DataRowView rowSid in dvProcesses)
{
string cmdText = String.Format("KILL {0}", rowSid["Id"]);
try
{
ExecuteNonQuery(cmdText);
}
catch(Exception ex)
{
Log.WriteError("Cannot drop MySQL connection: " + cmdText, ex);
}
}
}
private long CalculateDatabaseSize(string database)
{
// read mySQL INI file
string dataPath = null;
string iniPath = Path.Combine(InstallFolder, "my.ini");
if (File.Exists(iniPath))
{
string[] lines = File.ReadAllLines(iniPath);
Regex re = new Regex(@"^datadir\s?=\s?\""?(?<path>[^\""\n]*)", RegexOptions.IgnoreCase);
foreach (string line in lines)
{
Match m = re.Match(line);
if (m.Success)
{
dataPath = m.Groups["path"].Value.Trim();
break;
}
}
}
if (String.IsNullOrEmpty(dataPath))
dataPath = Path.Combine(InstallFolder, "data");
string dbFolder = Path.Combine(dataPath, database);
Log.WriteStart("Database path: " + dbFolder);
if (Directory.Exists(dbFolder))
{
Log.WriteStart("Data folder exists");
return FileUtils.CalculateFolderSize(dbFolder);
}
return 0;
}
#endregion
#region IHostingServiceProvier methods
public override string[] Install()
{
List<string> messages = new List<string>();
// check connectivity
MySqlConnection conn = new MySqlConnection(ConnectionString);
try
{
conn.Open();
}
catch (Exception ex)
{
messages.Add("Could not connect to the specified MySQL Server: " + ex.Message);
}
finally
{
if (conn.State == ConnectionState.Open)
conn.Close();
}
// check installation folder existance
if (String.IsNullOrEmpty(InstallFolder) ||
!FileUtils.DirectoryExists(InstallFolder))
{
messages.Add(String.Format("Installation folder '{0}' could not be found", InstallFolder));
}
return messages.ToArray();
}
public override void DeleteServiceItems(ServiceProviderItem[] items)
{
foreach (ServiceProviderItem item in items)
{
if (item is SqlDatabase)
{
try
{
// delete database
DeleteDatabase(item.Name);
}
catch (Exception ex)
{
Log.WriteError(String.Format("Error deleting '{0}' MS SQL Database", item.Name), ex);
}
}
else if (item is SqlUser)
{
try
{
// delete user
DeleteUser(item.Name, null);
}
catch (Exception ex)
{
Log.WriteError(String.Format("Error deleting '{0}' MS SQL User", item.Name), ex);
}
}
}
}
public override ServiceProviderItemDiskSpace[] GetServiceItemsDiskSpace(ServiceProviderItem[] items)
{
List<ServiceProviderItemDiskSpace> itemsDiskspace = new List<ServiceProviderItemDiskSpace>();
// update items with diskspace
foreach (ServiceProviderItem item in items)
{
if (item is SqlDatabase)
{
try
{
// get database details
Log.WriteStart(String.Format("Calculating '{0}' database size", item.Name));
// calculate disk space
ServiceProviderItemDiskSpace diskspace = new ServiceProviderItemDiskSpace();
diskspace.ItemId = item.Id;
diskspace.DiskSpace = CalculateDatabaseSize(item.Name);
itemsDiskspace.Add(diskspace);
Log.WriteEnd(String.Format("Calculating '{0}' database size", item.Name));
}
catch (Exception ex)
{
Log.WriteError(String.Format("Error calculating '{0}' SQL Server database size", item.Name), ex);
}
}
}
return itemsDiskspace.ToArray();
}
#endregion
public override bool IsInstalled()
{
string versionNumber = null;
RegistryKey HKLM = Registry.LocalMachine;
RegistryKey key = HKLM.OpenSubKey(@"SOFTWARE\MySQL AB\MySQL Server 4.1");
if (key != null)
{
versionNumber = (string)key.GetValue("Version");
}
else
{
key = HKLM.OpenSubKey(@"SOFTWARE\Wow6432Node\MySQL AB\MySQL Server 4.1");
if (key != null)
{
versionNumber = (string)key.GetValue("Version");
}
else
{
return false;
}
}
string[] split = versionNumber.Split(new char[] { '.' });
return split[0].Equals("4");
}
}
}
| |
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:2.0.50727.1434
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace WebsitePanel.Portal.VPS {
public partial class VpsDetailsConfiguration {
/// <summary>
/// asyncTasks control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.EnableAsyncTasksSupport asyncTasks;
/// <summary>
/// breadcrumb control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.VPS.UserControls.Breadcrumb breadcrumb;
/// <summary>
/// menu control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.VPS.UserControls.Menu menu;
/// <summary>
/// imgIcon control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Image imgIcon;
/// <summary>
/// locTitle control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.VPS.UserControls.FormTitle locTitle;
/// <summary>
/// tabs control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.VPS.UserControls.ServerTabs tabs;
/// <summary>
/// messageBox control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.UserControls.SimpleMessageBox messageBox;
/// <summary>
/// secSoftware control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.CollapsiblePanel secSoftware;
/// <summary>
/// SoftwarePanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel SoftwarePanel;
/// <summary>
/// locOperatingSystem control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locOperatingSystem;
/// <summary>
/// litOperatingSystem control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal litOperatingSystem;
/// <summary>
/// locAdministratorPassword control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locAdministratorPassword;
/// <summary>
/// btnChangePasswordPopup control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.LinkButton btnChangePasswordPopup;
/// <summary>
/// secResources control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.CollapsiblePanel secResources;
/// <summary>
/// ResourcesPanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel ResourcesPanel;
/// <summary>
/// lblCpu control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize lblCpu;
/// <summary>
/// litCpu control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal litCpu;
/// <summary>
/// lblRam control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize lblRam;
/// <summary>
/// litRam control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal litRam;
/// <summary>
/// lblHdd control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize lblHdd;
/// <summary>
/// litHdd control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal litHdd;
/// <summary>
/// secSnapshots control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.CollapsiblePanel secSnapshots;
/// <summary>
/// SnapshotsPanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel SnapshotsPanel;
/// <summary>
/// locSnapshots control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locSnapshots;
/// <summary>
/// litSnapshots control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal litSnapshots;
/// <summary>
/// secDvd control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.CollapsiblePanel secDvd;
/// <summary>
/// DvdPanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel DvdPanel;
/// <summary>
/// optionDvdInstalled control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.UserControls.CheckBoxOption optionDvdInstalled;
/// <summary>
/// secBios control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.CollapsiblePanel secBios;
/// <summary>
/// BiosPanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel BiosPanel;
/// <summary>
/// optionBootFromCD control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.UserControls.CheckBoxOption optionBootFromCD;
/// <summary>
/// optionNumLock control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.UserControls.CheckBoxOption optionNumLock;
/// <summary>
/// secActions control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.CollapsiblePanel secActions;
/// <summary>
/// ActionsPanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel ActionsPanel;
/// <summary>
/// optionStartShutdown control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.UserControls.CheckBoxOption optionStartShutdown;
/// <summary>
/// optionReset control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.UserControls.CheckBoxOption optionReset;
/// <summary>
/// optionPauseResume control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.UserControls.CheckBoxOption optionPauseResume;
/// <summary>
/// optionReinstall control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.UserControls.CheckBoxOption optionReinstall;
/// <summary>
/// optionReboot control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.UserControls.CheckBoxOption optionReboot;
/// <summary>
/// secNetwork control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.CollapsiblePanel secNetwork;
/// <summary>
/// NetworkPanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel NetworkPanel;
/// <summary>
/// optionExternalNetwork control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.UserControls.CheckBoxOption optionExternalNetwork;
/// <summary>
/// optionPrivateNetwork control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.UserControls.CheckBoxOption optionPrivateNetwork;
/// <summary>
/// btnEdit control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button btnEdit;
/// <summary>
/// FormComments control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize FormComments;
/// <summary>
/// ChangePasswordPanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel ChangePasswordPanel;
/// <summary>
/// locChangePassword control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locChangePassword;
/// <summary>
/// locNewPassword control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locNewPassword;
/// <summary>
/// password control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.PasswordControl password;
/// <summary>
/// btnChangePassword control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button btnChangePassword;
/// <summary>
/// btnCancelChangePassword control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button btnCancelChangePassword;
/// <summary>
/// ChangePasswordModal control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::AjaxControlToolkit.ModalPopupExtender ChangePasswordModal;
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Dispatcher
{
using System.Runtime;
using System.Xml;
using System.Xml.XPath;
#if NO
//
// A message is just one more source of Xml data. To filter a message, we create a navigator over it that
// surfaces its contained Xml to the filter engine.
// In M5.1, we navigate messages by first writing them into a message document. This turns the message into an
// Xml DOM. we then get a navigator from the DOM.
// In M5.2, we'll navigate messages without requiring this step.
//
internal class MessageNavigator : GenericSeekableNavigator
{
StringBuilder builder;
int headerCollectionVersion;
bool loaded;
bool navigatesBody;
internal MessageNavigator(MessageNavigator nav)
: base(nav)
{
this.headerCollectionVersion = nav.headerCollectionVersion;
this.loaded = nav.loaded;
this.navigatesBody = nav.navigatesBody;
}
internal MessageNavigator(Message message, bool navigateBody)
: base()
{
this.navigatesBody = navigateBody;
this.Load(message, this.navigatesBody);
}
internal bool IsLoaded
{
get
{
return this.loaded;
}
}
internal bool NavigatesBody
{
get
{
return this.navigatesBody;
}
}
internal override void Clear()
{
base.Clear();
this.loaded = false;
this.navigatesBody = false;
}
public override XPathNavigator Clone()
{
return new MessageNavigator(this);
}
internal MessageNavigator Ensure(Message message, bool navigateBody)
{
// Rebuild the navigator if:
// If this navigator does not navigate on bodies and now we need to (or vice versa)
// Or the header collection changed under us
if (this.navigatesBody != navigateBody || message.Headers.CollectionVersion != this.headerCollectionVersion)
{
this.Load(message, navigateBody);
}
else
{
this.MoveToRoot();
}
return this;
}
// To load a message into a message document, we write the message into a buffer and then let XPathDocument
// load that buffer
internal void Load(Message message, bool navigatesBody)
{
if (null == this.builder)
{
this.builder = new StringBuilder(1024);
}
StringWriter stringWriter = new StringWriter(this.builder);
XmlWriter writer = new XmlTextWriter(stringWriter);
message.WriteMessage(writer, navigatesBody);
writer.Close();
StringReader reader = new StringReader(this.builder.ToString());
XPathDocument messageDoc = new XPathDocument(reader);
reader.Close();
this.builder.Length = 0;
this.Init(messageDoc.CreateNavigator());
this.loaded = true;
this.navigatesBody = navigatesBody;
this.headerCollectionVersion = message.Headers.CollectionVersion;
}
}
#endif
// To prevent XPaths from running forever etc, users can specify limits on:
// the # of nodes a filter or filter table should inspect
//
// This file contains navigators that impose these limits
internal interface INodeCounter
{
int CounterMarker { get; set; }
int MaxCounter { set; }
int ElapsedCount(int marker);
void Increase();
void IncreaseBy(int count);
}
internal class DummyNodeCounter : INodeCounter
{
internal static DummyNodeCounter Dummy = new DummyNodeCounter();
public int CounterMarker
{
get { return 0; }
set { }
}
public int MaxCounter
{
set { }
}
public int ElapsedCount(int marker) { return 0; }
public void Increase() { }
public void IncreaseBy(int count) { }
}
/// <summary>
/// Seekable navigators that wrap other navigators and doesn't exceed node counting limits
/// </summary>
internal class SafeSeekableNavigator : SeekableXPathNavigator, INodeCounter
{
SeekableXPathNavigator navigator;
SafeSeekableNavigator counter;
int nodeCount;
int nodeCountMax;
internal SafeSeekableNavigator(SafeSeekableNavigator nav)
{
this.navigator = (SeekableXPathNavigator)nav.navigator.Clone();
this.counter = nav.counter;
}
internal SafeSeekableNavigator(SeekableXPathNavigator navigator, int nodeCountMax)
{
this.navigator = navigator;
this.counter = this;
this.nodeCount = nodeCountMax;
this.nodeCountMax = nodeCountMax;
}
public override string BaseURI
{
get
{
return this.navigator.BaseURI;
}
}
public int CounterMarker
{
get
{
return this.counter.nodeCount;
}
set
{
this.counter.nodeCount = value;
}
}
public int MaxCounter
{
set
{
this.counter.nodeCountMax = value;
}
}
/// <summary>
/// Setting the current position moves this navigator to the location specified by the given position
/// </summary>
public override long CurrentPosition
{
get
{
return this.navigator.CurrentPosition;
}
set
{
this.navigator.CurrentPosition = value;
}
}
public override bool HasAttributes
{
get
{
return this.navigator.HasAttributes;
}
}
public override bool HasChildren
{
get
{
return this.navigator.HasChildren;
}
}
public override bool IsEmptyElement
{
get
{
return this.navigator.IsEmptyElement;
}
}
public override string LocalName
{
get
{
return this.navigator.LocalName;
}
}
public override string Name
{
get
{
return this.navigator.Name;
}
}
public override string NamespaceURI
{
get
{
return this.navigator.NamespaceURI;
}
}
public override XmlNameTable NameTable
{
get
{
return this.navigator.NameTable;
}
}
public override XPathNodeType NodeType
{
get
{
return this.navigator.NodeType;
}
}
public override string Prefix
{
get
{
return this.navigator.Prefix;
}
}
public override string Value
{
get
{
return this.navigator.Value;
}
}
public override string XmlLang
{
get
{
return this.navigator.XmlLang;
}
}
public override XPathNavigator Clone()
{
return new SafeSeekableNavigator(this);
}
#if NO
internal SafeNavigator CreateSafeXPathNavigator()
{
return new SafeNavigator(this, this.navigator);
}
#endif
public override XmlNodeOrder ComparePosition(XPathNavigator navigator)
{
if (navigator == null)
{
return XmlNodeOrder.Unknown;
}
SafeSeekableNavigator nav = navigator as SafeSeekableNavigator;
if (nav != null)
{
return this.navigator.ComparePosition(nav.navigator);
}
return XmlNodeOrder.Unknown;
}
public override XmlNodeOrder ComparePosition(long x, long y)
{
return this.navigator.ComparePosition(x, y);
}
public int ElapsedCount(int marker)
{
return marker - this.counter.nodeCount;
}
public override string GetLocalName(long nodePosition)
{
return this.navigator.GetLocalName(nodePosition);
}
public override string GetName(long nodePosition)
{
return this.navigator.GetName(nodePosition);
}
public override string GetNamespace(long nodePosition)
{
return this.navigator.GetNamespace(nodePosition);
}
public override XPathNodeType GetNodeType(long nodePosition)
{
return this.navigator.GetNodeType(nodePosition);
}
public override string GetValue(long nodePosition)
{
return this.navigator.GetValue(nodePosition);
}
public override string GetNamespace(string name)
{
this.IncrementNodeCount();
return this.navigator.GetNamespace(name);
}
public override string GetAttribute(string localName, string namespaceURI)
{
this.IncrementNodeCount();
return this.navigator.GetAttribute(localName, namespaceURI);
}
public void Increase()
{
this.IncrementNodeCount();
}
public void IncreaseBy(int count)
{
this.counter.nodeCount -= (count - 1);
Increase();
}
internal void IncrementNodeCount()
{
if (this.counter.nodeCount > 0)
{
this.counter.nodeCount--;
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XPathNavigatorException(SR.GetString(SR.FilterNodeQuotaExceeded, this.counter.nodeCountMax)));
}
}
#if NO
internal virtual void Init(SeekableXPathNavigator navigator, int nodeCountMax)
{
this.navigator = navigator;
this.nodeCount = nodeCountMax;
this.counter = this;
}
#endif
public override bool IsDescendant(XPathNavigator navigator)
{
if (navigator == null)
{
return false;
}
SafeSeekableNavigator nav = navigator as SafeSeekableNavigator;
if (nav != null)
{
return this.navigator.IsDescendant(nav.navigator);
}
return false;
}
public override bool IsSamePosition(XPathNavigator other)
{
if (other == null)
{
return false;
}
SafeSeekableNavigator nav = other as SafeSeekableNavigator;
if (nav != null)
{
return this.navigator.IsSamePosition(nav.navigator);
}
return false;
}
public override void MoveToRoot()
{
this.IncrementNodeCount();
this.navigator.MoveToRoot();
}
public override bool MoveToNextNamespace(XPathNamespaceScope namespaceScope)
{
this.IncrementNodeCount();
return this.navigator.MoveToNextNamespace(namespaceScope);
}
public override bool MoveToNextAttribute()
{
this.IncrementNodeCount();
return this.navigator.MoveToNextAttribute();
}
public override bool MoveToPrevious()
{
this.IncrementNodeCount();
return this.navigator.MoveToPrevious();
}
public override bool MoveToFirstAttribute()
{
this.IncrementNodeCount();
return this.navigator.MoveToFirstAttribute();
}
public override bool MoveToNamespace(string name)
{
this.IncrementNodeCount();
return this.navigator.MoveToNamespace(name);
}
public override bool MoveToParent()
{
this.IncrementNodeCount();
return this.navigator.MoveToParent();
}
public override bool MoveTo(XPathNavigator other)
{
if (other == null)
{
return false;
}
this.IncrementNodeCount();
SafeSeekableNavigator nav = other as SafeSeekableNavigator;
if (nav != null)
{
return this.navigator.MoveTo(nav.navigator);
}
return false;
}
public override bool MoveToId(string id)
{
this.IncrementNodeCount();
return this.navigator.MoveToId(id);
}
public override bool MoveToFirstChild()
{
this.IncrementNodeCount();
return this.navigator.MoveToFirstChild();
}
public override bool MoveToFirstNamespace(XPathNamespaceScope namespaceScope)
{
this.IncrementNodeCount();
return this.navigator.MoveToFirstNamespace(namespaceScope);
}
public override bool MoveToAttribute(string localName, string namespaceURI)
{
this.IncrementNodeCount();
return this.navigator.MoveToAttribute(localName, namespaceURI);
}
public override bool MoveToNext()
{
this.IncrementNodeCount();
return this.navigator.MoveToNext();
}
public override bool MoveToFirst()
{
this.IncrementNodeCount();
return this.navigator.MoveToFirst();
}
}
/// <summary>
/// The filter engine works with seekable navigators. This class takes a generic XPathNavigator implementation
/// and transforms it into a seekable navigator. Seekable navigators associate a 'position' to every node in a DOM.
///
/// This class maintains a (position, navigator) map. Cloning navigators is unavoidable - XPathNavigator offers
/// no other way to snapshot its current position. However, caching allows memory allocations to be avoided - but
/// only once the navigator is warmed up.
/// </summary>
internal class GenericSeekableNavigator : SeekableXPathNavigator
{
QueryBuffer<XPathNavigator> nodes;
long currentPosition;
XPathNavigator navigator;
GenericSeekableNavigator dom;
#if NO
internal GenericSeekableNavigator()
{
this.nodes = new QueryBuffer<XPathNavigator>(4);
this.currentPosition = -1;
}
#endif
internal GenericSeekableNavigator(XPathNavigator navigator)
{
this.navigator = navigator;
this.nodes = new QueryBuffer<XPathNavigator>(4);
this.currentPosition = -1;
this.dom = this;
}
internal GenericSeekableNavigator(GenericSeekableNavigator navigator)
{
this.navigator = navigator.navigator.Clone();
this.nodes = default(QueryBuffer<XPathNavigator>);
this.currentPosition = navigator.currentPosition;
this.dom = navigator.dom;
}
public override string BaseURI
{
get
{
return this.navigator.BaseURI;
}
}
public override bool HasAttributes
{
get
{
return this.navigator.HasAttributes;
}
}
public override bool HasChildren
{
get
{
return this.navigator.HasChildren;
}
}
#if NO
internal XPathNavigator InternalNavigator
{
get
{
return this.navigator;
}
}
#endif
public override bool IsEmptyElement
{
get
{
return this.navigator.IsEmptyElement;
}
}
public override string LocalName
{
get
{
return this.navigator.LocalName;
}
}
public override string Name
{
get
{
return this.navigator.Name;
}
}
public override string NamespaceURI
{
get
{
return this.navigator.NamespaceURI;
}
}
public override XmlNameTable NameTable
{
get
{
return this.navigator.NameTable;
}
}
public override XPathNodeType NodeType
{
get
{
return this.navigator.NodeType;
}
}
public override string Prefix
{
get
{
return this.navigator.Prefix;
}
}
public override string Value
{
get
{
return this.navigator.Value;
}
}
public override string XmlLang
{
get
{
return this.navigator.XmlLang;
}
}
/// <summary>
/// Setting the current position moves this navigator to the location specified by the given position
/// </summary>
public override long CurrentPosition
{
get
{
if (-1 == this.currentPosition)
{
this.SnapshotNavigator();
}
return this.currentPosition;
}
set
{
this.navigator.MoveTo(this[value]);
this.currentPosition = value;
}
}
/// <summary>
/// Return the XPathNavigator that has the given position
/// </summary>
internal XPathNavigator this[long nodePosition]
{
get
{
int pos = (int)nodePosition;
Fx.Assert(this.dom.nodes.IsValidIndex(pos) && null != this.dom.nodes[pos], "");
return this.dom.nodes[pos];
}
}
#if NO
internal virtual void Clear()
{
this.navigator = null;
this.currentPosition = -1;
}
#endif
public override XPathNavigator Clone()
{
return new GenericSeekableNavigator(this);
}
public override XmlNodeOrder ComparePosition(XPathNavigator navigator)
{
if (navigator == null)
{
return XmlNodeOrder.Unknown;
}
GenericSeekableNavigator nav = navigator as GenericSeekableNavigator;
if (nav != null)
{
return this.navigator.ComparePosition(nav.navigator);
}
return XmlNodeOrder.Unknown;
}
public override XmlNodeOrder ComparePosition(long x, long y)
{
XPathNavigator nodeX = this[x];
XPathNavigator nodeY = this[y];
return nodeX.ComparePosition(nodeY);
}
public override string GetLocalName(long nodePosition)
{
return this[nodePosition].LocalName;
}
public override string GetName(long nodePosition)
{
return this[nodePosition].Name;
}
public override string GetNamespace(long nodePosition)
{
return this[nodePosition].NamespaceURI;
}
public override XPathNodeType GetNodeType(long nodePosition)
{
return this[nodePosition].NodeType;
}
public override string GetValue(long nodePosition)
{
return this[nodePosition].Value;
}
public override string GetNamespace(string name)
{
return this.navigator.GetNamespace(name);
}
public override string GetAttribute(string localName, string namespaceURI)
{
return this.navigator.GetAttribute(localName, namespaceURI);
}
#if NO
internal void Init(XPathNavigator navigator)
{
Fx.Assert(null != navigator, "");
this.navigator = navigator;
this.currentPosition = -1;
}
#endif
public override bool IsDescendant(XPathNavigator navigator)
{
if (navigator == null)
{
return false;
}
GenericSeekableNavigator nav = navigator as GenericSeekableNavigator;
if (null != nav)
{
return this.navigator.IsDescendant(nav.navigator);
}
return false;
}
public override bool IsSamePosition(XPathNavigator other)
{
GenericSeekableNavigator nav = other as GenericSeekableNavigator;
if (null != nav)
{
return this.navigator.IsSamePosition(nav.navigator);
}
return false;
}
public override void MoveToRoot()
{
this.currentPosition = -1;
this.navigator.MoveToRoot();
}
public override bool MoveToNextNamespace(XPathNamespaceScope namespaceScope)
{
this.currentPosition = -1;
return this.navigator.MoveToNextNamespace(namespaceScope);
}
public override bool MoveToNextAttribute()
{
this.currentPosition = -1;
return this.navigator.MoveToNextAttribute();
}
public override bool MoveToPrevious()
{
this.currentPosition = -1;
return this.navigator.MoveToPrevious();
}
public override bool MoveToFirstAttribute()
{
this.currentPosition = -1;
return this.navigator.MoveToFirstAttribute();
}
public override bool MoveToNamespace(string name)
{
this.currentPosition = -1;
return this.navigator.MoveToNamespace(name);
}
public override bool MoveToParent()
{
this.currentPosition = -1;
return this.navigator.MoveToParent();
}
public override bool MoveTo(XPathNavigator other)
{
GenericSeekableNavigator nav = other as GenericSeekableNavigator;
if (null != nav)
{
if (this.navigator.MoveTo(nav.navigator))
{
this.currentPosition = nav.currentPosition;
return true;
}
}
return false;
}
public override bool MoveToId(string id)
{
this.currentPosition = -1;
return this.navigator.MoveToId(id);
}
public override bool MoveToFirstChild()
{
this.currentPosition = -1;
return this.navigator.MoveToFirstChild();
}
public override bool MoveToFirstNamespace(XPathNamespaceScope namespaceScope)
{
this.currentPosition = -1;
return this.navigator.MoveToFirstNamespace(namespaceScope);
}
public override bool MoveToAttribute(string localName, string namespaceURI)
{
this.currentPosition = -1;
return this.navigator.MoveToAttribute(localName, namespaceURI);
}
public override bool MoveToNext()
{
this.currentPosition = -1;
return this.navigator.MoveToNext();
}
public override bool MoveToFirst()
{
this.currentPosition = -1;
return this.navigator.MoveToFirst();
}
internal void SnapshotNavigator()
{
this.currentPosition = this.dom.nodes.Count;
this.dom.nodes.Add(this.navigator.Clone());
/*
if (this.currentPosition < this.nodes.Count)
{
// Use a cached navigator
XPathNavigator clonedNavigator = this.nodes[(int)this.currentPosition];
Fx.Assert(null != clonedNavigator, "");
clonedNavigator.MoveTo(this);
}
else
{
this.nodes.Add(this.navigator.Clone());
}
*/
}
#region IQueryBufferPool Members
#if NO
/// <summary>
/// Reset the pool by deleting it entirely and starting it over
/// </summary>
public void Reset()
{
this.nodes.count = 0;
this.nodes.TrimToCount();
}
public void Trim()
{
this.nodes.TrimToCount();
}
#endif
#endregion
}
}
| |
using NUnit.Framework;
using VkNet.Enums.Filters;
namespace VkNet.Tests.Enum.SafetyEnums
{
[TestFixture]
public class MultivaluedFilterTest
{
[Test]
public void AccountFieldsTest()
{
// get test
Assert.That(actual: AccountFields.Country.ToString(), expression: Is.EqualTo(expected: "country"));
Assert.That(actual: AccountFields.HttpsRequired.ToString(), expression: Is.EqualTo(expected: "https_required"));
Assert.That(actual: AccountFields.OwnPostsDefault.ToString(), expression: Is.EqualTo(expected: "own_posts_default"));
Assert.That(actual: AccountFields.NoWallReplies.ToString(), expression: Is.EqualTo(expected: "no_wall_replies"));
Assert.That(actual: AccountFields.Intro.ToString(), expression: Is.EqualTo(expected: "intro"));
Assert.That(actual: AccountFields.Language.ToString(), expression: Is.EqualTo(expected: "lang"));
// parse test
Assert.That(actual: AccountFields.FromJsonString(val: "country"), expression: Is.EqualTo(expected: AccountFields.Country));
Assert.That(actual: AccountFields.FromJsonString(val: "https_required")
, expression: Is.EqualTo(expected: AccountFields.HttpsRequired));
Assert.That(actual: AccountFields.FromJsonString(val: "own_posts_default")
, expression: Is.EqualTo(expected: AccountFields.OwnPostsDefault));
Assert.That(actual: AccountFields.FromJsonString(val: "no_wall_replies")
, expression: Is.EqualTo(expected: AccountFields.NoWallReplies));
Assert.That(actual: AccountFields.FromJsonString(val: "intro"), expression: Is.EqualTo(expected: AccountFields.Intro));
Assert.That(actual: AccountFields.FromJsonString(val: "lang"), expression: Is.EqualTo(expected: AccountFields.Language));
}
[Test]
public void CountersFilterTest()
{
// get test
Assert.That(actual: CountersFilter.Friends.ToString(), expression: Is.EqualTo(expected: "friends"));
Assert.That(actual: CountersFilter.Messages.ToString(), expression: Is.EqualTo(expected: "messages"));
Assert.That(actual: CountersFilter.Photos.ToString(), expression: Is.EqualTo(expected: "photos"));
Assert.That(actual: CountersFilter.Videos.ToString(), expression: Is.EqualTo(expected: "videos"));
Assert.That(actual: CountersFilter.Gifts.ToString(), expression: Is.EqualTo(expected: "gifts"));
Assert.That(actual: CountersFilter.Events.ToString(), expression: Is.EqualTo(expected: "events"));
Assert.That(actual: CountersFilter.Groups.ToString(), expression: Is.EqualTo(expected: "groups"));
Assert.That(actual: CountersFilter.Notifications.ToString(), expression: Is.EqualTo(expected: "notifications"));
Assert.That(actual: CountersFilter.All.ToString()
, expression: Is.EqualTo(expected:
"app_requests,events,friends,friends_suggestions,gifts,groups,messages,notifications,photos,sdk,videos"));
// parse test
Assert.That(actual: CountersFilter.FromJsonString(val: "friends"), expression: Is.EqualTo(expected: CountersFilter.Friends));
Assert.That(actual: CountersFilter.FromJsonString(val: "messages"), expression: Is.EqualTo(expected: CountersFilter.Messages));
Assert.That(actual: CountersFilter.FromJsonString(val: "photos"), expression: Is.EqualTo(expected: CountersFilter.Photos));
Assert.That(actual: CountersFilter.FromJsonString(val: "videos"), expression: Is.EqualTo(expected: CountersFilter.Videos));
Assert.That(actual: CountersFilter.FromJsonString(val: "gifts"), expression: Is.EqualTo(expected: CountersFilter.Gifts));
Assert.That(actual: CountersFilter.FromJsonString(val: "events"), expression: Is.EqualTo(expected: CountersFilter.Events));
Assert.That(actual: CountersFilter.FromJsonString(val: "groups"), expression: Is.EqualTo(expected: CountersFilter.Groups));
Assert.That(actual: CountersFilter.FromJsonString(val: "notifications")
, expression: Is.EqualTo(expected: CountersFilter.Notifications));
Assert.That(actual: CountersFilter.FromJsonString(
val: "app_requests,events,friends,friends_suggestions,gifts,groups,messages,notifications,photos,sdk,videos")
, expression: Is.EqualTo(expected: CountersFilter.All));
}
[Test]
public void GroupsFieldsTest()
{
// get test
Assert.That(actual: GroupsFields.CityId.ToString(), expression: Is.EqualTo(expected: "city"));
Assert.That(actual: GroupsFields.CountryId.ToString(), expression: Is.EqualTo(expected: "country"));
Assert.That(actual: GroupsFields.Place.ToString(), expression: Is.EqualTo(expected: "place"));
Assert.That(actual: GroupsFields.Description.ToString(), expression: Is.EqualTo(expected: "description"));
Assert.That(actual: GroupsFields.WikiPage.ToString(), expression: Is.EqualTo(expected: "wiki_page"));
Assert.That(actual: GroupsFields.MembersCount.ToString(), expression: Is.EqualTo(expected: "members_count"));
Assert.That(actual: GroupsFields.Counters.ToString(), expression: Is.EqualTo(expected: "counters"));
Assert.That(actual: GroupsFields.StartDate.ToString(), expression: Is.EqualTo(expected: "start_date"));
Assert.That(actual: GroupsFields.EndDate.ToString(), expression: Is.EqualTo(expected: "finish_date"));
Assert.That(actual: GroupsFields.CanPost.ToString(), expression: Is.EqualTo(expected: "can_post"));
Assert.That(actual: GroupsFields.CanSeelAllPosts.ToString(), expression: Is.EqualTo(expected: "can_see_all_posts"));
Assert.That(actual: GroupsFields.CanUploadDocuments.ToString(), expression: Is.EqualTo(expected: "can_upload_doc"));
Assert.That(actual: GroupsFields.CanCreateTopic.ToString(), expression: Is.EqualTo(expected: "can_create_topic"));
Assert.That(actual: GroupsFields.Activity.ToString(), expression: Is.EqualTo(expected: "activity"));
Assert.That(actual: GroupsFields.Status.ToString(), expression: Is.EqualTo(expected: "status"));
Assert.That(actual: GroupsFields.Contacts.ToString(), expression: Is.EqualTo(expected: "contacts"));
Assert.That(actual: GroupsFields.Links.ToString(), expression: Is.EqualTo(expected: "links"));
Assert.That(actual: GroupsFields.FixedPostId.ToString(), expression: Is.EqualTo(expected: "fixed_post"));
Assert.That(actual: GroupsFields.IsVerified.ToString(), expression: Is.EqualTo(expected: "verified"));
Assert.That(actual: GroupsFields.Site.ToString(), expression: Is.EqualTo(expected: "site"));
Assert.That(actual: GroupsFields.BanInfo.ToString(), expression: Is.EqualTo(expected: "ban_info"));
Assert.That(actual: GroupsFields.All.ToString()
, expression: Is.EqualTo(expected:
"activity,ban_info,can_create_topic,can_post,can_see_all_posts,city,contacts,counters,country,description,finish_date,fixed_post,links,members_count,place,site,start_date,status,verified,wiki_page"));
Assert.That(actual: GroupsFields.AllUndocumented.ToString()
, expression: Is.EqualTo(expected:
"activity,ban_info,can_create_topic,can_post,can_see_all_posts,can_upload_doc,city,contacts,counters,country,description,finish_date,fixed_post,links,members_count,place,site,start_date,status,verified,wiki_page"));
// parse test
Assert.That(actual: GroupsFields.FromJsonString(val: "city"), expression: Is.EqualTo(expected: GroupsFields.CityId));
Assert.That(actual: GroupsFields.FromJsonString(val: "country"), expression: Is.EqualTo(expected: GroupsFields.CountryId));
Assert.That(actual: GroupsFields.FromJsonString(val: "place"), expression: Is.EqualTo(expected: GroupsFields.Place));
Assert.That(actual: GroupsFields.FromJsonString(val: "description")
, expression: Is.EqualTo(expected: GroupsFields.Description));
Assert.That(actual: GroupsFields.FromJsonString(val: "wiki_page"), expression: Is.EqualTo(expected: GroupsFields.WikiPage));
Assert.That(actual: GroupsFields.FromJsonString(val: "members_count")
, expression: Is.EqualTo(expected: GroupsFields.MembersCount));
Assert.That(actual: GroupsFields.FromJsonString(val: "counters"), expression: Is.EqualTo(expected: GroupsFields.Counters));
Assert.That(actual: GroupsFields.FromJsonString(val: "start_date"), expression: Is.EqualTo(expected: GroupsFields.StartDate));
Assert.That(actual: GroupsFields.FromJsonString(val: "finish_date"), expression: Is.EqualTo(expected: GroupsFields.EndDate));
Assert.That(actual: GroupsFields.FromJsonString(val: "can_post"), expression: Is.EqualTo(expected: GroupsFields.CanPost));
Assert.That(actual: GroupsFields.FromJsonString(val: "can_see_all_posts")
, expression: Is.EqualTo(expected: GroupsFields.CanSeelAllPosts));
Assert.That(actual: GroupsFields.FromJsonString(val: "can_upload_doc")
, expression: Is.EqualTo(expected: GroupsFields.CanUploadDocuments));
Assert.That(actual: GroupsFields.FromJsonString(val: "can_create_topic")
, expression: Is.EqualTo(expected: GroupsFields.CanCreateTopic));
Assert.That(actual: GroupsFields.FromJsonString(val: "activity"), expression: Is.EqualTo(expected: GroupsFields.Activity));
Assert.That(actual: GroupsFields.FromJsonString(val: "status"), expression: Is.EqualTo(expected: GroupsFields.Status));
Assert.That(actual: GroupsFields.FromJsonString(val: "contacts"), expression: Is.EqualTo(expected: GroupsFields.Contacts));
Assert.That(actual: GroupsFields.FromJsonString(val: "links"), expression: Is.EqualTo(expected: GroupsFields.Links));
Assert.That(actual: GroupsFields.FromJsonString(val: "fixed_post"), expression: Is.EqualTo(expected: GroupsFields.FixedPostId));
Assert.That(actual: GroupsFields.FromJsonString(val: "verified"), expression: Is.EqualTo(expected: GroupsFields.IsVerified));
Assert.That(actual: GroupsFields.FromJsonString(val: "site"), expression: Is.EqualTo(expected: GroupsFields.Site));
Assert.That(actual: GroupsFields.FromJsonString(val: "ban_info"), expression: Is.EqualTo(expected: GroupsFields.BanInfo));
Assert.That(actual: GroupsFields.FromJsonString(val:
"activity,ban_info,can_create_topic,can_post,can_see_all_posts,city,contacts,counters,country,description,finish_date,fixed_post,links,members_count,place,site,start_date,status,verified,wiki_page")
, expression: Is.EqualTo(expected: GroupsFields.All));
Assert.That(actual: GroupsFields.FromJsonString(val:
"activity,ban_info,can_create_topic,can_post,can_see_all_posts,can_upload_doc,city,contacts,counters,country,description,finish_date,fixed_post,links,members_count,place,site,start_date,status,verified,wiki_page")
, expression: Is.EqualTo(expected: GroupsFields.AllUndocumented));
}
[Test]
public void GroupsFiltersTest()
{
// get test
Assert.That(actual: GroupsFilters.Administrator.ToString(), expression: Is.EqualTo(expected: "admin"));
Assert.That(actual: GroupsFilters.Editor.ToString(), expression: Is.EqualTo(expected: "editor"));
Assert.That(actual: GroupsFilters.Moderator.ToString(), expression: Is.EqualTo(expected: "moder"));
Assert.That(actual: GroupsFilters.Groups.ToString(), expression: Is.EqualTo(expected: "groups"));
Assert.That(actual: GroupsFilters.Publics.ToString(), expression: Is.EqualTo(expected: "publics"));
Assert.That(actual: GroupsFilters.Events.ToString(), expression: Is.EqualTo(expected: "events"));
Assert.That(actual: GroupsFilters.All.ToString(), expression: Is.EqualTo(expected: "admin,editor,events,groups,moder,publics"));
// parse test
Assert.That(actual: GroupsFilters.FromJsonString(val: "admin"), expression: Is.EqualTo(expected: GroupsFilters.Administrator));
Assert.That(actual: GroupsFilters.FromJsonString(val: "editor"), expression: Is.EqualTo(expected: GroupsFilters.Editor));
Assert.That(actual: GroupsFilters.FromJsonString(val: "moder"), expression: Is.EqualTo(expected: GroupsFilters.Moderator));
Assert.That(actual: GroupsFilters.FromJsonString(val: "groups"), expression: Is.EqualTo(expected: GroupsFilters.Groups));
Assert.That(actual: GroupsFilters.FromJsonString(val: "publics"), expression: Is.EqualTo(expected: GroupsFilters.Publics));
Assert.That(actual: GroupsFilters.FromJsonString(val: "events"), expression: Is.EqualTo(expected: GroupsFilters.Events));
Assert.That(actual: GroupsFilters.FromJsonString(val: "admin,editor,moder,groups,publics,events")
, expression: Is.EqualTo(expected: GroupsFilters.All));
}
[Test]
public void SubscribeFilterTest()
{
// get test
Assert.That(actual: SubscribeFilter.Message.ToString(), expression: Is.EqualTo(expected: "msg"));
Assert.That(actual: SubscribeFilter.Friend.ToString(), expression: Is.EqualTo(expected: "friend"));
Assert.That(actual: SubscribeFilter.Call.ToString(), expression: Is.EqualTo(expected: "call"));
Assert.That(actual: SubscribeFilter.Reply.ToString(), expression: Is.EqualTo(expected: "reply"));
Assert.That(actual: SubscribeFilter.Mention.ToString(), expression: Is.EqualTo(expected: "mention"));
Assert.That(actual: SubscribeFilter.Group.ToString(), expression: Is.EqualTo(expected: "group"));
Assert.That(actual: SubscribeFilter.Like.ToString(), expression: Is.EqualTo(expected: "like"));
Assert.That(actual: SubscribeFilter.All.ToString()
, expression: Is.EqualTo(expected: "call,friend,group,like,mention,msg,reply"));
// parse test
Assert.That(actual: SubscribeFilter.FromJsonString(val: "msg"), expression: Is.EqualTo(expected: SubscribeFilter.Message));
Assert.That(actual: SubscribeFilter.FromJsonString(val: "friend"), expression: Is.EqualTo(expected: SubscribeFilter.Friend));
Assert.That(actual: SubscribeFilter.FromJsonString(val: "call"), expression: Is.EqualTo(expected: SubscribeFilter.Call));
Assert.That(actual: SubscribeFilter.FromJsonString(val: "reply"), expression: Is.EqualTo(expected: SubscribeFilter.Reply));
Assert.That(actual: SubscribeFilter.FromJsonString(val: "mention"), expression: Is.EqualTo(expected: SubscribeFilter.Mention));
Assert.That(actual: SubscribeFilter.FromJsonString(val: "group"), expression: Is.EqualTo(expected: SubscribeFilter.Group));
Assert.That(actual: SubscribeFilter.FromJsonString(val: "like"), expression: Is.EqualTo(expected: SubscribeFilter.Like));
Assert.That(actual: SubscribeFilter.FromJsonString(val: "msg,friend,call,reply,mention,group,like")
, expression: Is.EqualTo(expected: SubscribeFilter.All));
}
[Test]
public void UsersFieldsTest()
{
// get test
Assert.That(actual: UsersFields.Nickname.ToString(), expression: Is.EqualTo(expected: "nickname"));
Assert.That(actual: UsersFields.Domain.ToString(), expression: Is.EqualTo(expected: "domain"));
Assert.That(actual: UsersFields.Sex.ToString(), expression: Is.EqualTo(expected: "sex"));
Assert.That(actual: UsersFields.BirthDate.ToString(), expression: Is.EqualTo(expected: "bdate"));
Assert.That(actual: UsersFields.City.ToString(), expression: Is.EqualTo(expected: "city"));
Assert.That(actual: UsersFields.Country.ToString(), expression: Is.EqualTo(expected: "country"));
Assert.That(actual: UsersFields.Timezone.ToString(), expression: Is.EqualTo(expected: "timezone"));
Assert.That(actual: UsersFields.Photo50.ToString(), expression: Is.EqualTo(expected: "photo_50"));
Assert.That(actual: UsersFields.Photo100.ToString(), expression: Is.EqualTo(expected: "photo_100"));
Assert.That(actual: UsersFields.Photo200Orig.ToString(), expression: Is.EqualTo(expected: "photo_200_orig"));
Assert.That(actual: UsersFields.Photo200.ToString(), expression: Is.EqualTo(expected: "photo_200"));
Assert.That(actual: UsersFields.Photo400Orig.ToString(), expression: Is.EqualTo(expected: "photo_400_orig"));
Assert.That(actual: UsersFields.PhotoMax.ToString(), expression: Is.EqualTo(expected: "photo_max"));
Assert.That(actual: UsersFields.PhotoMaxOrig.ToString(), expression: Is.EqualTo(expected: "photo_max_orig"));
Assert.That(actual: UsersFields.HasMobile.ToString(), expression: Is.EqualTo(expected: "has_mobile"));
Assert.That(actual: UsersFields.Contacts.ToString(), expression: Is.EqualTo(expected: "contacts"));
Assert.That(actual: UsersFields.Education.ToString(), expression: Is.EqualTo(expected: "education"));
Assert.That(actual: UsersFields.Online.ToString(), expression: Is.EqualTo(expected: "online"));
Assert.That(actual: UsersFields.OnlineMobile.ToString(), expression: Is.EqualTo(expected: "online_mobile"));
Assert.That(actual: UsersFields.FriendLists.ToString(), expression: Is.EqualTo(expected: "lists"));
Assert.That(actual: UsersFields.Relation.ToString(), expression: Is.EqualTo(expected: "relation"));
Assert.That(actual: UsersFields.LastSeen.ToString(), expression: Is.EqualTo(expected: "last_seen"));
Assert.That(actual: UsersFields.Status.ToString(), expression: Is.EqualTo(expected: "status"));
Assert.That(actual: UsersFields.CanWritePrivateMessage.ToString()
, expression: Is.EqualTo(expected: "can_write_private_message"));
Assert.That(actual: UsersFields.CanSeeAllPosts.ToString(), expression: Is.EqualTo(expected: "can_see_all_posts"));
Assert.That(actual: UsersFields.CanPost.ToString(), expression: Is.EqualTo(expected: "can_post"));
Assert.That(actual: UsersFields.Universities.ToString(), expression: Is.EqualTo(expected: "universities"));
Assert.That(actual: UsersFields.Connections.ToString(), expression: Is.EqualTo(expected: "connections"));
Assert.That(actual: UsersFields.Site.ToString(), expression: Is.EqualTo(expected: "site"));
Assert.That(actual: UsersFields.Schools.ToString(), expression: Is.EqualTo(expected: "schools"));
Assert.That(actual: UsersFields.CanSeeAudio.ToString(), expression: Is.EqualTo(expected: "can_see_audio"));
Assert.That(actual: UsersFields.CommonCount.ToString(), expression: Is.EqualTo(expected: "common_count"));
Assert.That(actual: UsersFields.Relatives.ToString(), expression: Is.EqualTo(expected: "relatives"));
Assert.That(actual: UsersFields.Counters.ToString(), expression: Is.EqualTo(expected: "counters"));
Assert.That(actual: UsersFields.All.ToString()
, expression: Is.EqualTo(expected:
"bdate,can_post,can_see_all_posts,can_see_audio,can_write_private_message,city,common_count,connections,contacts,counters,country,domain,education,has_mobile,last_seen,lists,nickname,online,online_mobile,photo_100,photo_200,photo_200_orig,photo_400_orig,photo_50,photo_max,photo_max_orig,relation,relatives,schools,sex,site,status,timezone,universities"));
// parse test
Assert.That(actual: UsersFields.FromJsonString(val: "nickname"), expression: Is.EqualTo(expected: UsersFields.Nickname));
Assert.That(actual: UsersFields.FromJsonString(val: "domain"), expression: Is.EqualTo(expected: UsersFields.Domain));
Assert.That(actual: UsersFields.FromJsonString(val: "sex"), expression: Is.EqualTo(expected: UsersFields.Sex));
Assert.That(actual: UsersFields.FromJsonString(val: "bdate"), expression: Is.EqualTo(expected: UsersFields.BirthDate));
Assert.That(actual: UsersFields.FromJsonString(val: "city"), expression: Is.EqualTo(expected: UsersFields.City));
Assert.That(actual: UsersFields.FromJsonString(val: "country"), expression: Is.EqualTo(expected: UsersFields.Country));
Assert.That(actual: UsersFields.FromJsonString(val: "timezone"), expression: Is.EqualTo(expected: UsersFields.Timezone));
Assert.That(actual: UsersFields.FromJsonString(val: "photo_50"), expression: Is.EqualTo(expected: UsersFields.Photo50));
Assert.That(actual: UsersFields.FromJsonString(val: "photo_100"), expression: Is.EqualTo(expected: UsersFields.Photo100));
Assert.That(actual: UsersFields.FromJsonString(val: "photo_200_orig")
, expression: Is.EqualTo(expected: UsersFields.Photo200Orig));
Assert.That(actual: UsersFields.FromJsonString(val: "photo_200"), expression: Is.EqualTo(expected: UsersFields.Photo200));
Assert.That(actual: UsersFields.FromJsonString(val: "photo_400_orig")
, expression: Is.EqualTo(expected: UsersFields.Photo400Orig));
Assert.That(actual: UsersFields.FromJsonString(val: "photo_max"), expression: Is.EqualTo(expected: UsersFields.PhotoMax));
Assert.That(actual: UsersFields.FromJsonString(val: "photo_max_orig")
, expression: Is.EqualTo(expected: UsersFields.PhotoMaxOrig));
Assert.That(actual: UsersFields.FromJsonString(val: "has_mobile"), expression: Is.EqualTo(expected: UsersFields.HasMobile));
Assert.That(actual: UsersFields.FromJsonString(val: "contacts"), expression: Is.EqualTo(expected: UsersFields.Contacts));
Assert.That(actual: UsersFields.FromJsonString(val: "education"), expression: Is.EqualTo(expected: UsersFields.Education));
Assert.That(actual: UsersFields.FromJsonString(val: "online"), expression: Is.EqualTo(expected: UsersFields.Online));
Assert.That(actual: UsersFields.FromJsonString(val: "online_mobile")
, expression: Is.EqualTo(expected: UsersFields.OnlineMobile));
Assert.That(actual: UsersFields.FromJsonString(val: "lists"), expression: Is.EqualTo(expected: UsersFields.FriendLists));
Assert.That(actual: UsersFields.FromJsonString(val: "relation"), expression: Is.EqualTo(expected: UsersFields.Relation));
Assert.That(actual: UsersFields.FromJsonString(val: "last_seen"), expression: Is.EqualTo(expected: UsersFields.LastSeen));
Assert.That(actual: UsersFields.FromJsonString(val: "status"), expression: Is.EqualTo(expected: UsersFields.Status));
Assert.That(actual: UsersFields.FromJsonString(val: "can_write_private_message")
, expression: Is.EqualTo(expected: UsersFields.CanWritePrivateMessage));
Assert.That(actual: UsersFields.FromJsonString(val: "can_see_all_posts")
, expression: Is.EqualTo(expected: UsersFields.CanSeeAllPosts));
Assert.That(actual: UsersFields.FromJsonString(val: "can_post"), expression: Is.EqualTo(expected: UsersFields.CanPost));
Assert.That(actual: UsersFields.FromJsonString(val: "universities")
, expression: Is.EqualTo(expected: UsersFields.Universities));
Assert.That(actual: UsersFields.FromJsonString(val: "connections"), expression: Is.EqualTo(expected: UsersFields.Connections));
Assert.That(actual: UsersFields.FromJsonString(val: "site"), expression: Is.EqualTo(expected: UsersFields.Site));
Assert.That(actual: UsersFields.FromJsonString(val: "schools"), expression: Is.EqualTo(expected: UsersFields.Schools));
Assert.That(actual: UsersFields.FromJsonString(val: "can_see_audio")
, expression: Is.EqualTo(expected: UsersFields.CanSeeAudio));
Assert.That(actual: UsersFields.FromJsonString(val: "common_count"), expression: Is.EqualTo(expected: UsersFields.CommonCount));
Assert.That(actual: UsersFields.FromJsonString(val: "relatives"), expression: Is.EqualTo(expected: UsersFields.Relatives));
Assert.That(actual: UsersFields.FromJsonString(val: "counters"), expression: Is.EqualTo(expected: UsersFields.Counters));
Assert.That(actual: UsersFields.FromJsonString(val:
"nickname,domain,sex,bdate,city,country,timezone,photo_50,photo_100,photo_200_orig,photo_200,photo_400_orig,photo_max,photo_max_orig,has_mobile,contacts,education,online,online_mobile,lists,relation,last_seen,status,can_write_private_message,can_see_all_posts,can_post,universities,connections,site,schools,can_see_audio,common_count,relatives,counters")
, expression: Is.EqualTo(expected: UsersFields.All));
}
[Test]
public void VideoFiltersTest()
{
// get test
Assert.That(actual: VideoFilters.Mp4.ToString(), expression: Is.EqualTo(expected: "mp4"));
Assert.That(actual: VideoFilters.Youtube.ToString(), expression: Is.EqualTo(expected: "youtube"));
Assert.That(actual: VideoFilters.Vimeo.ToString(), expression: Is.EqualTo(expected: "vimeo"));
Assert.That(actual: VideoFilters.Short.ToString(), expression: Is.EqualTo(expected: "short"));
Assert.That(actual: VideoFilters.Long.ToString(), expression: Is.EqualTo(expected: "long"));
Assert.That(actual: VideoFilters.All.ToString(), expression: Is.EqualTo(expected: "long,mp4,short,vimeo,youtube"));
// parse test
Assert.That(actual: VideoFilters.FromJsonString(val: "mp4"), expression: Is.EqualTo(expected: VideoFilters.Mp4));
Assert.That(actual: VideoFilters.FromJsonString(val: "youtube"), expression: Is.EqualTo(expected: VideoFilters.Youtube));
Assert.That(actual: VideoFilters.FromJsonString(val: "vimeo"), expression: Is.EqualTo(expected: VideoFilters.Vimeo));
Assert.That(actual: VideoFilters.FromJsonString(val: "short"), expression: Is.EqualTo(expected: VideoFilters.Short));
Assert.That(actual: VideoFilters.FromJsonString(val: "long"), expression: Is.EqualTo(expected: VideoFilters.Long));
Assert.That(actual: VideoFilters.FromJsonString(val: "mp4,youtube,vimeo,short,long")
, expression: Is.EqualTo(expected: VideoFilters.All));
}
}
}
| |
namespace DCalc.UI
{
partial class SettingsForm
{
/// <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()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(SettingsForm));
this.gbControl = new System.Windows.Forms.GroupBox();
this.edtCustomCount = new System.Windows.Forms.TextBox();
this.rbCustomCount = new System.Windows.Forms.RadioButton();
this.rbProcCountThreads = new System.Windows.Forms.RadioButton();
this.rbSingleThread = new System.Windows.Forms.RadioButton();
this.edtQueueSize = new System.Windows.Forms.TextBox();
this.cbbLocalLoadBalancer = new System.Windows.Forms.ComboBox();
this.cbbRemoteLoadBalancer = new System.Windows.Forms.ComboBox();
this.lbExecutiveQueue = new System.Windows.Forms.Label();
this.lbRemoteLoadBalancer = new System.Windows.Forms.Label();
this.lbLocalLoadBalancer = new System.Windows.Forms.Label();
this.btAccept = new System.Windows.Forms.Button();
this.btCancel = new System.Windows.Forms.Button();
this.gbControl.SuspendLayout();
this.SuspendLayout();
//
// gbControl
//
this.gbControl.Controls.Add(this.edtCustomCount);
this.gbControl.Controls.Add(this.rbCustomCount);
this.gbControl.Controls.Add(this.rbProcCountThreads);
this.gbControl.Controls.Add(this.rbSingleThread);
this.gbControl.Controls.Add(this.edtQueueSize);
this.gbControl.Controls.Add(this.cbbLocalLoadBalancer);
this.gbControl.Controls.Add(this.cbbRemoteLoadBalancer);
this.gbControl.Controls.Add(this.lbExecutiveQueue);
this.gbControl.Controls.Add(this.lbRemoteLoadBalancer);
this.gbControl.Controls.Add(this.lbLocalLoadBalancer);
this.gbControl.Location = new System.Drawing.Point(1, -1);
this.gbControl.Name = "gbControl";
this.gbControl.Size = new System.Drawing.Size(309, 190);
this.gbControl.TabIndex = 0;
this.gbControl.TabStop = false;
this.gbControl.Text = "Dispatcher Setup";
//
// edtCustomCount
//
this.edtCustomCount.Location = new System.Drawing.Point(196, 162);
this.edtCustomCount.Name = "edtCustomCount";
this.edtCustomCount.Size = new System.Drawing.Size(72, 20);
this.edtCustomCount.TabIndex = 6;
this.edtCustomCount.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
this.edtCustomCount.TextChanged += new System.EventHandler(this.edtQueueSize_TextChanged);
this.edtCustomCount.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.all_KeyPress);
//
// rbCustomCount
//
this.rbCustomCount.AutoSize = true;
this.rbCustomCount.Location = new System.Drawing.Point(9, 163);
this.rbCustomCount.Name = "rbCustomCount";
this.rbCustomCount.Size = new System.Drawing.Size(187, 17);
this.rbCustomCount.TabIndex = 5;
this.rbCustomCount.TabStop = true;
this.rbCustomCount.Text = "Spawn a c&ustom count of threads:";
this.rbCustomCount.UseVisualStyleBackColor = true;
this.rbCustomCount.CheckedChanged += new System.EventHandler(this.rbCustomCount_CheckedChanged);
//
// rbProcCountThreads
//
this.rbProcCountThreads.AutoSize = true;
this.rbProcCountThreads.Location = new System.Drawing.Point(9, 145);
this.rbProcCountThreads.Name = "rbProcCountThreads";
this.rbProcCountThreads.Size = new System.Drawing.Size(244, 17);
this.rbProcCountThreads.TabIndex = 4;
this.rbProcCountThreads.TabStop = true;
this.rbProcCountThreads.Text = "Spawn a thread on &each locally available CPU";
this.rbProcCountThreads.UseVisualStyleBackColor = true;
//
// rbSingleThread
//
this.rbSingleThread.AutoSize = true;
this.rbSingleThread.Location = new System.Drawing.Point(9, 128);
this.rbSingleThread.Name = "rbSingleThread";
this.rbSingleThread.Size = new System.Drawing.Size(174, 17);
this.rbSingleThread.TabIndex = 3;
this.rbSingleThread.TabStop = true;
this.rbSingleThread.Text = "Spawn one &single thread locally";
this.rbSingleThread.UseVisualStyleBackColor = true;
//
// edtQueueSize
//
this.edtQueueSize.Location = new System.Drawing.Point(127, 100);
this.edtQueueSize.Name = "edtQueueSize";
this.edtQueueSize.Size = new System.Drawing.Size(72, 20);
this.edtQueueSize.TabIndex = 2;
this.edtQueueSize.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
this.edtQueueSize.TextChanged += new System.EventHandler(this.edtQueueSize_TextChanged);
this.edtQueueSize.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.all_KeyPress);
//
// cbbLocalLoadBalancer
//
this.cbbLocalLoadBalancer.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cbbLocalLoadBalancer.FormattingEnabled = true;
this.cbbLocalLoadBalancer.Location = new System.Drawing.Point(9, 32);
this.cbbLocalLoadBalancer.Name = "cbbLocalLoadBalancer";
this.cbbLocalLoadBalancer.Size = new System.Drawing.Size(294, 21);
this.cbbLocalLoadBalancer.TabIndex = 0;
this.cbbLocalLoadBalancer.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.all_KeyPress);
//
// cbbRemoteLoadBalancer
//
this.cbbRemoteLoadBalancer.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cbbRemoteLoadBalancer.FormattingEnabled = true;
this.cbbRemoteLoadBalancer.Location = new System.Drawing.Point(9, 72);
this.cbbRemoteLoadBalancer.Name = "cbbRemoteLoadBalancer";
this.cbbRemoteLoadBalancer.Size = new System.Drawing.Size(294, 21);
this.cbbRemoteLoadBalancer.TabIndex = 1;
this.cbbRemoteLoadBalancer.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.all_KeyPress);
//
// lbExecutiveQueue
//
this.lbExecutiveQueue.AutoSize = true;
this.lbExecutiveQueue.Location = new System.Drawing.Point(6, 103);
this.lbExecutiveQueue.Name = "lbExecutiveQueue";
this.lbExecutiveQueue.Size = new System.Drawing.Size(115, 13);
this.lbExecutiveQueue.TabIndex = 2;
this.lbExecutiveQueue.Text = "Executive Queue Size:";
//
// lbRemoteLoadBalancer
//
this.lbRemoteLoadBalancer.AutoSize = true;
this.lbRemoteLoadBalancer.Location = new System.Drawing.Point(6, 56);
this.lbRemoteLoadBalancer.Name = "lbRemoteLoadBalancer";
this.lbRemoteLoadBalancer.Size = new System.Drawing.Size(210, 13);
this.lbRemoteLoadBalancer.TabIndex = 1;
this.lbRemoteLoadBalancer.Text = "Load Balancer between all executive units:";
//
// lbLocalLoadBalancer
//
this.lbLocalLoadBalancer.AutoSize = true;
this.lbLocalLoadBalancer.Location = new System.Drawing.Point(6, 16);
this.lbLocalLoadBalancer.Name = "lbLocalLoadBalancer";
this.lbLocalLoadBalancer.Size = new System.Drawing.Size(193, 13);
this.lbLocalLoadBalancer.TabIndex = 0;
this.lbLocalLoadBalancer.Text = "Load bancer between local processors:";
//
// btAccept
//
this.btAccept.Location = new System.Drawing.Point(235, 195);
this.btAccept.Name = "btAccept";
this.btAccept.Size = new System.Drawing.Size(75, 23);
this.btAccept.TabIndex = 1;
this.btAccept.Text = "&Accept";
this.btAccept.UseVisualStyleBackColor = true;
this.btAccept.Click += new System.EventHandler(this.btAccept_Click);
//
// btCancel
//
this.btCancel.Location = new System.Drawing.Point(156, 195);
this.btCancel.Name = "btCancel";
this.btCancel.Size = new System.Drawing.Size(75, 23);
this.btCancel.TabIndex = 2;
this.btCancel.Text = "&Cancel";
this.btCancel.UseVisualStyleBackColor = true;
this.btCancel.Click += new System.EventHandler(this.btCancel_Click);
//
// SettingsForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(310, 220);
this.Controls.Add(this.btCancel);
this.Controls.Add(this.btAccept);
this.Controls.Add(this.gbControl);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "SettingsForm";
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Configure Execution Options";
this.gbControl.ResumeLayout(false);
this.gbControl.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.GroupBox gbControl;
private System.Windows.Forms.TextBox edtQueueSize;
private System.Windows.Forms.ComboBox cbbLocalLoadBalancer;
private System.Windows.Forms.ComboBox cbbRemoteLoadBalancer;
private System.Windows.Forms.Label lbExecutiveQueue;
private System.Windows.Forms.Label lbRemoteLoadBalancer;
private System.Windows.Forms.Label lbLocalLoadBalancer;
private System.Windows.Forms.Button btAccept;
private System.Windows.Forms.Button btCancel;
private System.Windows.Forms.RadioButton rbProcCountThreads;
private System.Windows.Forms.RadioButton rbSingleThread;
private System.Windows.Forms.TextBox edtCustomCount;
private System.Windows.Forms.RadioButton rbCustomCount;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.ComponentModel.Composition.Primitives;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using Microsoft.Internal;
namespace System.ComponentModel.Composition.Hosting
{
/// <summary>
/// A mutable collection of <see cref="ComposablePartCatalog"/>s.
/// </summary>
/// <remarks>
/// This type is thread safe.
/// </remarks>
public class AggregateCatalog : ComposablePartCatalog, INotifyComposablePartCatalogChanged
{
private readonly ComposablePartCatalogCollection _catalogs = null;
private volatile int _isDisposed = 0;
/// <summary>
/// Initializes a new instance of the <see cref="AggregateCatalog"/> class.
/// </summary>
public AggregateCatalog()
: this((IEnumerable<ComposablePartCatalog>)null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="AggregateCatalog"/> class
/// with the specified catalogs.
/// </summary>
/// <param name="catalogs">
/// An <see cref="Array"/> of <see cref="ComposablePartCatalog"/> objects to add to the
/// <see cref="AggregateCatalog"/>.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="catalogs"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="catalogs"/> contains an element that is <see langword="null"/>.
/// </exception>
public AggregateCatalog(params ComposablePartCatalog[] catalogs)
: this((IEnumerable<ComposablePartCatalog>)catalogs)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="AggregateCatalog"/> class
/// with the specified catalogs.
/// </summary>
/// <param name="catalogs">
/// An <see cref="IEnumerable{T}"/> of <see cref="ComposablePartCatalog"/> objects to add
/// to the <see cref="AggregateCatalog"/>; or <see langword="null"/> to
/// create an <see cref="AggregateCatalog"/> that is empty.
/// </param>
/// <exception cref="ArgumentException">
/// <paramref name="catalogs"/> contains an element that is <see langword="null"/>.
/// </exception>
public AggregateCatalog(IEnumerable<ComposablePartCatalog> catalogs)
{
Requires.NullOrNotNullElements(catalogs, nameof(catalogs));
_catalogs = new ComposablePartCatalogCollection(catalogs, OnChanged, OnChanging);
}
/// <summary>
/// Notify when the contents of the Catalog has changed.
/// </summary>
public event EventHandler<ComposablePartCatalogChangeEventArgs> Changed
{
add
{
_catalogs.Changed += value;
}
remove
{
_catalogs.Changed -= value;
}
}
/// <summary>
/// Notify when the contents of the Catalog has changing.
/// </summary>
public event EventHandler<ComposablePartCatalogChangeEventArgs> Changing
{
add
{
_catalogs.Changing += value;
}
remove
{
_catalogs.Changing -= value;
}
}
/// <summary>
/// Returns the export definitions that match the constraint defined by the specified definition.
/// </summary>
/// <param name="definition">
/// The <see cref="ImportDefinition"/> that defines the conditions of the
/// <see cref="ExportDefinition"/> objects to return.
/// </param>
/// <returns>
/// An <see cref="IEnumerable{T}"/> of <see cref="Tuple{T1, T2}"/> containing the
/// <see cref="ExportDefinition"/> objects and their associated
/// <see cref="ComposablePartDefinition"/> for objects that match the constraint defined
/// by <paramref name="definition"/>.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="definition"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The <see cref="AggregateCatalog"/> has been disposed of.
/// </exception>
public override IEnumerable<Tuple<ComposablePartDefinition, ExportDefinition>> GetExports(ImportDefinition definition)
{
ThrowIfDisposed();
Requires.NotNull(definition, nameof(definition));
// We optimize for the case where the result is comparible with the requested cardinality, though we do remain correct in all cases.
// We do so to avoid any unnecessary allocations
IEnumerable<Tuple<ComposablePartDefinition, ExportDefinition>> result = null;
List<Tuple<ComposablePartDefinition, ExportDefinition>> aggregateResult = null;
foreach (var catalog in _catalogs)
{
var catalogExports = catalog.GetExports(definition);
if (catalogExports != ComposablePartCatalog._EmptyExportsList)
{
// ideally this is the case we will always hit
if (result == null)
{
result = catalogExports;
}
else
{
// sadly the result has already been assigned, which means we are in the aggregate case
if (aggregateResult == null)
{
aggregateResult = new List<Tuple<ComposablePartDefinition, ExportDefinition>>(result);
result = aggregateResult;
}
aggregateResult.AddRange(catalogExports);
}
}
}
return result ?? ComposablePartCatalog._EmptyExportsList;
}
/// <summary>
/// Gets the underlying catalogs of the catalog.
/// </summary>
/// <value>
/// An <see cref="ICollection{T}"/> of underlying <see cref="ComposablePartCatalog"/> objects
/// of the <see cref="AggregateCatalog"/>.
/// </value>
/// <exception cref="ObjectDisposedException">
/// The <see cref="AggregateCatalog"/> has been disposed of.
/// </exception>
public ICollection<ComposablePartCatalog> Catalogs
{
get
{
ThrowIfDisposed();
Debug.Assert(_catalogs != null);
return _catalogs;
}
}
protected override void Dispose(bool disposing)
{
try
{
if (disposing)
{
if (Interlocked.CompareExchange(ref _isDisposed, 1, 0) == 0)
{
_catalogs.Dispose();
}
}
}
finally
{
base.Dispose(disposing);
}
}
public override IEnumerator<ComposablePartDefinition> GetEnumerator()
{
return _catalogs.SelectMany(catalog => catalog).GetEnumerator();
}
/// <summary>
/// Raises the <see cref="INotifyComposablePartCatalogChanged.Changed"/> event.
/// </summary>
/// <param name="e">
/// An <see cref="ComposablePartCatalogChangeEventArgs"/> containing the data for the event.
/// </param>
protected virtual void OnChanged(ComposablePartCatalogChangeEventArgs e)
{
_catalogs.OnChanged(this, e);
}
/// <summary>
/// Raises the <see cref="INotifyComposablePartCatalogChanged.Changing"/> event.
/// </summary>
/// <param name="e">
/// An <see cref="ComposablePartCatalogChangeEventArgs"/> containing the data for the event.
/// </param>
protected virtual void OnChanging(ComposablePartCatalogChangeEventArgs e)
{
_catalogs.OnChanging(this, e);
}
[DebuggerStepThrough]
private void ThrowIfDisposed()
{
if (_isDisposed == 1)
{
throw ExceptionBuilder.CreateObjectDisposed(this);
}
}
}
}
| |
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Xml;
using Avalonia.Controls;
using Avalonia.Markup.Xaml.Styling;
using Avalonia.Markup.Xaml.Templates;
using Avalonia.Media;
using Avalonia.Styling;
using Avalonia.UnitTests;
using Xunit;
namespace Avalonia.Markup.Xaml.UnitTests.Xaml
{
public class StyleTests : XamlTestBase
{
[Fact]
public void Color_Can_Be_Added_To_Style_Resources()
{
using (UnitTestApplication.Start(TestServices.MockPlatformWrapper))
{
var xaml = @"
<UserControl xmlns='https://github.com/avaloniaui'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
<UserControl.Styles>
<Style>
<Style.Resources>
<Color x:Key='color'>#ff506070</Color>
</Style.Resources>
</Style>
</UserControl.Styles>
</UserControl>";
var userControl = (UserControl)AvaloniaRuntimeXamlLoader.Load(xaml);
var color = (Color)((Style)userControl.Styles[0]).Resources["color"];
Assert.Equal(0xff506070, color.ToUint32());
}
}
[Fact]
public void DataTemplate_Can_Be_Added_To_Style_Resources()
{
using (UnitTestApplication.Start(TestServices.MockPlatformWrapper))
{
var xaml = @"
<UserControl xmlns='https://github.com/avaloniaui'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
<UserControl.Styles>
<Style>
<Style.Resources>
<DataTemplate x:Key='dataTemplate'><TextBlock/></DataTemplate>
</Style.Resources>
</Style>
</UserControl.Styles>
</UserControl>";
var userControl = (UserControl)AvaloniaRuntimeXamlLoader.Load(xaml);
var dataTemplate = (DataTemplate)((Style)userControl.Styles[0]).Resources["dataTemplate"];
Assert.NotNull(dataTemplate);
}
}
[Fact]
public void ControlTemplate_Can_Be_Added_To_Style_Resources()
{
using (UnitTestApplication.Start(TestServices.MockPlatformWrapper))
{
var xaml = @"
<UserControl xmlns='https://github.com/avaloniaui'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
<UserControl.Styles>
<Style>
<Style.Resources>
<ControlTemplate x:Key='controlTemplate' TargetType='{x:Type Button}'>
<ContentPresenter Content='{TemplateBinding Content}'/>
</ControlTemplate>
</Style.Resources>
</Style>
</UserControl.Styles>
</UserControl>";
var userControl = (UserControl)AvaloniaRuntimeXamlLoader.Load(xaml);
var controlTemplate = (ControlTemplate)((Style)userControl.Styles[0]).Resources["controlTemplate"];
Assert.NotNull(controlTemplate);
Assert.Equal(typeof(Button), controlTemplate.TargetType);
}
}
[Fact]
public void SolidColorBrush_Can_Be_Added_To_Style_Resources()
{
using (UnitTestApplication.Start(TestServices.MockPlatformWrapper))
{
var xaml = @"
<UserControl xmlns='https://github.com/avaloniaui'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
<UserControl.Styles>
<Style>
<Style.Resources>
<SolidColorBrush x:Key='brush'>#ff506070</SolidColorBrush>
</Style.Resources>
</Style>
</UserControl.Styles>
</UserControl>";
var userControl = (UserControl)AvaloniaRuntimeXamlLoader.Load(xaml);
var brush = (ISolidColorBrush)((Style)userControl.Styles[0]).Resources["brush"];
Assert.Equal(0xff506070, brush.Color.ToUint32());
}
}
[Fact]
public void StyleInclude_Is_Built()
{
using (UnitTestApplication.Start(TestServices.StyledWindow
.With(theme: () => new Styles())))
{
var xaml = @"
<ContentControl xmlns='https://github.com/avaloniaui'>
<ContentControl.Styles>
<StyleInclude Source='resm:Avalonia.Markup.Xaml.UnitTests.Xaml.Style1.xaml?assembly=Avalonia.Markup.Xaml.UnitTests'/>
</ContentControl.Styles>
</ContentControl>";
var window = AvaloniaRuntimeXamlLoader.Parse<ContentControl>(xaml);
Assert.Single(window.Styles);
var styleInclude = window.Styles[0] as StyleInclude;
Assert.NotNull(styleInclude);
Assert.NotNull(styleInclude.Source);
Assert.NotNull(styleInclude.Loaded);
}
}
[Fact]
public void Setter_Can_Contain_Template()
{
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
var xaml = @"
<Window xmlns='https://github.com/avaloniaui'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
<Window.Styles>
<Style Selector='ContentControl'>
<Setter Property='Content'>
<Template>
<TextBlock>Hello World!</TextBlock>
</Template>
</Setter>
</Style>
</Window.Styles>
<ContentControl Name='target'/>
</Window>";
var window = (Window)AvaloniaRuntimeXamlLoader.Load(xaml);
var target = window.Find<ContentControl>("target");
Assert.IsType<TextBlock>(target.Content);
Assert.Equal("Hello World!", ((TextBlock)target.Content).Text);
}
}
[Fact]
public void Setter_Value_Is_Bound_Directly_If_The_Target_Type_Derives_From_ITemplate()
{
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
var xaml = @"
<Window xmlns='https://github.com/avaloniaui'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
<Window.Styles>
<Style Selector=':is(Control)'>
<Setter Property='FocusAdorner'>
<FocusAdornerTemplate>
<Rectangle Stroke='Black'
StrokeThickness='1'
StrokeDashArray='1,2'/>
</FocusAdornerTemplate>
</Setter>
</Style>
</Window.Styles>
<TextBlock Name='target'/>
</Window>";
var window = (Window)AvaloniaRuntimeXamlLoader.Load(xaml);
var target = window.Find<TextBlock>("target");
Assert.NotNull(target.FocusAdorner);
}
}
[Fact]
public void Setter_Can_Set_Attached_Property()
{
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
var xaml = @"
<Window xmlns='https://github.com/avaloniaui'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
xmlns:local='clr-namespace:Avalonia.Markup.Xaml.UnitTests.Xaml;assembly=Avalonia.Markup.Xaml.UnitTests'>
<Window.Styles>
<Style Selector='TextBlock'>
<Setter Property='DockPanel.Dock' Value='Right'/>
</Style>
</Window.Styles>
<TextBlock/>
</Window>";
var window = (Window)AvaloniaRuntimeXamlLoader.Load(xaml);
var textBlock = (TextBlock)window.Content;
window.ApplyTemplate();
Assert.Equal(Dock.Right, DockPanel.GetDock(textBlock));
}
}
[Fact(Skip = "The animation system currently needs to be able to set any property on any object")]
public void Disallows_Setting_Non_Registered_Property()
{
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
var xaml = @"
<Window xmlns='https://github.com/avaloniaui'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
xmlns:local='clr-namespace:Avalonia.Markup.Xaml.UnitTests.Xaml;assembly=Avalonia.Markup.Xaml.UnitTests'>
<Window.Styles>
<Style Selector='TextBlock'>
<Setter Property='Button.IsDefault' Value='True'/>
</Style>
</Window.Styles>
<TextBlock/>
</Window>";
var ex = Assert.Throws<XmlException>(() => AvaloniaRuntimeXamlLoader.Load(xaml));
Assert.Equal(
"Property 'Button.IsDefault' is not registered on 'Avalonia.Controls.TextBlock'.",
ex.InnerException.Message);
}
}
[Fact]
public void Style_Can_Use_Not_Selector()
{
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
var xaml = @"
<Window xmlns='https://github.com/avaloniaui'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
<Window.Styles>
<Style Selector='Border:not(.foo)'>
<Setter Property='Background' Value='Red'/>
</Style>
</Window.Styles>
<StackPanel>
<Border Name='foo' Classes='foo bar'/>
<Border Name='notFoo' Classes='bar'/>
</StackPanel>
</Window>";
var window = (Window)AvaloniaRuntimeXamlLoader.Load(xaml);
var foo = window.FindControl<Border>("foo");
var notFoo = window.FindControl<Border>("notFoo");
Assert.Null(foo.Background);
Assert.Equal(Colors.Red, ((ISolidColorBrush)notFoo.Background).Color);
}
}
[Fact]
public void Style_Can_Use_NthChild_Selector()
{
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
var xaml = @"
<Window xmlns='https://github.com/avaloniaui'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
<Window.Styles>
<Style Selector='Border.foo:nth-child(2n+1)'>
<Setter Property='Background' Value='Red'/>
</Style>
</Window.Styles>
<StackPanel>
<Border x:Name='b1' Classes='foo'/>
<Border x:Name='b2' />
</StackPanel>
</Window>";
var window = (Window)AvaloniaRuntimeXamlLoader.Load(xaml);
var b1 = window.FindControl<Border>("b1");
var b2 = window.FindControl<Border>("b2");
Assert.Equal(Brushes.Red, b1.Background);
Assert.Null(b2.Background);
}
}
[Fact]
public void Style_Can_Use_NthChild_Selector_After_Reoder()
{
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
var xaml = @"
<Window xmlns='https://github.com/avaloniaui'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
<Window.Styles>
<Style Selector='Border:nth-child(2n)'>
<Setter Property='Background' Value='Red'/>
</Style>
</Window.Styles>
<StackPanel x:Name='parent'>
<Border x:Name='b1' />
<Border x:Name='b2' />
</StackPanel>
</Window>";
var window = (Window)AvaloniaRuntimeXamlLoader.Load(xaml);
var parent = window.FindControl<StackPanel>("parent");
var b1 = window.FindControl<Border>("b1");
var b2 = window.FindControl<Border>("b2");
Assert.Null(b1.Background);
Assert.Equal(Brushes.Red, b2.Background);
parent.Children.Remove(b1);
Assert.Null(b1.Background);
Assert.Null(b2.Background);
parent.Children.Add(b1);
Assert.Equal(Brushes.Red, b1.Background);
Assert.Null(b2.Background);
}
}
[Fact]
public void Style_Can_Use_NthLastChild_Selector_After_Reoder()
{
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
var xaml = @"
<Window xmlns='https://github.com/avaloniaui'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
<Window.Styles>
<Style Selector='Border:nth-last-child(2n)'>
<Setter Property='Background' Value='Red'/>
</Style>
</Window.Styles>
<StackPanel x:Name='parent'>
<Border x:Name='b1' />
<Border x:Name='b2' />
</StackPanel>
</Window>";
var window = (Window)AvaloniaRuntimeXamlLoader.Load(xaml);
var parent = window.FindControl<StackPanel>("parent");
var b1 = window.FindControl<Border>("b1");
var b2 = window.FindControl<Border>("b2");
Assert.Equal(Brushes.Red, b1.Background);
Assert.Null(b2.Background);
parent.Children.Remove(b1);
Assert.Null(b1.Background);
Assert.Null(b2.Background);
parent.Children.Add(b1);
Assert.Null(b1.Background);
Assert.Equal(Brushes.Red, b2.Background);
}
}
[Fact]
public void Style_Can_Use_NthChild_Selector_With_ListBox()
{
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
var xaml = @"
<Window xmlns='https://github.com/avaloniaui'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
<Window.Styles>
<Style Selector='ListBoxItem:nth-child(2n)'>
<Setter Property='Background' Value='{Binding}'/>
</Style>
</Window.Styles>
<ListBox x:Name='list' />
</Window>";
var window = (Window)AvaloniaRuntimeXamlLoader.Load(xaml);
var collection = new ObservableCollection<IBrush>()
{
Brushes.Red, Brushes.Green, Brushes.Blue
};
var list = window.FindControl<ListBox>("list");
list.VirtualizationMode = ItemVirtualizationMode.Simple;
list.Items = collection;
window.Show();
IEnumerable<IBrush> GetColors() => list.Presenter.Panel.Children.Cast<ListBoxItem>().Select(t => t.Background);
Assert.Equal(new[] { Brushes.Transparent, Brushes.Green, Brushes.Transparent }, GetColors());
collection.Remove(Brushes.Green);
Assert.Equal(new[] { Brushes.Transparent, Brushes.Blue }, GetColors());
collection.Add(Brushes.Violet);
collection.Add(Brushes.Black);
Assert.Equal(new[] { Brushes.Transparent, Brushes.Blue, Brushes.Transparent, Brushes.Black }, GetColors());
}
}
[Fact]
public void Style_Can_Use_NthChild_Selector_With_ItemsRepeater()
{
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
var xaml = @"
<Window xmlns='https://github.com/avaloniaui'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
<Window.Styles>
<Style Selector='TextBlock'>
<Setter Property='Foreground' Value='Transparent'/>
</Style>
<Style Selector='TextBlock:nth-child(2n)'>
<Setter Property='Foreground' Value='{Binding}'/>
</Style>
</Window.Styles>
<ItemsRepeater x:Name='list' />
</Window>";
var window = (Window)AvaloniaRuntimeXamlLoader.Load(xaml);
var collection = new ObservableCollection<IBrush>()
{
Brushes.Red, Brushes.Green, Brushes.Blue
};
var list = window.FindControl<ItemsRepeater>("list");
list.Items = collection;
window.Show();
IEnumerable<IBrush> GetColors() => Enumerable.Range(0, list.ItemsSourceView.Count)
.Select(t => (list.GetOrCreateElement(t) as TextBlock)!.Foreground);
Assert.Equal(new[] { Brushes.Transparent, Brushes.Green, Brushes.Transparent }, GetColors());
collection.Remove(Brushes.Green);
Assert.Equal(new[] { Brushes.Transparent, Brushes.Blue }, GetColors());
collection.Add(Brushes.Violet);
collection.Add(Brushes.Black);
Assert.Equal(new[] { Brushes.Transparent, Brushes.Blue, Brushes.Transparent, Brushes.Black }, GetColors());
}
}
[Fact]
public void Style_Can_Use_Or_Selector_1()
{
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
var xaml = @"
<Window xmlns='https://github.com/avaloniaui'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
<Window.Styles>
<Style Selector='Border.foo, Border.bar'>
<Setter Property='Background' Value='Red'/>
</Style>
</Window.Styles>
<StackPanel>
<Border Name='foo' Classes='foo'/>
<Border Name='bar' Classes='bar'/>
<Border Name='baz' Classes='baz'/>
</StackPanel>
</Window>";
var window = (Window)AvaloniaRuntimeXamlLoader.Load(xaml);
var foo = window.FindControl<Border>("foo");
var bar = window.FindControl<Border>("bar");
var baz = window.FindControl<Border>("baz");
Assert.Equal(Brushes.Red, foo.Background);
Assert.Equal(Brushes.Red, bar.Background);
Assert.Null(baz.Background);
}
}
[Fact]
public void Style_Can_Use_Or_Selector_2()
{
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
var xaml = @"
<Window xmlns='https://github.com/avaloniaui'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
<Window.Styles>
<Style Selector='Button,Carousel,ListBox'>
<Setter Property='Background' Value='Red'/>
</Style>
</Window.Styles>
<StackPanel>
<Button Name='button'/>
<Carousel Name='carousel'/>
<ListBox Name='listBox'/>
</StackPanel>
</Window>";
var window = (Window)AvaloniaRuntimeXamlLoader.Load(xaml);
var button = window.FindControl<Button>("button");
var carousel = window.FindControl<Carousel>("carousel");
var listBox = window.FindControl<ListBox>("listBox");
Assert.Equal(Brushes.Red, button.Background);
Assert.Equal(Brushes.Red, carousel.Background);
Assert.Equal(Brushes.Red, listBox.Background);
}
}
[Fact]
public void Transitions_Can_Be_Styled()
{
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
var xaml = @"
<Window xmlns='https://github.com/avaloniaui'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
<Window.Styles>
<Style Selector='Border'>
<Setter Property='Transitions'>
<Transitions>
<DoubleTransition Property='Width' Duration='0:0:1'/>
</Transitions>
</Setter>
</Style>
<Style Selector='Border.foo'>
<Setter Property='Transitions'>
<Transitions>
<DoubleTransition Property='Height' Duration='0:0:1'/>
</Transitions>
</Setter>
</Style>
</Window.Styles>
<Border/>
</Window>";
var window = (Window)AvaloniaRuntimeXamlLoader.Load(xaml);
var border = (Border)window.Content;
Assert.Equal(1, border.Transitions.Count);
Assert.Equal(Border.WidthProperty, border.Transitions[0].Property);
border.Classes.Add("foo");
Assert.Equal(1, border.Transitions.Count);
Assert.Equal(Border.HeightProperty, border.Transitions[0].Property);
border.Classes.Remove("foo");
Assert.Equal(1, border.Transitions.Count);
Assert.Equal(Border.WidthProperty, border.Transitions[0].Property);
}
}
[Fact]
public void Style_Can_Use_Class_Selector_With_Dash()
{
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
var xaml = @"
<Window xmlns='https://github.com/avaloniaui'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
<Window.Styles>
<Style Selector='Border.foo-bar'>
<Setter Property='Background' Value='Red'/>
</Style>
</Window.Styles>
<StackPanel>
<Border Name='foo' Classes='foo-bar'/>
</StackPanel>
</Window>";
var window = (Window)AvaloniaRuntimeXamlLoader.Load(xaml);
var foo = window.FindControl<Border>("foo");
Assert.Equal(Colors.Red, ((ISolidColorBrush)foo.Background).Color);
}
}
[Fact]
public void Style_Can_Use_Pseudolass_Selector_With_Dash()
{
using (UnitTestApplication.Start(TestServices.StyledWindow))
{
var xaml = @"
<Window xmlns='https://github.com/avaloniaui'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
<Window.Styles>
<Style Selector='Border:foo-bar'>
<Setter Property='Background' Value='Red'/>
</Style>
</Window.Styles>
<StackPanel>
<Border Name='foo'/>
</StackPanel>
</Window>";
var window = (Window)AvaloniaRuntimeXamlLoader.Load(xaml);
var foo = window.FindControl<Border>("foo");
Assert.Null(foo.Background);
((IPseudoClasses)foo.Classes).Add(":foo-bar");
Assert.Equal(Colors.Red, ((ISolidColorBrush)foo.Background).Color);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using T5CANLib;
using System.IO;
using System.Threading;
using System.Diagnostics;
using System.Linq;
using Microsoft.Win32;
namespace T5CanFlasher
{
public partial class frmMain : Form
{
T5CAN t5can;
T5CANLib.CAN.ICANDevice device;
Stopwatch stopwatch = new Stopwatch();
ECUType ECU_type = ECUType.Unknown;
string commlogFilename = Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData) + "\\commlog.txt";
private T5CanFlasher.Properties.Settings set = new T5CanFlasher.Properties.Settings();
public frmMain(string[] argv)
{
InitializeComponent();
manageControls(programMode.notconnected);
switch (set.AdapterType)
{
case "LAWICEL":
comboInterface.SelectedIndex = 0;
break;
case "COMBI":
comboInterface.SelectedIndex = 1;
break;
case "DIY":
comboInterface.SelectedIndex = 2;
break;
case "J4T":
comboInterface.SelectedIndex = 3;
break;
default:
comboInterface.SelectedIndex = 0;
break;
}
if (argv.Length > 0)
{
foreach (string arg in argv)
{
switch (arg)
{
case "LAWICEL":
comboInterface.SelectedIndex = 0;
break;
case "COMBI":
comboInterface.SelectedIndex = 1;
break;
case "DIY":
comboInterface.SelectedIndex = 2;
break;
case "J4T":
comboInterface.SelectedIndex = 3;
break;
default:
comboInterface.SelectedIndex = 0;
break;
}
}
}
else
{
LoadRegistrySettings();
}
}
// Load the Main form
private void frmMain_Load(object sender, EventArgs e)
{
//device.EnableLogging(Application.StartupPath);
manageControls(programMode.notconnected);
AddToLog("T5 CAN Flasher version: " + Application.ProductVersion.ToString());
t5can = new T5CAN();
t5can.onWriteProgress += new T5CAN.WriteProgress(t5can_onWriteProgress);
t5can.onCanInfo += new T5CAN.CanInfo(t5can_onCanInfo);
t5can.onBytesTransmitted += new T5CAN.BytesTransmitted(t5can_onBytesTransmitted);
Application.DoEvents();
// Wait for the Main form to load (before trying to connect to an ECU)
Application.Idle += new EventHandler(frmMain_Loaded);
//device.DisableLogging();
}
// Try to connect to ECU once the main form has loaded
private void frmMain_Loaded(object sender, EventArgs e)
{
Application.Idle -= new EventHandler(frmMain_Loaded);
Connect();
}
private void LoadRegistrySettings()
{
RegistryKey TempKey = Registry.CurrentUser.CreateSubKey("Software");
using (RegistryKey Settings = TempKey.CreateSubKey("T5CANFlasher"))
{
if (Settings != null)
{
string[] vals = Settings.GetValueNames();
foreach (string a in vals)
{
try
{
if (a == "AdapterType")
{
comboInterface.SelectedItem = Settings.GetValue(a).ToString();
}
else if (a == "EnableLogging")
{
cboxEnLog.Checked = Convert.ToBoolean(Settings.GetValue(a).ToString());
}
}
catch (Exception)
{
}
}
}
}
}
private static void SaveRegistrySetting(string key, string value)
{
RegistryKey TempKey = Registry.CurrentUser.CreateSubKey("Software");
using (RegistryKey saveSettings = TempKey.CreateSubKey("T5CANFlasher"))
{
saveSettings.SetValue(key, value);
}
}
private void SaveRegistrySetting(string key, bool value)
{
RegistryKey TempKey = Registry.CurrentUser.CreateSubKey("Software");
using (RegistryKey saveSettings = TempKey.CreateSubKey("T5CANFlasher"))
{
saveSettings.SetValue(key, value);
}
}
private void AddToLog(string item)
{
DateTime dt = DateTime.Now;
string line = dt.ToString("HH:mm:ss") + "." + dt.Millisecond.ToString("D3") + " - " + item;
listBox1.Items.Add(line);
listBox1.SelectedIndex = listBox1.Items.Count - 1;
using (StreamWriter sw = new StreamWriter(commlogFilename, true))
{
sw.WriteLine(line);
}
//while (listBox1.Items.Count > 5000) listBox1.Items.RemoveAt(0);
Application.DoEvents();
}
int last_progress = 0;
int delaycount = 0;
void t5can_onBytesTransmitted(object sender, WriteProgressEventArgs e)
{
if (stopwatch.ElapsedMilliseconds > 0)
{
int bytespersecond = (1000 * e.Percentage) / (int)stopwatch.ElapsedMilliseconds;
label2.Text = "Transmission speed: " + bytespersecond.ToString() + " B/s";
label1.Text = "Transferred: " + e.Percentage.ToString() + " Bytes";
// calculate ETA
// total amount to transfer = 100/percentage * bytetransferred
if (progressBar1.Value > 0)
{
if (progressBar1.Value != last_progress)
{
int totalbytes = (int)((float)((float)100 / (float)progressBar1.Value) * (float)e.Percentage);
// time remaining = (totalbytes - bytestranferred)/bytespersecond
int secondsleft = (totalbytes - e.Percentage) / bytespersecond;
int minutes = secondsleft / 60;
int seconds = secondsleft - (minutes * 60);
label3.Text = "Remaining time: " + minutes.ToString("D2") + ":" + seconds.ToString("D2");
last_progress = progressBar1.Value;
//Console.WriteLine("total bytes: " + totalbytes.ToString() + " seconds left: " + secondsleft.ToString() + " bytestransferred: :" + e.Percentage.ToString() + " bps: " + bytespersecond.ToString());
//if ((delaycount++ % 10) == 0)
{
Application.DoEvents();
}
}
else if ((delaycount++ % 10) == 0)
{
int totalbytes = (int)((float)((float)100 / (float)progressBar1.Value) * (float)e.Percentage);
// time remaining = (totalbytes - bytestranferred)/bytespersecond
int secondsleft = (totalbytes - e.Percentage) / bytespersecond;
int minutes = secondsleft / 60;
int seconds = secondsleft - (minutes * 60);
label3.Text = "Remaining time: " + minutes.ToString("D2") + ":" + seconds.ToString("D2");
last_progress = progressBar1.Value;
//Console.WriteLine("total bytes: " + totalbytes.ToString() + " seconds left: " + secondsleft.ToString() + " bytestransferred: :" + e.Percentage.ToString() + " bps: " + bytespersecond.ToString());
Application.DoEvents();
}
}
}
}
void t5can_onCanInfo(object sender, CanInfoEventArgs e)
{
if (e.Type == ActivityType.StartUploadingBootloader || e.Type == ActivityType.StartFlashing || e.Type == ActivityType.StartDownloadingFlash || e.Type == ActivityType.StartDownloadingFooter)
{
stopwatch.Reset();
stopwatch.Start();
}
else if (e.Type == ActivityType.FinishedUploadingBootloader || e.Type == ActivityType.FinishedDownloadingFlash || e.Type == ActivityType.FinishedDownloadingFooter || e.Type == ActivityType.FinishedFlashing)
{
progressBar1.Value = 0;
}
AddToLog(e.Info);
}
void t5can_onWriteProgress(object sender, WriteProgressEventArgs e)
{
if (progressBar1.Value != e.Percentage)
{
progressBar1.Value = e.Percentage;
if (e.Percentage > 99)
{
progressBar1.Value = 0;
}
Application.DoEvents();
}
}
// EXIT
private void btnExit_Click(object sender, EventArgs e)
{
try
{
SaveRegistrySetting("AdapterType", comboInterface.SelectedItem.ToString());
SaveRegistrySetting("EnableLogging", cboxEnLog.Checked);
}
catch (Exception) { }
try
{
t5can.Cleanup();
}
catch (Exception E)
{
Console.WriteLine(E.Message);
}
Environment.Exit(0);
}
// FLASH
private void btnFLASH_Click(object sender, EventArgs e)
{
manageControls(programMode.active);
if (cboxEnLog.Checked)
{
device.EnableLogging(Application.StartupPath);
}
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Binary files|*.bin";
ofd.Multiselect = false;
if (ofd.ShowDialog() == DialogResult.OK)
{
FileInfo fi = new FileInfo(ofd.FileName);
bool OkToUpgrade = true;
switch (ECU_type)
{
case ECUType.T52ECU:
if (fi.Length != 0x20000)
{
MessageBox.Show("Not a Trionic 5.2 BIN File",
"ERROR",
MessageBoxButtons.OK,
MessageBoxIcon.Stop);
}
OkToUpgrade = false;
break;
case ECUType.T55ECU:
switch (fi.Length)
{
case 0x20000:
DialogResult result = MessageBox.Show("Do you want to upload a T5.2 BIN file to your T5.5 ECU",
"ECU Conversion Question",
MessageBoxButtons.YesNo,
MessageBoxIcon.Question,
MessageBoxDefaultButton.Button2);
OkToUpgrade = (result == DialogResult.Yes) ? true : false;
break;
case 0x40000:
break;
default:
MessageBox.Show("Not a Trionic 5.5 BIN File",
"ERROR",
MessageBoxButtons.OK,
MessageBoxIcon.Stop);
OkToUpgrade = false;
break;
}
break;
case ECUType.T55AST52:
switch (fi.Length)
{
case 0x20000:
break;
case 0x40000:
DialogResult result = MessageBox.Show("Do you want to upload a T5.5 BIN file to your ECU that has been used as a T5.2?",
"ECU Conversion Question",
MessageBoxButtons.YesNo,
MessageBoxIcon.Question,
MessageBoxDefaultButton.Button2);
OkToUpgrade = (result == DialogResult.Yes) ? true : false;
break;
default:
MessageBox.Show("Not a Trionic BIN File",
"ERROR",
MessageBoxButtons.OK,
MessageBoxIcon.Stop);
OkToUpgrade = false;
break;
}
break;
}
if (OkToUpgrade)
{
AddToLog("Starting FLASH update session...");
statusActivity.Text = "Updating FLASH";
T5CANLib.UpgradeResult result = t5can.UpgradeECU(ofd.FileName, ECU_type);
statusActivity.Text = "IDLE";
switch (result)
{
case T5CANLib.UpgradeResult.Success:
AddToLog("!!! SUCCESS !!!");
getECUinfo();
AddToLog("Your ECU is ready to use your new BIN file :-)");
break;
case T5CANLib.UpgradeResult.InvalidFile:
AddToLog("!!! ERROR !!! Invalid file for the selected ECU type :-o");
break;
case T5CANLib.UpgradeResult.InvalidECUType:
AddToLog("!!! ERROR !!! Invalid ECU type selected :-o");
break;
case T5CANLib.UpgradeResult.ProgrammingFailed:
AddToLog("!!! FAILURE !!! Could not program the FLASH in your ECU :-(");
break;
case T5CANLib.UpgradeResult.EraseFailed:
AddToLog("!!! FAILURE !!! Could not erase the FLASH in your ECU :-(");
break;
case T5CANLib.UpgradeResult.ChecksumFailed:
AddToLog("!!! FAILURE !!! Checksums don't match after FLASHing :-(");
break;
default:
AddToLog("!!! ERROR!!! There was a problem I haven't catered for ???");
break;
}
switch (result)
{
case T5CANLib.UpgradeResult.ProgrammingFailed:
case T5CANLib.UpgradeResult.EraseFailed:
case T5CANLib.UpgradeResult.ChecksumFailed:
AddToLog("There are many reasons why you saw this error message,");
AddToLog("e.g. a problem with your power supply voltage or you may");
AddToLog("be unlucky enough to have 'Bad FLASH chips' :-(");
AddToLog("You should retry FLASHing your BIN file but if it fails");
AddToLog("again your only option is to try to recover your ECU");
AddToLog("using a BDM interface !!!");
break;
default:
break;
}
}
}
device.DisableLogging();
manageControls(programMode.connected);
}
// DUMP
private void btnDUMP_Click(object sender, EventArgs e)
{
manageControls(programMode.active);
if (cboxEnLog.Checked)
{
device.EnableLogging(Application.StartupPath);
}
SaveFileDialog sfd = new SaveFileDialog();
sfd.DefaultExt = "bin";
sfd.Filter = "Binary files|*.bin";
if (sfd.ShowDialog() == DialogResult.OK)
{
switch (ECU_type)
{
case ECUType.T52ECU:
AddToLog("Reading a 128 kB T5.2 BIN file from your Trionic 5.2 ECU...");
break;
case ECUType.T55AST52:
AddToLog("Reading a 128 kB T5.2 BIN file from your Trionic 5.5 ECU...");
break;
case ECUType.T55ECU:
AddToLog("Reading a 256 kB T5.5 BIN file from your Trionic 5.5 ECU...");
break;
default:
break;
}
statusActivity.Text = "Reading FLASH";
t5can.DumpECU(sfd.FileName, ECU_type);
statusActivity.Text = "IDLE";
}
device.DisableLogging();
manageControls(programMode.connected);
}
// Try to connect to an ECU
private void btnConnect_Click(object sender, EventArgs e)
{
Connect();
}
// Try to connect to an ECU
private void Connect()
{
if (cboxEnLog.Checked)
{
device.EnableLogging(Application.StartupPath);
}
manageControls(programMode.active);
if (device != null)
{
t5can.setCANDevice(device);
if (t5can.openDevice())
{
statusAdapter.Text = "Adapter: Connected";
//AddToLog("Table: " + t5can.getSymbolTable());
// send bootloader
Console.WriteLine("Uploading bootloader");
statusActivity.Text = "Sending Bootloader";
if (t5can.UploadBootLoader())
{
Console.WriteLine("Bootloader uploaded");
getECUinfo();
// enable flash and dump buttons
manageControls(programMode.connected);
}
else
{
AddToLog("Couldn't connect to your T5 ECU");
manageControls(programMode.notconnected);
}
statusActivity.Text = "IDLE";
}
else
{
AddToLog("Couldn't open CAN connection");
statusAdapter.Text = "Adapter: Not Connected";
manageControls(programMode.notconnected);
}
device.DisableLogging();
}
}
private void getECUinfo()
{
statusActivity.Text = "getting Footer";
byte[] footer = t5can.getECUFooter();
byte[] chiptypes = t5can.GetChipTypes();
statusActivity.Text = "IDLE";
string swversion = t5can.getIdentifierFromFooter(footer, ECUIdentifier.Dataname);
string romoffset = t5can.getIdentifierFromFooter(footer, ECUIdentifier.ROMoffset);
string checksum = t5can.ReturnChecksum();
statusSWVersion.Text = "SW Version: " + swversion;
statusChecksum.Text = "Checksum: " + checksum;
// identify ECU
string flashzize = "256 kB";
switch (chiptypes[0])
{
case 0xB8: // Intel/CSI/OnSemi 28F512
case 0x25: // AMD 28F512
statusFLASHType.Text = "Type: 28F512";
flashzize = "128 kB";
break;
case 0x5D: // Atmel 29C512
statusFLASHType.Text = "Type: 29C512";
flashzize = "128 kB";
break;
case 0xB4: // Intel/CSI/OnSemi 28F010
case 0xA7: // AMD 28F010
statusFLASHType.Text = "Type: 28F010";
break;
case 0x20: // AMD/ST 29F010
case 0xA4: // AMIC 29F010
statusFLASHType.Text = "Type: 29F010";
break;
case 0xD5: // Atmel 29C010
statusFLASHType.Text = "Type: 29C010";
break;
case 0xB5: // SST 39F010
statusFLASHType.Text = "Type: 39F010";
break;
default:
statusFLASHType.Text = "Type: 0x" + chiptypes[0].ToString("X2") + " - Unknown";
flashzize = "Unknown";
break;
}
statusFLASHSize.Text = "Size: " + flashzize;
switch (chiptypes[1])
{
case 0x89: // Intel
statusFLASHMake.Text = "Make: Intel";
break;
case 0x01: // AMD
statusFLASHMake.Text = "Make: AMD/Spansion";
break;
case 0x31: // CSI/OnSemi
statusFLASHMake.Text = "Make: CSI";
break;
case 0x1F: // Atmel
statusFLASHMake.Text = "Make: Atmel";
break;
case 0xBF: // SST/Microchip
statusFLASHMake.Text = "Make: SST/Microchip";
break;
case 0x20: // ST
statusFLASHMake.Text = "Make: ST Microelectronics";
break;
case 0x37: // AMIC
statusFLASHMake.Text = "Make: AMIC";
break;
default:
statusFLASHMake.Text = "Make: 0x" + chiptypes[1].ToString("X2") + " - Unknown";
break;
}
switch (flashzize)
{
case "128 kB":
switch (romoffset)
{
case "060000":
ECU_type = ECUType.T52ECU;
statusECU.Text = "ECU Type: Trionic 5.2";
AddToLog("This is a Trionic 5.2 ECU with 128 kB of FLASH");
break;
default:
ECU_type = ECUType.Unknown;
statusECU.Text = "ECU Type: Unknown";
AddToLog("!!! ERROR !!! This type of ECU is unknown");
break;
}
break;
case "256 kB":
switch (romoffset)
{
case "040000":
ECU_type = ECUType.T55ECU;
statusECU.Text = "ECU Type: Trionic 5.5";
AddToLog("This is a Trionic 5.5 ECU with 256 kB of FLASH");
break;
case "060000":
ECU_type = ECUType.T55AST52;
statusECU.Text = "ECU Type: T5.5 as T5.2";
AddToLog("This is a Trionic 5.5 ECU with a T5.2 BIN");
break;
default:
ECU_type = ECUType.Unknown;
statusECU.Text = "ECU Type: Unknown";
AddToLog("!!! ERROR !!! This type of ECU is unknown");
break;
}
break;
default:
ECU_type = ECUType.Unknown;
statusECU.Text = "ECU Type: Unknown";
AddToLog("!!! ERROR !!! This type of ECU is unknown");
break;
}
AddToLog("Part Number: " + t5can.getIdentifierFromFooter(footer, ECUIdentifier.Partnumber));
AddToLog("Software ID: " + t5can.getIdentifierFromFooter(footer, ECUIdentifier.SoftwareID));
AddToLog("SW Version: " + swversion);
AddToLog("Engine Type: " + t5can.getIdentifierFromFooter(footer, ECUIdentifier.EngineType));
AddToLog("IMMO Code: " + t5can.getIdentifierFromFooter(footer, ECUIdentifier.ImmoCode));
AddToLog("Other Info: " + t5can.getIdentifierFromFooter(footer, ECUIdentifier.Unknown));
AddToLog("ROM Start: 0x" + romoffset);
AddToLog("Code End: 0x" + t5can.getIdentifierFromFooter(footer, ECUIdentifier.CodeEnd));
AddToLog("ROM End: 0x" + t5can.getIdentifierFromFooter(footer, ECUIdentifier.ROMend));
AddToLog("Checksum: " + checksum);
}
private void comboInterface_SelectedIndexChanged(object sender, EventArgs e)
{
switch (comboInterface.SelectedIndex)
{
case 0: // useLawicel
device = new T5CANLib.CAN.CANUSBDevice();
this.Text = "Trionic 5 CAN Flasher v" + Application.ProductVersion.ToString() + " [Lawicel Adapter]";
break;
case 1: // useCombiadapter
device = new T5CANLib.CAN.LPCCANDevice_T5();
this.Text = "Trionic 5 CAN Flasher v" + Application.ProductVersion.ToString() + " [Combi Adapter]";
break;
case 2: // useDIYadapter
device = new T5CANLib.CAN.MctCanDevice();
this.Text = "Trionic 5 CAN Flasher v" + Application.ProductVersion.ToString() + " [DIY Adapter]";
break;
case 3: // useJust4Trionic
device = new T5CANLib.CAN.Just4TrionicDevice();
this.Text = "Trionic 5 CAN Flasher v" + Application.ProductVersion.ToString() + " [Just4Trionic Adapter]";
break;
default:
device = null;
this.Text = "Trionic 5 CAN Flasher v" + Application.ProductVersion.ToString() + " [!!! No Adapter Selected !!!]";
break;
}
//Connect();
}
private void btnAbout_Click(object sender, EventArgs e)
{
// show the about screen
frmAbout about = new frmAbout();
about.SetVersion(Application.ProductVersion.ToString());
about.ShowDialog();
}
private void manageControls(programMode mode)
{
switch (mode)
{
case programMode.notconnected:
comboInterface.Enabled = true;
btnConnect.Enabled = true;
btnDUMP.Enabled = false;
btnFLASH.Enabled = false;
btnAbout.Enabled = true;
btnExit.Enabled = true;
cboxEnLog.Enabled = true;
break;
case programMode.connected:
comboInterface.Enabled = false;
btnConnect.Enabled = false;
btnDUMP.Enabled = true;
btnFLASH.Enabled = true;
btnAbout.Enabled = true;
btnExit.Enabled = true;
cboxEnLog.Enabled = true;
break;
case programMode.active:
comboInterface.Enabled = false;
btnConnect.Enabled = false;
btnDUMP.Enabled = false;
btnFLASH.Enabled = false;
btnAbout.Enabled = false;
btnExit.Enabled = false;
cboxEnLog.Enabled = false;
break;
default: // only allow the user to exit in case we get here
comboInterface.Enabled = false;
btnConnect.Enabled = false;
btnDUMP.Enabled = false;
btnFLASH.Enabled = false;
btnAbout.Enabled = false;
btnExit.Enabled = true;
cboxEnLog.Enabled = false;
break;
}
}
private enum programMode : int
{
notconnected,
connected,
active
}
}
}
| |
#region Copyright
/*Copyright (C) 2015 Wosad Inc
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Windows.Controls;
using Dynamo.Controls;
using Dynamo.Models;
using Dynamo.Wpf;
using ProtoCore.AST.AssociativeAST;
using Wosad.Common.CalculationLogger;
using Wosad.Dynamo.Common;
using Wosad.Loads.ASCE7.Entities;
using System.Xml;
using System.Windows.Input;
using WosadDynamoUI.Views.Loads.ASCE7;
using GalaSoft.MvvmLight.Command;
using System.Reflection;
using Wosad.Dynamo.Common.Infra.TreeItems;
using System.Windows.Resources;
using System.Windows;
using System.IO;
using Wosad.Dynamo.UI.Common.TreeItems;
using Dynamo.Nodes;
using Dynamo.Graph.Nodes;
using Dynamo.Graph;
namespace Wosad.Loads.ASCE7.Gravity.Dead
{
/// <summary>
///Building component ID (name) used for calculation of dead weight
/// </summary>
[NodeName("Component ID selection")]
[NodeCategory("Wosad.Loads.ASCE7.Gravity.Dead")]
[NodeDescription("Building component ID (name) used for calculation of dead weight")]
[IsDesignScriptCompatible]
public class ComponentIdSelection : UiNodeBase
{
public ComponentIdSelection()
{
ReportEntry="";
ComponentId = "Deck3InLWFill";
ComponentOption1 = 1;
ComponentOption2 = 0;
ComponentValue = 0;
//OutPortData.Add(new PortData("ReportEntry", "calculation log entries (for reporting)"));
OutPortData.Add(new PortData("ComponentId", "building component id (name)"));
OutPortData.Add(new PortData("ComponentOption1", "building component subtype (option1)"));
OutPortData.Add(new PortData("ComponentOption2", "building component subtype (option2)"));
OutPortData.Add(new PortData("ComponentValue", "building component numerical value"));
RegisterAllPorts();
//PropertyChanged += NodePropertyChanged;
}
/// <summary>
/// Gets the type of this class, to be used in base class for reflection
/// </summary>
protected override Type GetModelType()
{
return GetType();
}
#region properties
#region InputProperties
#endregion
#region OutputProperties
#region ComponentIdProperty
/// <summary>
/// ComponentId property
/// </summary>
/// <value>building component id (name)</value>
public string _ComponentId;
public string ComponentId
{
get { return _ComponentId; }
set
{
_ComponentId = value;
OnNodeModified(true);
RaisePropertyChanged("ComponentId");
}
}
#endregion
#region ComponentOption1Property
/// <summary>
/// ComponentOption1 property
/// </summary>
/// <value>building component subtype (option1)</value>
public double _ComponentOption1;
public double ComponentOption1
{
get { return _ComponentOption1; }
set
{
_ComponentOption1 = value;
RaisePropertyChanged("ComponentOption1");
OnNodeModified(true);
}
}
#endregion
#region ComponentOption2Property
/// <summary>
/// ComponentOption2 property
/// </summary>
/// <value>building component subtype (option2)</value>
public double _ComponentOption2;
public double ComponentOption2
{
get { return _ComponentOption2; }
set
{
_ComponentOption2 = value;
RaisePropertyChanged("ComponentOption2");
OnNodeModified(true);
}
}
#endregion
#region ComponentValueProperty
/// <summary>
/// ComponentValue property
/// </summary>
/// <value>building component numerical value</value>
public double _ComponentValue;
public double ComponentValue
{
get { return _ComponentValue; }
set
{
_ComponentValue = value;
RaisePropertyChanged("ComponentValue");
OnNodeModified(true);
}
}
#endregion
#region ComponentDescriptionProperty
private string componentDescription;
public string ComponentDescription
{
get { return componentDescription; }
set
{
componentDescription = value;
RaisePropertyChanged("ComponentDescription");
}
}
#endregion
#region ReportEntryProperty
/// <summary>
/// log property
/// </summary>
/// <value>Calculation entries that can be converted into a report.</value>
public string reportEntry;
public string ReportEntry
{
get { return reportEntry; }
set
{
reportEntry = value;
RaisePropertyChanged("ReportEntry");
OnNodeModified(true);
}
}
#endregion
#endregion
#endregion
#region Serialization
/// <summary>
///Saves property values to be retained when opening the node
/// </summary>
protected override void SerializeCore(XmlElement nodeElement, SaveContext context)
{
base.SerializeCore(nodeElement, context);
nodeElement.SetAttribute("ComponentId", ComponentId);
nodeElement.SetAttribute("ComponentOption1", ComponentOption1.ToString());
nodeElement.SetAttribute("ComponentOption2", ComponentOption2.ToString());
nodeElement.SetAttribute("ComponentValue", ComponentValue.ToString());
}
/// <summary>
///Retrieved property values when opening the node
/// </summary>
protected override void DeserializeCore(XmlElement nodeElement, SaveContext context)
{
base.DeserializeCore(nodeElement, context);
var attribComponentId = nodeElement.Attributes["ComponentId"];
if (attribComponentId != null)
{
ComponentId = attribComponentId.Value;
SetComponentDescription();
}
var attribComponentOption1 = nodeElement.Attributes["ComponentOption1"];
var attribComponentOption2 = nodeElement.Attributes["ComponentOption2"];
var attribComponentValue = nodeElement.Attributes["ComponentValue"];
try
{
this.ComponentOption1 = double.Parse(attribComponentOption1.Value);
this.ComponentOption2 = double.Parse(attribComponentOption2.Value);
this.ComponentValue = double.Parse(attribComponentValue.Value);
}
catch (Exception)
{
}
}
public void UpdateSelectionEvents()
{
if (TreeViewControl != null)
{
TreeViewControl.SelectedItemChanged += OnTreeViewSelectionChanged;
}
}
private void OnTreeViewSelectionChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
OnSelectedItemChanged(e.NewValue);
}
private void SetComponentDescription()
{
Uri uri = new Uri("pack://application:,,,/WosadDynamoUI;component/Views/Loads/ASCE7/Dead/ComponentDeadWeightTreeData.xml");
XmlTreeHelper treeHelper = new XmlTreeHelper();
treeHelper.ExamineXmlTreeFile(uri, new EvaluateXmlNodeDelegate(FindDescription));
}
private void FindDescription(XmlNode node)
{
if (null != node.Attributes["Tag"])
{
if (node.Attributes["Tag"].Value== ComponentId)
{
ComponentDescription = node.Attributes["Description"].Value;
}
}
}
#endregion
#region treeView elements
public TreeView TreeViewControl { get; set; }
private ICommand selectedItemChanged;
public ICommand SelectedItemChanged
{
get
{
if (ComponentDescription == null)
{
selectedItemChanged = new RelayCommand<object>((i) =>
{
OnSelectedItemChanged(i);
});
}
return selectedItemChanged;
}
}
public void DisplayComponentUI(XTreeItem selectedComponent)
{
if (selectedComponent != null && selectedComponent.Tag != "X" && selectedComponent.ResourcePath != null)
{
Assembly execAssembly = Assembly.GetExecutingAssembly();
AssemblyName assemblyName = new AssemblyName(execAssembly.FullName);
string execAssemblyName = assemblyName.Name;
string typeStr =execAssemblyName +".Views.Loads.ASCE7." + selectedComponent.ResourcePath;
try
{
Type subMenuType = execAssembly.GetType(typeStr);
UserControl subMenu = (UserControl)Activator.CreateInstance(subMenuType);
AdditionalUI = subMenu;
if (selectedComponent.Id != "X") //parse default values
{
int ind1, ind2;
double numeric;
string DefaultValues = selectedComponent.Id;
string[] Vals = DefaultValues.Split(',');
if (Vals.Length == 3)
{
bool ind1Res = int.TryParse(Vals[0], out ind1); if (ind1Res == true) ComponentOption1 = ind1;
bool ind2Res = int.TryParse(Vals[1], out ind2); if (ind2Res == true) ComponentOption2 = ind2;
bool numRes = double.TryParse(Vals[2], out numeric); if (numRes == true) ComponentValue = numeric;
}
else
{
ComponentOption1 = -1;
ComponentOption2 = -1;
ComponentValue = 0;
}
}
}
catch (Exception)
{
AdditionalUI = null;
}
}
else
{
AdditionalUI = null;
}
}
private XTreeItem selectedItem;
public XTreeItem SelectedItem
{
get { return selectedItem; }
set
{
selectedItem = value;
}
}
private void OnSelectedItemChanged(object i)
{
XmlElement item = i as XmlElement;
XTreeItem xtreeItem = new XTreeItem()
{
Description = item.GetAttribute("Description"),
Header = item.GetAttribute("Header"),
Id = item.GetAttribute("Id"),
ResourcePath = item.GetAttribute("ResourcePath"),
Tag = item.GetAttribute("Tag"),
TemplateName = item.GetAttribute("TemplateName")
};
if (item != null)
{
//string id = item.GetAttribute("Tag");
string id =xtreeItem.Tag;
if (id != "X")
{
ComponentId = id;
//ComponentDescription = item.GetAttribute("Description");
ComponentDescription = xtreeItem.Description;
SelectedItem = xtreeItem;
DisplayComponentUI(xtreeItem);
}
}
}
#endregion
#region Additional UI
private UserControl additionalUI;
public UserControl AdditionalUI
{
get { return additionalUI; }
set
{
additionalUI = value;
RaisePropertyChanged("AdditionalUI");
}
}
#endregion
/// <summary>
///Customization of WPF view in Dynamo UI
/// </summary>
public class ComponentIdViewCustomization : UiNodeBaseViewCustomization,
INodeViewCustomization<ComponentIdSelection>
{
public void CustomizeView(ComponentIdSelection model, NodeView nodeView)
{
ComponentIdView control = new ComponentIdView();
control.DataContext = model;
TreeView tv = control.FindName("selectionTree") as TreeView;
if (tv!=null)
{
model.TreeViewControl = tv;
model.UpdateSelectionEvents();
}
nodeView.inputGrid.Children.Add(control);
base.CustomizeView(model, nodeView);
}
}
}
}
| |
using System.Collections.Generic;
using Cottle.Contexts.Monitor;
using Cottle.Documents;
using NUnit.Framework;
namespace Cottle.Test.Contexts
{
public static class MonitorContextTester
{
[Test]
public static void GeneratorAccessDefined()
{
var backend = Context.CreateCustom(new Dictionary<Value, Value>
{
["range"] = Value.FromGenerator(i => i * 2, 5)
});
var usage = MonitorContextTester.MonitorAndRender("{for i in [0, 1, 2]:{range[i]}}", backend, "024");
for (var i = 0; i < 3; ++i)
{
var rangeUsage = MonitorContextTester.GetChildField(usage, "range", 3, i);
Assert.That(rangeUsage.Value.Type, Is.EqualTo(ValueContent.Map));
var fieldUsage = MonitorContextTester.GetChildField(rangeUsage, i, 1, 0);
Assert.That(fieldUsage.Value.AsNumber, Is.EqualTo(i * 2));
}
}
[Test]
public static void GroupFieldsUsages()
{
const string template = "{set x to parent.child}{x.a}{x.b}{parent.child.c}";
var root = MonitorContextTester.MonitorAndRender(template, Context.Empty, string.Empty);
var rootFields = root.GroupFieldUsages();
Assert.That(rootFields, Does.ContainKey((Value)"parent"));
var parent = rootFields["parent"];
Assert.That(parent.Value, Is.EqualTo(Value.Undefined));
var parentFields = parent.GroupFieldUsages();
Assert.That(parentFields, Does.ContainKey((Value)"child"));
var child = parentFields["child"];
Assert.That(child.Value, Is.EqualTo(Value.Undefined));
var childFields = child.GroupFieldUsages();
Assert.That(childFields, Does.ContainKey((Value)"a"));
Assert.That(childFields, Does.ContainKey((Value)"b"));
Assert.That(childFields, Does.ContainKey((Value)"c"));
}
[Test]
public static void MemberAccessDefined()
{
var backend = Context.CreateCustom(new Dictionary<Value, Value>
{
["parent"] = new Dictionary<Value, Value>
{
["child"] = "value"
}
});
var usage = MonitorContextTester.MonitorAndRender("{parent.child}", backend, "value");
var parent = MonitorContextTester.GetChildField(usage, "parent", 1, 0);
Assert.That(parent.Value.Type, Is.EqualTo(ValueContent.Map));
var child = MonitorContextTester.GetChildField(parent, "child", 1, 0);
Assert.That(child.Value, Is.EqualTo((Value)"value"));
Assert.That(child.Fields.Count, Is.EqualTo(0));
}
[Test]
public static void MemberAccessMissing()
{
var usage = MonitorContextTester.MonitorAndRender("{parent.child}", Context.Empty, string.Empty);
Assert.That(usage.Value, Is.EqualTo(Value.Undefined));
var parent = MonitorContextTester.GetChildField(usage, "parent", 1, 0);
Assert.That(parent.Value, Is.EqualTo(Value.Undefined));
var child = MonitorContextTester.GetChildField(parent, "child", 1, 0);
Assert.That(child.Value, Is.EqualTo(Value.Undefined));
Assert.That(child.Fields.Count, Is.EqualTo(0));
}
[Test]
public static void MemberAccessMultiple()
{
const string template = "{parent.child}{parent.child}";
var usage = MonitorContextTester.MonitorAndRender(template, Context.Empty, string.Empty);
var parent0 = MonitorContextTester.GetChildField(usage, "parent", 2, 0);
Assert.That(parent0.Value, Is.EqualTo(Value.Undefined));
var child0 = MonitorContextTester.GetChildField(parent0, "child", 1, 0);
Assert.That(child0.Value, Is.EqualTo(Value.Undefined));
var parent1 = MonitorContextTester.GetChildField(usage, "parent", 2, 0);
Assert.That(parent1.Value, Is.EqualTo(Value.Undefined));
var child1 = MonitorContextTester.GetChildField(parent1, "child", 1, 0);
Assert.That(child1.Value, Is.EqualTo(Value.Undefined));
}
[Test]
public static void MemberChildAccessDefined()
{
var backend = Context.CreateCustom(new Dictionary<Value, Value>
{
["parent"] = new Dictionary<Value, Value>
{
["child"] = new Dictionary<Value, Value>
{
["subchild"] = "value"
}
}
});
var usage = MonitorContextTester.MonitorAndRender("{parent.child.subchild}", backend, "value");
var parent = MonitorContextTester.GetChildField(usage, "parent", 1, 0);
Assert.That(parent.Value.Type, Is.EqualTo(ValueContent.Map));
var child = MonitorContextTester.GetChildField(parent, "child", 1, 0);
Assert.That(child.Value.Type, Is.EqualTo(ValueContent.Map));
var subchild = MonitorContextTester.GetChildField(child, "subchild", 1, 0);
Assert.That(subchild.Value, Is.EqualTo((Value)"value"));
Assert.That(subchild.Fields.Count, Is.EqualTo(0));
}
[Test]
public static void MemberChildAccessMissing()
{
var usage = MonitorContextTester.MonitorAndRender("{parent.child.subchild}", Context.Empty, string.Empty);
Assert.That(usage.Value, Is.EqualTo(Value.Undefined));
var parent = MonitorContextTester.GetChildField(usage, "parent", 1, 0);
Assert.That(parent.Value, Is.EqualTo(Value.Undefined));
var child = MonitorContextTester.GetChildField(parent, "child", 1, 0);
Assert.That(child.Value, Is.EqualTo(Value.Undefined));
var subchild = MonitorContextTester.GetChildField(child, "subchild", 1, 0);
Assert.That(subchild.Value, Is.EqualTo(Value.Undefined));
}
[Test]
public static void ScalarAccessDefined()
{
var backend = Context.CreateCustom(new Dictionary<Value, Value> { { "a", 17 } });
var usage = MonitorContextTester.MonitorAndRender("{a}", backend, "17");
Assert.That(usage.Fields.Count, Is.EqualTo(1));
Assert.That(usage.Fields["a"].Count, Is.EqualTo(1));
Assert.That(usage.Fields["a"][0].Fields, Is.Empty);
Assert.That(usage.Fields["a"][0].Value, Is.EqualTo(Value.FromNumber(17)));
}
[Test]
public static void ScalarAccessMissing()
{
var usage = MonitorContextTester.MonitorAndRender("{scalar}", Context.Empty, string.Empty);
var scalar = MonitorContextTester.GetChildField(usage, "scalar", 1, 0);
Assert.That(scalar.Value, Is.EqualTo(Value.Undefined));
Assert.That(scalar.Fields.Count, Is.EqualTo(0));
}
private static ISymbolUsage GetChildField(ISymbolUsage parent, Value field, int count, int index)
{
Assert.That(parent.Fields.ContainsKey(field), Is.True);
Assert.That(parent.Fields[field].Count, Is.EqualTo(count));
return parent.Fields[field][index];
}
private static ISymbolUsage MonitorAndRender(string template, IContext backend, string expected)
{
#pragma warning disable 618
var document = new SimpleDocument(template);
var (context, usage) = Context.CreateMonitor(backend);
#pragma warning restore 618
Assert.That(document.Render(context), Is.EqualTo(expected));
return usage;
}
}
}
| |
#region License
/*
* Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
#region Imports
using System;
using System.Collections;
using System.Collections.Generic;
using System.Xml;
using NVelocity.Runtime;
using NVelocity.Runtime.Resource.Loader;
using Spring.Core.TypeResolution;
using Spring.Objects;
using Spring.Objects.Factory;
using Spring.Objects.Factory.Config;
using Spring.Objects.Factory.Support;
using Spring.Objects.Factory.Xml;
using Spring.Template.Velocity;
using Spring.Util;
#endregion
namespace Spring.Template.Velocity.Config {
/// <summary>
/// Implementation of the custom configuration parser for template configurations
/// based on
/// <see cref="ObjectsNamespaceParser"/>
/// </summary>
/// <author>Erez Mazor</author>
/// <see cref="ObjectsNamespaceParser"/>
[
NamespaceParser(
Namespace = "http://www.springframework.net/nvelocity",
SchemaLocationAssemblyHint = typeof(TemplateNamespaceParser),
SchemaLocation = "/Spring.Template.Velocity.Config/spring-nvelocity-1.3.xsd")
]
public class TemplateNamespaceParser : ObjectsNamespaceParser {
private const string TemplateTypePrefix = "template: ";
static TemplateNamespaceParser() {
TypeRegistry.RegisterType(TemplateTypePrefix + TemplateDefinitionConstants.NVelocityElement, typeof(VelocityEngineFactoryObject));
}
/// <summary>
/// Initializes a new instance of the <see cref="TemplateNamespaceParser"/> class.
/// </summary>
public TemplateNamespaceParser() {
}
/// <see cref="INamespaceParser"/>
public override IObjectDefinition ParseElement(XmlElement element, ParserContext parserContext) {
string name = element.GetAttribute(ObjectDefinitionConstants.IdAttribute);
IConfigurableObjectDefinition templateDefinition = ParseTemplateDefinition(element, parserContext);
if (!StringUtils.HasText(name)) {
name = ObjectDefinitionReaderUtils.GenerateObjectName(templateDefinition, parserContext.Registry);
}
parserContext.Registry.RegisterObjectDefinition(name, templateDefinition);
return null;
}
/// <summary>
/// Parse a template definition from the templating namespace
/// </summary>
/// <param name="element">the root element defining the templating object</param>
/// <param name="parserContext">the parser context</param>
/// <returns></returns>
private IConfigurableObjectDefinition ParseTemplateDefinition(XmlElement element, ParserContext parserContext) {
switch (element.LocalName) {
case TemplateDefinitionConstants.NVelocityElement:
return ParseNVelocityEngine(element, parserContext);
default:
throw new ArgumentException(string.Format("undefined element for templating namespace: {0}", element.LocalName));
}
}
/// <summary>
/// Parses the object definition for the engine object, configures a single NVelocity template engine based
/// on the element definitions.
/// </summary>
/// <param name="element">the root element defining the velocity engine</param>
/// <param name="parserContext">the parser context</param>
private IConfigurableObjectDefinition ParseNVelocityEngine(XmlElement element, ParserContext parserContext) {
string typeName = GetTypeName(element);
IConfigurableObjectDefinition configurableObjectDefinition = parserContext.ReaderContext.ObjectDefinitionFactory.CreateObjectDefinition(
typeName, null, parserContext.ReaderContext.Reader.Domain);
string preferFileSystemAccess = GetAttributeValue(element, TemplateDefinitionConstants.AttributePreferFileSystemAccess);
string overrideLogging = GetAttributeValue(element, TemplateDefinitionConstants.AttributeOverrideLogging);
string configFile = GetAttributeValue(element, TemplateDefinitionConstants.AttributeConfigFile);
MutablePropertyValues objectDefinitionProperties = new MutablePropertyValues();
if (StringUtils.HasText(preferFileSystemAccess)) {
objectDefinitionProperties.Add(TemplateDefinitionConstants.PropertyPreferFileSystemAccess, preferFileSystemAccess);
}
if (StringUtils.HasText(overrideLogging)) {
objectDefinitionProperties.Add(TemplateDefinitionConstants.PropertyOverrideLogging, overrideLogging);
}
if (StringUtils.HasText(configFile)) {
objectDefinitionProperties.Add(TemplateDefinitionConstants.PropertyConfigFile, configFile);
}
XmlNodeList childElements = element.ChildNodes;
if (childElements.Count > 0) {
ParseChildDefinitions(childElements, parserContext, objectDefinitionProperties);
}
configurableObjectDefinition.PropertyValues = objectDefinitionProperties;
return configurableObjectDefinition;
}
/// <summary>
/// Parses child element definitions for the NVelocity engine. Typically resource loaders and locally defined properties are parsed here
/// </summary>
/// <param name="childElements">the XmlNodeList representing the child configuration of the root NVelocity engine element</param>
/// <param name="parserContext">the parser context</param>
/// <param name="objectDefinitionProperties">the MutablePropertyValues used to configure this object</param>
private void ParseChildDefinitions(XmlNodeList childElements, ParserContext parserContext, MutablePropertyValues objectDefinitionProperties) {
IDictionary<string, object> properties = new Dictionary<string, object>();
foreach (XmlElement element in childElements) {
switch (element.LocalName) {
case TemplateDefinitionConstants.ElementResourceLoader:
ParseResourceLoader(element, objectDefinitionProperties, properties);
break;
case TemplateDefinitionConstants.ElementNVelocityProperties:
ParseNVelocityProperties(element, parserContext, properties);
break;
}
}
if (properties.Count > 0) {
objectDefinitionProperties.Add(TemplateDefinitionConstants.PropertyVelocityProperties, properties);
}
}
/// <summary>
/// Configures the NVelocity resource loader definitions from the xml definition
/// </summary>
/// <param name="element">the root resource loader element</param>
/// <param name="objectDefinitionProperties">the MutablePropertyValues used to configure this object</param>
/// <param name="properties">the properties used to initialize the velocity engine</param>
private void ParseResourceLoader(XmlElement element, MutablePropertyValues objectDefinitionProperties, IDictionary<string, object> properties) {
string caching = GetAttributeValue(element, TemplateDefinitionConstants.AttributeTemplateCaching);
string defaultCacheSize = GetAttributeValue(element, TemplateDefinitionConstants.AttributeDefaultCacheSize);
string modificationCheckInterval = GetAttributeValue(element, TemplateDefinitionConstants.AttributeModificationCheckInterval);
if (!string.IsNullOrEmpty(defaultCacheSize)) {
properties.Add(RuntimeConstants.RESOURCE_MANAGER_DEFAULTCACHE_SIZE, defaultCacheSize);
}
XmlNodeList loaderElements = element.ChildNodes;
switch (loaderElements[0].LocalName) {
case VelocityConstants.File:
AppendFileLoaderProperties(loaderElements, properties);
AppendResourceLoaderGlobalProperties(properties, VelocityConstants.File, caching,
modificationCheckInterval);
break;
case VelocityConstants.Assembly:
AppendAssemblyLoaderProperties(loaderElements, properties);
AppendResourceLoaderGlobalProperties(properties, VelocityConstants.Assembly, caching, null);
break;
case TemplateDefinitionConstants.Spring:
AppendResourceLoaderPaths(loaderElements, objectDefinitionProperties);
AppendResourceLoaderGlobalProperties(properties, TemplateDefinitionConstants.Spring, caching, null);
break;
case TemplateDefinitionConstants.Custom:
XmlElement firstElement = (XmlElement)loaderElements.Item(0);
AppendCustomLoaderProperties(firstElement, properties);
AppendResourceLoaderGlobalProperties(properties, firstElement.LocalName, caching, modificationCheckInterval);
break;
default:
throw new ArgumentException(string.Format("undefined element for resource loadre type: {0}", element.LocalName));
}
}
/// <summary>
/// Set the caching and modification interval checking properties of a resource loader of a given type
/// </summary>
/// <param name="properties">the properties used to initialize the velocity engine</param>
/// <param name="type">type of the resource loader</param>
/// <param name="caching">caching flag</param>
/// <param name="modificationInterval">modification interval value</param>
private void AppendResourceLoaderGlobalProperties(IDictionary<string, object> properties, string type, string caching, string modificationInterval) {
AppendResourceLoaderGlobalProperty(properties, type,
TemplateDefinitionConstants.PropertyResourceLoaderCaching,
Convert.ToBoolean(caching));
AppendResourceLoaderGlobalProperty
(properties, type, TemplateDefinitionConstants.PropertyResourceLoaderModificationCheckInterval, Convert.ToInt64(modificationInterval));
}
/// <summary>
/// Set global velocity resource loader properties (caching, modification interval etc.)
/// </summary>
/// <param name="properties">the properties used to initialize the velocity engine</param>
/// <param name="type">the type of resource loader</param>
/// <param name="property">the suffix property</param>
/// <param name="value">the value of the property</param>
private void AppendResourceLoaderGlobalProperty(IDictionary<string, object> properties, string type, string property, object value) {
if (null != value) {
properties.Add(type + VelocityConstants.Separator + property, value);
}
}
/// <summary>
/// Creates a nvelocity file based resource loader by setting the required properties
/// </summary>
/// <param name="elements">a list of nv:file elements defining the paths to template files</param>
/// <param name="properties">the properties used to initialize the velocity engine</param>
private void AppendFileLoaderProperties(XmlNodeList elements, IDictionary<string, object> properties) {
IList paths = new List<string>(elements.Count);
foreach (XmlElement element in elements) {
paths.Add(GetAttributeValue(element, VelocityConstants.Path));
}
properties.Add(RuntimeConstants.RESOURCE_LOADER, VelocityConstants.File);
properties.Add(getResourceLoaderProperty(VelocityConstants.File, VelocityConstants.Class), TemplateDefinitionConstants.FileResourceLoaderClass);
properties.Add(getResourceLoaderProperty(VelocityConstants.File, VelocityConstants.Path), StringUtils.CollectionToCommaDelimitedString(paths));
}
/// <summary>
/// Creates a nvelocity assembly based resource loader by setting the required properties
/// </summary>
/// <param name="elements">a list of nv:assembly elements defining the assemblies</param>
/// <param name="properties">the properties used to initialize the velocity engine</param>
private void AppendAssemblyLoaderProperties(XmlNodeList elements, IDictionary<string, object> properties) {
IList assemblies = new List<string>(elements.Count);
foreach (XmlElement element in elements) {
assemblies.Add(GetAttributeValue(element, VelocityConstants.Name));
}
properties.Add(RuntimeConstants.RESOURCE_LOADER, VelocityConstants.Assembly);
properties.Add(getResourceLoaderProperty(VelocityConstants.Assembly, VelocityConstants.Class), TemplateDefinitionConstants.AssemblyResourceLoaderClass);
properties.Add(getResourceLoaderProperty(VelocityConstants.Assembly, VelocityConstants.Assembly), StringUtils.CollectionToCommaDelimitedString(assemblies));
}
/// <summary>
/// Creates a spring resource loader by setting the ResourceLoaderPaths of the
/// engine factory (the resource loader itself will be created internally either as
/// spring or as file resource loader based on the value of prefer-file-system-access
/// attribute).
/// </summary>
/// <param name="elements">list of resource loader path elements</param>
/// <param name="objectDefinitionProperties">the MutablePropertyValues to set the property for the engine factory</param>
private void AppendResourceLoaderPaths(XmlNodeList elements, MutablePropertyValues objectDefinitionProperties) {
IList<string> paths = new List<string>();
foreach (XmlElement element in elements) {
string path = GetAttributeValue(element, TemplateDefinitionConstants.AttributeUri);
paths.Add(path);
}
objectDefinitionProperties.Add(TemplateDefinitionConstants.PropertyResourceLoaderPaths, paths);
}
/// <summary>
/// Create a custom resource loader from an nv:custom element
/// generates the 4 required nvelocity props for a resource loader (name, description, class and path).
/// </summary>
/// <param name="element">the nv:custom xml definition element</param>
/// <param name="properties">the properties used to initialize the velocity engine</param>
private void AppendCustomLoaderProperties(XmlElement element, IDictionary<string, object> properties) {
string name = GetAttributeValue(element, VelocityConstants.Name);
string description = GetAttributeValue(element, VelocityConstants.Description);
string type = GetAttributeValue(element, VelocityConstants.Type);
string path = GetAttributeValue(element, VelocityConstants.Path);
properties.Add(RuntimeConstants.RESOURCE_LOADER, name);
properties.Add(getResourceLoaderProperty(name, VelocityConstants.Description), description);
properties.Add(getResourceLoaderProperty(name, VelocityConstants.Class), type.Replace(',', ';'));
properties.Add(getResourceLoaderProperty(name, VelocityConstants.Path), path);
}
/// <summary>
/// Parses the nvelocity properties map using <code>ObjectNamespaceParserHelper</code>
/// and appends it to the properties dictionary
/// </summary>
/// <param name="element">root element of the map element</param>
/// <param name="parserContext">the parser context</param>
/// <param name="properties">the properties used to initialize the velocity engine</param>
private void ParseNVelocityProperties(XmlElement element, ParserContext parserContext, IDictionary<string, object> properties) {
IDictionary parsedProperties = ParseDictionaryElement(element,
TemplateDefinitionConstants.ElementNVelocityProperties, parserContext);
foreach (DictionaryEntry entry in parsedProperties) {
properties.Add(Convert.ToString(entry.Key), entry.Value);
}
}
/// <summary>
/// Gets the name of the object type for the specified element.
/// </summary>
/// <param name="element">The element.</param>
/// <returns>The name of the object type.</returns>
private string GetTypeName(XmlElement element) {
string typeName = element.GetAttribute(ObjectDefinitionConstants.TypeAttribute);
if (StringUtils.IsNullOrEmpty(typeName)) {
return TemplateTypePrefix + element.LocalName;
}
return typeName;
}
/// <summary>
/// constructs an nvelocity style resource loader property in the format:
/// prefix.resource.loader.suffix
/// </summary>
/// <param name="type">the prefix</param>
/// <param name="suffix">the suffix</param>
/// <returns>a concatenated string like: prefix.resource.loader.suffix</returns>
public static string getResourceLoaderProperty(string type, string suffix) {
return type + VelocityConstants.Separator + RuntimeConstants.RESOURCE_LOADER + VelocityConstants.Separator +
suffix;
}
/// <summary>
/// This method is overriden from ObjectsNamespaceParser since when invoked on
/// sub-elements from the objets namespace (e.g., objects:objectMap for nvelocity
/// property map) the <code>element.SelectNodes</code> fails because it is in
/// the nvelocity custom namespace and not the object's namespace (http://www.springframwork.net)
/// to amend this the object's namespace is added to the provided XmlNamespaceManager
/// </summary>
///<param name="element"> The element to be searched in. </param>
/// <param name="childElementName"> The name of the child nodes to look for.
/// </param>
/// <returns> The child <see cref="System.Xml.XmlNode"/>s of the supplied
/// <paramref name="element"/> with the supplied <paramref name="childElementName"/>.
/// </returns>
/// <see cref="ObjectsNamespaceParser"/>
[Obsolete("not used anymore - ObjectsNamespaceParser will be dropped with 2.x, use ObjectDefinitionParserHelper instead")]
protected override XmlNodeList SelectNodes(XmlElement element, string childElementName) {
XmlNamespaceManager nsManager = new XmlNamespaceManager(new NameTable());
nsManager.AddNamespace(GetNamespacePrefix(element), element.NamespaceURI);
nsManager.AddNamespace(GetNamespacePrefix(element), Namespace);
return element.SelectNodes(GetNamespacePrefix(element) + ":" + childElementName, nsManager);
}
private string GetNamespacePrefix(XmlElement element) {
return StringUtils.HasText(element.Prefix) ? element.Prefix : "spring";
}
}
#region Element & Attribute Name Constants
/// <summary>
/// Template definition constants
/// </summary>
public class TemplateDefinitionConstants {
/// <summary>
/// Engine element definition
/// </summary>
public const string NVelocityElement = "engine";
/// <summary>
/// Spring resource loader element definition
/// </summary>
public const string Spring = "spring";
/// <summary>
/// Custom resource loader element definition
/// </summary>
public const string Custom = "custom";
/// <summary>
/// uri attribute of the spring element
/// </summary>
public const string AttributeUri = "uri";
/// <summary>
/// prefer-file-system-access attribute of the engine factory
/// </summary>
public const string AttributePreferFileSystemAccess = "prefer-file-system-access";
/// <summary>
/// config-file attribute of the engine factory
/// </summary>
public const string AttributeConfigFile = "config-file";
/// <summary>
/// override-logging attribute of the engine factory
/// </summary>
public const string AttributeOverrideLogging = "override-logging";
/// <summary>
/// template-caching attribute of the nvelocity engine
/// </summary>
public const string AttributeTemplateCaching = "template-caching";
/// <summary>
/// default-cache-size attribute of the nvelocity engine resource manager
/// </summary>
public const string AttributeDefaultCacheSize = "default-cache-size";
/// <summary>
/// modification-check-interval attribute of the nvelocity engine resource loader
/// </summary>
public const string AttributeModificationCheckInterval = "modification-check-interval";
/// <summary>
/// resource loader element
/// </summary>
public const string ElementResourceLoader = "resource-loader";
/// <summary>
/// nvelocity propeties element (map)
/// </summary>
public const string ElementNVelocityProperties = "nvelocity-properties";
/// <summary>
/// PreferFileSystemAccess property of the engine factory
/// </summary>
public const string PropertyPreferFileSystemAccess = "PreferFileSystemAccess";
/// <summary>
/// OverrideLogging property of the engine factory
/// </summary>
public const string PropertyOverrideLogging = "OverrideLogging";
/// <summary>
/// ConfigLocation property of the engine factory
/// </summary>
public const string PropertyConfigFile = "ConfigLocation";
/// <summary>
/// ResourceLoaderPaths property of the engine factory
/// </summary>
public const string PropertyResourceLoaderPaths = "ResourceLoaderPaths";
/// <summary>
/// VelocityProperties property of the engine factory
/// </summary>
public const string PropertyVelocityProperties = "VelocityProperties";
/// <summary>
/// resource.loader.cache property of the resource loader configuration
/// </summary>
public const string PropertyResourceLoaderCaching = "resource.loader.cache";
/// <summary>
/// resource.loader.modificationCheckInterval property of the resource loader configuration
/// </summary>
public const string PropertyResourceLoaderModificationCheckInterval = "resource.loader.modificationCheckInterval";
/// <summary>
/// the type used for file resource loader
/// </summary>
public const string FileResourceLoaderClass = "NVelocity.Runtime.Resource.Loader.FileResourceLoader; NVelocity";
/// <summary>
/// the type used for assembly resource loader
/// </summary>
public const string AssemblyResourceLoaderClass = "NVelocity.Runtime.Resource.Loader.AssemblyResourceLoader; NVelocity";
/// <summary>
/// the type used for spring resource loader
/// </summary>
public const string SpringResourceLoaderClass = "Spring.Template.Velocity.SpringResourceLoader; Spring.Template.Velocity";
}
#endregion
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Text.RegularExpressions;
using ScrollsModLoader.Interfaces;
using UnityEngine;
using Mono.Cecil;
namespace TimerChange.mod {
public class TimerChange : BaseMod {
private const int DEFAULT_TIMEOUT = 91;
private const int DEFAULT_TOTAL_TIMEOUT = -1;
private int[] kerning = new int[] { 24, 14, 23, 21, 23, 20, 21, 22, 23, 21 };
private FieldInfo activeColorField;
private FieldInfo battleUIField;
private FieldInfo battleUISkinField;
private FieldInfo commField;
private FieldInfo leftColorField;
private FieldInfo roundTimeField;
private FieldInfo roundTimerField;
private FieldInfo showClockField;
private MethodInfo endTurnMethod;
private MethodInfo showEndTurnMethod;
private int p1TotalSeconds;
private int p1TurnSeconds;
private int p2TotalSeconds;
private int p2TurnSeconds;
private int totalTimeout = DEFAULT_TOTAL_TIMEOUT;
private int timeout = DEFAULT_TIMEOUT;
private bool turnEnded = false;
private TileColor activePlayer = TileColor.unknown;
public TimerChange() {
activeColorField = typeof(BattleMode).GetField("activeColor", BindingFlags.Instance | BindingFlags.NonPublic);
battleUIField = typeof(BattleMode).GetField("battleUI", BindingFlags.Instance | BindingFlags.NonPublic);
battleUISkinField = typeof(BattleMode).GetField("battleUISkin", BindingFlags.Instance | BindingFlags.NonPublic);
commField = typeof(BattleMode).GetField("comm", BindingFlags.Instance | BindingFlags.NonPublic);
leftColorField = typeof(BattleMode).GetField("leftColor", BindingFlags.Instance | BindingFlags.NonPublic);
roundTimeField = typeof(BattleMode).GetField("roundTime", BindingFlags.Instance | BindingFlags.NonPublic);
roundTimerField = typeof(BattleMode).GetField("roundTimer", BindingFlags.Instance | BindingFlags.NonPublic);
showClockField = typeof(BattleMode).GetField("showClock", BindingFlags.Instance | BindingFlags.NonPublic);
endTurnMethod = typeof(BattleMode).GetMethod("endTurn", BindingFlags.Instance | BindingFlags.NonPublic);
showEndTurnMethod = typeof(BattleModeUI).GetMethod("ShowEndTurn", BindingFlags.Instance | BindingFlags.NonPublic);
}
public static string GetName() {
return "TimerChange";
}
public static int GetVersion() {
return 6;
}
public static MethodDefinition[] GetHooks(TypeDefinitionCollection scrollsTypes, int version) {
try {
return new MethodDefinition[] {
scrollsTypes["BattleMode"].Methods.GetMethod("_handleMessage", new Type[]{typeof(Message)}),
scrollsTypes["BattleMode"].Methods.GetMethod("OnGUI", new Type[]{}),
scrollsTypes["Communicator"].Methods.GetMethod("sendRequest", new Type[]{ typeof(Message) }),
};
}
catch {
return new MethodDefinition[] { };
}
}
public override bool WantsToReplace(InvocationInfo info) {
// don't display TimerChange commands in chat
if (info.target is Communicator && info.targetMethod.Equals("sendRequest") && info.arguments[0] is RoomChatMessageMessage) {
RoomChatMessageMessage msg = (RoomChatMessageMessage) info.arguments[0];
if (isTimerChangeMsg(msg)) {
return true;
}
}
return false;
}
public override void ReplaceMethod(InvocationInfo info, out object returnValue) {
// when method is replaced, we know command line arguments etc are correct
returnValue = null;
RoomChatMessageMessage msg = (RoomChatMessageMessage) info.arguments[0];
bool emitError = false;
string[] cmds = msg.text.Split(' ');
RoomChatMessageMessage newMsg = new RoomChatMessageMessage();
newMsg.from = GetName(); // name of the mod, that is
newMsg.roomName = App.ArenaChat.ChatRooms.GetCurrentRoom().name;
switch (cmds.Length) {
case 2:
newMsg.roomName = App.ArenaChat.ChatRooms.GetCurrentRoom().name;
try {
timeout = Convert.ToInt32(cmds[1]);
if (timeout > 0 && timeout < DEFAULT_TIMEOUT) {
totalTimeout = DEFAULT_TOTAL_TIMEOUT;
newMsg.text = "Turn timeout set to " + timeout + " seconds. Total timeout disabled.";
}
else {
emitError = true;
}
}
catch (Exception) {
emitError = true;
}
break;
case 3:
newMsg.roomName = App.ArenaChat.ChatRooms.GetCurrentRoom().name;
try {
timeout = Convert.ToInt32(cmds[1]);
int seconds;
int minutes = splitMinutesAndSeconds(cmds[2], out seconds);
totalTimeout = minutes * 60 + seconds;
if (timeout > 0 && timeout < DEFAULT_TIMEOUT && totalTimeout > 0) {
newMsg.text = "Turn timeout set to " + timeout + " seconds. Total timeout set to " + minutes + " minutes and " + seconds + " seconds.";
}
else {
emitError = true;
}
}
catch (Exception) {
emitError = true;
}
break;
}
if (emitError) {
timeout = DEFAULT_TIMEOUT;
totalTimeout = DEFAULT_TOTAL_TIMEOUT;
newMsg.text = "Invalid command. Turn timeout set to default. Total timeout disabled.";
}
App.ChatUI.handleMessage(newMsg);
App.ArenaChat.ChatRooms.ChatMessage(newMsg);
}
public override void BeforeInvoke(InvocationInfo info) {
}
private void printTotalTimer(BattleMode target, string text, Rect rect) {
GUI.skin.label.fontSize = GUI.skin.label.fontSize;
GUI.color = Color.white;
for (int i = 0; i < text.Length; i++) {
if (text[i] != ' ') {
int num7 = (int)(text[i] - '0');
rect.width = rect.height * (float)kerning[num7] / 34f;
if (text.Length == 1) {
rect.x += rect.width / 2f;
}
GUI.DrawTexture(rect, ResourceManager.LoadTexture("BattleMode/Clock/time__n_" + text[i]));
}
rect.x += rect.width * 1.1f;
}
}
public override void AfterInvoke(InvocationInfo info, ref object returnValue) {
// set timeout to user-defined value on game start
if (info.target is BattleMode && info.targetMethod.Equals("_handleMessage") && timeout < DEFAULT_TIMEOUT) {
BattleMode target = (BattleMode)info.target;
Message msg = (Message) info.arguments[0];
if (msg is GameInfoMessage) {
showClockField.SetValue(target, true);
roundTimeField.SetValue(target, timeout);
p1TotalSeconds = 0;
p2TotalSeconds = 0;
}
}
if (info.target is BattleMode && info.targetMethod.Equals("OnGUI") && (timeout < DEFAULT_TIMEOUT || totalTimeout != DEFAULT_TOTAL_TIMEOUT)) {
BattleMode target = (BattleMode)info.target;
TileColor nowActivePlayer = (TileColor)activeColorField.GetValue(target);
bool playerChanged = nowActivePlayer != activePlayer;
activePlayer = nowActivePlayer;
float roundTimer = (float)roundTimerField.GetValue(target);
float roundTime = (float)roundTimeField.GetValue(target);
float timePassed = (roundTimer >= 0f) ? Mathf.Floor(Time.time - roundTimer) : 0f;
if (activeColorField.GetValue(target).Equals(leftColorField.GetValue(target))) {
int seconds = Mathf.Max(0, (int)(roundTime + 1 - timePassed)); // add +1 so round stops 1 second AFTER hitting 0
p1TurnSeconds = (int)Mathf.Min(timePassed, roundTime);
// add last turn time to the total time
if (playerChanged) {
p2TotalSeconds += p2TurnSeconds;
p2TurnSeconds = 0;
}
if (seconds == 0 && !turnEnded) {
turnEnded = true;
BattleModeUI battleUI = (BattleModeUI)battleUIField.GetValue(target);
showEndTurnMethod.Invoke(battleUI, new object[] { false } );
endTurnMethod.Invoke(target, new object[] { });
}
// out of total time, surrender game!
if (totalTimeout != DEFAULT_TOTAL_TIMEOUT && totalTimeout - p1TotalSeconds - p1TurnSeconds < 0) {
((Communicator)commField.GetValue(target)).sendBattleRequest(new SurrenderMessage());
}
}
else {
// add last turn time to the total time
if (playerChanged) {
p1TotalSeconds += p1TurnSeconds;
p1TurnSeconds = 0;
}
p2TurnSeconds = (int)Mathf.Min(timePassed, roundTime);
turnEnded = false;
}
// draw indicators for the amount of time left
if (totalTimeout != DEFAULT_TOTAL_TIMEOUT) {
GUISkin skin = GUI.skin;
GUI.skin = (UnityEngine.GUISkin) battleUISkinField.GetValue(target);
// light transparency on the text background
GUI.color = new Color(1f, 1f, 1f, 0.75f);
// position of GUI box containing names
float namesBoxX = (float)Screen.width * 0.5f - (float)Screen.height * 0.3f;
float namesBoxY = (float)Screen.height * 0.027f;
float namesBoxW = (float)Screen.height * 0.6f;
// from GUIClock.renderHeight
float height = (float)Screen.height * 0.08f;
float width = height * 164f / 88f;
GUI.DrawTexture(new Rect((float)(Screen.width / 2) - width / 2f - namesBoxX, (float)Screen.height * 0.01f, width, height), ResourceManager.LoadTexture("BattleUI/battlegui_timerbox"));
GUI.DrawTexture(new Rect((float)(Screen.width / 2) - width / 2f + namesBoxX, (float)Screen.height * 0.01f, width, height), ResourceManager.LoadTexture("BattleUI/battlegui_timerbox"));
GUI.skin = skin;
int elapsedTimeP1 = totalTimeout - p1TotalSeconds - p1TurnSeconds;
int elapsedMinsP1 = elapsedTimeP1 / 60;
int elapsedSecsP1 = elapsedTimeP1 % 60;
string p1Text = (elapsedMinsP1 < 10 ? "0" : "") + elapsedMinsP1 + " " + (elapsedSecsP1 < 10 ? "0" : "") + elapsedSecsP1;
Rect p1Rect = new Rect((float)(Screen.width / 2) - width / 2f - namesBoxX + Screen.height * 0.025f, (float)Screen.height * 0.035f, 0f, (float)Screen.height * 0.03f);
printTotalTimer(target, p1Text, p1Rect);
int elapsedTimeP2 = totalTimeout - p2TotalSeconds - p2TurnSeconds;
int elapsedMinsP2 = elapsedTimeP2 / 60;
int elapsedSecsP2 = elapsedTimeP2 % 60;
string p2Text = (elapsedMinsP2 < 10 ? "0" : "") + elapsedMinsP2 + " " + (elapsedSecsP2 < 10 ? "0" : "") + elapsedSecsP2;
Rect p2Rect = new Rect((float)(Screen.width / 2) - width / 2f + namesBoxX + Screen.height * 0.025f, (float)Screen.height * 0.035f, 0f, (float)Screen.height * 0.03f);
printTotalTimer(target, p2Text, p2Rect);
}
}
}
private bool isTimerChangeMsg(RoomChatMessageMessage msg) {
string[] cmds = msg.text.ToLower().Split(' ');
return cmds[0].Equals("/timerchange") || cmds[0].Equals("/tc");
}
private int splitMinutesAndSeconds(string text, out int seconds) {
string[] split = text.Split(new char[] {':','.',','});
if (split.Length == 2) {
seconds = Convert.ToInt32(split[1]);
return Convert.ToInt32(split[0]);
}
else {
seconds = Convert.ToInt32(split[0]);
return 0;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Description;
using Albums.Services.Areas.HelpPage.Models;
namespace Albums.Services.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
model = GenerateApiModel(apiDescription, sampleGenerator);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HelpPageSampleGenerator sampleGenerator)
{
HelpPageApiModel apiModel = new HelpPageApiModel();
apiModel.ApiDescription = apiDescription;
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception Message: {0}", e.Message));
}
return apiModel;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="DataPortalException.cs" company="Marimer LLC">
// Copyright (c) Marimer LLC. All rights reserved.
// Website: http://www.lhotka.net/cslanet/
// </copyright>
// <summary>This exception is returned for any errors occuring</summary>
//-----------------------------------------------------------------------
using System;
#if !NETFX_CORE
using System.Security.Permissions;
#endif
namespace Csla
{
/// <summary>
/// This exception is returned for any errors occurring
/// during the server-side DataPortal invocation.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1032:ImplementStandardExceptionConstructors")]
[Serializable]
public class DataPortalException : Exception
{
/// <summary>
/// Creates an instance of the object.
/// </summary>
/// <param name="message">Text describing the exception.</param>
/// <param name="businessObject">The business object
/// as it was at the time of the exception.</param>
public DataPortalException(string message, object businessObject)
: base(message)
{
_innerStackTrace = String.Empty;
_businessObject = businessObject;
}
/// <summary>
/// Creates an instance of the object.
/// </summary>
/// <param name="message">Text describing the exception.</param>
/// <param name="ex">Inner exception.</param>
/// <param name="businessObject">The business object
/// as it was at the time of the exception.</param>
public DataPortalException(string message, Exception ex, object businessObject)
: base(message, ex)
{
_innerStackTrace = ex.StackTrace;
_businessObject = businessObject;
}
/// <summary>
/// Creates an instance of the object.
/// </summary>
/// <param name="message">
/// Exception message.
/// </param>
/// <param name="ex">
/// Inner exception.
/// </param>
public DataPortalException(string message, Exception ex)
: base(message, ex)
{
_innerStackTrace = ex.StackTrace;
}
#if !NETFX_PHONE || PCL46
#if !NETCORE && !PCL46 && !ANDROID
/// <summary>
/// Creates an instance of the object.
/// </summary>
/// <param name="info">Info about the exception.</param>
public DataPortalException(WcfPortal.WcfErrorInfo info)
: base(info.Message)
{
this.ErrorInfo = new Csla.Server.Hosts.HttpChannel.HttpErrorInfo(info);
}
#endif
/// <summary>
/// Creates an instance of the object.
/// </summary>
/// <param name="info">Info about the exception.</param>
public DataPortalException(Csla.Server.Hosts.HttpChannel.HttpErrorInfo info)
: base(info.Message)
{
this.ErrorInfo = info;
}
/// <summary>
/// Gets a string representation
/// of this object.
/// </summary>
public override string ToString()
{
var sb = new System.Text.StringBuilder();
sb.AppendLine(base.ToString());
if (ErrorInfo != null)
{
sb.AppendLine("------------------------------");
var error = this.ErrorInfo;
while (error != null)
{
sb.AppendFormat("{0}: {1}", error.ExceptionTypeName, error.Message);
sb.Append(Environment.NewLine);
sb.Append(error.StackTrace);
sb.Append(Environment.NewLine);
error = error.InnerError;
}
}
return sb.ToString();
}
/// <summary>
/// Gets information about the original
/// server-side exception. That exception
/// is not an exception on the client side,
/// but this property returns information
/// about the exception.
/// </summary>
public Csla.Server.Hosts.HttpChannel.HttpErrorInfo ErrorInfo { get; private set; }
#endif
private object _businessObject;
private string _innerStackTrace;
/// <summary>
/// Returns a reference to the business object
/// from the server-side DataPortal.
/// </summary>
/// <remarks>
/// Remember that this object may be in an invalid
/// or undefined state. This is the business object
/// (and any child objects) as it existed when the
/// exception occured on the server. Thus the object
/// state may have been altered by the server and
/// may no longer reflect data in the database.
/// </remarks>
public object BusinessObject
{
get { return _businessObject; }
}
/// <summary>
/// Gets the original server-side exception.
/// </summary>
/// <returns>An exception object.</returns>
/// <remarks>
/// When an exception occurs in business code behind
/// the data portal, it is wrapped in a
/// <see cref="Csla.Server.DataPortalException"/>, which
/// is then wrapped in a
/// <see cref="Csla.DataPortalException"/>. This property
/// unwraps and returns the original exception
/// thrown by the business code on the server.
/// </remarks>
public Exception BusinessException
{
get
{
var result = this.InnerException.InnerException;
var dpe = result as DataPortalException;
if (dpe != null && dpe.InnerException != null)
result = dpe.InnerException;
var cme = result as Csla.Reflection.CallMethodException;
if (cme != null && cme.InnerException != null)
result = cme.InnerException;
return result;
}
}
/// <summary>
/// Get the combined stack trace from the server
/// and client.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.String.Format(System.String,System.Object,System.Object,System.Object)")]
public override string StackTrace
{
get { return String.Format("{0}{1}{2}", _innerStackTrace, Environment.NewLine, base.StackTrace); }
}
#if !(ANDROID || IOS) && !NETFX_CORE
/// <summary>
/// Creates an instance of the object for serialization.
/// </summary>
/// <param name="info">Serialiation info object.</param>
/// <param name="context">Serialization context object.</param>
protected DataPortalException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
: base(info, context)
{
_businessObject = info.GetValue("_businessObject", typeof(object));
_innerStackTrace = info.GetString("_innerStackTrace");
}
/// <summary>
/// Serializes the object.
/// </summary>
/// <param name="info">Serialiation info object.</param>
/// <param name="context">Serialization context object.</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")]
[SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)]
[SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.SerializationFormatter)]
public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
{
base.GetObjectData(info, context);
info.AddValue("_businessObject", _businessObject);
info.AddValue("_innerStackTrace", _innerStackTrace);
}
#endif
}
}
| |
// 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.
////////////////////////////////////////////////////////////////////////////////
//
namespace System.Reflection
{
using System;
using System.Diagnostics.SymbolStore;
using System.Runtime.Remoting;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Runtime.CompilerServices;
using System.Security;
using System.Security.Permissions;
using System.IO;
using System.Globalization;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
[Serializable]
[Flags]
[System.Runtime.InteropServices.ComVisible(true)]
public enum PortableExecutableKinds
{
NotAPortableExecutableImage = 0x0,
ILOnly = 0x1,
Required32Bit = 0x2,
PE32Plus = 0x4,
Unmanaged32Bit = 0x8,
[ComVisible(false)]
Preferred32Bit = 0x10,
}
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public enum ImageFileMachine
{
I386 = 0x014c,
IA64 = 0x0200,
AMD64 = 0x8664,
ARM = 0x01c4,
}
[Serializable]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(_Module))]
[System.Runtime.InteropServices.ComVisible(true)]
#pragma warning disable 618
[PermissionSetAttribute(SecurityAction.InheritanceDemand, Unrestricted = true)]
#pragma warning restore 618
public abstract class Module : _Module, ISerializable, ICustomAttributeProvider
{
#region Static Constructor
static Module()
{
__Filters _fltObj;
_fltObj = new __Filters();
FilterTypeName = new TypeFilter(_fltObj.FilterTypeName);
FilterTypeNameIgnoreCase = new TypeFilter(_fltObj.FilterTypeNameIgnoreCase);
}
#endregion
#region Constructor
protected Module()
{
}
#endregion
#region Public Statics
public static readonly TypeFilter FilterTypeName;
public static readonly TypeFilter FilterTypeNameIgnoreCase;
public static bool operator ==(Module left, Module right)
{
if (ReferenceEquals(left, right))
return true;
if ((object)left == null || (object)right == null ||
left is RuntimeModule || right is RuntimeModule)
{
return false;
}
return left.Equals(right);
}
public static bool operator !=(Module left, Module right)
{
return !(left == right);
}
public override bool Equals(object o)
{
return base.Equals(o);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
#endregion
#region Literals
private const BindingFlags DefaultLookup = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public;
#endregion
#region object overrides
public override String ToString()
{
return ScopeName;
}
#endregion
public virtual IEnumerable<CustomAttributeData> CustomAttributes
{
get
{
return GetCustomAttributesData();
}
}
#region ICustomAttributeProvider Members
public virtual Object[] GetCustomAttributes(bool inherit)
{
throw new NotImplementedException();
}
public virtual Object[] GetCustomAttributes(Type attributeType, bool inherit)
{
throw new NotImplementedException();
}
public virtual bool IsDefined(Type attributeType, bool inherit)
{
throw new NotImplementedException();
}
public virtual IList<CustomAttributeData> GetCustomAttributesData()
{
throw new NotImplementedException();
}
#endregion
#region public instances members
public MethodBase ResolveMethod(int metadataToken)
{
return ResolveMethod(metadataToken, null, null);
}
public virtual MethodBase ResolveMethod(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
{
// This API was made virtual in V4. Code compiled against V2 might use
// "call" rather than "callvirt" to call it.
// This makes sure those code still works.
RuntimeModule rtModule = this as RuntimeModule;
if (rtModule != null)
return rtModule.ResolveMethod(metadataToken, genericTypeArguments, genericMethodArguments);
throw new NotImplementedException();
}
public FieldInfo ResolveField(int metadataToken)
{
return ResolveField(metadataToken, null, null);
}
public virtual FieldInfo ResolveField(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
{
// This API was made virtual in V4. Code compiled against V2 might use
// "call" rather than "callvirt" to call it.
// This makes sure those code still works.
RuntimeModule rtModule = this as RuntimeModule;
if (rtModule != null)
return rtModule.ResolveField(metadataToken, genericTypeArguments, genericMethodArguments);
throw new NotImplementedException();
}
public Type ResolveType(int metadataToken)
{
return ResolveType(metadataToken, null, null);
}
public virtual Type ResolveType(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
{
// This API was made virtual in V4. Code compiled against V2 might use
// "call" rather than "callvirt" to call it.
// This makes sure those code still works.
RuntimeModule rtModule = this as RuntimeModule;
if (rtModule != null)
return rtModule.ResolveType(metadataToken, genericTypeArguments, genericMethodArguments);
throw new NotImplementedException();
}
public MemberInfo ResolveMember(int metadataToken)
{
return ResolveMember(metadataToken, null, null);
}
public virtual MemberInfo ResolveMember(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
{
// This API was made virtual in V4. Code compiled against V2 might use
// "call" rather than "callvirt" to call it.
// This makes sure those code still works.
RuntimeModule rtModule = this as RuntimeModule;
if (rtModule != null)
return rtModule.ResolveMember(metadataToken, genericTypeArguments, genericMethodArguments);
throw new NotImplementedException();
}
public virtual byte[] ResolveSignature(int metadataToken)
{
// This API was made virtual in V4. Code compiled against V2 might use
// "call" rather than "callvirt" to call it.
// This makes sure those code still works.
RuntimeModule rtModule = this as RuntimeModule;
if (rtModule != null)
return rtModule.ResolveSignature(metadataToken);
throw new NotImplementedException();
}
public virtual string ResolveString(int metadataToken)
{
// This API was made virtual in V4. Code compiled against V2 might use
// "call" rather than "callvirt" to call it.
// This makes sure those code still works.
RuntimeModule rtModule = this as RuntimeModule;
if (rtModule != null)
return rtModule.ResolveString(metadataToken);
throw new NotImplementedException();
}
public virtual void GetPEKind(out PortableExecutableKinds peKind, out ImageFileMachine machine)
{
// This API was made virtual in V4. Code compiled against V2 might use
// "call" rather than "callvirt" to call it.
// This makes sure those code still works.
RuntimeModule rtModule = this as RuntimeModule;
if (rtModule != null)
rtModule.GetPEKind(out peKind, out machine);
throw new NotImplementedException();
}
public virtual int MDStreamVersion
{
get
{
// This API was made virtual in V4. Code compiled against V2 might use
// "call" rather than "callvirt" to call it.
// This makes sure those code still works.
RuntimeModule rtModule = this as RuntimeModule;
if (rtModule != null)
return rtModule.MDStreamVersion;
throw new NotImplementedException();
}
}
[System.Security.SecurityCritical] // auto-generated_required
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new NotImplementedException();
}
[System.Runtime.InteropServices.ComVisible(true)]
public virtual Type GetType(String className, bool ignoreCase)
{
return GetType(className, false, ignoreCase);
}
[System.Runtime.InteropServices.ComVisible(true)]
public virtual Type GetType(String className) {
return GetType(className, false, false);
}
[System.Runtime.InteropServices.ComVisible(true)]
public virtual Type GetType(String className, bool throwOnError, bool ignoreCase)
{
throw new NotImplementedException();
}
public virtual String FullyQualifiedName
{
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
get
{
throw new NotImplementedException();
}
}
public virtual Type[] FindTypes(TypeFilter filter,Object filterCriteria)
{
Type[] c = GetTypes();
int cnt = 0;
for (int i = 0;i<c.Length;i++) {
if (filter!=null && !filter(c[i],filterCriteria))
c[i] = null;
else
cnt++;
}
if (cnt == c.Length)
return c;
Type[] ret = new Type[cnt];
cnt=0;
for (int i=0;i<c.Length;i++) {
if (c[i] != null)
ret[cnt++] = c[i];
}
return ret;
}
public virtual Type[] GetTypes()
{
throw new NotImplementedException();
}
public virtual Guid ModuleVersionId
{
get
{
// This API was made virtual in V4. Code compiled against V2 might use
// "call" rather than "callvirt" to call it.
// This makes sure those code still works.
RuntimeModule rtModule = this as RuntimeModule;
if (rtModule != null)
return rtModule.ModuleVersionId;
throw new NotImplementedException();
}
}
public virtual int MetadataToken
{
get
{
// This API was made virtual in V4. Code compiled against V2 might use
// "call" rather than "callvirt" to call it.
// This makes sure those code still works.
RuntimeModule rtModule = this as RuntimeModule;
if (rtModule != null)
return rtModule.MetadataToken;
throw new NotImplementedException();
}
}
public virtual bool IsResource()
{
// This API was made virtual in V4. Code compiled against V2 might use
// "call" rather than "callvirt" to call it.
// This makes sure those code still works.
RuntimeModule rtModule = this as RuntimeModule;
if (rtModule != null)
return rtModule.IsResource();
throw new NotImplementedException();
}
public FieldInfo[] GetFields()
{
return GetFields(Module.DefaultLookup);
}
public virtual FieldInfo[] GetFields(BindingFlags bindingFlags)
{
// This API was made virtual in V4. Code compiled against V2 might use
// "call" rather than "callvirt" to call it.
// This makes sure those code still works.
RuntimeModule rtModule = this as RuntimeModule;
if (rtModule != null)
return rtModule.GetFields(bindingFlags);
throw new NotImplementedException();
}
public FieldInfo GetField(String name)
{
return GetField(name,Module.DefaultLookup);
}
public virtual FieldInfo GetField(String name, BindingFlags bindingAttr)
{
// This API was made virtual in V4. Code compiled against V2 might use
// "call" rather than "callvirt" to call it.
// This makes sure those code still works.
RuntimeModule rtModule = this as RuntimeModule;
if (rtModule != null)
return rtModule.GetField(name, bindingAttr);
throw new NotImplementedException();
}
public MethodInfo[] GetMethods()
{
return GetMethods(Module.DefaultLookup);
}
public virtual MethodInfo[] GetMethods(BindingFlags bindingFlags)
{
// This API was made virtual in V4. Code compiled against V2 might use
// "call" rather than "callvirt" to call it.
// This makes sure those code still works.
RuntimeModule rtModule = this as RuntimeModule;
if (rtModule != null)
return rtModule.GetMethods(bindingFlags);
throw new NotImplementedException();
}
public MethodInfo GetMethod(
String name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
{
if (name == null)
throw new ArgumentNullException("name");
if (types == null)
throw new ArgumentNullException("types");
Contract.EndContractBlock();
for (int i = 0; i < types.Length; i++)
{
if (types[i] == null)
throw new ArgumentNullException("types");
}
return GetMethodImpl(name, bindingAttr, binder, callConvention, types, modifiers);
}
public MethodInfo GetMethod(String name, Type[] types)
{
if (name == null)
throw new ArgumentNullException("name");
if (types == null)
throw new ArgumentNullException("types");
Contract.EndContractBlock();
for (int i = 0; i < types.Length; i++)
{
if (types[i] == null)
throw new ArgumentNullException("types");
}
return GetMethodImpl(name, Module.DefaultLookup, null, CallingConventions.Any, types, null);
}
public MethodInfo GetMethod(String name)
{
if (name == null)
throw new ArgumentNullException("name");
Contract.EndContractBlock();
return GetMethodImpl(name, Module.DefaultLookup, null, CallingConventions.Any,
null, null);
}
protected virtual MethodInfo GetMethodImpl(String name, BindingFlags bindingAttr, Binder binder,
CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
{
throw new NotImplementedException();
}
public virtual String ScopeName
{
get
{
// This API was made virtual in V4. Code compiled against V2 might use
// "call" rather than "callvirt" to call it.
// This makes sure those code still works.
RuntimeModule rtModule = this as RuntimeModule;
if (rtModule != null)
return rtModule.ScopeName;
throw new NotImplementedException();
}
}
public virtual String Name
{
get
{
// This API was made virtual in V4. Code compiled against V2 might use
// "call" rather than "callvirt" to call it.
// This makes sure those code still works.
RuntimeModule rtModule = this as RuntimeModule;
if (rtModule != null)
return rtModule.Name;
throw new NotImplementedException();
}
}
public virtual Assembly Assembly
{
[Pure]
get
{
// This API was made virtual in V4. Code compiled against V2 might use
// "call" rather than "callvirt" to call it.
// This makes sure those code still works.
RuntimeModule rtModule = this as RuntimeModule;
if (rtModule != null)
return rtModule.Assembly;
throw new NotImplementedException();
}
}
// This API never fails, it will return an empty handle for non-runtime handles and
// a valid handle for reflection only modules.
public ModuleHandle ModuleHandle
{
get
{
return GetModuleHandle();
}
}
// Used to provide implementation and overriding point for ModuleHandle.
// To get a module handle inside mscorlib, use GetNativeHandle instead.
internal virtual ModuleHandle GetModuleHandle()
{
return ModuleHandle.EmptyHandle;
}
#if FEATURE_X509 && FEATURE_CAS_POLICY
public virtual System.Security.Cryptography.X509Certificates.X509Certificate GetSignerCertificate()
{
throw new NotImplementedException();
}
#endif // FEATURE_X509 && FEATURE_CAS_POLICY
#endregion
#if !FEATURE_CORECLR
void _Module.GetTypeInfoCount(out uint pcTInfo)
{
throw new NotImplementedException();
}
void _Module.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
{
throw new NotImplementedException();
}
void _Module.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
{
throw new NotImplementedException();
}
void _Module.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
{
throw new NotImplementedException();
}
#endif
}
[Serializable]
internal class RuntimeModule : Module
{
internal RuntimeModule() { throw new NotSupportedException(); }
#region FCalls
[System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void GetType(RuntimeModule module, String className, bool ignoreCase, bool throwOnError, ObjectHandleOnStack type, ObjectHandleOnStack keepAlive);
[System.Security.SecurityCritical]
[DllImport(JitHelpers.QCall)]
[SuppressUnmanagedCodeSecurity]
private static extern bool nIsTransientInternal(RuntimeModule module);
[System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void GetScopeName(RuntimeModule module, StringHandleOnStack retString);
[System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void GetFullyQualifiedName(RuntimeModule module, StringHandleOnStack retString);
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern static RuntimeType[] GetTypes(RuntimeModule module);
[System.Security.SecuritySafeCritical] // auto-generated
internal RuntimeType[] GetDefinedTypes()
{
return GetTypes(GetNativeHandle());
}
[System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern static bool IsResource(RuntimeModule module);
#if FEATURE_X509 && FEATURE_CAS_POLICY
[System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
static private extern void GetSignerCertificate(RuntimeModule module, ObjectHandleOnStack retData);
#endif // FEATURE_X509 && FEATURE_CAS_POLICY
#endregion
#region Module overrides
private static RuntimeTypeHandle[] ConvertToTypeHandleArray(Type[] genericArguments)
{
if (genericArguments == null)
return null;
int size = genericArguments.Length;
RuntimeTypeHandle[] typeHandleArgs = new RuntimeTypeHandle[size];
for (int i = 0; i < size; i++)
{
Type typeArg = genericArguments[i];
if (typeArg == null)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidGenericInstArray"));
typeArg = typeArg.UnderlyingSystemType;
if (typeArg == null)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidGenericInstArray"));
if (!(typeArg is RuntimeType))
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidGenericInstArray"));
typeHandleArgs[i] = typeArg.GetTypeHandleInternal();
}
return typeHandleArgs;
}
[System.Security.SecuritySafeCritical] // auto-generated
public override byte[] ResolveSignature(int metadataToken)
{
MetadataToken tk = new MetadataToken(metadataToken);
if (!MetadataImport.IsValidToken(tk))
throw new ArgumentOutOfRangeException("metadataToken",
Environment.GetResourceString("Argument_InvalidToken", tk, this));
if (!tk.IsMemberRef && !tk.IsMethodDef && !tk.IsTypeSpec && !tk.IsSignature && !tk.IsFieldDef)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidToken", tk, this),
"metadataToken");
ConstArray signature;
if (tk.IsMemberRef)
signature = MetadataImport.GetMemberRefProps(metadataToken);
else
signature = MetadataImport.GetSignatureFromToken(metadataToken);
byte[] sig = new byte[signature.Length];
for (int i = 0; i < signature.Length; i++)
sig[i] = signature[i];
return sig;
}
[System.Security.SecuritySafeCritical] // auto-generated
public override MethodBase ResolveMethod(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
{
MetadataToken tk = new MetadataToken(metadataToken);
if (!MetadataImport.IsValidToken(tk))
throw new ArgumentOutOfRangeException("metadataToken",
Environment.GetResourceString("Argument_InvalidToken", tk, this));
RuntimeTypeHandle[] typeArgs = ConvertToTypeHandleArray(genericTypeArguments);
RuntimeTypeHandle[] methodArgs = ConvertToTypeHandleArray(genericMethodArguments);
try
{
if (!tk.IsMethodDef && !tk.IsMethodSpec)
{
if (!tk.IsMemberRef)
throw new ArgumentException("metadataToken",
Environment.GetResourceString("Argument_ResolveMethod", tk, this));
unsafe
{
ConstArray sig = MetadataImport.GetMemberRefProps(tk);
if (*(MdSigCallingConvention*)sig.Signature.ToPointer() == MdSigCallingConvention.Field)
throw new ArgumentException("metadataToken",
Environment.GetResourceString("Argument_ResolveMethod", tk, this));
}
}
IRuntimeMethodInfo methodHandle = ModuleHandle.ResolveMethodHandleInternal(GetNativeHandle(), tk, typeArgs, methodArgs);
Type declaringType = RuntimeMethodHandle.GetDeclaringType(methodHandle);
if (declaringType.IsGenericType || declaringType.IsArray)
{
MetadataToken tkDeclaringType = new MetadataToken(MetadataImport.GetParentToken(tk));
if (tk.IsMethodSpec)
tkDeclaringType = new MetadataToken(MetadataImport.GetParentToken(tkDeclaringType));
declaringType = ResolveType(tkDeclaringType, genericTypeArguments, genericMethodArguments);
}
return System.RuntimeType.GetMethodBase(declaringType as RuntimeType, methodHandle);
}
catch (BadImageFormatException e)
{
throw new ArgumentException(Environment.GetResourceString("Argument_BadImageFormatExceptionResolve"), e);
}
}
[System.Security.SecurityCritical] // auto-generated
private FieldInfo ResolveLiteralField(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
{
MetadataToken tk = new MetadataToken(metadataToken);
if (!MetadataImport.IsValidToken(tk) || !tk.IsFieldDef)
throw new ArgumentOutOfRangeException("metadataToken",
String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Argument_InvalidToken", tk, this)));
int tkDeclaringType;
string fieldName;
fieldName = MetadataImport.GetName(tk).ToString();
tkDeclaringType = MetadataImport.GetParentToken(tk);
Type declaringType = ResolveType(tkDeclaringType, genericTypeArguments, genericMethodArguments);
declaringType.GetFields();
try
{
return declaringType.GetField(fieldName,
BindingFlags.Static | BindingFlags.Instance |
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.DeclaredOnly);
}
catch
{
throw new ArgumentException(Environment.GetResourceString("Argument_ResolveField", tk, this), "metadataToken");
}
}
[System.Security.SecuritySafeCritical] // auto-generated
public override FieldInfo ResolveField(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
{
MetadataToken tk = new MetadataToken(metadataToken);
if (!MetadataImport.IsValidToken(tk))
throw new ArgumentOutOfRangeException("metadataToken",
Environment.GetResourceString("Argument_InvalidToken", tk, this));
RuntimeTypeHandle[] typeArgs = ConvertToTypeHandleArray(genericTypeArguments);
RuntimeTypeHandle[] methodArgs = ConvertToTypeHandleArray(genericMethodArguments);
try
{
IRuntimeFieldInfo fieldHandle = null;
if (!tk.IsFieldDef)
{
if (!tk.IsMemberRef)
throw new ArgumentException("metadataToken",
Environment.GetResourceString("Argument_ResolveField", tk, this));
unsafe
{
ConstArray sig = MetadataImport.GetMemberRefProps(tk);
if (*(MdSigCallingConvention*)sig.Signature.ToPointer() != MdSigCallingConvention.Field)
throw new ArgumentException("metadataToken",
Environment.GetResourceString("Argument_ResolveField", tk, this));
}
fieldHandle = ModuleHandle.ResolveFieldHandleInternal(GetNativeHandle(), tk, typeArgs, methodArgs);
}
fieldHandle = ModuleHandle.ResolveFieldHandleInternal(GetNativeHandle(), metadataToken, typeArgs, methodArgs);
RuntimeType declaringType = RuntimeFieldHandle.GetApproxDeclaringType(fieldHandle.Value);
if (declaringType.IsGenericType || declaringType.IsArray)
{
int tkDeclaringType = ModuleHandle.GetMetadataImport(GetNativeHandle()).GetParentToken(metadataToken);
declaringType = (RuntimeType)ResolveType(tkDeclaringType, genericTypeArguments, genericMethodArguments);
}
return System.RuntimeType.GetFieldInfo(declaringType, fieldHandle);
}
catch(MissingFieldException)
{
return ResolveLiteralField(tk, genericTypeArguments, genericMethodArguments);
}
catch (BadImageFormatException e)
{
throw new ArgumentException(Environment.GetResourceString("Argument_BadImageFormatExceptionResolve"), e);
}
}
[System.Security.SecuritySafeCritical] // auto-generated
public override Type ResolveType(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
{
MetadataToken tk = new MetadataToken(metadataToken);
if (tk.IsGlobalTypeDefToken)
throw new ArgumentException(Environment.GetResourceString("Argument_ResolveModuleType", tk), "metadataToken");
if (!MetadataImport.IsValidToken(tk))
throw new ArgumentOutOfRangeException("metadataToken",
Environment.GetResourceString("Argument_InvalidToken", tk, this));
if (!tk.IsTypeDef && !tk.IsTypeSpec && !tk.IsTypeRef)
throw new ArgumentException(Environment.GetResourceString("Argument_ResolveType", tk, this), "metadataToken");
RuntimeTypeHandle[] typeArgs = ConvertToTypeHandleArray(genericTypeArguments);
RuntimeTypeHandle[] methodArgs = ConvertToTypeHandleArray(genericMethodArguments);
try
{
Type t = GetModuleHandle().ResolveTypeHandle(metadataToken, typeArgs, methodArgs).GetRuntimeType();
if (t == null)
throw new ArgumentException(Environment.GetResourceString("Argument_ResolveType", tk, this), "metadataToken");
return t;
}
catch (BadImageFormatException e)
{
throw new ArgumentException(Environment.GetResourceString("Argument_BadImageFormatExceptionResolve"), e);
}
}
[System.Security.SecuritySafeCritical] // auto-generated
public override MemberInfo ResolveMember(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
{
MetadataToken tk = new MetadataToken(metadataToken);
if (tk.IsProperty)
throw new ArgumentException(Environment.GetResourceString("InvalidOperation_PropertyInfoNotAvailable"));
if (tk.IsEvent)
throw new ArgumentException(Environment.GetResourceString("InvalidOperation_EventInfoNotAvailable"));
if (tk.IsMethodSpec || tk.IsMethodDef)
return ResolveMethod(metadataToken, genericTypeArguments, genericMethodArguments);
if (tk.IsFieldDef)
return ResolveField(metadataToken, genericTypeArguments, genericMethodArguments);
if (tk.IsTypeRef || tk.IsTypeDef || tk.IsTypeSpec)
return ResolveType(metadataToken, genericTypeArguments, genericMethodArguments);
if (tk.IsMemberRef)
{
if (!MetadataImport.IsValidToken(tk))
throw new ArgumentOutOfRangeException("metadataToken",
Environment.GetResourceString("Argument_InvalidToken", tk, this));
ConstArray sig = MetadataImport.GetMemberRefProps(tk);
unsafe
{
if (*(MdSigCallingConvention*)sig.Signature.ToPointer() == MdSigCallingConvention.Field)
{
return ResolveField(tk, genericTypeArguments, genericMethodArguments);
}
else
{
return ResolveMethod(tk, genericTypeArguments, genericMethodArguments);
}
}
}
throw new ArgumentException("metadataToken",
Environment.GetResourceString("Argument_ResolveMember", tk, this));
}
[System.Security.SecuritySafeCritical] // auto-generated
public override string ResolveString(int metadataToken)
{
MetadataToken tk = new MetadataToken(metadataToken);
if (!tk.IsString)
throw new ArgumentException(
String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Argument_ResolveString"), metadataToken, ToString()));
if (!MetadataImport.IsValidToken(tk))
throw new ArgumentOutOfRangeException("metadataToken",
String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Argument_InvalidToken", tk, this)));
string str = MetadataImport.GetUserString(metadataToken);
if (str == null)
throw new ArgumentException(
String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Argument_ResolveString"), metadataToken, ToString()));
return str;
}
public override void GetPEKind(out PortableExecutableKinds peKind, out ImageFileMachine machine)
{
ModuleHandle.GetPEKind(GetNativeHandle(), out peKind, out machine);
}
public override int MDStreamVersion
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
return ModuleHandle.GetMDStreamVersion(GetNativeHandle());
}
}
#endregion
#region Data Members
#pragma warning disable 169
// If you add any data members, you need to update the native declaration ReflectModuleBaseObject.
private RuntimeType m_runtimeType;
private RuntimeAssembly m_runtimeAssembly;
private IntPtr m_pRefClass;
private IntPtr m_pData;
private IntPtr m_pGlobals;
private IntPtr m_pFields;
#pragma warning restore 169
#endregion
#region Protected Virtuals
protected override MethodInfo GetMethodImpl(String name, BindingFlags bindingAttr, Binder binder,
CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
{
return GetMethodInternal(name, bindingAttr, binder, callConvention, types, modifiers);
}
internal MethodInfo GetMethodInternal(String name, BindingFlags bindingAttr, Binder binder,
CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
{
if (RuntimeType == null)
return null;
if (types == null)
{
return RuntimeType.GetMethod(name, bindingAttr);
}
else
{
return RuntimeType.GetMethod(name, bindingAttr, binder, callConvention, types, modifiers);
}
}
#endregion
#region Internal Members
internal RuntimeType RuntimeType
{
get
{
if (m_runtimeType == null)
m_runtimeType = ModuleHandle.GetModuleType(GetNativeHandle());
return m_runtimeType;
}
}
[System.Security.SecuritySafeCritical]
internal bool IsTransientInternal()
{
return RuntimeModule.nIsTransientInternal(this.GetNativeHandle());
}
internal MetadataImport MetadataImport
{
[System.Security.SecurityCritical] // auto-generated
get
{
unsafe
{
return ModuleHandle.GetMetadataImport(GetNativeHandle());
}
}
}
#endregion
#region ICustomAttributeProvider Members
public override Object[] GetCustomAttributes(bool inherit)
{
return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType);
}
public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
{
if (attributeType == null)
throw new ArgumentNullException("attributeType");
Contract.EndContractBlock();
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"attributeType");
return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType);
}
[System.Security.SecuritySafeCritical] // auto-generated
public override bool IsDefined(Type attributeType, bool inherit)
{
if (attributeType == null)
throw new ArgumentNullException("attributeType");
Contract.EndContractBlock();
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"attributeType");
return CustomAttribute.IsDefined(this, attributeRuntimeType);
}
public override IList<CustomAttributeData> GetCustomAttributesData()
{
return CustomAttributeData.GetCustomAttributesInternal(this);
}
#endregion
#region Public Virtuals
[System.Security.SecurityCritical] // auto-generated_required
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
{
throw new ArgumentNullException("info");
}
Contract.EndContractBlock();
UnitySerializationHolder.GetUnitySerializationInfo(info, UnitySerializationHolder.ModuleUnity, this.ScopeName, this.GetRuntimeAssembly());
}
[System.Security.SecuritySafeCritical] // auto-generated
[System.Runtime.InteropServices.ComVisible(true)]
public override Type GetType(String className, bool throwOnError, bool ignoreCase)
{
// throw on null strings regardless of the value of "throwOnError"
if (className == null)
throw new ArgumentNullException("className");
RuntimeType retType = null;
Object keepAlive = null;
GetType(GetNativeHandle(), className, throwOnError, ignoreCase, JitHelpers.GetObjectHandleOnStack(ref retType), JitHelpers.GetObjectHandleOnStack(ref keepAlive));
GC.KeepAlive(keepAlive);
return retType;
}
[System.Security.SecurityCritical] // auto-generated
internal string GetFullyQualifiedName()
{
String fullyQualifiedName = null;
GetFullyQualifiedName(GetNativeHandle(), JitHelpers.GetStringHandleOnStack(ref fullyQualifiedName));
return fullyQualifiedName;
}
public override String FullyQualifiedName
{
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#else
[System.Security.SecuritySafeCritical]
#endif
get
{
String fullyQualifiedName = GetFullyQualifiedName();
if (fullyQualifiedName != null) {
bool checkPermission = true;
try {
Path.GetFullPathInternal(fullyQualifiedName);
}
catch(ArgumentException) {
checkPermission = false;
}
if (checkPermission) {
new FileIOPermission( FileIOPermissionAccess.PathDiscovery, fullyQualifiedName ).Demand();
}
}
return fullyQualifiedName;
}
}
[System.Security.SecuritySafeCritical] // auto-generated
public override Type[] GetTypes()
{
return GetTypes(GetNativeHandle());
}
#endregion
#region Public Members
public override Guid ModuleVersionId
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
unsafe
{
Guid mvid;
MetadataImport.GetScopeProps(out mvid);
return mvid;
}
}
}
public override int MetadataToken
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
return ModuleHandle.GetToken(GetNativeHandle());
}
}
public override bool IsResource()
{
return IsResource(GetNativeHandle());
}
public override FieldInfo[] GetFields(BindingFlags bindingFlags)
{
if (RuntimeType == null)
return new FieldInfo[0];
return RuntimeType.GetFields(bindingFlags);
}
public override FieldInfo GetField(String name, BindingFlags bindingAttr)
{
if (name == null)
throw new ArgumentNullException("name");
if (RuntimeType == null)
return null;
return RuntimeType.GetField(name, bindingAttr);
}
public override MethodInfo[] GetMethods(BindingFlags bindingFlags)
{
if (RuntimeType == null)
return new MethodInfo[0];
return RuntimeType.GetMethods(bindingFlags);
}
public override String ScopeName
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
string scopeName = null;
GetScopeName(GetNativeHandle(), JitHelpers.GetStringHandleOnStack(ref scopeName));
return scopeName;
}
}
public override String Name
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
String s = GetFullyQualifiedName();
#if !FEATURE_PAL
int i = s.LastIndexOf('\\');
#else
int i = s.LastIndexOf(System.IO.Path.DirectorySeparatorChar);
#endif
if (i == -1)
return s;
return new String(s.ToCharArray(), i + 1, s.Length - i - 1);
}
}
public override Assembly Assembly
{
[Pure]
get
{
return GetRuntimeAssembly();
}
}
internal RuntimeAssembly GetRuntimeAssembly()
{
return m_runtimeAssembly;
}
internal override ModuleHandle GetModuleHandle()
{
return new ModuleHandle(this);
}
internal RuntimeModule GetNativeHandle()
{
return this;
}
#if FEATURE_X509 && FEATURE_CAS_POLICY
[System.Security.SecuritySafeCritical] // auto-generated
public override System.Security.Cryptography.X509Certificates.X509Certificate GetSignerCertificate()
{
byte[] data = null;
GetSignerCertificate(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref data));
return (data != null) ? new System.Security.Cryptography.X509Certificates.X509Certificate(data) : null;
}
#endif // FEATURE_X509 && FEATURE_CAS_POLICY
#endregion
}
}
| |
#define AWS_APM_API
//
// Copyright 2014-2015 Amazon.com,
// Inc. or its affiliates. All Rights Reserved.
//
// Licensed under the Amazon Software License (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/asl/
//
// or in the "license" file accompanying this file. This file is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, express or implied. See the License
// for the specific language governing permissions and
// limitations under the License.
//
using Amazon.Runtime.Internal.Util;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
namespace Amazon.Runtime.Internal
{
/// <summary>
/// A runtime pipeline contains a collection of handlers which represent
/// different stages of request and response processing.
/// </summary>
public partial class RuntimePipeline : IDisposable
{
#region Private members
bool _disposed;
ILogger _logger;
// The top-most handler in the pipeline.
IPipelineHandler _handler;
#endregion
#region Properties
/// <summary>
/// The top-most handler in the pipeline.
/// </summary>
public IPipelineHandler Handler
{
get { return _handler; }
}
#endregion
#region Constructors
/// <summary>
/// Constructor for RuntimePipeline.
/// </summary>
/// <param name="handler">The handler with which the pipeline is initalized.</param>
public RuntimePipeline(IPipelineHandler handler)
{
if (handler == null)
throw new ArgumentNullException("handler");
var logger =
Amazon.Runtime.Internal.Util.Logger.GetLogger(typeof(RuntimePipeline));
_handler = handler;
_handler.Logger = logger;
_logger = logger;
}
/// <summary>
/// Constructor for RuntimePipeline.
/// </summary>
/// <param name="handlers">List of handlers with which the pipeline is initalized.</param>
public RuntimePipeline(IList<IPipelineHandler> handlers)
: this(handlers, Amazon.Runtime.Internal.Util.Logger.GetLogger(typeof(RuntimePipeline)))
{
}
/// <summary>
/// Constructor for RuntimePipeline.
/// </summary>
/// <param name="handlers">List of handlers with which the pipeline is initalized.</param>
/// <param name="logger">The logger used to log messages.</param>
public RuntimePipeline(IList<IPipelineHandler> handlers, ILogger logger)
{
if (handlers == null || handlers.Count == 0)
throw new ArgumentNullException("handlers");
if (logger == null)
throw new ArgumentNullException("logger");
_logger = logger;
foreach (var handler in handlers)
{
this.AddHandler(handler);
}
}
/// <summary>
/// Constructor for RuntimePipeline.
/// </summary>
/// <param name="handler">The handler with which the pipeline is initalized.</param>
/// <param name="logger">The logger used to log messages.</param>
public RuntimePipeline(IPipelineHandler handler, ILogger logger)
{
if (handler == null)
throw new ArgumentNullException("handler");
if (logger == null)
throw new ArgumentNullException("logger");
_handler = handler;
_handler.Logger = logger;
_logger = logger;
}
#endregion
#region Invoke methods
/// <summary>
/// Invokes the pipeline synchronously.
/// </summary>
/// <param name="executionContext">Request context</param>
/// <returns>Response context</returns>
public IResponseContext InvokeSync(IExecutionContext executionContext)
{
ThrowIfDisposed();
_handler.InvokeSync(executionContext);
return executionContext.ResponseContext;
}
#if AWS_ASYNC_API
/// <summary>
/// Invokes the pipeline asynchronously.
/// </summary>
/// <param name="executionContext">Request context</param>
/// <returns>Response context</returns>
public System.Threading.Tasks.Task<T> InvokeAsync<T>(IExecutionContext executionContext)
where T : AmazonWebServiceResponse, new()
{
ThrowIfDisposed();
return _handler.InvokeAsync<T>(executionContext);
}
#elif AWS_APM_API
/// <summary>
/// Invokes the pipeline asynchronously.
/// </summary>
/// <param name="executionContext">Request context</param>
/// <returns>IAsyncResult which represents the in progress asynchronous operation.</returns>
public IAsyncResult InvokeAsync(IAsyncExecutionContext executionContext)
{
ThrowIfDisposed();
return _handler.InvokeAsync(executionContext);
}
#endif
#endregion
#region Handler methods
/// <summary>
/// Adds a new handler to the top of the pipeline.
/// </summary>
/// <param name="handler">The handler to be added to the pipeline.</param>
public void AddHandler(IPipelineHandler handler)
{
if (handler == null)
throw new ArgumentNullException("handler");
ThrowIfDisposed();
var innerMostHandler = GetInnermostHandler(handler);
if (_handler != null)
{
innerMostHandler.InnerHandler = _handler;
_handler.OuterHandler = innerMostHandler;
}
_handler = handler;
SetHandlerProperties(handler);
}
/// <summary>
/// Adds a handler after the first instance of handler of type T.
/// </summary>
/// <typeparam name="T">Type of the handler after which the given handler instance is added.</typeparam>
/// <param name="handler">The handler to be added to the pipeline.</param>
public void AddHandlerAfter<T>(IPipelineHandler handler)
where T : IPipelineHandler
{
if (handler == null)
throw new ArgumentNullException("handler");
ThrowIfDisposed();
var type = typeof(T);
var current = _handler;
while (current != null)
{
if (current.GetType() == type)
{
InsertHandler(handler, current);
SetHandlerProperties(handler);
return;
}
current = current.InnerHandler;
}
throw new InvalidOperationException(
string.Format(CultureInfo.InvariantCulture, "Cannot find a handler of type {0}", type.Name));
}
/// <summary>
/// Adds a handler before the first instance of handler of type T.
/// </summary>
/// <typeparam name="T">Type of the handler before which the given handler instance is added.</typeparam>
/// <param name="handler">The handler to be added to the pipeline.</param>
public void AddHandlerBefore<T>(IPipelineHandler handler)
where T : IPipelineHandler
{
if (handler == null)
throw new ArgumentNullException("handler");
ThrowIfDisposed();
var type = typeof(T);
if (_handler.GetType() == type)
{
// Add the handler to the top of the pipeline
AddHandler(handler);
SetHandlerProperties(handler);
return;
}
var current = _handler;
while (current != null)
{
if (current.InnerHandler != null &&
current.InnerHandler.GetType() == type)
{
InsertHandler(handler, current);
SetHandlerProperties(handler);
return;
}
current = current.InnerHandler;
}
throw new InvalidOperationException(
string.Format(CultureInfo.InvariantCulture, "Cannot find a handler of type {0}", type.Name));
}
/// <summary>
/// Removes the first occurance of a handler of type T.
/// </summary>
/// <typeparam name="T">Type of the handler which will be removed.</typeparam>
public void RemoveHandler<T>()
{
ThrowIfDisposed();
var type = typeof(T);
var current = _handler;
while (current != null)
{
if (current.GetType() == type)
{
// Cannot remove the handler if it's the only one in the pipeline
if (current == _handler && _handler.InnerHandler == null)
{
throw new InvalidOperationException(
"The pipeline contains a single handler, cannot remove the only handler in the pipeline.");
}
// current is the top, point top to current's inner handler
if (current == _handler)
_handler = current.InnerHandler;
// Wireup outer handler to current's inner handler
if (current.OuterHandler != null)
current.OuterHandler.InnerHandler = current.InnerHandler;
// Wireup inner handler to current's outer handler
if (current.InnerHandler != null)
current.InnerHandler.OuterHandler = current.OuterHandler;
// Cleanup current
current.InnerHandler = null;
current.OuterHandler = null;
return;
}
current = current.InnerHandler;
}
throw new InvalidOperationException(
string.Format(CultureInfo.InvariantCulture, "Cannot find a handler of type {0}", type.Name));
}
/// <summary>
/// Replaces the first occurance of a handler of type T with the given handler.
/// </summary>
/// <typeparam name="T">Type of the handler which will be replaced.</typeparam>
/// <param name="handler">The handler to be added to the pipeline.</param>
public void ReplaceHandler<T>(IPipelineHandler handler)
where T : IPipelineHandler
{
if (handler == null)
throw new ArgumentNullException("handler");
ThrowIfDisposed();
var type = typeof(T);
IPipelineHandler previous = null;
var current = _handler;
while (current != null)
{
if (current.GetType() == type)
{
// Replace current with handler.
handler.InnerHandler = current.InnerHandler;
handler.OuterHandler = current.OuterHandler;
if(previous != null)
{
// Wireup previous handler
previous.InnerHandler = handler;
}
else
{
// Current is the top, replace it.
_handler = handler;
}
if (current.InnerHandler != null)
{
// Wireup next handler
current.InnerHandler.OuterHandler = handler;
}
// Cleanup current
current.InnerHandler = null;
current.OuterHandler = null;
SetHandlerProperties(handler);
return;
}
previous = current;
current = current.InnerHandler;
}
throw new InvalidOperationException(
string.Format(CultureInfo.InvariantCulture, "Cannot find a handler of type {0}", type.Name));
}
/// <summary>
/// Inserts the given handler after current handler in the pipeline.
/// </summary>
/// <param name="handler">Handler to be inserted in the pipeline.</param>
/// <param name="current">Handler after which the given handler is inserted.</param>
private static void InsertHandler(IPipelineHandler handler, IPipelineHandler current)
{
var next = current.InnerHandler;
current.InnerHandler = handler;
handler.OuterHandler = current;
if (next!=null)
{
var innerMostHandler = GetInnermostHandler(handler);
innerMostHandler.InnerHandler = next;
next.OuterHandler = innerMostHandler;
}
}
/// <summary>
/// Gets the innermost handler by traversing the inner handler till
/// it reaches the last one.
/// </summary>
private static IPipelineHandler GetInnermostHandler(IPipelineHandler handler)
{
Debug.Assert(handler != null);
var current = handler;
while (current.InnerHandler != null)
{
current = current.InnerHandler;
}
return current;
}
private void SetHandlerProperties(IPipelineHandler handler)
{
ThrowIfDisposed();
handler.Logger = _logger;
}
/// <summary>
/// Retrieves a list of handlers, in the order of their execution.
/// </summary>
/// <returns>Handlers in the current pipeline.</returns>
public List<IPipelineHandler> Handlers
{
get
{
return EnumerateHandlers().ToList();
}
}
/// <summary>
/// Retrieves current handlers, in the order of their execution.
/// </summary>
/// <returns>Handlers in the current pipeline.</returns>
public IEnumerable<IPipelineHandler> EnumerateHandlers()
{
var handler = this.Handler;
while(handler != null)
{
yield return handler;
handler = handler.InnerHandler;
}
}
#endregion
#region Dispose methods
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (_disposed)
return;
if (disposing)
{
var handler = this.Handler;
while (handler != null)
{
var innerHandler = handler.InnerHandler;
var disposable = handler as IDisposable;
if (disposable != null)
{
disposable.Dispose();
}
handler = innerHandler;
}
_disposed = true;
}
}
private void ThrowIfDisposed()
{
if (this._disposed)
throw new ObjectDisposedException(GetType().FullName);
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.IO;
using Microsoft.Protocols.TestTools.StackSdk;
using Microsoft.Protocols.TestTools.StackSdk.Messages;
namespace Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Cifs
{
/// <summary>
/// Packets for SmbFind Request
/// </summary>
public class SmbFindRequestPacket : SmbSingleRequestPacket
{
#region Fields
private SMB_COM_FIND_Request_SMB_Parameters smbParameters;
private SMB_COM_FIND_Request_SMB_Data smbData;
#endregion
#region Properties
/// <summary>
/// get or set the Smb_Parameters:SMB_COM_FIND_Request_SMB_Parameters
/// </summary>
public SMB_COM_FIND_Request_SMB_Parameters SmbParameters
{
get
{
return this.smbParameters;
}
set
{
this.smbParameters = value;
}
}
/// <summary>
/// get or set the Smb_Data:SMB_COM_FIND_Request_SMB_Data
/// </summary>
public SMB_COM_FIND_Request_SMB_Data SmbData
{
get
{
return this.smbData;
}
set
{
this.smbData = value;
}
}
#endregion
#region Constructor
/// <summary>
/// Constructor.
/// </summary>
public SmbFindRequestPacket()
: base()
{
this.InitDefaultValue();
}
/// <summary>
/// Constructor: Create a request directly from a buffer.
/// </summary>
public SmbFindRequestPacket(byte[] data)
: base(data)
{
}
/// <summary>
/// Deep copy constructor.
/// </summary>
public SmbFindRequestPacket(SmbFindRequestPacket packet)
: base(packet)
{
this.InitDefaultValue();
this.smbParameters.WordCount = packet.SmbParameters.WordCount;
this.smbParameters.MaxCount = packet.SmbParameters.MaxCount;
this.smbParameters.SearchAttributes = packet.SmbParameters.SearchAttributes;
this.smbData.ByteCount = packet.SmbData.ByteCount;
this.smbData.BufferFormat1 = packet.SmbData.BufferFormat1;
if (packet.smbData.FileName != null)
{
this.smbData.FileName = new byte[packet.smbData.FileName.Length];
Array.Copy(packet.smbData.FileName, this.smbData.FileName, packet.smbData.FileName.Length);
}
else
{
this.smbData.FileName = new byte[0];
}
this.smbData.BufferFormat2 = packet.SmbData.BufferFormat2;
this.smbData.ResumeKeyLength = packet.SmbData.ResumeKeyLength;
if (packet.smbData.ResumeKey != null)
{
this.smbData.ResumeKey = new SMB_Resume_Key[packet.smbData.ResumeKey.Length];
for (int i = 0; i < packet.smbData.ResumeKey.Length; i++)
{
this.smbData.ResumeKey[i] = new SMB_Resume_Key();
this.smbData.ResumeKey[i].Reserved = packet.SmbData.ResumeKey[i].Reserved;
if (packet.smbData.ResumeKey[i].ServerState != null)
{
this.smbData.ResumeKey[i].ServerState
= new byte[packet.smbData.ResumeKey[i].ServerState.Length];
Array.Copy(packet.smbData.ResumeKey[i].ServerState, this.smbData.ResumeKey[i].ServerState,
packet.smbData.ResumeKey[i].ServerState.Length);
}
else
{
this.smbData.ResumeKey[i].ServerState = new byte[0];
}
if (packet.smbData.ResumeKey[i].ClientState != null)
{
this.smbData.ResumeKey[i].ClientState
= new byte[packet.smbData.ResumeKey[i].ClientState.Length];
Array.Copy(packet.smbData.ResumeKey[i].ClientState, this.smbData.ResumeKey[i].ClientState,
packet.smbData.ResumeKey[i].ClientState.Length);
}
else
{
this.smbData.ResumeKey[i].ClientState = new byte[0];
}
}
}
}
#endregion
#region override methods
/// <summary>
/// to create an instance of the StackPacket class that is identical to the current StackPacket.
/// </summary>
/// <returns>a new Packet cloned from this.</returns>
public override StackPacket Clone()
{
return new SmbFindRequestPacket(this);
}
/// <summary>
/// Encode the struct of SMB_COM_FIND_Request_SMB_Parameters into the struct of SmbParameters
/// </summary>
protected override void EncodeParameters()
{
this.smbParametersBlock = TypeMarshal.ToStruct<SmbParameters>(
CifsMessageUtils.ToBytes<SMB_COM_FIND_Request_SMB_Parameters>(this.smbParameters));
}
/// <summary>
/// Encode the struct of SMB_COM_FIND_Request_SMB_Data into the struct of SmbData
/// </summary>
protected override void EncodeData()
{
this.smbDataBlock.ByteCount = this.SmbData.ByteCount;
this.smbDataBlock.Bytes = new byte[this.smbDataBlock.ByteCount];
using (MemoryStream memoryStream = new MemoryStream(this.smbDataBlock.Bytes))
{
using (Channel channel = new Channel(null, memoryStream))
{
channel.BeginWriteGroup();
channel.Write<byte>(this.smbData.BufferFormat1);
if (this.smbData.FileName != null)
{
channel.WriteBytes(this.smbData.FileName);
}
channel.Write<byte>(this.smbData.BufferFormat2);
channel.Write<ushort>(this.smbData.ResumeKeyLength);
if (this.smbData.ResumeKey != null)
{
foreach (SMB_Resume_Key resumeKey in this.smbData.ResumeKey)
{
channel.Write<SMB_Resume_Key>(resumeKey);
}
}
channel.EndWriteGroup();
}
}
}
/// <summary>
/// to decode the smb parameters: from the general SmbParameters to the concrete Smb Parameters.
/// </summary>
protected override void DecodeParameters()
{
this.smbParameters = TypeMarshal.ToStruct<SMB_COM_FIND_Request_SMB_Parameters>(
TypeMarshal.ToBytes(this.smbParametersBlock));
}
/// <summary>
/// to decode the smb data: from the general SmbDada to the concrete Smb Data.
/// </summary>
protected override void DecodeData()
{
using (MemoryStream memoryStream = new MemoryStream(CifsMessageUtils.ToBytes<SmbData>(this.smbDataBlock)))
{
using (Channel channel = new Channel(null, memoryStream))
{
this.smbData.ByteCount = channel.Read<ushort>();
this.smbData.BufferFormat1 = channel.Read<byte>();
this.smbData.FileName = CifsMessageUtils.ReadNullTerminatedString(channel,
(this.smbHeader.Flags2 & SmbFlags2.SMB_FLAGS2_UNICODE) == SmbFlags2.SMB_FLAGS2_UNICODE);
this.smbData.BufferFormat2 = channel.Read<byte>();
this.smbData.ResumeKeyLength = channel.Read<ushort>();
if (this.smbData.ResumeKeyLength != 0)
{
this.smbData.ResumeKey = new SMB_Resume_Key[] { channel.Read<SMB_Resume_Key>() };
}
else
{
this.smbData.ResumeKey = new SMB_Resume_Key[0];
}
}
}
}
#endregion
#region initialize fields with default value
/// <summary>
/// init packet, set default field data
/// </summary>
private void InitDefaultValue()
{
this.smbData.FileName = new byte[0];
this.smbData.ResumeKey = new SMB_Resume_Key[0];
}
#endregion
}
}
| |
// Copyright (C) Pash Contributors. License: GPL/BSD. See https://github.com/Pash-Project/Pash/
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Pash.ParserIntrinsics.Tests
{
[TestFixture]
public class ParserTests
{
[Test]
public void GrammarErrorsCount()
{
// Obviously, we'd rather drive this to 0, but for now, let's lock it down
//
// Report this number in https://github.com/Pash-Project/Pash/issues/38
Assert.AreEqual(3, PowerShellGrammar.Parser.Language.Errors.Count, PowerShellGrammar.Parser.Language.Errors.JoinString("\r\n"));
}
[Test]
public void MultilineIfTest()
{
AssertIsValidInput(@"
if ($true)
{
}
");
}
[Test]
public void MultilineHashTable()
{
AssertIsValidInput(@"
@{
a = 'b'
c = 'd'
}
");
}
[Test]
[TestCase(@"if ($true) {}")]
[TestCase(@"if ($true) { }")] // having whitespace here was causing a parse error.
[TestCase(@"if ($host.Name -eq ""Console"") { }")]
[TestCase(@"if ($host.Name -ne ""Console"") { }")]
[TestCase(@"if ($true) {} else {}")]
[TestCase(@"if ($true) {} elseif ($true) {} ")]
[TestCase(@"if ($true) {} elseif ($true) {} else {}")]
[TestCase(@"if ($true) {} elseif ($true) {} elseif ($true) {} else {}")]
public void IfElseSyntax(string input)
{
AssertIsValidInput(input);
}
[Test]
[TestCase(@"[int]")]
[TestCase(@"[int][string]7")] // double cast is OK
[TestCase(@"[int]-3"), Description("Cast, not subtraction")]
[TestCase(@"[int],[string]")]
[TestCase(@"$x = [int]")]
[TestCase(@"$x::MaxValue")]
[TestCase(@"[int]::Parse('7')")]
[TestCase(@"$x::Parse()")]
[TestCase(@"$x.Assembly")]
[TestCase(@"$x.AsType()")]
[TestCase(@"[char]::IsUpper(""AbC"", 1)", Description = "two parameters")]
public void TypesAndMembers(string input)
{
AssertIsValidInput(input);
}
[Test]
[TestCase(@"[int] ::MaxValue")]
public void WhitespaceProhibition(string input)
{
AssertIsNotValidInput(input);
}
[Test]
[TestCase(@"$i = 100 # $i designates an int value 100@")]
[TestCase(@"$j = $i # $j designates an int value 100, which is a copy@")]
[TestCase(@"$a = 10,20,30 # $a designates an object[], Length 3, value 10,20,30@")]
[TestCase(@"$b = $a # $b designates exactly the same array as does $a, not a copy@")]
[TestCase(@"$a[1] = 50 # element 1 (which has a value type) is changed from 20 to 50 @")]
[TestCase(@"$b[1] # $b refers to the same array as $a, so $b[1] is 50@")]
public void Section4_Types(string input)
{
AssertIsValidInput(input);
}
[Test]
[TestCase(@"$a = 10,20,30")]
[TestCase(@"$a.Length # get instance property")]
[TestCase(@"(10,20,30).Length")]
[TestCase(@"$property = ""Length""")]
[TestCase(@"$a.$property # property name is a variable")]
[TestCase(@"$h1 = @{ FirstName = ""James""; LastName = ""Anderson""; IDNum = 123 }")]
[TestCase(@"$h1.FirstName # designates the key FirstName")]
[TestCase(@"$h1.Keys # gets the collection of keys")]
[TestCase(@"[int]::MinValue # get static property")]
[TestCase(@"[double]::PositiveInfinity # get static property")]
[TestCase(@"$property = ""MinValue""")]
[TestCase(@"[long]::$property # property name is a variable")]
[TestCase(@"
foreach ($t in [byte],[int],[long])
{
$t::MaxValue # get static property
}
", Explicit = true)]
[TestCase(@"$a = @{ID=1},@{ID=2},@{ID=3}")]
[TestCase(@"$a.ID # get ID from each element in the array ")]
public void Section7_1_2_MemberAccess(string input)
{
AssertIsValidInput(input);
}
[Test]
[TestCase(@"[math]::Sqrt(2.0) # call method with argument 2.0")]
[TestCase(@"[char]::IsUpper(""a"") # call method")]
[TestCase(@"$b = ""abc#$%XYZabc""
$b.ToUpper() # call instance method", Explicit = true)]
[TestCase(@"[math]::Sqrt(2) # convert 2 to 2.0 and call method")]
[TestCase(@"[math]::Sqrt(2D) # convert 2D to 2.0 and call method")]
[TestCase(@"[math]::Sqrt($true) # convert $true to 1.0 and call method")]
[TestCase(@"[math]::Sqrt(""20"") # convert ""20"" to 20 and call method")]
[TestCase(@"$a = [math]::Sqrt # get method descriptor for Sqrt")]
[TestCase(@"$a.Invoke(2.0) # call Sqrt via the descriptor")]
[TestCase(@"$a = [math]::(""Sq""+""rt"") # get method descriptor for Sqrt")]
[TestCase(@"$a.Invoke(2.0) # call Sqrt via the descriptor")]
[TestCase(@"$a = [char]::ToLower # get method descriptor for ToLower")]
[TestCase(@"$a.Invoke(""X"") # call ToLower via the descriptor")]
public void Section7_1_3_InvocationExpressions(string input)
{
AssertIsValidInput(input);
}
[TestCase(@"$a = [int[]](10,20,30) # [int[]], Length 3", Explicit = true)]
[TestCase(@"$a[1] # returns int 20")]
[TestCase(@"$a[20] # no such position, returns $null")]
[TestCase(@"$a[-1] # returns int 30, i.e., $a[$a.Length-1]")]
[TestCase(@"$a[2] = 5 # changes int 30 to int 5")]
[TestCase(@"$a[20] = 5 # implementation-defined behavior")]
[TestCase(@"$a = New-Object 'double[,]' 3,2")]
[TestCase(@"$a[0,0] = 10.5 # changes 0.0 to 10.5")]
[TestCase(@"$a[0,0]++ # changes 10.5 to 10.6")]
[TestCase(@"$list = (""red"",$true,10),20,(1.2, ""yes""", Explicit = true)]
[TestCase(@"$list[2][1] # returns string ""yes""")]
[TestCase(@"$a = @{ A = 10 },@{ B = $true },@{ C = 123.45 }")]
[TestCase(@"$a[1][""B""] # $a[1] is a Hashtable, where B is a key")]
[TestCase(@"$a = ""red"",""green""")]
[TestCase(@"$a[1][4] # returns string ""n"" from string in $a[1]")]
public void Section7_1_4_1_SubscriptingAnArray(string input)
{
AssertIsValidInput(input);
}
[Test]
[TestCase(@"$s = ""Hello""")]
[TestCase(@"$s = ""Hello"" # string, Length 5, positions 0-4")]
[TestCase(@"$c = $s[1] # returns ""e"" as a string")]
[TestCase(@"$c = $s[20] # no such position, returns $null")]
[TestCase(@"$c = $s[-1] # returns ""o"", i.e., $s[$s.Length-1]")]
public void Section7_1_4_2_SubscriptingAString(string input)
{
AssertIsValidInput(input);
}
[Test]
[TestCase(@"[int[]](30,40,50,60,70,80,90)", Explicit = true)]
[TestCase(@"$a = [int[]](30,40,50,60,70,80,90)", Explicit = true)]
[TestCase(@"$a[1,3,5] # slice has Length 3, value 40,60,80")]
[TestCase(@"++$a[1,3,5][1] # preincrement 60 in array 40,60,80")]
[TestCase(@"$a[,5] # slice with Length 1")]
[TestCase(@"$a[@()] # slice with Length 0")]
[TestCase(@"$a[-1..-3] # slice with Length 0, value 90,80,70")]
[TestCase(@"$a = New-Object 'int[,]' 3,2")]
[TestCase(@"$a[0,0] = 10; $a[0,1] = 20; $a[1,0] = 30")]
[TestCase(@"$a[1,1] = 40; $a[2,0] = 50; $a[2,1] = 60")]
[TestCase(@"$a[(0,1),(1,0)] # slice with Length 2, value 20,30, parens needed")]
[TestCase(@"$h1 = @{ FirstName = ""James""; LastName = ""Anderson""; IDNum = 123 }")]
[TestCase(@"$h1['FirstName'] # the value associated with key FirstName")]
[TestCase(@"$h1['BirthDate'] # no such key, returns $null")]
[TestCase(@"$h1['FirstName','IDNum'] # returns [object[]], Length 2 (James/123)")]
[TestCase(@"$h1['FirstName','xxx'] # returns [object[]], Length 2 (James/$null)")]
[TestCase(@"$h1[$null,'IDNum'] # returns [object[]], Length 1 (123)")]
public void Section7_1_4_5GeneratingArraySlices(string input)
{
AssertIsValidInput(input);
}
[Test]
[TestCase(@"$i = 0 # $i = 0")]
[TestCase(@"$i++ # $i is incremented by 1")]
[TestCase(@"$j = $i-- # $j takes on the value of $i before the decrement")]
[TestCase(@"$a = 1,2,3")]
[TestCase(@"$b = 9,8,7")]
[TestCase(@"$i = 0")]
[TestCase(@"$j = 1")]
[TestCase(@"$b[$j--] = $a[$i++] # $b[1] takes on the value of $a[0], then $j is")]
[TestCase(@" # decremented, $i incremented")]
[TestCase(@"$i = 2147483647 # $i holds a value of type int")]
[TestCase(@"$i++ # $i now holds a value of type double because")]
[TestCase(@" # 2147483648 is too big to fit in type int")]
[TestCase(@"[int]$k = 0 # $k is constrained to int", Explicit = true)]
[TestCase(@"$k = [int]::MaxValue # $k is set to 2147483647")]
[TestCase(@"$k++ # 2147483648 is too big to fit, imp-def bahavior")]
[TestCase(@"$x = $null # target is unconstrained, $null goes to [int]0")]
[TestCase(@"$x++ # value treated as int, 0->1")]
public void Section7_1_5_Postfix_Increment_And_DecrementOperators(string input)
{
AssertIsValidInput(input);
}
[Test]
[TestCase(@"$j = 20")]
[TestCase(@"$($i = 10) # pipeline gets nothing")]
[TestCase(@"$(($i = 10)) # pipeline gets int 10")]
[TestCase(@"$($i = 10; $j) # pipeline gets int 20")]
[TestCase(@"$(($i = 10); $j) # pipeline gets [object[]](10,20)")]
[TestCase(@"$(($i = 10); ++$j) # pipeline gets int 10")]
[TestCase(@"$(($i = 10); (++$j)) # pipeline gets [object[]](10,22)")]
[TestCase(@"$($i = 10; ++$j) # pipeline gets nothing")]
[TestCase(@"$(2,4,6) # pipeline gets [object[]](2,4,6)")]
public void Section7_1_6_SubexpressionOperator(string input)
{
AssertIsValidInput(input);
}
[Test, Explicit("Punting for now")]
public void StringWithDollarSign()
{
// This `$%` threw off the tokenizer
AssertIsValidInput(@"""abc#$%XYZabc""");
}
[Test]
public void ArrayLiteralParameter()
{
AssertIsValidInput(@"echo 1,2");
}
[Test]
public void UnaryArrayLiteralParameterShouldFail()
{
AssertIsNotValidInput(@"echo ,2");
}
[Test]
public void ParenthesisedUnaryArrayLiteralParameter()
{
AssertIsValidInput(@"echo (,2)");
}
[Test]
public void BinaryOperatorTest()
{
AssertIsValidInput(@"$foo.bar -or $true");
}
static void AssertIsValidInput(string input)
{
var parseTree = PowerShellGrammar.Parser.Parse(input);
if (parseTree.HasErrors())
{
Assert.Fail(parseTree.ParserMessages[0].ToString());
}
}
static void AssertIsNotValidInput(string input)
{
var parseTree = PowerShellGrammar.Parser.Parse(input);
if (!parseTree.HasErrors())
{
Assert.Fail();
}
}
}
}
| |
// 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.
/*=============================================================================
**
** Class: Stack
**
** Purpose: Represents a simple last-in-first-out (LIFO)
** non-generic collection of objects.
**
**
=============================================================================*/
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
namespace System.Collections
{
// A simple stack of objects. Internally it is implemented as an array,
// so Push can be O(n). Pop is O(1).
[DebuggerTypeProxy(typeof(System.Collections.Stack.StackDebugView))]
[DebuggerDisplay("Count = {Count}")]
[Serializable]
public class Stack : ICollection, ICloneable
{
private Object[] _array; // Storage for stack elements
[ContractPublicPropertyName("Count")]
private int _size; // Number of items in the stack.
private int _version; // Used to keep enumerator in sync w/ collection.
[NonSerialized]
private Object _syncRoot;
private const int _defaultCapacity = 10;
public Stack()
{
_array = new Object[_defaultCapacity];
_size = 0;
_version = 0;
}
// Create a stack with a specific initial capacity. The initial capacity
// must be a non-negative number.
public Stack(int initialCapacity)
{
if (initialCapacity < 0)
throw new ArgumentOutOfRangeException(nameof(initialCapacity), SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
if (initialCapacity < _defaultCapacity)
initialCapacity = _defaultCapacity; // Simplify doubling logic in Push.
_array = new Object[initialCapacity];
_size = 0;
_version = 0;
}
// Fills a Stack with the contents of a particular collection. The items are
// pushed onto the stack in the same order they are read by the enumerator.
//
public Stack(ICollection col) : this((col == null ? 32 : col.Count))
{
if (col == null)
throw new ArgumentNullException(nameof(col));
Contract.EndContractBlock();
IEnumerator en = col.GetEnumerator();
while (en.MoveNext())
Push(en.Current);
}
public virtual int Count
{
get
{
Contract.Ensures(Contract.Result<int>() >= 0);
return _size;
}
}
public virtual bool IsSynchronized
{
get { return false; }
}
public virtual Object SyncRoot
{
get
{
if (_syncRoot == null)
{
System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null);
}
return _syncRoot;
}
}
// Removes all Objects from the Stack.
public virtual void Clear()
{
Array.Clear(_array, 0, _size); // Don't need to doc this but we clear the elements so that the gc can reclaim the references.
_size = 0;
_version++;
}
public virtual Object Clone()
{
Contract.Ensures(Contract.Result<Object>() != null);
Stack s = new Stack(_size);
s._size = _size;
Array.Copy(_array, 0, s._array, 0, _size);
s._version = _version;
return s;
}
public virtual bool Contains(Object obj)
{
int count = _size;
while (count-- > 0)
{
if (obj == null)
{
if (_array[count] == null)
return true;
}
else if (_array[count] != null && _array[count].Equals(obj))
{
return true;
}
}
return false;
}
// Copies the stack into an array.
public virtual void CopyTo(Array array, int index)
{
if (array == null)
throw new ArgumentNullException(nameof(array));
if (array.Rank != 1)
throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array));
if (index < 0)
throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum);
if (array.Length - index < _size)
throw new ArgumentException(SR.Argument_InvalidOffLen);
Contract.EndContractBlock();
int i = 0;
object[] objArray = array as object[];
if (objArray != null)
{
while (i < _size)
{
objArray[i + index] = _array[_size - i - 1];
i++;
}
}
else
{
while (i < _size)
{
array.SetValue(_array[_size - i - 1], i + index);
i++;
}
}
}
// Returns an IEnumerator for this Stack.
public virtual IEnumerator GetEnumerator()
{
Contract.Ensures(Contract.Result<IEnumerator>() != null);
return new StackEnumerator(this);
}
// Returns the top object on the stack without removing it. If the stack
// is empty, Peek throws an InvalidOperationException.
public virtual Object Peek()
{
if (_size == 0)
throw new InvalidOperationException(SR.InvalidOperation_EmptyStack);
Contract.EndContractBlock();
return _array[_size - 1];
}
// Pops an item from the top of the stack. If the stack is empty, Pop
// throws an InvalidOperationException.
public virtual Object Pop()
{
if (_size == 0)
throw new InvalidOperationException(SR.InvalidOperation_EmptyStack);
//Contract.Ensures(Count == Contract.OldValue(Count) - 1);
Contract.EndContractBlock();
_version++;
Object obj = _array[--_size];
_array[_size] = null; // Free memory quicker.
return obj;
}
// Pushes an item to the top of the stack.
//
public virtual void Push(Object obj)
{
//Contract.Ensures(Count == Contract.OldValue(Count) + 1);
if (_size == _array.Length)
{
Object[] newArray = new Object[2 * _array.Length];
Array.Copy(_array, 0, newArray, 0, _size);
_array = newArray;
}
_array[_size++] = obj;
_version++;
}
// Returns a synchronized Stack.
//
public static Stack Synchronized(Stack stack)
{
if (stack == null)
throw new ArgumentNullException(nameof(stack));
Contract.Ensures(Contract.Result<Stack>() != null);
Contract.EndContractBlock();
return new SyncStack(stack);
}
// Copies the Stack to an array, in the same order Pop would return the items.
public virtual Object[] ToArray()
{
Contract.Ensures(Contract.Result<Object[]>() != null);
if (_size == 0)
return Array.Empty<Object>();
Object[] objArray = new Object[_size];
int i = 0;
while (i < _size)
{
objArray[i] = _array[_size - i - 1];
i++;
}
return objArray;
}
private class SyncStack : Stack
{
private Stack _s;
private Object _root;
internal SyncStack(Stack stack)
{
_s = stack;
_root = stack.SyncRoot;
}
public override bool IsSynchronized
{
get { return true; }
}
public override Object SyncRoot
{
get
{
return _root;
}
}
public override int Count
{
get
{
lock (_root)
{
return _s.Count;
}
}
}
public override bool Contains(Object obj)
{
lock (_root)
{
return _s.Contains(obj);
}
}
public override Object Clone()
{
lock (_root)
{
return new SyncStack((Stack)_s.Clone());
}
}
public override void Clear()
{
lock (_root)
{
_s.Clear();
}
}
public override void CopyTo(Array array, int arrayIndex)
{
lock (_root)
{
_s.CopyTo(array, arrayIndex);
}
}
public override void Push(Object value)
{
lock (_root)
{
_s.Push(value);
}
}
[SuppressMessage("Microsoft.Contracts", "CC1055")] // Thread safety problems with precondition - can't express the precondition as of Dev10.
public override Object Pop()
{
lock (_root)
{
return _s.Pop();
}
}
public override IEnumerator GetEnumerator()
{
lock (_root)
{
return _s.GetEnumerator();
}
}
[SuppressMessage("Microsoft.Contracts", "CC1055")] // Thread safety problems with precondition - can't express the precondition
public override Object Peek()
{
lock (_root)
{
return _s.Peek();
}
}
public override Object[] ToArray()
{
lock (_root)
{
return _s.ToArray();
}
}
}
private class StackEnumerator : IEnumerator, ICloneable
{
private Stack _stack;
private int _index;
private int _version;
private Object _currentElement;
internal StackEnumerator(Stack stack)
{
_stack = stack;
_version = _stack._version;
_index = -2;
_currentElement = null;
}
public object Clone() => MemberwiseClone();
public virtual bool MoveNext()
{
bool retval;
if (_version != _stack._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
if (_index == -2)
{ // First call to enumerator.
_index = _stack._size - 1;
retval = (_index >= 0);
if (retval)
_currentElement = _stack._array[_index];
return retval;
}
if (_index == -1)
{ // End of enumeration.
return false;
}
retval = (--_index >= 0);
if (retval)
_currentElement = _stack._array[_index];
else
_currentElement = null;
return retval;
}
public virtual Object Current
{
get
{
if (_index == -2) throw new InvalidOperationException(SR.InvalidOperation_EnumNotStarted);
if (_index == -1) throw new InvalidOperationException(SR.InvalidOperation_EnumEnded);
return _currentElement;
}
}
public virtual void Reset()
{
if (_version != _stack._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
_index = -2;
_currentElement = null;
}
}
internal class StackDebugView
{
private Stack _stack;
public StackDebugView(Stack stack)
{
if (stack == null)
throw new ArgumentNullException(nameof(stack));
Contract.EndContractBlock();
_stack = stack;
}
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public Object[] Items
{
get
{
return _stack.ToArray();
}
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Text;
using log4net;
namespace OpenSim.Framework
{
/// <summary>
/// Used for requests to untrusted endpoints that may potentially be
/// malicious
/// </summary>
public static class UntrustedHttpWebRequest
{
/// <summary>Setting this to true will allow HTTP connections to localhost</summary>
private const bool DEBUG = true;
private static readonly ILog m_log =
LogManager.GetLogger(
System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
private static readonly ICollection<string> allowableSchemes = new List<string> { "http", "https" };
/// <summary>
/// Creates an HttpWebRequest that is hardened against malicious
/// endpoints after ensuring the given Uri is safe to retrieve
/// </summary>
/// <param name="uri">Web location to request</param>
/// <returns>A hardened HttpWebRequest if the uri was determined to be safe</returns>
/// <exception cref="ArgumentNullException">If uri is null</exception>
/// <exception cref="ArgumentException">If uri is unsafe</exception>
public static HttpWebRequest Create(Uri uri)
{
return Create(uri, DEBUG, 1000 * 5, 1000 * 20, 10);
}
/// <summary>
/// Creates an HttpWebRequest that is hardened against malicious
/// endpoints after ensuring the given Uri is safe to retrieve
/// </summary>
/// <param name="uri">Web location to request</param>
/// <param name="allowLoopback">True to allow connections to localhost, otherwise false</param>
/// <param name="readWriteTimeoutMS">Read write timeout, in milliseconds</param>
/// <param name="timeoutMS">Connection timeout, in milliseconds</param>
/// <param name="maximumRedirects">Maximum number of allowed redirects</param>
/// <returns>A hardened HttpWebRequest if the uri was determined to be safe</returns>
/// <exception cref="ArgumentNullException">If uri is null</exception>
/// <exception cref="ArgumentException">If uri is unsafe</exception>
public static HttpWebRequest Create(Uri uri, bool allowLoopback, int readWriteTimeoutMS, int timeoutMS, int maximumRedirects)
{
if (uri == null)
throw new ArgumentNullException("uri");
if (!IsUriAllowable(uri, allowLoopback))
throw new ArgumentException("Uri " + uri + " was rejected");
HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(uri);
httpWebRequest.MaximumAutomaticRedirections = maximumRedirects;
httpWebRequest.ReadWriteTimeout = readWriteTimeoutMS;
httpWebRequest.Timeout = timeoutMS;
httpWebRequest.KeepAlive = false;
return httpWebRequest;
}
public static string PostToUntrustedUrl(Uri url, string data)
{
try
{
byte[] requestData = System.Text.Encoding.UTF8.GetBytes(data);
HttpWebRequest request = Create(url);
request.Method = "POST";
request.ContentLength = requestData.Length;
request.ContentType = "application/x-www-form-urlencoded";
using (Stream requestStream = request.GetRequestStream())
requestStream.Write(requestData, 0, requestData.Length);
using (WebResponse response = request.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
return responseStream.GetStreamString();
}
}
catch (Exception ex)
{
m_log.Warn("POST to untrusted URL " + url + " failed: " + ex.Message);
return null;
}
}
public static string GetUntrustedUrl(Uri url)
{
try
{
HttpWebRequest request = Create(url);
using (WebResponse response = request.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
return responseStream.GetStreamString();
}
}
catch (Exception ex)
{
m_log.Warn("GET from untrusted URL " + url + " failed: " + ex.Message);
return null;
}
}
/// <summary>
/// Determines whether a URI is allowed based on scheme and host name.
/// No requireSSL check is done here
/// </summary>
/// <param name="allowLoopback">True to allow loopback addresses to be used</param>
/// <param name="uri">The URI to test for whether it should be allowed.</param>
/// <returns>
/// <c>true</c> if [is URI allowable] [the specified URI]; otherwise, <c>false</c>.
/// </returns>
private static bool IsUriAllowable(Uri uri, bool allowLoopback)
{
if (!allowableSchemes.Contains(uri.Scheme))
{
m_log.WarnFormat("Rejecting URL {0} because it uses a disallowed scheme.", uri);
return false;
}
// Try to interpret the hostname as an IP address so we can test for internal
// IP address ranges. Note that IP addresses can appear in many forms
// (e.g. http://127.0.0.1, http://2130706433, http://0x0100007f, http://::1
// So we convert them to a canonical IPAddress instance, and test for all
// non-routable IP ranges: 10.*.*.*, 127.*.*.*, ::1
// Note that Uri.IsLoopback is very unreliable, not catching many of these variants.
IPAddress hostIPAddress;
if (IPAddress.TryParse(uri.DnsSafeHost, out hostIPAddress))
{
byte[] addressBytes = hostIPAddress.GetAddressBytes();
// The host is actually an IP address.
switch (hostIPAddress.AddressFamily)
{
case System.Net.Sockets.AddressFamily.InterNetwork:
if (!allowLoopback && (addressBytes[0] == 127 || addressBytes[0] == 10))
{
m_log.WarnFormat("Rejecting URL {0} because it is a loopback address.", uri);
return false;
}
break;
case System.Net.Sockets.AddressFamily.InterNetworkV6:
if (!allowLoopback && IsIPv6Loopback(hostIPAddress))
{
m_log.WarnFormat("Rejecting URL {0} because it is a loopback address.", uri);
return false;
}
break;
default:
m_log.WarnFormat("Rejecting URL {0} because it does not use an IPv4 or IPv6 address.", uri);
return false;
}
}
else
{
// The host is given by name. We require names to contain periods to
// help make sure it's not an internal address.
if (!allowLoopback && !uri.Host.Contains("."))
{
m_log.WarnFormat("Rejecting URL {0} because it does not contain a period in the host name.", uri);
return false;
}
}
return true;
}
/// <summary>
/// Determines whether an IP address is the IPv6 equivalent of "localhost/127.0.0.1".
/// </summary>
/// <param name="ip">The ip address to check.</param>
/// <returns>
/// <c>true</c> if this is a loopback IP address; <c>false</c> otherwise.
/// </returns>
private static bool IsIPv6Loopback(IPAddress ip)
{
if (ip == null)
throw new ArgumentNullException("ip");
byte[] addressBytes = ip.GetAddressBytes();
for (int i = 0; i < addressBytes.Length - 1; i++)
{
if (addressBytes[i] != 0)
return false;
}
if (addressBytes[addressBytes.Length - 1] != 1)
return false;
return true;
}
}
}
| |
//
// Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.Targets
{
using System;
using System.Reflection;
using NLog.Common;
using NLog.Internal;
/// <summary>
/// Calls the specified static method on each log message and passes contextual parameters to it.
/// </summary>
/// <seealso href="https://github.com/nlog/nlog/wiki/MethodCall-target">Documentation on NLog Wiki</seealso>
/// <example>
/// <p>
/// To set up the target in the <a href="config.html">configuration file</a>,
/// use the following syntax:
/// </p>
/// <code lang="XML" source="examples/targets/Configuration File/MethodCall/NLog.config" />
/// <p>
/// This assumes just one target and a single rule. More configuration
/// options are described <a href="config.html">here</a>.
/// </p>
/// <p>
/// To set up the log target programmatically use code like this:
/// </p>
/// <code lang="C#" source="examples/targets/Configuration API/MethodCall/Simple/Example.cs" />
/// </example>
[Target("MethodCall")]
public sealed class MethodCallTarget : MethodCallTargetBase
{
/// <summary>
/// Gets or sets the class name.
/// </summary>
/// <docgen category='Invocation Options' order='10' />
public string ClassName { get; set; }
/// <summary>
/// Gets or sets the method name. The method must be public and static.
///
/// Use the AssemblyQualifiedName , https://msdn.microsoft.com/en-us/library/system.type.assemblyqualifiedname(v=vs.110).aspx
/// e.g.
/// </summary>
/// <docgen category='Invocation Options' order='10' />
public string MethodName { get; set; }
Action<LogEventInfo, object[]> _logEventAction;
/// <summary>
/// Initializes a new instance of the <see cref="MethodCallTarget" /> class.
/// </summary>
public MethodCallTarget() : base()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="MethodCallTarget" /> class.
/// </summary>
/// <param name="name">Name of the target.</param>
public MethodCallTarget(string name) : this(name, null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="MethodCallTarget" /> class.
/// </summary>
/// <param name="name">Name of the target.</param>
/// <param name="logEventAction">Method to call on logevent.</param>
public MethodCallTarget(string name, Action<LogEventInfo, object[]> logEventAction) : this()
{
Name = name;
_logEventAction = logEventAction;
}
/// <inheritdoc/>
protected override void InitializeTarget()
{
base.InitializeTarget();
if (ClassName != null && MethodName != null)
{
_logEventAction = null;
var targetType = Type.GetType(ClassName);
if (targetType != null)
{
var methodInfo = targetType.GetMethod(MethodName);
if (methodInfo is null)
{
throw new NLogConfigurationException($"MethodCallTarget: MethodName={MethodName} not found in ClassName={ClassName} - it should be static");
}
else
{
_logEventAction = BuildLogEventAction(methodInfo);
}
}
else
{
throw new NLogConfigurationException($"MethodCallTarget: failed to get type from ClassName={ClassName}");
}
}
else if (_logEventAction is null)
{
throw new NLogConfigurationException($"MethodCallTarget: Missing configuration of ClassName and MethodName");
}
}
private static Action<LogEventInfo, object[]> BuildLogEventAction(MethodInfo methodInfo)
{
var neededParameters = methodInfo.GetParameters().Length;
return (logEvent, parameters) =>
{
var missingParameters = neededParameters - parameters.Length;
if (missingParameters > 0)
{
//fill missing parameters with Type.Missing
var newParams = new object[neededParameters];
for (int i = 0; i < parameters.Length; ++i)
newParams[i] = parameters[i];
for (int i = parameters.Length; i < neededParameters; ++i)
newParams[i] = Type.Missing;
parameters = newParams;
}
methodInfo.Invoke(null, parameters);
};
}
/// <summary>
/// Calls the specified Method.
/// </summary>
/// <param name="parameters">Method parameters.</param>
/// <param name="logEvent">The logging event.</param>
protected override void DoInvoke(object[] parameters, AsyncLogEventInfo logEvent)
{
try
{
ExecuteLogMethod(parameters, logEvent.LogEvent);
logEvent.Continuation(null);
}
catch (Exception ex)
{
if (ExceptionMustBeRethrown(ex))
{
throw;
}
logEvent.Continuation(ex);
}
}
/// <summary>
/// Calls the specified Method.
/// </summary>
/// <param name="parameters">Method parameters.</param>
protected override void DoInvoke(object[] parameters)
{
ExecuteLogMethod(parameters, null);
}
private void ExecuteLogMethod(object[] parameters, LogEventInfo logEvent)
{
if (_logEventAction != null)
{
_logEventAction.Invoke(logEvent, parameters);
}
else
{
InternalLogger.Trace("{0}: No invoke because class/method was not found or set", this);
}
}
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="PanZoomGestureRecognizer.cs" company="OxyPlot">
// Copyright (c) 2014 OxyPlot contributors
// </copyright>
// <summary>
// Recognizes drag/pinch multi-touch gestures and translates them into pan/zoom information.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
#if __UNIFIED__
namespace OxyPlot.Xamarin.iOS
#else
namespace OxyPlot.MonoTouch
#endif
{
using System;
using System.Collections.Generic;
using System.Linq;
#if __UNIFIED__
using global::Foundation;
using global::UIKit;
#else
using global::MonoTouch.Foundation;
using global::MonoTouch.UIKit;
#endif
/// <summary>
/// Recognizes drag/pinch multi-touch gestures and translates them into pan/zoom information.
/// </summary>
public class PanZoomGestureRecognizer : UIGestureRecognizer
{
/// <summary>
/// Up to 2 touches being currently tracked in a pan/zoom.
/// </summary>
private readonly List<UITouch> activeTouches = new List<UITouch>();
/// <summary>
/// Distance between touch points when the second touch point begins. Used to determine
/// whether the touch points cross along a given axis during the zoom gesture.
/// </summary>
private ScreenVector startingDistance = default(ScreenVector);
/// <summary>
/// Initializes a new instance of the <see cref="PanZoomGestureRecognizer"/> class.
/// </summary>
/// <remarks>
/// To add methods that will be invoked upon recognition, you can use the AddTarget method.
/// </remarks>
public PanZoomGestureRecognizer()
{
this.ZoomThreshold = 20d;
this.AllowPinchPastZero = true;
}
/// <summary>
/// Gets or sets a value indicating whether this <see cref="PanZoomGestureRecognizer"/> keeps the aspect ratio when pinching.
/// </summary>
/// <value><c>true</c> if keep aspect ratio when pinching; otherwise, <c>false</c>.</value>
public bool KeepAspectRatioWhenPinching { get; set; }
/// <summary>
/// Gets or sets how far apart touch points must be on a certain axis to enable scaling that axis.
/// (only applies if KeepAspectRatioWhenPinching is <c>false</c>)
/// </summary>
public double ZoomThreshold { get; set; }
/// <summary>
/// Gets or sets a value indicating whether a zoom-out gesture can turn into a zoom-in gesture if the fingers cross.
/// If <c>true</c>, and <see cref="KeepAspectRatioWhenPinching" /> is <c>false</c>, a zoom-out gesture
/// can turn into a zoom-in gesture if the fingers cross. Setting to <c>false</c> will
/// instead simply stop the zoom at that point.
/// </summary>
public bool AllowPinchPastZero { get; set; }
/// <summary>
/// Gets or sets the current calculated pan/zoom changes.
/// </summary>
/// <value>
/// The touch event arguments.
/// </value>
public OxyTouchEventArgs TouchEventArgs { get; set; }
/// <summary>
/// Called when a touch gesture begins.
/// </summary>
/// <param name="touches">The touches.</param>
/// <param name="evt">The event arguments.</param>
public override void TouchesBegan(NSSet touches, UIEvent evt)
{
base.TouchesBegan(touches, evt);
if (this.activeTouches.Count >= 2)
{
// we already have two touches
return;
}
// Grab 1-2 touches to track
var newTouches = touches.ToArray<UITouch>();
var firstTouch = !this.activeTouches.Any();
this.activeTouches.AddRange(newTouches.Take(2 - this.activeTouches.Count));
if (firstTouch)
{
// HandleTouchStarted initializes the entire multitouch gesture,
// with the first touch used for panning.
this.TouchEventArgs = this.activeTouches.First().ToTouchEventArgs(this.View);
}
this.CalculateStartingDistance();
}
/// <summary>
/// Called when a touch gesture is moving.
/// </summary>
/// <param name="touches">The touches.</param>
/// <param name="evt">The event arguments.</param>
public override void TouchesMoved(NSSet touches, UIEvent evt)
{
base.TouchesMoved(touches, evt);
if (this.activeTouches.Any(touch => touch.Phase == UITouchPhase.Moved))
{
// get current and previous location of the first touch point
var t1 = this.activeTouches.First();
var l1 = t1.LocationInView(this.View).ToScreenPoint();
var pl1 = t1.Phase == UITouchPhase.Moved ? t1.PreviousLocationInView(this.View).ToScreenPoint() : l1;
var l = l1;
var t = l1 - pl1;
var s = new ScreenVector(1, 1);
if (this.activeTouches.Count > 1)
{
// get current and previous location of the second touch point
var t2 = this.activeTouches.ElementAt(1);
var l2 = t2.LocationInView(this.View).ToScreenPoint();
var pl2 = t2.Phase == UITouchPhase.Moved ? t2.PreviousLocationInView(this.View).ToScreenPoint() : l2;
var d = l1 - l2;
var pd = pl1 - pl2;
if (!this.KeepAspectRatioWhenPinching)
{
if (!this.AllowPinchPastZero)
{
// Don't allow fingers crossing in a zoom-out gesture to turn it back into a zoom-in gesture
d = this.PreventCross(d);
}
var scalex = this.CalculateScaleFactor(d.X, pd.X);
var scaley = this.CalculateScaleFactor(d.Y, pd.Y);
s = new ScreenVector(scalex, scaley);
}
else
{
var scale = pd.Length > 0 ? d.Length / pd.Length : 1;
s = new ScreenVector(scale, scale);
}
}
var e = new OxyTouchEventArgs { Position = l, DeltaTranslation = t, DeltaScale = s };
this.TouchEventArgs = e;
this.State = UIGestureRecognizerState.Changed;
}
}
/// <summary>
/// Called when a touch gesture ends.
/// </summary>
/// <param name="touches">The touches.</param>
/// <param name="evt">The event arguments.</param>
public override void TouchesEnded(NSSet touches, UIEvent evt)
{
base.TouchesEnded(touches, evt);
// We already have the only two touches we care about, so ignore the params
var secondTouch = this.activeTouches.ElementAtOrDefault(1);
if (secondTouch != null && secondTouch.Phase == UITouchPhase.Ended)
{
this.activeTouches.Remove(secondTouch);
}
var firstTouch = this.activeTouches.FirstOrDefault();
if (firstTouch != null && firstTouch.Phase == UITouchPhase.Ended)
{
this.activeTouches.Remove(firstTouch);
if (!this.activeTouches.Any())
{
this.TouchEventArgs = firstTouch.ToTouchEventArgs(this.View);
this.State = UIGestureRecognizerState.Ended;
}
}
}
/// <summary>
/// Called when a touch gesture is cancelled.
/// </summary>
/// <param name="touches">The touches.</param>
/// <param name="evt">The event arguments.</param>
public override void TouchesCancelled(NSSet touches, UIEvent evt)
{
base.TouchesCancelled(touches, evt);
// I'm not sure if it's actually possible for one touch to be canceled without
// both being canceled, but just to be safe let's stay consistent with TouchesEnded
// and handle that scenario.
// We already have the only two touches we care about, so ignore the params
var secondTouch = this.activeTouches.ElementAtOrDefault(1);
if (secondTouch != null && secondTouch.Phase == UITouchPhase.Cancelled)
{
this.activeTouches.Remove(secondTouch);
}
var firstTouch = this.activeTouches.FirstOrDefault();
if (firstTouch != null && firstTouch.Phase == UITouchPhase.Cancelled)
{
this.activeTouches.Remove(firstTouch);
if (!this.activeTouches.Any())
{
this.TouchEventArgs = firstTouch.ToTouchEventArgs(this.View);
this.State = UIGestureRecognizerState.Cancelled;
}
}
}
/// <summary>
/// Determines whether the direction has changed.
/// </summary>
/// <param name="current">The current value.</param>
/// <param name="original">The original value.</param>
/// <returns><c>true</c> if the direction changed.</returns>
private static bool DidDirectionChange(double current, double original)
{
return (current >= 0) != (original >= 0);
}
/// <summary>
/// Calculates the scale factor.
/// </summary>
/// <param name="distance">The distance.</param>
/// <param name="previousDistance">The previous distance.</param>
/// <returns>The scale factor.</returns>
private double CalculateScaleFactor(double distance, double previousDistance)
{
return Math.Abs(previousDistance) > this.ZoomThreshold
&& Math.Abs(distance) > this.ZoomThreshold
? Math.Abs(distance / previousDistance)
: 1;
}
/// <summary>
/// Calculates the starting distance.
/// </summary>
private void CalculateStartingDistance()
{
if (this.activeTouches.Count < 2)
{
this.startingDistance = default(ScreenVector);
return;
}
var loc1 = this.activeTouches.ElementAt(0).LocationInView(this.View).ToScreenPoint();
var loc2 = this.activeTouches.ElementAt(1).LocationInView(this.View).ToScreenPoint();
this.startingDistance = loc1 - loc2;
}
/// <summary>
/// Applies the "prevent fingers crossing" to the specified vector.
/// </summary>
/// <param name="currentDistance">The current distance.</param>
/// <returns>A vector where the "prevent fingers crossing" is applied.</returns>
private ScreenVector PreventCross(ScreenVector currentDistance)
{
var x = currentDistance.X;
var y = currentDistance.Y;
if (DidDirectionChange(x, this.startingDistance.X))
{
x = 0;
}
if (DidDirectionChange(y, this.startingDistance.Y))
{
y = 0;
}
return new ScreenVector(x, y);
}
}
}
| |
//
// TextEntryBackend.cs
//
// Author:
// Lluis Sanchez <lluis@xamarin.com>
//
// Copyright (c) 2011 Xamarin Inc
//
// 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 Xwt.Backends;
using Xwt.Drawing;
namespace Xwt.GtkBackend
{
public partial class TextEntryBackend : WidgetBackend, ITextEntryBackend
{
public override void Initialize ()
{
Widget = new Gtk.Entry ();
Widget.Show ();
}
protected virtual Gtk.Entry TextEntry {
get { return (Gtk.Entry)base.Widget; }
}
protected new Gtk.Entry Widget {
get { return TextEntry; }
set { base.Widget = value; }
}
protected new ITextEntryEventSink EventSink {
get { return (ITextEntryEventSink)base.EventSink; }
}
public string Text {
get { return Widget.Text; }
set { Widget.Text = value ?? ""; } // null value causes GTK error
}
public Alignment TextAlignment {
get {
if (Widget.Xalign == 0)
return Alignment.Start;
else if (Widget.Xalign == 1)
return Alignment.End;
else
return Alignment.Center;
}
set {
switch (value) {
case Alignment.Start: Widget.Xalign = 0; break;
case Alignment.End: Widget.Xalign = 1; break;
case Alignment.Center: Widget.Xalign = 0.5f; break;
}
}
}
public override Color BackgroundColor {
get {
return base.BackgroundColor;
}
set {
base.BackgroundColor = value;
Widget.ModifyBase (Gtk.StateType.Normal, value.ToGtkValue ());
}
}
public bool ReadOnly {
get {
return !Widget.IsEditable;
}
set {
Widget.IsEditable = !value;
}
}
public bool ShowFrame {
get {
return Widget.HasFrame;
}
set {
Widget.HasFrame = value;
}
}
public int CursorPosition {
get {
return Widget.Position;
}
set {
Widget.Position = value;
}
}
public int SelectionStart {
get {
int start, end;
Widget.GetSelectionBounds (out start, out end);
return start;
}
set {
int cacheStart = SelectionStart;
int cacheLength = SelectionLength;
Widget.GrabFocus ();
if (String.IsNullOrEmpty (Text))
return;
Widget.SelectRegion (value, value + cacheLength);
if (cacheStart != value)
HandleSelectionChanged ();
}
}
public int SelectionLength {
get {
int start, end;
Widget.GetSelectionBounds (out start, out end);
return end - start;
}
set {
int cacheStart = SelectionStart;
int cacheLength = SelectionLength;
Widget.GrabFocus ();
if (String.IsNullOrEmpty (Text))
return;
Widget.SelectRegion (cacheStart, cacheStart + value);
if (cacheLength != value)
HandleSelectionChanged ();
}
}
public string SelectedText {
get {
int start = SelectionStart;
int end = start + SelectionLength;
if (start == end) return String.Empty;
try {
return Text.Substring (start, end - start);
} catch {
return String.Empty;
}
}
set {
int cacheSelStart = SelectionStart;
int pos = cacheSelStart;
if (SelectionLength > 0) {
Widget.DeleteSelection ();
}
Widget.InsertText (value, ref pos);
Widget.GrabFocus ();
Widget.SelectRegion (cacheSelStart, pos);
HandleSelectionChanged ();
}
}
public bool MultiLine {
get; set;
}
/// <summary>
/// Set the list of completions that will be shown by the entry
/// </summary>
/// <param name="completions">The list of completion or null if no completions should be shown</param>
public void SetCompletions (string[] completions)
{
var widgetCompletion = Widget.Completion;
if (completions == null || completions.Length == 0) {
if (widgetCompletion != null)
widgetCompletion.Model = null;
return;
}
if (widgetCompletion == null)
Widget.Completion = widgetCompletion = CreateCompletion ();
var model = new Gtk.ListStore (typeof(string));
foreach (var c in completions)
model.SetValue (model.Append (), 0, c);
widgetCompletion.Model = model;
}
/// <summary>
/// Set a custom matching function used to decide which completion from SetCompletions list are shown
/// for the given input
/// </summary>
/// <param name="matchFunc">A function which parameter are, in order, the current text entered by the user and a completion candidate.
/// Returns true if the candidate should be included in the completion list.</param>
public void SetCompletionMatchFunc (Func<string, string, bool> matchFunc)
{
var widgetCompletion = Widget.Completion;
if (widgetCompletion == null)
Widget.Completion = widgetCompletion = CreateCompletion ();
widgetCompletion.MatchFunc = delegate (Gtk.EntryCompletion completion, string key, Gtk.TreeIter iter) {
var completionText = (string)completion.Model.GetValue (iter, 0);
return matchFunc (key, completionText);
};
}
Gtk.EntryCompletion CreateCompletion ()
{
return new Gtk.EntryCompletion () {
PopupCompletion = true,
TextColumn = 0,
InlineCompletion = true,
InlineSelection = true
};
}
public override void EnableEvent (object eventId)
{
base.EnableEvent (eventId);
if (eventId is TextEntryEvent) {
switch ((TextEntryEvent)eventId) {
case TextEntryEvent.Changed: Widget.Changed += HandleChanged; break;
case TextEntryEvent.Activated: Widget.Activated += HandleActivated; break;
case TextEntryEvent.SelectionChanged:
enableSelectionChangedEvent = true;
Widget.MoveCursor += HandleMoveCursor;
Widget.ButtonPressEvent += HandleButtonPressEvent;
Widget.ButtonReleaseEvent += HandleButtonReleaseEvent;
Widget.MotionNotifyEvent += HandleMotionNotifyEvent;
break;
}
}
}
public override void DisableEvent (object eventId)
{
base.DisableEvent (eventId);
if (eventId is TextEntryEvent) {
switch ((TextEntryEvent)eventId) {
case TextEntryEvent.Changed: Widget.Changed -= HandleChanged; break;
case TextEntryEvent.Activated: Widget.Activated -= HandleActivated; break;
case TextEntryEvent.SelectionChanged:
enableSelectionChangedEvent = false;
Widget.MoveCursor -= HandleMoveCursor;
Widget.ButtonPressEvent -= HandleButtonPressEvent;
Widget.ButtonReleaseEvent -= HandleButtonReleaseEvent;
Widget.MotionNotifyEvent -= HandleMotionNotifyEvent;
break;
}
}
}
void HandleChanged (object sender, EventArgs e)
{
ApplicationContext.InvokeUserCode (delegate {
EventSink.OnChanged ();
EventSink.OnSelectionChanged ();
});
}
void HandleActivated (object sender, EventArgs e)
{
ApplicationContext.InvokeUserCode (delegate {
EventSink.OnActivated ();
});
}
bool enableSelectionChangedEvent;
void HandleSelectionChanged ()
{
if (enableSelectionChangedEvent)
ApplicationContext.InvokeUserCode (delegate {
EventSink.OnSelectionChanged ();
});
}
void HandleMoveCursor (object sender, EventArgs e)
{
HandleSelectionChanged ();
}
int cacheSelectionStart, cacheSelectionLength;
bool isMouseSelection;
[GLib.ConnectBefore]
void HandleButtonPressEvent (object o, Gtk.ButtonPressEventArgs args)
{
if (args.Event.Button == 1) {
HandleSelectionChanged ();
cacheSelectionStart = SelectionStart;
cacheSelectionLength = SelectionLength;
isMouseSelection = true;
}
}
[GLib.ConnectBefore]
void HandleMotionNotifyEvent (object o, Gtk.MotionNotifyEventArgs args)
{
if (isMouseSelection)
if (cacheSelectionStart != SelectionStart || cacheSelectionLength != SelectionLength)
HandleSelectionChanged ();
cacheSelectionStart = SelectionStart;
cacheSelectionLength = SelectionLength;
}
[GLib.ConnectBefore]
void HandleButtonReleaseEvent (object o, Gtk.ButtonReleaseEventArgs args)
{
if (args.Event.Button == 1) {
isMouseSelection = false;
HandleSelectionChanged ();
}
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.ServiceModel.Description
{
using System;
using System.CodeDom;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Globalization;
using System.Reflection;
using System.Runtime;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Threading;
class ClientClassGenerator : IServiceContractGenerationExtension
{
bool tryAddHelperMethod = false;
bool generateEventAsyncMethods = false;
internal ClientClassGenerator(bool tryAddHelperMethod)
: this(tryAddHelperMethod, false)
{
}
internal ClientClassGenerator(bool tryAddHelperMethod, bool generateEventAsyncMethods)
{
this.tryAddHelperMethod = tryAddHelperMethod;
this.generateEventAsyncMethods = generateEventAsyncMethods;
}
static Type clientBaseType = typeof(ClientBase<>);
static Type duplexClientBaseType = typeof(DuplexClientBase<>);
static Type instanceContextType = typeof(InstanceContext);
static Type objectType = typeof(object);
static Type objectArrayType = typeof(object[]);
static Type exceptionType = typeof(Exception);
static Type boolType = typeof(bool);
static Type stringType = typeof(string);
static Type endpointAddressType = typeof(EndpointAddress);
static Type uriType = typeof(Uri);
static Type bindingType = typeof(Binding);
static Type sendOrPostCallbackType = typeof(SendOrPostCallback);
static Type asyncCompletedEventArgsType = typeof(AsyncCompletedEventArgs);
static Type eventHandlerType = typeof(EventHandler<>);
static Type voidType = typeof(void);
static Type asyncResultType = typeof(IAsyncResult);
static Type asyncCallbackType = typeof(AsyncCallback);
static CodeTypeReference voidTypeRef = new CodeTypeReference(typeof(void));
static CodeTypeReference asyncResultTypeRef = new CodeTypeReference(typeof(IAsyncResult));
static string inputInstanceName = "callbackInstance";
static string invokeAsyncCompletedEventArgsTypeName = "InvokeAsyncCompletedEventArgs";
static string invokeAsyncMethodName = "InvokeAsync";
static string raiseExceptionIfNecessaryMethodName = "RaiseExceptionIfNecessary";
static string beginOperationDelegateTypeName = "BeginOperationDelegate";
static string endOperationDelegateTypeName = "EndOperationDelegate";
static string getDefaultValueForInitializationMethodName = "GetDefaultValueForInitialization";
// IMPORTANT: this table tracks the set of .ctors in ClientBase and DuplexClientBase.
// This table must be kept in [....]
// for DuplexClientBase, the initial InstanceContext param is assumed; ctor overloads must match between ClientBase and DuplexClientBase
static Type[][] ClientCtorParamTypes = new Type[][]
{
new Type[] { },
new Type[] { stringType, },
new Type[] { stringType, stringType, },
new Type[] { stringType, endpointAddressType, },
new Type[] { bindingType, endpointAddressType, },
};
static string[][] ClientCtorParamNames = new string[][]
{
new string[] { },
new string[] { "endpointConfigurationName", },
new string[] { "endpointConfigurationName", "remoteAddress", },
new string[] { "endpointConfigurationName", "remoteAddress", },
new string[] { "binding", "remoteAddress", },
};
static Type[] EventArgsCtorParamTypes = new Type[]
{
objectArrayType,
exceptionType,
boolType,
objectType
};
static string[] EventArgsCtorParamNames = new string[]
{
"results",
"exception",
"cancelled",
"userState"
};
static string[] EventArgsPropertyNames = new string[]
{
"Results",
"Error",
"Cancelled",
"UserState"
};
#if DEBUG
static BindingFlags ctorBindingFlags = BindingFlags.Instance | BindingFlags.NonPublic;
static string DebugCheckTable_errorString = "Client code generation table out of [....] with ClientBase and DuplexClientBase ctors. Please investigate.";
// check the table against what we would get from reflection
static void DebugCheckTable()
{
Fx.Assert(ClientCtorParamNames.Length == ClientCtorParamTypes.Length, DebugCheckTable_errorString);
for (int i = 0; i < ClientCtorParamTypes.Length; i++)
{
DebugCheckTable_ValidateCtor(clientBaseType.GetConstructor(ctorBindingFlags, null, ClientCtorParamTypes[i], null), ClientCtorParamNames[i]);
Type[] duplexCtorTypes1 = DebugCheckTable_InsertAtStart(ClientCtorParamTypes[i], objectType);
Type[] duplexCtorTypes2 = DebugCheckTable_InsertAtStart(ClientCtorParamTypes[i], instanceContextType);
string[] duplexCtorNames = DebugCheckTable_InsertAtStart(ClientCtorParamNames[i], inputInstanceName);
DebugCheckTable_ValidateCtor(duplexClientBaseType.GetConstructor(ctorBindingFlags, null, duplexCtorTypes1, null), duplexCtorNames);
DebugCheckTable_ValidateCtor(duplexClientBaseType.GetConstructor(ctorBindingFlags, null, duplexCtorTypes2, null), duplexCtorNames);
}
// ClientBase<> has extra InstanceContext overloads that we do not call directly from the generated code, but which we
// need to account for in this assert
Fx.Assert(clientBaseType.GetConstructors(ctorBindingFlags).Length == ClientCtorParamTypes.Length * 2, DebugCheckTable_errorString);
// DuplexClientBase<> also has extra object/InstanceContext overloads (but we call these)
Fx.Assert(duplexClientBaseType.GetConstructors(ctorBindingFlags).Length == ClientCtorParamTypes.Length * 2, DebugCheckTable_errorString);
}
static T[] DebugCheckTable_InsertAtStart<T>(T[] arr, T item)
{
T[] newArr = new T[arr.Length + 1];
newArr[0] = item;
Array.Copy(arr, 0, newArr, 1, arr.Length);
return newArr;
}
static void DebugCheckTable_ValidateCtor(ConstructorInfo ctor, string[] paramNames)
{
Fx.Assert(ctor != null, DebugCheckTable_errorString);
ParameterInfo[] parameters = ctor.GetParameters();
Fx.Assert(parameters.Length == paramNames.Length, DebugCheckTable_errorString);
for (int i = 0; i < paramNames.Length; i++)
{
Fx.Assert(parameters[i].Name == paramNames[i], DebugCheckTable_errorString);
}
}
#endif
void IServiceContractGenerationExtension.GenerateContract(ServiceContractGenerationContext context)
{
#if DEBUG
// DebugCheckTable();
#endif
CodeTypeDeclaration clientType = context.TypeFactory.CreateClassType();
// Have to make sure that client name does not match any methods: member names can not be the same as their enclosing type (CSharp only)
clientType.Name = NamingHelper.GetUniqueName(GetClientClassName(context.ContractType.Name), DoesMethodNameExist, context.Operations);
CodeTypeReference contractTypeRef = context.ContractTypeReference;
if (context.DuplexCallbackType == null)
clientType.BaseTypes.Add(new CodeTypeReference(context.ServiceContractGenerator.GetCodeTypeReference(typeof(ClientBase<>)).BaseType, context.ContractTypeReference));
else
clientType.BaseTypes.Add(new CodeTypeReference(context.ServiceContractGenerator.GetCodeTypeReference(typeof(DuplexClientBase<>)).BaseType, context.ContractTypeReference));
clientType.BaseTypes.Add(context.ContractTypeReference);
if (!(ClientCtorParamNames.Length == ClientCtorParamTypes.Length))
{
Fx.Assert("Invalid client generation constructor table initialization");
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, "Invalid client generation constructor table initialization")));
}
for (int i = 0; i < ClientCtorParamNames.Length; i++)
{
if (!(ClientCtorParamNames[i].Length == ClientCtorParamTypes[i].Length))
{
Fx.Assert("Invalid client generation constructor table initialization");
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, "Invalid client generation constructor table initialization")));
}
CodeConstructor ctor = new CodeConstructor();
ctor.Attributes = MemberAttributes.Public;
if (context.DuplexCallbackType != null)
{
ctor.Parameters.Add(new CodeParameterDeclarationExpression(typeof(InstanceContext), inputInstanceName));
ctor.BaseConstructorArgs.Add(new CodeVariableReferenceExpression(inputInstanceName));
}
for (int j = 0; j < ClientCtorParamNames[i].Length; j++)
{
ctor.Parameters.Add(new CodeParameterDeclarationExpression(ClientCtorParamTypes[i][j], ClientCtorParamNames[i][j]));
ctor.BaseConstructorArgs.Add(new CodeVariableReferenceExpression(ClientCtorParamNames[i][j]));
}
clientType.Members.Add(ctor);
}
foreach (OperationContractGenerationContext operationContext in context.Operations)
{
// Note that we generate all the client-side methods, even inherited ones.
if (operationContext.Operation.IsServerInitiated()) continue;
CodeTypeReference declaringContractTypeRef = operationContext.DeclaringTypeReference;
GenerateClientClassMethod(clientType, contractTypeRef, operationContext.SyncMethod, this.tryAddHelperMethod, declaringContractTypeRef);
if (operationContext.IsAsync)
{
CodeMemberMethod beginMethod = GenerateClientClassMethod(clientType, contractTypeRef, operationContext.BeginMethod, this.tryAddHelperMethod, declaringContractTypeRef);
CodeMemberMethod endMethod = GenerateClientClassMethod(clientType, contractTypeRef, operationContext.EndMethod, this.tryAddHelperMethod, declaringContractTypeRef);
if (this.generateEventAsyncMethods)
{
GenerateEventAsyncMethods(context, clientType, operationContext.SyncMethod.Name, beginMethod, endMethod);
}
}
if (operationContext.IsTask)
{
GenerateClientClassMethod(clientType, contractTypeRef, operationContext.TaskMethod, !operationContext.Operation.HasOutputParameters && this.tryAddHelperMethod, declaringContractTypeRef);
}
}
context.Namespace.Types.Add(clientType);
context.ClientType = clientType;
context.ClientTypeReference = ServiceContractGenerator.NamespaceHelper.GetCodeTypeReference(context.Namespace, clientType);
}
static CodeMemberMethod GenerateClientClassMethod(CodeTypeDeclaration clientType, CodeTypeReference contractTypeRef, CodeMemberMethod method, bool addHelperMethod, CodeTypeReference declaringContractTypeRef)
{
CodeMemberMethod methodImpl = GetImplementationOfMethod(contractTypeRef, method);
AddMethodImpl(methodImpl);
int methodPosition = clientType.Members.Add(methodImpl);
CodeMemberMethod helperMethod = null;
if (addHelperMethod)
{
helperMethod = GenerateHelperMethod(declaringContractTypeRef, methodImpl);
if (helperMethod != null)
{
clientType.Members[methodPosition].CustomAttributes.Add(CreateEditorBrowsableAttribute(EditorBrowsableState.Advanced));
clientType.Members.Add(helperMethod);
}
}
return (helperMethod != null) ? helperMethod : methodImpl;
}
internal static CodeAttributeDeclaration CreateEditorBrowsableAttribute(EditorBrowsableState editorBrowsableState)
{
CodeAttributeDeclaration browsableAttribute = new CodeAttributeDeclaration(new CodeTypeReference(typeof(EditorBrowsableAttribute)));
CodeTypeReferenceExpression browsableAttributeState = new CodeTypeReferenceExpression(typeof(EditorBrowsableState));
CodeAttributeArgument browsableAttributeValue = new CodeAttributeArgument(new CodeFieldReferenceExpression(browsableAttributeState, editorBrowsableState.ToString()));
browsableAttribute.Arguments.Add(browsableAttributeValue);
return browsableAttribute;
}
private static CodeMemberMethod GenerateHelperMethod(CodeTypeReference ifaceType, CodeMemberMethod method)
{
CodeMemberMethod helperMethod = new CodeMemberMethod();
helperMethod.Name = method.Name;
helperMethod.Attributes = MemberAttributes.Public | MemberAttributes.Final;
CodeMethodInvokeExpression invokeMethod = new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(new CodeCastExpression(ifaceType, new CodeThisReferenceExpression()), method.Name));
bool hasTypedMessage = false;
foreach (CodeParameterDeclarationExpression param in method.Parameters)
{
CodeTypeDeclaration paramTypeDecl = ServiceContractGenerator.NamespaceHelper.GetCodeType(param.Type);
if (paramTypeDecl != null)
{
hasTypedMessage = true;
CodeVariableReferenceExpression inValue = new CodeVariableReferenceExpression("inValue");
helperMethod.Statements.Add(new CodeVariableDeclarationStatement(param.Type, inValue.VariableName, new CodeObjectCreateExpression(param.Type)));
invokeMethod.Parameters.Add(inValue);
GenerateParameters(helperMethod, paramTypeDecl, inValue, FieldDirection.In);
}
else
{
helperMethod.Parameters.Add(new CodeParameterDeclarationExpression(param.Type, param.Name));
invokeMethod.Parameters.Add(new CodeArgumentReferenceExpression(param.Name));
}
}
if (method.ReturnType.BaseType == voidTypeRef.BaseType)
helperMethod.Statements.Add(invokeMethod);
else
{
CodeTypeDeclaration returnTypeDecl = ServiceContractGenerator.NamespaceHelper.GetCodeType(method.ReturnType);
if (returnTypeDecl != null)
{
hasTypedMessage = true;
CodeVariableReferenceExpression outVar = new CodeVariableReferenceExpression("retVal");
helperMethod.Statements.Add(new CodeVariableDeclarationStatement(method.ReturnType, outVar.VariableName, invokeMethod));
CodeMethodReturnStatement returnStatement = GenerateParameters(helperMethod, returnTypeDecl, outVar, FieldDirection.Out);
if (returnStatement != null)
helperMethod.Statements.Add(returnStatement);
}
else
{
helperMethod.Statements.Add(new CodeMethodReturnStatement(invokeMethod));
helperMethod.ReturnType = method.ReturnType;
}
}
if (hasTypedMessage)
method.PrivateImplementationType = ifaceType;
return hasTypedMessage ? helperMethod : null;
}
private static CodeMethodReturnStatement GenerateParameters(CodeMemberMethod helperMethod, CodeTypeDeclaration codeTypeDeclaration, CodeExpression target, FieldDirection dir)
{
CodeMethodReturnStatement returnStatement = null;
foreach (CodeTypeMember member in codeTypeDeclaration.Members)
{
CodeMemberField field = member as CodeMemberField;
if (field == null)
continue;
CodeFieldReferenceExpression fieldRef = new CodeFieldReferenceExpression(target, field.Name);
CodeTypeDeclaration bodyTypeDecl = ServiceContractGenerator.NamespaceHelper.GetCodeType(field.Type);
if (bodyTypeDecl != null)
{
if (dir == FieldDirection.In)
helperMethod.Statements.Add(new CodeAssignStatement(fieldRef, new CodeObjectCreateExpression(field.Type)));
returnStatement = GenerateParameters(helperMethod, bodyTypeDecl, fieldRef, dir);
continue;
}
CodeParameterDeclarationExpression param = GetRefParameter(helperMethod.Parameters, dir, field);
if (param == null && dir == FieldDirection.Out && helperMethod.ReturnType.BaseType == voidTypeRef.BaseType)
{
helperMethod.ReturnType = field.Type;
returnStatement = new CodeMethodReturnStatement(fieldRef);
}
else
{
if (param == null)
{
param = new CodeParameterDeclarationExpression(field.Type, NamingHelper.GetUniqueName(field.Name, DoesParameterNameExist, helperMethod));
param.Direction = dir;
helperMethod.Parameters.Add(param);
}
if (dir == FieldDirection.Out)
helperMethod.Statements.Add(new CodeAssignStatement(new CodeArgumentReferenceExpression(param.Name), fieldRef));
else
helperMethod.Statements.Add(new CodeAssignStatement(fieldRef, new CodeArgumentReferenceExpression(param.Name)));
}
}
return returnStatement;
}
private static CodeParameterDeclarationExpression GetRefParameter(CodeParameterDeclarationExpressionCollection parameters, FieldDirection dir, CodeMemberField field)
{
foreach (CodeParameterDeclarationExpression p in parameters)
{
if (p.Name == field.Name)
{
if (p.Direction != dir && p.Type.BaseType == field.Type.BaseType)
{
p.Direction = FieldDirection.Ref;
return p;
}
return null;
}
}
return null;
}
internal static bool DoesMemberNameExist(string name, object typeDeclarationObject)
{
CodeTypeDeclaration typeDeclaration = (CodeTypeDeclaration)typeDeclarationObject;
if (string.Compare(typeDeclaration.Name, name, StringComparison.OrdinalIgnoreCase) == 0)
{
return true;
}
foreach (CodeTypeMember member in typeDeclaration.Members)
{
if (string.Compare(member.Name, name, StringComparison.OrdinalIgnoreCase) == 0)
{
return true;
}
}
return false;
}
internal static bool DoesTypeNameExists(string name, object codeTypeDeclarationCollectionObject)
{
CodeTypeDeclarationCollection codeTypeDeclarations = (CodeTypeDeclarationCollection)codeTypeDeclarationCollectionObject;
foreach (CodeTypeDeclaration codeTypeDeclaration in codeTypeDeclarations)
{
if (string.Compare(codeTypeDeclaration.Name, name, StringComparison.OrdinalIgnoreCase) == 0)
{
return true;
}
}
return false;
}
internal static bool DoesTypeAndMemberNameExist(string name, object nameCollection)
{
object[] nameCollections = (object[])nameCollection;
if (DoesTypeNameExists(name, nameCollections[0]))
{
return true;
}
if (DoesMemberNameExist(name, nameCollections[1]))
{
return true;
}
return false;
}
internal static bool DoesMethodNameExist(string name, object operationsObject)
{
Collection<OperationContractGenerationContext> operations = (Collection<OperationContractGenerationContext>)operationsObject;
foreach (OperationContractGenerationContext operationContext in operations)
{
if (String.Compare(operationContext.SyncMethod.Name, name, StringComparison.OrdinalIgnoreCase) == 0)
return true;
if (operationContext.IsAsync)
{
if (String.Compare(operationContext.BeginMethod.Name, name, StringComparison.OrdinalIgnoreCase) == 0)
return true;
if (String.Compare(operationContext.EndMethod.Name, name, StringComparison.OrdinalIgnoreCase) == 0)
return true;
}
if (operationContext.IsTask)
{
if (String.Compare(operationContext.TaskMethod.Name, name, StringComparison.OrdinalIgnoreCase) == 0)
return true;
}
}
return false;
}
internal static bool DoesParameterNameExist(string name, object methodObject)
{
CodeMemberMethod method = (CodeMemberMethod)methodObject;
if (String.Compare(method.Name, name, StringComparison.OrdinalIgnoreCase) == 0)
return true;
CodeParameterDeclarationExpressionCollection parameters = method.Parameters;
foreach (CodeParameterDeclarationExpression p in parameters)
{
if (String.Compare(p.Name, name, StringComparison.OrdinalIgnoreCase) == 0)
return true;
}
return false;
}
static void AddMethodImpl(CodeMemberMethod method)
{
CodeMethodInvokeExpression methodInvoke = new CodeMethodInvokeExpression(GetChannelReference(), method.Name);
foreach (CodeParameterDeclarationExpression parameter in method.Parameters)
{
methodInvoke.Parameters.Add(new CodeDirectionExpression(parameter.Direction, new CodeVariableReferenceExpression(parameter.Name)));
}
if (IsVoid(method))
method.Statements.Add(methodInvoke);
else
method.Statements.Add(new CodeMethodReturnStatement(methodInvoke));
}
static CodeMemberMethod GetImplementationOfMethod(CodeTypeReference ifaceType, CodeMemberMethod method)
{
CodeMemberMethod m = new CodeMemberMethod();
m.Name = method.Name;
m.ImplementationTypes.Add(ifaceType);
m.Attributes = MemberAttributes.Public | MemberAttributes.Final;
foreach (CodeParameterDeclarationExpression parameter in method.Parameters)
{
CodeParameterDeclarationExpression newParam = new CodeParameterDeclarationExpression(parameter.Type, parameter.Name);
newParam.Direction = parameter.Direction;
m.Parameters.Add(newParam);
}
m.ReturnType = method.ReturnType;
return m;
}
static void GenerateEventAsyncMethods(ServiceContractGenerationContext context, CodeTypeDeclaration clientType,
string syncMethodName, CodeMemberMethod beginMethod, CodeMemberMethod endMethod)
{
CodeTypeDeclaration operationCompletedEventArgsType = CreateOperationCompletedEventArgsType(context, syncMethodName, endMethod);
CodeMemberEvent operationCompletedEvent = CreateOperationCompletedEvent(context, clientType, syncMethodName, operationCompletedEventArgsType);
CodeMemberField beginOperationDelegate = CreateBeginOperationDelegate(context, clientType, syncMethodName);
CodeMemberMethod beginOperationMethod = CreateBeginOperationMethod(context, clientType, syncMethodName, beginMethod);
CodeMemberField endOperationDelegate = CreateEndOperationDelegate(context, clientType, syncMethodName);
CodeMemberMethod endOperationMethod = CreateEndOperationMethod(context, clientType, syncMethodName, endMethod);
CodeMemberField operationCompletedDelegate = CreateOperationCompletedDelegate(context, clientType, syncMethodName);
CodeMemberMethod operationCompletedMethod = CreateOperationCompletedMethod(context, clientType, syncMethodName, operationCompletedEventArgsType, operationCompletedEvent);
CodeMemberMethod eventAsyncMethod = CreateEventAsyncMethod(context, clientType, syncMethodName, beginMethod,
beginOperationDelegate, beginOperationMethod, endOperationDelegate, endOperationMethod, operationCompletedDelegate, operationCompletedMethod);
CreateEventAsyncMethodOverload(clientType, eventAsyncMethod);
// hide the normal async methods from intellisense
beginMethod.CustomAttributes.Add(CreateEditorBrowsableAttribute(EditorBrowsableState.Advanced));
endMethod.CustomAttributes.Add(CreateEditorBrowsableAttribute(EditorBrowsableState.Advanced));
}
static CodeTypeDeclaration CreateOperationCompletedEventArgsType(ServiceContractGenerationContext context,
string syncMethodName, CodeMemberMethod endMethod)
{
if ((endMethod.Parameters.Count == 1) && (endMethod.ReturnType.BaseType == voidTypeRef.BaseType))
{
// no need to create new event args type, use AsyncCompletedEventArgs
return null;
}
CodeTypeDeclaration argsType = context.TypeFactory.CreateClassType();
argsType.BaseTypes.Add(new CodeTypeReference(asyncCompletedEventArgsType));
// define object[] results field.
CodeMemberField resultsField = new CodeMemberField();
resultsField.Type = new CodeTypeReference(objectArrayType);
CodeFieldReferenceExpression resultsFieldReference = new CodeFieldReferenceExpression();
resultsFieldReference.TargetObject = new CodeThisReferenceExpression();
// create constructor, that assigns the results field.
CodeConstructor ctor = new CodeConstructor();
ctor.Attributes = MemberAttributes.Public;
for (int i = 0; i < EventArgsCtorParamTypes.Length; i++)
{
ctor.Parameters.Add(new CodeParameterDeclarationExpression(EventArgsCtorParamTypes[i], EventArgsCtorParamNames[i]));
if (i > 0)
{
ctor.BaseConstructorArgs.Add(new CodeVariableReferenceExpression(EventArgsCtorParamNames[i]));
}
}
argsType.Members.Add(ctor);
ctor.Statements.Add(new CodeAssignStatement(resultsFieldReference, new CodeVariableReferenceExpression(EventArgsCtorParamNames[0])));
// create properties for the out parameters
int asyncResultParamIndex = GetAsyncResultParamIndex(endMethod);
int count = 0;
for (int i = 0; i < endMethod.Parameters.Count; i++)
{
if (i != asyncResultParamIndex)
{
CreateEventAsyncCompletedArgsTypeProperty(argsType,
endMethod.Parameters[i].Type,
endMethod.Parameters[i].Name,
new CodeArrayIndexerExpression(resultsFieldReference, new CodePrimitiveExpression(count++)));
}
}
// create the property for the return type
if (endMethod.ReturnType.BaseType != voidTypeRef.BaseType)
{
CreateEventAsyncCompletedArgsTypeProperty(
argsType,
endMethod.ReturnType,
NamingHelper.GetUniqueName("Result", DoesMemberNameExist, argsType),
new CodeArrayIndexerExpression(resultsFieldReference,
new CodePrimitiveExpression(count)));
}
// Name the "results" field after generating the properties to make sure it does
// not conflict with the property names.
resultsField.Name = NamingHelper.GetUniqueName("results", DoesMemberNameExist, argsType);
resultsFieldReference.FieldName = resultsField.Name;
argsType.Members.Add(resultsField);
// Name the type making sure that it does not conflict with its members and types already present in
// the namespace.
argsType.Name = NamingHelper.GetUniqueName(GetOperationCompletedEventArgsTypeName(syncMethodName),
DoesTypeAndMemberNameExist, new object[] { context.Namespace.Types, argsType });
context.Namespace.Types.Add(argsType);
return argsType;
}
static int GetAsyncResultParamIndex(CodeMemberMethod endMethod)
{
int index = endMethod.Parameters.Count - 1;
if (endMethod.Parameters[index].Type.BaseType != asyncResultTypeRef.BaseType)
{
// workaround for CSD Dev Framework:10826, the unwrapped end method has IAsyncResult as first param.
index = 0;
}
return index;
}
static CodeMemberProperty CreateEventAsyncCompletedArgsTypeProperty(CodeTypeDeclaration ownerTypeDecl,
CodeTypeReference propertyType, string propertyName, CodeExpression propertyValueExpr)
{
CodeMemberProperty property = new CodeMemberProperty();
property.Attributes = MemberAttributes.Public | MemberAttributes.Final;
property.Type = propertyType;
property.Name = propertyName;
property.HasSet = false;
property.HasGet = true;
CodeCastExpression castExpr = new CodeCastExpression(propertyType, propertyValueExpr);
CodeMethodReturnStatement returnStmt = new CodeMethodReturnStatement(castExpr);
property.GetStatements.Add(new CodeMethodInvokeExpression(new CodeBaseReferenceExpression(), raiseExceptionIfNecessaryMethodName));
property.GetStatements.Add(returnStmt);
ownerTypeDecl.Members.Add(property);
return property;
}
static CodeMemberEvent CreateOperationCompletedEvent(ServiceContractGenerationContext context,
CodeTypeDeclaration clientType, string syncMethodName, CodeTypeDeclaration operationCompletedEventArgsType)
{
CodeMemberEvent operationCompletedEvent = new CodeMemberEvent();
operationCompletedEvent.Attributes = MemberAttributes.Public;
operationCompletedEvent.Type = new CodeTypeReference(eventHandlerType);
if (operationCompletedEventArgsType == null)
{
operationCompletedEvent.Type.TypeArguments.Add(asyncCompletedEventArgsType);
}
else
{
operationCompletedEvent.Type.TypeArguments.Add(operationCompletedEventArgsType.Name);
}
operationCompletedEvent.Name = NamingHelper.GetUniqueName(GetOperationCompletedEventName(syncMethodName),
DoesMethodNameExist, context.Operations);
clientType.Members.Add(operationCompletedEvent);
return operationCompletedEvent;
}
static CodeMemberField CreateBeginOperationDelegate(ServiceContractGenerationContext context,
CodeTypeDeclaration clientType, string syncMethodName)
{
CodeMemberField beginOperationDelegate = new CodeMemberField();
beginOperationDelegate.Attributes = MemberAttributes.Private;
beginOperationDelegate.Type = new CodeTypeReference(beginOperationDelegateTypeName);
beginOperationDelegate.Name = NamingHelper.GetUniqueName(GetBeginOperationDelegateName(syncMethodName),
DoesMethodNameExist, context.Operations);
clientType.Members.Add(beginOperationDelegate);
return beginOperationDelegate;
}
static CodeMemberMethod CreateBeginOperationMethod(ServiceContractGenerationContext context, CodeTypeDeclaration clientType,
string syncMethodName, CodeMemberMethod beginMethod)
{
CodeMemberMethod onBeginOperationMethod = new CodeMemberMethod();
onBeginOperationMethod.Attributes = MemberAttributes.Private;
onBeginOperationMethod.ReturnType = new CodeTypeReference(asyncResultType);
onBeginOperationMethod.Name = NamingHelper.GetUniqueName(GetBeginOperationMethodName(syncMethodName),
DoesMethodNameExist, context.Operations);
CodeParameterDeclarationExpression inValuesParam = new CodeParameterDeclarationExpression();
inValuesParam.Type = new CodeTypeReference(objectArrayType);
inValuesParam.Name = NamingHelper.GetUniqueName("inValues", DoesParameterNameExist, beginMethod);
onBeginOperationMethod.Parameters.Add(inValuesParam);
CodeMethodInvokeExpression invokeBegin = new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), beginMethod.Name);
CodeExpression inValuesRef = new CodeVariableReferenceExpression(inValuesParam.Name);
for (int i = 0; i < beginMethod.Parameters.Count - 2; i++)
{
CodeVariableDeclarationStatement variableDecl = new CodeVariableDeclarationStatement();
variableDecl.Type = beginMethod.Parameters[i].Type;
variableDecl.Name = beginMethod.Parameters[i].Name;
variableDecl.InitExpression = new CodeCastExpression(variableDecl.Type,
new CodeArrayIndexerExpression(inValuesRef, new CodePrimitiveExpression(i)));
onBeginOperationMethod.Statements.Add(variableDecl);
invokeBegin.Parameters.Add(new CodeDirectionExpression(beginMethod.Parameters[i].Direction,
new CodeVariableReferenceExpression(variableDecl.Name)));
}
for (int i = beginMethod.Parameters.Count - 2; i < beginMethod.Parameters.Count; i++)
{
onBeginOperationMethod.Parameters.Add(new CodeParameterDeclarationExpression(
beginMethod.Parameters[i].Type, beginMethod.Parameters[i].Name));
invokeBegin.Parameters.Add(new CodeVariableReferenceExpression(beginMethod.Parameters[i].Name));
}
onBeginOperationMethod.Statements.Add(new CodeMethodReturnStatement(invokeBegin));
clientType.Members.Add(onBeginOperationMethod);
return onBeginOperationMethod;
}
static CodeMemberField CreateEndOperationDelegate(ServiceContractGenerationContext context,
CodeTypeDeclaration clientType, string syncMethodName)
{
CodeMemberField endOperationDelegate = new CodeMemberField();
endOperationDelegate.Attributes = MemberAttributes.Private;
endOperationDelegate.Type = new CodeTypeReference(endOperationDelegateTypeName);
endOperationDelegate.Name = NamingHelper.GetUniqueName(GetEndOperationDelegateName(syncMethodName),
DoesMethodNameExist, context.Operations);
clientType.Members.Add(endOperationDelegate);
return endOperationDelegate;
}
static CodeMemberMethod CreateEndOperationMethod(ServiceContractGenerationContext context, CodeTypeDeclaration clientType, string syncMethodName, CodeMemberMethod endMethod)
{
CodeMemberMethod onEndOperationMethod = new CodeMemberMethod();
onEndOperationMethod.Attributes = MemberAttributes.Private;
onEndOperationMethod.ReturnType = new CodeTypeReference(objectArrayType);
onEndOperationMethod.Name = NamingHelper.GetUniqueName(GetEndOperationMethodName(syncMethodName), DoesMethodNameExist, context.Operations);
int asyncResultParamIndex = GetAsyncResultParamIndex(endMethod);
CodeMethodInvokeExpression invokeEnd = new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), endMethod.Name);
CodeArrayCreateExpression retArray = new CodeArrayCreateExpression();
retArray.CreateType = new CodeTypeReference(objectArrayType);
for (int i = 0; i < endMethod.Parameters.Count; i++)
{
if (i == asyncResultParamIndex)
{
onEndOperationMethod.Parameters.Add(new CodeParameterDeclarationExpression(
endMethod.Parameters[i].Type, endMethod.Parameters[i].Name));
invokeEnd.Parameters.Add(new CodeVariableReferenceExpression(endMethod.Parameters[i].Name));
}
else
{
CodeVariableDeclarationStatement variableDecl = new CodeVariableDeclarationStatement(
endMethod.Parameters[i].Type, endMethod.Parameters[i].Name);
CodeMethodReferenceExpression getDefaultValueMethodRef = new CodeMethodReferenceExpression(new CodeThisReferenceExpression(), getDefaultValueForInitializationMethodName, endMethod.Parameters[i].Type);
variableDecl.InitExpression = new CodeMethodInvokeExpression(getDefaultValueMethodRef);
onEndOperationMethod.Statements.Add(variableDecl);
invokeEnd.Parameters.Add(new CodeDirectionExpression(endMethod.Parameters[i].Direction,
new CodeVariableReferenceExpression(variableDecl.Name)));
retArray.Initializers.Add(new CodeVariableReferenceExpression(variableDecl.Name));
}
}
if (endMethod.ReturnType.BaseType != voidTypeRef.BaseType)
{
CodeVariableDeclarationStatement retValDecl = new CodeVariableDeclarationStatement();
retValDecl.Type = endMethod.ReturnType;
retValDecl.Name = NamingHelper.GetUniqueName("retVal", DoesParameterNameExist, endMethod);
retValDecl.InitExpression = invokeEnd;
retArray.Initializers.Add(new CodeVariableReferenceExpression(retValDecl.Name));
onEndOperationMethod.Statements.Add(retValDecl);
}
else
{
onEndOperationMethod.Statements.Add(invokeEnd);
}
if (retArray.Initializers.Count > 0)
{
onEndOperationMethod.Statements.Add(new CodeMethodReturnStatement(retArray));
}
else
{
onEndOperationMethod.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(null)));
}
clientType.Members.Add(onEndOperationMethod);
return onEndOperationMethod;
}
static CodeMemberField CreateOperationCompletedDelegate(ServiceContractGenerationContext context,
CodeTypeDeclaration clientType, string syncMethodName)
{
CodeMemberField operationCompletedDelegate = new CodeMemberField();
operationCompletedDelegate.Attributes = MemberAttributes.Private;
operationCompletedDelegate.Type = new CodeTypeReference(sendOrPostCallbackType);
operationCompletedDelegate.Name = NamingHelper.GetUniqueName(GetOperationCompletedDelegateName(syncMethodName),
DoesMethodNameExist, context.Operations);
clientType.Members.Add(operationCompletedDelegate);
return operationCompletedDelegate;
}
static CodeMemberMethod CreateOperationCompletedMethod(ServiceContractGenerationContext context, CodeTypeDeclaration clientType,
string syncMethodName, CodeTypeDeclaration operationCompletedEventArgsType, CodeMemberEvent operationCompletedEvent)
{
CodeMemberMethod operationCompletedMethod = new CodeMemberMethod();
operationCompletedMethod.Attributes = MemberAttributes.Private;
operationCompletedMethod.Name = NamingHelper.GetUniqueName(GetOperationCompletedMethodName(syncMethodName),
DoesMethodNameExist, context.Operations);
operationCompletedMethod.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(objectType), "state"));
operationCompletedMethod.ReturnType = new CodeTypeReference(voidType);
CodeVariableDeclarationStatement eventArgsDecl =
new CodeVariableDeclarationStatement(invokeAsyncCompletedEventArgsTypeName, "e");
eventArgsDecl.InitExpression = new CodeCastExpression(invokeAsyncCompletedEventArgsTypeName,
new CodeArgumentReferenceExpression(operationCompletedMethod.Parameters[0].Name));
CodeObjectCreateExpression newEventArgsExpr;
CodeVariableReferenceExpression eventArgsRef = new CodeVariableReferenceExpression(eventArgsDecl.Name);
if (operationCompletedEventArgsType != null)
{
newEventArgsExpr = new CodeObjectCreateExpression(operationCompletedEventArgsType.Name,
new CodePropertyReferenceExpression(eventArgsRef, EventArgsPropertyNames[0]),
new CodePropertyReferenceExpression(eventArgsRef, EventArgsPropertyNames[1]),
new CodePropertyReferenceExpression(eventArgsRef, EventArgsPropertyNames[2]),
new CodePropertyReferenceExpression(eventArgsRef, EventArgsPropertyNames[3]));
}
else
{
newEventArgsExpr = new CodeObjectCreateExpression(asyncCompletedEventArgsType,
new CodePropertyReferenceExpression(eventArgsRef, EventArgsPropertyNames[1]),
new CodePropertyReferenceExpression(eventArgsRef, EventArgsPropertyNames[2]),
new CodePropertyReferenceExpression(eventArgsRef, EventArgsPropertyNames[3]));
}
CodeEventReferenceExpression completedEvent = new CodeEventReferenceExpression(new CodeThisReferenceExpression(), operationCompletedEvent.Name);
CodeDelegateInvokeExpression raiseEventExpr = new CodeDelegateInvokeExpression(
completedEvent,
new CodeThisReferenceExpression(),
newEventArgsExpr);
CodeConditionStatement ifEventHandlerNotNullBlock = new CodeConditionStatement(
new CodeBinaryOperatorExpression(
completedEvent,
CodeBinaryOperatorType.IdentityInequality,
new CodePrimitiveExpression(null)),
eventArgsDecl,
new CodeExpressionStatement(raiseEventExpr));
operationCompletedMethod.Statements.Add(ifEventHandlerNotNullBlock);
clientType.Members.Add(operationCompletedMethod);
return operationCompletedMethod;
}
static CodeMemberMethod CreateEventAsyncMethod(ServiceContractGenerationContext context, CodeTypeDeclaration clientType,
string syncMethodName, CodeMemberMethod beginMethod,
CodeMemberField beginOperationDelegate, CodeMemberMethod beginOperationMethod,
CodeMemberField endOperationDelegate, CodeMemberMethod endOperationMethod,
CodeMemberField operationCompletedDelegate, CodeMemberMethod operationCompletedMethod)
{
CodeMemberMethod eventAsyncMethod = new CodeMemberMethod();
eventAsyncMethod.Name = NamingHelper.GetUniqueName(GetEventAsyncMethodName(syncMethodName),
DoesMethodNameExist, context.Operations);
eventAsyncMethod.Attributes = MemberAttributes.Public | MemberAttributes.Final;
eventAsyncMethod.ReturnType = new CodeTypeReference(voidType);
CodeArrayCreateExpression invokeAsyncInValues = new CodeArrayCreateExpression(new CodeTypeReference(objectArrayType));
for (int i = 0; i < beginMethod.Parameters.Count - 2; i++)
{
CodeParameterDeclarationExpression beginMethodParameter = beginMethod.Parameters[i];
CodeParameterDeclarationExpression eventAsyncMethodParameter = new CodeParameterDeclarationExpression(
beginMethodParameter.Type, beginMethodParameter.Name);
eventAsyncMethodParameter.Direction = FieldDirection.In;
eventAsyncMethod.Parameters.Add(eventAsyncMethodParameter);
invokeAsyncInValues.Initializers.Add(new CodeVariableReferenceExpression(eventAsyncMethodParameter.Name));
}
string userStateParamName = NamingHelper.GetUniqueName("userState", DoesParameterNameExist, eventAsyncMethod);
eventAsyncMethod.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(objectType), userStateParamName));
eventAsyncMethod.Statements.Add(CreateDelegateIfNotNull(beginOperationDelegate, beginOperationMethod));
eventAsyncMethod.Statements.Add(CreateDelegateIfNotNull(endOperationDelegate, endOperationMethod));
eventAsyncMethod.Statements.Add(CreateDelegateIfNotNull(operationCompletedDelegate, operationCompletedMethod));
CodeMethodInvokeExpression invokeAsync = new CodeMethodInvokeExpression(new CodeBaseReferenceExpression(), invokeAsyncMethodName);
invokeAsync.Parameters.Add(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), beginOperationDelegate.Name));
if (invokeAsyncInValues.Initializers.Count > 0)
{
invokeAsync.Parameters.Add(invokeAsyncInValues);
}
else
{
invokeAsync.Parameters.Add(new CodePrimitiveExpression(null));
}
invokeAsync.Parameters.Add(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), endOperationDelegate.Name));
invokeAsync.Parameters.Add(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), operationCompletedDelegate.Name));
invokeAsync.Parameters.Add(new CodeVariableReferenceExpression(userStateParamName));
eventAsyncMethod.Statements.Add(new CodeExpressionStatement(invokeAsync));
clientType.Members.Add(eventAsyncMethod);
return eventAsyncMethod;
}
static CodeMemberMethod CreateEventAsyncMethodOverload(CodeTypeDeclaration clientType, CodeMemberMethod eventAsyncMethod)
{
CodeMemberMethod eventAsyncMethodOverload = new CodeMemberMethod();
eventAsyncMethodOverload.Attributes = eventAsyncMethod.Attributes;
eventAsyncMethodOverload.Name = eventAsyncMethod.Name;
eventAsyncMethodOverload.ReturnType = eventAsyncMethod.ReturnType;
CodeMethodInvokeExpression invokeEventAsyncMethod = new CodeMethodInvokeExpression(
new CodeThisReferenceExpression(), eventAsyncMethod.Name);
for (int i = 0; i < eventAsyncMethod.Parameters.Count - 1; i++)
{
eventAsyncMethodOverload.Parameters.Add(new CodeParameterDeclarationExpression(
eventAsyncMethod.Parameters[i].Type,
eventAsyncMethod.Parameters[i].Name));
invokeEventAsyncMethod.Parameters.Add(new CodeVariableReferenceExpression(
eventAsyncMethod.Parameters[i].Name));
}
invokeEventAsyncMethod.Parameters.Add(new CodePrimitiveExpression(null));
eventAsyncMethodOverload.Statements.Add(invokeEventAsyncMethod);
int eventAsyncMethodPosition = clientType.Members.IndexOf(eventAsyncMethod);
Fx.Assert(eventAsyncMethodPosition != -1,
"The eventAsyncMethod must be added to the clientType before calling CreateEventAsyncMethodOverload");
clientType.Members.Insert(eventAsyncMethodPosition, eventAsyncMethodOverload);
return eventAsyncMethodOverload;
}
static CodeStatement CreateDelegateIfNotNull(CodeMemberField delegateField, CodeMemberMethod delegateMethod)
{
return new CodeConditionStatement(
new CodeBinaryOperatorExpression(
new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), delegateField.Name),
CodeBinaryOperatorType.IdentityEquality,
new CodePrimitiveExpression(null)),
new CodeAssignStatement(
new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), delegateField.Name),
new CodeDelegateCreateExpression(delegateField.Type,
new CodeThisReferenceExpression(), delegateMethod.Name)));
}
static string GetClassName(string interfaceName)
{
// maybe strip a leading 'I'
if (interfaceName.Length >= 2 &&
String.Compare(interfaceName, 0, Strings.InterfaceTypePrefix, 0, Strings.InterfaceTypePrefix.Length, StringComparison.Ordinal) == 0 &&
Char.IsUpper(interfaceName, 1))
return interfaceName.Substring(1);
else
return interfaceName;
}
static string GetEventAsyncMethodName(string syncMethodName)
{
return string.Format(CultureInfo.InvariantCulture, "{0}Async", syncMethodName);
}
static string GetBeginOperationDelegateName(string syncMethodName)
{
return string.Format(CultureInfo.InvariantCulture, "onBegin{0}Delegate", syncMethodName);
}
static string GetBeginOperationMethodName(string syncMethodName)
{
return string.Format(CultureInfo.InvariantCulture, "OnBegin{0}", syncMethodName);
}
static string GetEndOperationDelegateName(string syncMethodName)
{
return string.Format(CultureInfo.InvariantCulture, "onEnd{0}Delegate", syncMethodName);
}
static string GetEndOperationMethodName(string syncMethodName)
{
return string.Format(CultureInfo.InvariantCulture, "OnEnd{0}", syncMethodName);
}
static string GetOperationCompletedDelegateName(string syncMethodName)
{
return string.Format(CultureInfo.InvariantCulture, "on{0}CompletedDelegate", syncMethodName);
}
static string GetOperationCompletedMethodName(string syncMethodName)
{
return string.Format(CultureInfo.InvariantCulture, "On{0}Completed", syncMethodName);
}
static string GetOperationCompletedEventName(string syncMethodName)
{
return string.Format(CultureInfo.InvariantCulture, "{0}Completed", syncMethodName);
}
static string GetOperationCompletedEventArgsTypeName(string syncMethodName)
{
return string.Format(CultureInfo.InvariantCulture, "{0}CompletedEventArgs", syncMethodName);
}
static internal string GetClientClassName(string interfaceName)
{
return GetClassName(interfaceName) + Strings.ClientTypeSuffix;
}
static bool IsVoid(CodeMemberMethod method)
{
return method.ReturnType == null || String.Compare(method.ReturnType.BaseType, typeof(void).FullName, StringComparison.Ordinal) == 0;
}
static CodeExpression GetChannelReference()
{
return new CodePropertyReferenceExpression(new CodeBaseReferenceExpression(), Strings.ClientBaseChannelProperty);
}
static class Strings
{
public const string ClientBaseChannelProperty = "Channel";
public const string ClientTypeSuffix = "Client";
public const string InterfaceTypePrefix = "I";
}
}
}
| |
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Text;
namespace EduHub.Data.Entities
{
/// <summary>
/// VELS Dimension Results Data Set
/// </summary>
[GeneratedCode("EduHub Data", "0.9")]
public sealed partial class STVDIDataSet : EduHubDataSet<STVDI>
{
/// <inheritdoc />
public override string Name { get { return "STVDI"; } }
/// <inheritdoc />
public override bool SupportsEntityLastModified { get { return true; } }
internal STVDIDataSet(EduHubContext Context)
: base(Context)
{
Index_CAMPUS = new Lazy<NullDictionary<int?, IReadOnlyList<STVDI>>>(() => this.ToGroupedNullDictionary(i => i.CAMPUS));
Index_LW_DATE = new Lazy<NullDictionary<DateTime?, IReadOnlyList<STVDI>>>(() => this.ToGroupedNullDictionary(i => i.LW_DATE));
Index_ORIGINAL_SCHOOL = new Lazy<NullDictionary<string, IReadOnlyList<STVDI>>>(() => this.ToGroupedNullDictionary(i => i.ORIGINAL_SCHOOL));
Index_SKEY = new Lazy<Dictionary<string, IReadOnlyList<STVDI>>>(() => this.ToGroupedDictionary(i => i.SKEY));
Index_SKEY_VDIMENSION_VDOMAIN_YEAR_SEMESTER_SCORE = new Lazy<Dictionary<Tuple<string, string, string, string, string>, IReadOnlyList<STVDI>>>(() => this.ToGroupedDictionary(i => Tuple.Create(i.SKEY, i.VDIMENSION, i.VDOMAIN, i.YEAR_SEMESTER, i.SCORE)));
Index_TID = new Lazy<Dictionary<int, STVDI>>(() => this.ToDictionary(i => i.TID));
Index_VDIMENSION = new Lazy<NullDictionary<string, IReadOnlyList<STVDI>>>(() => this.ToGroupedNullDictionary(i => i.VDIMENSION));
Index_VDOMAIN = new Lazy<NullDictionary<string, IReadOnlyList<STVDI>>>(() => this.ToGroupedNullDictionary(i => i.VDOMAIN));
}
/// <summary>
/// Matches CSV file headers to actions, used to deserialize <see cref="STVDI" />
/// </summary>
/// <param name="Headers">The CSV column headers</param>
/// <returns>An array of actions which deserialize <see cref="STVDI" /> fields for each CSV column header</returns>
internal override Action<STVDI, string>[] BuildMapper(IReadOnlyList<string> Headers)
{
var mapper = new Action<STVDI, string>[Headers.Count];
for (var i = 0; i < Headers.Count; i++) {
switch (Headers[i]) {
case "TID":
mapper[i] = (e, v) => e.TID = int.Parse(v);
break;
case "SKEY":
mapper[i] = (e, v) => e.SKEY = v;
break;
case "SCHOOL_YEAR":
mapper[i] = (e, v) => e.SCHOOL_YEAR = v;
break;
case "CAMPUS":
mapper[i] = (e, v) => e.CAMPUS = v == null ? (int?)null : int.Parse(v);
break;
case "YEAR_SEMESTER":
mapper[i] = (e, v) => e.YEAR_SEMESTER = v;
break;
case "VDOMAIN":
mapper[i] = (e, v) => e.VDOMAIN = v;
break;
case "VDIMENSION":
mapper[i] = (e, v) => e.VDIMENSION = v;
break;
case "SCORE":
mapper[i] = (e, v) => e.SCORE = v;
break;
case "ORIGINAL_SCHOOL":
mapper[i] = (e, v) => e.ORIGINAL_SCHOOL = v;
break;
case "LW_DATE":
mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
break;
case "LW_TIME":
mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v);
break;
case "LW_USER":
mapper[i] = (e, v) => e.LW_USER = v;
break;
default:
mapper[i] = MapperNoOp;
break;
}
}
return mapper;
}
/// <summary>
/// Merges <see cref="STVDI" /> delta entities
/// </summary>
/// <param name="Entities">Iterator for base <see cref="STVDI" /> entities</param>
/// <param name="DeltaEntities">List of delta <see cref="STVDI" /> entities</param>
/// <returns>A merged <see cref="IEnumerable{STVDI}"/> of entities</returns>
internal override IEnumerable<STVDI> ApplyDeltaEntities(IEnumerable<STVDI> Entities, List<STVDI> DeltaEntities)
{
HashSet<int> Index_TID = new HashSet<int>(DeltaEntities.Select(i => i.TID));
using (var deltaIterator = DeltaEntities.GetEnumerator())
{
using (var entityIterator = Entities.GetEnumerator())
{
while (deltaIterator.MoveNext())
{
var deltaClusteredKey = deltaIterator.Current.SKEY;
bool yieldEntity = false;
while (entityIterator.MoveNext())
{
var entity = entityIterator.Current;
bool overwritten = Index_TID.Remove(entity.TID);
if (entity.SKEY.CompareTo(deltaClusteredKey) <= 0)
{
if (!overwritten)
{
yield return entity;
}
}
else
{
yieldEntity = !overwritten;
break;
}
}
yield return deltaIterator.Current;
if (yieldEntity)
{
yield return entityIterator.Current;
}
}
while (entityIterator.MoveNext())
{
yield return entityIterator.Current;
}
}
}
}
#region Index Fields
private Lazy<NullDictionary<int?, IReadOnlyList<STVDI>>> Index_CAMPUS;
private Lazy<NullDictionary<DateTime?, IReadOnlyList<STVDI>>> Index_LW_DATE;
private Lazy<NullDictionary<string, IReadOnlyList<STVDI>>> Index_ORIGINAL_SCHOOL;
private Lazy<Dictionary<string, IReadOnlyList<STVDI>>> Index_SKEY;
private Lazy<Dictionary<Tuple<string, string, string, string, string>, IReadOnlyList<STVDI>>> Index_SKEY_VDIMENSION_VDOMAIN_YEAR_SEMESTER_SCORE;
private Lazy<Dictionary<int, STVDI>> Index_TID;
private Lazy<NullDictionary<string, IReadOnlyList<STVDI>>> Index_VDIMENSION;
private Lazy<NullDictionary<string, IReadOnlyList<STVDI>>> Index_VDOMAIN;
#endregion
#region Index Methods
/// <summary>
/// Find STVDI by CAMPUS field
/// </summary>
/// <param name="CAMPUS">CAMPUS value used to find STVDI</param>
/// <returns>List of related STVDI entities</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<STVDI> FindByCAMPUS(int? CAMPUS)
{
return Index_CAMPUS.Value[CAMPUS];
}
/// <summary>
/// Attempt to find STVDI by CAMPUS field
/// </summary>
/// <param name="CAMPUS">CAMPUS value used to find STVDI</param>
/// <param name="Value">List of related STVDI entities</param>
/// <returns>True if the list of related STVDI entities is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByCAMPUS(int? CAMPUS, out IReadOnlyList<STVDI> Value)
{
return Index_CAMPUS.Value.TryGetValue(CAMPUS, out Value);
}
/// <summary>
/// Attempt to find STVDI by CAMPUS field
/// </summary>
/// <param name="CAMPUS">CAMPUS value used to find STVDI</param>
/// <returns>List of related STVDI entities, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<STVDI> TryFindByCAMPUS(int? CAMPUS)
{
IReadOnlyList<STVDI> value;
if (Index_CAMPUS.Value.TryGetValue(CAMPUS, out value))
{
return value;
}
else
{
return null;
}
}
/// <summary>
/// Find STVDI by LW_DATE field
/// </summary>
/// <param name="LW_DATE">LW_DATE value used to find STVDI</param>
/// <returns>List of related STVDI entities</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<STVDI> FindByLW_DATE(DateTime? LW_DATE)
{
return Index_LW_DATE.Value[LW_DATE];
}
/// <summary>
/// Attempt to find STVDI by LW_DATE field
/// </summary>
/// <param name="LW_DATE">LW_DATE value used to find STVDI</param>
/// <param name="Value">List of related STVDI entities</param>
/// <returns>True if the list of related STVDI entities is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByLW_DATE(DateTime? LW_DATE, out IReadOnlyList<STVDI> Value)
{
return Index_LW_DATE.Value.TryGetValue(LW_DATE, out Value);
}
/// <summary>
/// Attempt to find STVDI by LW_DATE field
/// </summary>
/// <param name="LW_DATE">LW_DATE value used to find STVDI</param>
/// <returns>List of related STVDI entities, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<STVDI> TryFindByLW_DATE(DateTime? LW_DATE)
{
IReadOnlyList<STVDI> value;
if (Index_LW_DATE.Value.TryGetValue(LW_DATE, out value))
{
return value;
}
else
{
return null;
}
}
/// <summary>
/// Find STVDI by ORIGINAL_SCHOOL field
/// </summary>
/// <param name="ORIGINAL_SCHOOL">ORIGINAL_SCHOOL value used to find STVDI</param>
/// <returns>List of related STVDI entities</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<STVDI> FindByORIGINAL_SCHOOL(string ORIGINAL_SCHOOL)
{
return Index_ORIGINAL_SCHOOL.Value[ORIGINAL_SCHOOL];
}
/// <summary>
/// Attempt to find STVDI by ORIGINAL_SCHOOL field
/// </summary>
/// <param name="ORIGINAL_SCHOOL">ORIGINAL_SCHOOL value used to find STVDI</param>
/// <param name="Value">List of related STVDI entities</param>
/// <returns>True if the list of related STVDI entities is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByORIGINAL_SCHOOL(string ORIGINAL_SCHOOL, out IReadOnlyList<STVDI> Value)
{
return Index_ORIGINAL_SCHOOL.Value.TryGetValue(ORIGINAL_SCHOOL, out Value);
}
/// <summary>
/// Attempt to find STVDI by ORIGINAL_SCHOOL field
/// </summary>
/// <param name="ORIGINAL_SCHOOL">ORIGINAL_SCHOOL value used to find STVDI</param>
/// <returns>List of related STVDI entities, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<STVDI> TryFindByORIGINAL_SCHOOL(string ORIGINAL_SCHOOL)
{
IReadOnlyList<STVDI> value;
if (Index_ORIGINAL_SCHOOL.Value.TryGetValue(ORIGINAL_SCHOOL, out value))
{
return value;
}
else
{
return null;
}
}
/// <summary>
/// Find STVDI by SKEY field
/// </summary>
/// <param name="SKEY">SKEY value used to find STVDI</param>
/// <returns>List of related STVDI entities</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<STVDI> FindBySKEY(string SKEY)
{
return Index_SKEY.Value[SKEY];
}
/// <summary>
/// Attempt to find STVDI by SKEY field
/// </summary>
/// <param name="SKEY">SKEY value used to find STVDI</param>
/// <param name="Value">List of related STVDI entities</param>
/// <returns>True if the list of related STVDI entities is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindBySKEY(string SKEY, out IReadOnlyList<STVDI> Value)
{
return Index_SKEY.Value.TryGetValue(SKEY, out Value);
}
/// <summary>
/// Attempt to find STVDI by SKEY field
/// </summary>
/// <param name="SKEY">SKEY value used to find STVDI</param>
/// <returns>List of related STVDI entities, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<STVDI> TryFindBySKEY(string SKEY)
{
IReadOnlyList<STVDI> value;
if (Index_SKEY.Value.TryGetValue(SKEY, out value))
{
return value;
}
else
{
return null;
}
}
/// <summary>
/// Find STVDI by SKEY, VDIMENSION, VDOMAIN, YEAR_SEMESTER and SCORE fields
/// </summary>
/// <param name="SKEY">SKEY value used to find STVDI</param>
/// <param name="VDIMENSION">VDIMENSION value used to find STVDI</param>
/// <param name="VDOMAIN">VDOMAIN value used to find STVDI</param>
/// <param name="YEAR_SEMESTER">YEAR_SEMESTER value used to find STVDI</param>
/// <param name="SCORE">SCORE value used to find STVDI</param>
/// <returns>List of related STVDI entities</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<STVDI> FindBySKEY_VDIMENSION_VDOMAIN_YEAR_SEMESTER_SCORE(string SKEY, string VDIMENSION, string VDOMAIN, string YEAR_SEMESTER, string SCORE)
{
return Index_SKEY_VDIMENSION_VDOMAIN_YEAR_SEMESTER_SCORE.Value[Tuple.Create(SKEY, VDIMENSION, VDOMAIN, YEAR_SEMESTER, SCORE)];
}
/// <summary>
/// Attempt to find STVDI by SKEY, VDIMENSION, VDOMAIN, YEAR_SEMESTER and SCORE fields
/// </summary>
/// <param name="SKEY">SKEY value used to find STVDI</param>
/// <param name="VDIMENSION">VDIMENSION value used to find STVDI</param>
/// <param name="VDOMAIN">VDOMAIN value used to find STVDI</param>
/// <param name="YEAR_SEMESTER">YEAR_SEMESTER value used to find STVDI</param>
/// <param name="SCORE">SCORE value used to find STVDI</param>
/// <param name="Value">List of related STVDI entities</param>
/// <returns>True if the list of related STVDI entities is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindBySKEY_VDIMENSION_VDOMAIN_YEAR_SEMESTER_SCORE(string SKEY, string VDIMENSION, string VDOMAIN, string YEAR_SEMESTER, string SCORE, out IReadOnlyList<STVDI> Value)
{
return Index_SKEY_VDIMENSION_VDOMAIN_YEAR_SEMESTER_SCORE.Value.TryGetValue(Tuple.Create(SKEY, VDIMENSION, VDOMAIN, YEAR_SEMESTER, SCORE), out Value);
}
/// <summary>
/// Attempt to find STVDI by SKEY, VDIMENSION, VDOMAIN, YEAR_SEMESTER and SCORE fields
/// </summary>
/// <param name="SKEY">SKEY value used to find STVDI</param>
/// <param name="VDIMENSION">VDIMENSION value used to find STVDI</param>
/// <param name="VDOMAIN">VDOMAIN value used to find STVDI</param>
/// <param name="YEAR_SEMESTER">YEAR_SEMESTER value used to find STVDI</param>
/// <param name="SCORE">SCORE value used to find STVDI</param>
/// <returns>List of related STVDI entities, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<STVDI> TryFindBySKEY_VDIMENSION_VDOMAIN_YEAR_SEMESTER_SCORE(string SKEY, string VDIMENSION, string VDOMAIN, string YEAR_SEMESTER, string SCORE)
{
IReadOnlyList<STVDI> value;
if (Index_SKEY_VDIMENSION_VDOMAIN_YEAR_SEMESTER_SCORE.Value.TryGetValue(Tuple.Create(SKEY, VDIMENSION, VDOMAIN, YEAR_SEMESTER, SCORE), out value))
{
return value;
}
else
{
return null;
}
}
/// <summary>
/// Find STVDI by TID field
/// </summary>
/// <param name="TID">TID value used to find STVDI</param>
/// <returns>Related STVDI entity</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public STVDI FindByTID(int TID)
{
return Index_TID.Value[TID];
}
/// <summary>
/// Attempt to find STVDI by TID field
/// </summary>
/// <param name="TID">TID value used to find STVDI</param>
/// <param name="Value">Related STVDI entity</param>
/// <returns>True if the related STVDI entity is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByTID(int TID, out STVDI Value)
{
return Index_TID.Value.TryGetValue(TID, out Value);
}
/// <summary>
/// Attempt to find STVDI by TID field
/// </summary>
/// <param name="TID">TID value used to find STVDI</param>
/// <returns>Related STVDI entity, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public STVDI TryFindByTID(int TID)
{
STVDI value;
if (Index_TID.Value.TryGetValue(TID, out value))
{
return value;
}
else
{
return null;
}
}
/// <summary>
/// Find STVDI by VDIMENSION field
/// </summary>
/// <param name="VDIMENSION">VDIMENSION value used to find STVDI</param>
/// <returns>List of related STVDI entities</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<STVDI> FindByVDIMENSION(string VDIMENSION)
{
return Index_VDIMENSION.Value[VDIMENSION];
}
/// <summary>
/// Attempt to find STVDI by VDIMENSION field
/// </summary>
/// <param name="VDIMENSION">VDIMENSION value used to find STVDI</param>
/// <param name="Value">List of related STVDI entities</param>
/// <returns>True if the list of related STVDI entities is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByVDIMENSION(string VDIMENSION, out IReadOnlyList<STVDI> Value)
{
return Index_VDIMENSION.Value.TryGetValue(VDIMENSION, out Value);
}
/// <summary>
/// Attempt to find STVDI by VDIMENSION field
/// </summary>
/// <param name="VDIMENSION">VDIMENSION value used to find STVDI</param>
/// <returns>List of related STVDI entities, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<STVDI> TryFindByVDIMENSION(string VDIMENSION)
{
IReadOnlyList<STVDI> value;
if (Index_VDIMENSION.Value.TryGetValue(VDIMENSION, out value))
{
return value;
}
else
{
return null;
}
}
/// <summary>
/// Find STVDI by VDOMAIN field
/// </summary>
/// <param name="VDOMAIN">VDOMAIN value used to find STVDI</param>
/// <returns>List of related STVDI entities</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<STVDI> FindByVDOMAIN(string VDOMAIN)
{
return Index_VDOMAIN.Value[VDOMAIN];
}
/// <summary>
/// Attempt to find STVDI by VDOMAIN field
/// </summary>
/// <param name="VDOMAIN">VDOMAIN value used to find STVDI</param>
/// <param name="Value">List of related STVDI entities</param>
/// <returns>True if the list of related STVDI entities is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByVDOMAIN(string VDOMAIN, out IReadOnlyList<STVDI> Value)
{
return Index_VDOMAIN.Value.TryGetValue(VDOMAIN, out Value);
}
/// <summary>
/// Attempt to find STVDI by VDOMAIN field
/// </summary>
/// <param name="VDOMAIN">VDOMAIN value used to find STVDI</param>
/// <returns>List of related STVDI entities, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<STVDI> TryFindByVDOMAIN(string VDOMAIN)
{
IReadOnlyList<STVDI> value;
if (Index_VDOMAIN.Value.TryGetValue(VDOMAIN, out value))
{
return value;
}
else
{
return null;
}
}
#endregion
#region SQL Integration
/// <summary>
/// Returns a <see cref="SqlCommand"/> which checks for the existence of a STVDI table, and if not found, creates the table and associated indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[STVDI]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[STVDI](
[TID] int IDENTITY NOT NULL,
[SKEY] varchar(10) NOT NULL,
[SCHOOL_YEAR] varchar(4) NULL,
[CAMPUS] int NULL,
[YEAR_SEMESTER] varchar(6) NULL,
[VDOMAIN] varchar(10) NULL,
[VDIMENSION] varchar(10) NULL,
[SCORE] varchar(6) NULL,
[ORIGINAL_SCHOOL] varchar(8) NULL,
[LW_DATE] datetime NULL,
[LW_TIME] smallint NULL,
[LW_USER] varchar(128) NULL,
CONSTRAINT [STVDI_Index_TID] PRIMARY KEY NONCLUSTERED (
[TID] ASC
)
);
CREATE NONCLUSTERED INDEX [STVDI_Index_CAMPUS] ON [dbo].[STVDI]
(
[CAMPUS] ASC
);
CREATE NONCLUSTERED INDEX [STVDI_Index_LW_DATE] ON [dbo].[STVDI]
(
[LW_DATE] ASC
);
CREATE NONCLUSTERED INDEX [STVDI_Index_ORIGINAL_SCHOOL] ON [dbo].[STVDI]
(
[ORIGINAL_SCHOOL] ASC
);
CREATE CLUSTERED INDEX [STVDI_Index_SKEY] ON [dbo].[STVDI]
(
[SKEY] ASC
);
CREATE NONCLUSTERED INDEX [STVDI_Index_SKEY_VDIMENSION_VDOMAIN_YEAR_SEMESTER_SCORE] ON [dbo].[STVDI]
(
[SKEY] ASC,
[VDIMENSION] ASC,
[VDOMAIN] ASC,
[YEAR_SEMESTER] ASC,
[SCORE] ASC
);
CREATE NONCLUSTERED INDEX [STVDI_Index_VDIMENSION] ON [dbo].[STVDI]
(
[VDIMENSION] ASC
);
CREATE NONCLUSTERED INDEX [STVDI_Index_VDOMAIN] ON [dbo].[STVDI]
(
[VDOMAIN] ASC
);
END");
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which disables all non-clustered table indexes.
/// Typically called before <see cref="SqlBulkCopy"/> to improve performance.
/// <see cref="GetSqlRebuildIndexesCommand(SqlConnection)"/> should be called to rebuild and enable indexes after performance sensitive work is completed.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>A <see cref="SqlCommand"/> which (when executed) will disable all non-clustered table indexes</returns>
public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STVDI]') AND name = N'STVDI_Index_CAMPUS')
ALTER INDEX [STVDI_Index_CAMPUS] ON [dbo].[STVDI] DISABLE;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STVDI]') AND name = N'STVDI_Index_LW_DATE')
ALTER INDEX [STVDI_Index_LW_DATE] ON [dbo].[STVDI] DISABLE;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STVDI]') AND name = N'STVDI_Index_ORIGINAL_SCHOOL')
ALTER INDEX [STVDI_Index_ORIGINAL_SCHOOL] ON [dbo].[STVDI] DISABLE;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STVDI]') AND name = N'STVDI_Index_SKEY_VDIMENSION_VDOMAIN_YEAR_SEMESTER_SCORE')
ALTER INDEX [STVDI_Index_SKEY_VDIMENSION_VDOMAIN_YEAR_SEMESTER_SCORE] ON [dbo].[STVDI] DISABLE;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STVDI]') AND name = N'STVDI_Index_TID')
ALTER INDEX [STVDI_Index_TID] ON [dbo].[STVDI] DISABLE;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STVDI]') AND name = N'STVDI_Index_VDIMENSION')
ALTER INDEX [STVDI_Index_VDIMENSION] ON [dbo].[STVDI] DISABLE;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STVDI]') AND name = N'STVDI_Index_VDOMAIN')
ALTER INDEX [STVDI_Index_VDOMAIN] ON [dbo].[STVDI] DISABLE;
");
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which rebuilds and enables all non-clustered table indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>A <see cref="SqlCommand"/> which (when executed) will rebuild and enable all non-clustered table indexes</returns>
public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STVDI]') AND name = N'STVDI_Index_CAMPUS')
ALTER INDEX [STVDI_Index_CAMPUS] ON [dbo].[STVDI] REBUILD PARTITION = ALL;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STVDI]') AND name = N'STVDI_Index_LW_DATE')
ALTER INDEX [STVDI_Index_LW_DATE] ON [dbo].[STVDI] REBUILD PARTITION = ALL;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STVDI]') AND name = N'STVDI_Index_ORIGINAL_SCHOOL')
ALTER INDEX [STVDI_Index_ORIGINAL_SCHOOL] ON [dbo].[STVDI] REBUILD PARTITION = ALL;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STVDI]') AND name = N'STVDI_Index_SKEY_VDIMENSION_VDOMAIN_YEAR_SEMESTER_SCORE')
ALTER INDEX [STVDI_Index_SKEY_VDIMENSION_VDOMAIN_YEAR_SEMESTER_SCORE] ON [dbo].[STVDI] REBUILD PARTITION = ALL;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STVDI]') AND name = N'STVDI_Index_TID')
ALTER INDEX [STVDI_Index_TID] ON [dbo].[STVDI] REBUILD PARTITION = ALL;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STVDI]') AND name = N'STVDI_Index_VDIMENSION')
ALTER INDEX [STVDI_Index_VDIMENSION] ON [dbo].[STVDI] REBUILD PARTITION = ALL;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STVDI]') AND name = N'STVDI_Index_VDOMAIN')
ALTER INDEX [STVDI_Index_VDOMAIN] ON [dbo].[STVDI] REBUILD PARTITION = ALL;
");
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which deletes the <see cref="STVDI"/> entities passed
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <param name="Entities">The <see cref="STVDI"/> entities to be deleted</param>
public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<STVDI> Entities)
{
SqlCommand command = new SqlCommand();
int parameterIndex = 0;
StringBuilder builder = new StringBuilder();
List<int> Index_TID = new List<int>();
foreach (var entity in Entities)
{
Index_TID.Add(entity.TID);
}
builder.AppendLine("DELETE [dbo].[STVDI] WHERE");
// Index_TID
builder.Append("[TID] IN (");
for (int index = 0; index < Index_TID.Count; index++)
{
if (index != 0)
builder.Append(", ");
// TID
var parameterTID = $"@p{parameterIndex++}";
builder.Append(parameterTID);
command.Parameters.Add(parameterTID, SqlDbType.Int).Value = Index_TID[index];
}
builder.Append(");");
command.Connection = SqlConnection;
command.CommandText = builder.ToString();
return command;
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the STVDI data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the STVDI data set</returns>
public override EduHubDataSetDataReader<STVDI> GetDataSetDataReader()
{
return new STVDIDataReader(Load());
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the STVDI data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the STVDI data set</returns>
public override EduHubDataSetDataReader<STVDI> GetDataSetDataReader(List<STVDI> Entities)
{
return new STVDIDataReader(new EduHubDataSetLoadedReader<STVDI>(this, Entities));
}
// Modest implementation to primarily support SqlBulkCopy
private class STVDIDataReader : EduHubDataSetDataReader<STVDI>
{
public STVDIDataReader(IEduHubDataSetReader<STVDI> Reader)
: base (Reader)
{
}
public override int FieldCount { get { return 12; } }
public override object GetValue(int i)
{
switch (i)
{
case 0: // TID
return Current.TID;
case 1: // SKEY
return Current.SKEY;
case 2: // SCHOOL_YEAR
return Current.SCHOOL_YEAR;
case 3: // CAMPUS
return Current.CAMPUS;
case 4: // YEAR_SEMESTER
return Current.YEAR_SEMESTER;
case 5: // VDOMAIN
return Current.VDOMAIN;
case 6: // VDIMENSION
return Current.VDIMENSION;
case 7: // SCORE
return Current.SCORE;
case 8: // ORIGINAL_SCHOOL
return Current.ORIGINAL_SCHOOL;
case 9: // LW_DATE
return Current.LW_DATE;
case 10: // LW_TIME
return Current.LW_TIME;
case 11: // LW_USER
return Current.LW_USER;
default:
throw new ArgumentOutOfRangeException(nameof(i));
}
}
public override bool IsDBNull(int i)
{
switch (i)
{
case 2: // SCHOOL_YEAR
return Current.SCHOOL_YEAR == null;
case 3: // CAMPUS
return Current.CAMPUS == null;
case 4: // YEAR_SEMESTER
return Current.YEAR_SEMESTER == null;
case 5: // VDOMAIN
return Current.VDOMAIN == null;
case 6: // VDIMENSION
return Current.VDIMENSION == null;
case 7: // SCORE
return Current.SCORE == null;
case 8: // ORIGINAL_SCHOOL
return Current.ORIGINAL_SCHOOL == null;
case 9: // LW_DATE
return Current.LW_DATE == null;
case 10: // LW_TIME
return Current.LW_TIME == null;
case 11: // LW_USER
return Current.LW_USER == null;
default:
return false;
}
}
public override string GetName(int ordinal)
{
switch (ordinal)
{
case 0: // TID
return "TID";
case 1: // SKEY
return "SKEY";
case 2: // SCHOOL_YEAR
return "SCHOOL_YEAR";
case 3: // CAMPUS
return "CAMPUS";
case 4: // YEAR_SEMESTER
return "YEAR_SEMESTER";
case 5: // VDOMAIN
return "VDOMAIN";
case 6: // VDIMENSION
return "VDIMENSION";
case 7: // SCORE
return "SCORE";
case 8: // ORIGINAL_SCHOOL
return "ORIGINAL_SCHOOL";
case 9: // LW_DATE
return "LW_DATE";
case 10: // LW_TIME
return "LW_TIME";
case 11: // LW_USER
return "LW_USER";
default:
throw new ArgumentOutOfRangeException(nameof(ordinal));
}
}
public override int GetOrdinal(string name)
{
switch (name)
{
case "TID":
return 0;
case "SKEY":
return 1;
case "SCHOOL_YEAR":
return 2;
case "CAMPUS":
return 3;
case "YEAR_SEMESTER":
return 4;
case "VDOMAIN":
return 5;
case "VDIMENSION":
return 6;
case "SCORE":
return 7;
case "ORIGINAL_SCHOOL":
return 8;
case "LW_DATE":
return 9;
case "LW_TIME":
return 10;
case "LW_USER":
return 11;
default:
throw new ArgumentOutOfRangeException(nameof(name));
}
}
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Diagnostics;
using System.Linq;
using System.Reflection.Metadata.Ecma335;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.CSharp.UnitTests;
using Microsoft.VisualStudio.Debugger.Evaluation;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator
{
public class InstructionDecoderTests : ExpressionCompilerTestBase
{
[Fact]
void GetNameGenerics()
{
var source = @"
using System;
class Class1<T>
{
void M1<U>(Action<Int32> a)
{
}
void M2<U>(Action<T> a)
{
}
void M3<U>(Action<U> a)
{
}
}";
Assert.Equal(
"Class1<T>.M1<U>(System.Action<int> a)",
GetName(source, "Class1.M1", DkmVariableInfoFlags.Names | DkmVariableInfoFlags.Types));
Assert.Equal(
"Class1<T>.M2<U>(System.Action<T> a)",
GetName(source, "Class1.M2", DkmVariableInfoFlags.Names | DkmVariableInfoFlags.Types));
Assert.Equal(
"Class1<T>.M3<U>(System.Action<U> a)",
GetName(source, "Class1.M3", DkmVariableInfoFlags.Names | DkmVariableInfoFlags.Types));
Assert.Equal(
"Class1<string>.M1<decimal>(System.Action<int> a)",
GetName(source, "Class1.M1", DkmVariableInfoFlags.Names | DkmVariableInfoFlags.Types, new[] { typeof(string), typeof(decimal) }));
Assert.Equal(
"Class1<string>.M2<decimal>(System.Action<string> a)",
GetName(source, "Class1.M2", DkmVariableInfoFlags.Names | DkmVariableInfoFlags.Types, new[] { typeof(string), typeof(decimal) }));
Assert.Equal(
"Class1<string>.M3<decimal>(System.Action<decimal> a)",
GetName(source, "Class1.M3", DkmVariableInfoFlags.Names | DkmVariableInfoFlags.Types, new[] { typeof(string), typeof(decimal) }));
}
[Fact]
void GetNameNullTypeArguments()
{
var source = @"
using System;
class Class1<T>
{
void M<U>(Action<U> a)
{
}
}";
Assert.Equal(
"Class1<T>.M<U>(System.Action<U> a)",
GetName(source, "Class1.M", DkmVariableInfoFlags.Names | DkmVariableInfoFlags.Types, typeArguments: new Type[] { null, null }));
Assert.Equal(
"Class1<T>.M<U>(System.Action<U> a)",
GetName(source, "Class1.M", DkmVariableInfoFlags.Names | DkmVariableInfoFlags.Types, typeArguments: new[] { typeof(string), null }));
Assert.Equal(
"Class1<T>.M<U>(System.Action<U> a)",
GetName(source, "Class1.M", DkmVariableInfoFlags.Names | DkmVariableInfoFlags.Types, typeArguments: new[] { null, typeof(decimal) }));
}
[Fact]
void GetNameGenericArgumentTypeNotInReferences()
{
var source = @"
class Class1
{
}";
var serializedTypeArgumentName = "Class1, " + nameof(InstructionDecoderTests) + ", Culture=neutral, PublicKeyToken=null";
Assert.Equal(
"System.Collections.Generic.Comparer<Class1>.Create(System.Comparison<Class1> comparison)",
GetName(source, "System.Collections.Generic.Comparer.Create", DkmVariableInfoFlags.Names | DkmVariableInfoFlags.Types, typeArguments: new[] { serializedTypeArgumentName }));
}
[Fact, WorkItem(1107977)]
void GetNameGenericAsync()
{
var source = @"
using System.Threading.Tasks;
class C
{
static async Task<T> M<T>(T x)
{
await Task.Yield();
return x;
}
}";
Assert.Equal(
"C.M<System.Exception>(System.Exception x)",
GetName(source, "C.<M>d__0.MoveNext", DkmVariableInfoFlags.Names | DkmVariableInfoFlags.Types, new[] { typeof(Exception) }));
}
[Fact]
void GetNameLambda()
{
var source = @"
using System;
class C
{
void M()
{
Func<int> f = () => 3;
}
}";
Assert.Equal(
"C.M.AnonymousMethod__0_0()",
GetName(source, "C.<>c.<M>b__0_0", DkmVariableInfoFlags.Names | DkmVariableInfoFlags.Types));
}
[Fact]
void GetNameGenericLambda()
{
var source = @"
using System;
class C<T>
{
void M<U>() where U : T
{
Func<U, T> f = (U u) => u;
}
}";
Assert.Equal(
"C<System.Exception>.M.AnonymousMethod__0_0(System.ArgumentException u)",
GetName(source, "C.<>c__0.<M>b__0_0", DkmVariableInfoFlags.Names | DkmVariableInfoFlags.Types, new[] { typeof(Exception), typeof(ArgumentException) }));
}
[Fact]
void GetNameProperties()
{
var source = @"
class C
{
int P { get; set; }
int this[object x]
{
get { return 42; }
set { }
}
}";
Assert.Equal(
"C.P.get()",
GetName(source, "C.get_P", DkmVariableInfoFlags.Names | DkmVariableInfoFlags.Types));
Assert.Equal(
"C.P.set(int value)",
GetName(source, "C.set_P", DkmVariableInfoFlags.Names | DkmVariableInfoFlags.Types));
Assert.Equal(
"C.this[object].get(object x)",
GetName(source, "C.get_Item", DkmVariableInfoFlags.Names | DkmVariableInfoFlags.Types));
Assert.Equal(
"C.this[object].set(object x, int value)",
GetName(source, "C.set_Item", DkmVariableInfoFlags.Names | DkmVariableInfoFlags.Types));
}
[Fact]
void GetNameExplicitInterfaceImplementation()
{
var source = @"
using System;
class C : IDisposable
{
void IDisposable.Dispose() { }
}";
Assert.Equal(
"C.System.IDisposable.Dispose()",
GetName(source, "C.System.IDisposable.Dispose", DkmVariableInfoFlags.Names | DkmVariableInfoFlags.Types));
}
[Fact]
void GetNameExtensionMethod()
{
var source = @"
static class Extensions
{
static void M(this string @this) { }
}";
Assert.Equal(
"Extensions.M(string this)",
GetName(source, "Extensions.M", DkmVariableInfoFlags.Names | DkmVariableInfoFlags.Types));
}
[Fact]
void GetNameArgumentFlagsNone()
{
var source = @"
static class C
{
static void M1() { }
static void M2(int x, int y) { }
}";
Assert.Equal(
"C.M1",
GetName(source, "C.M1", DkmVariableInfoFlags.None));
Assert.Equal(
"C.M2",
GetName(source, "C.M2", DkmVariableInfoFlags.None));
}
[Fact, WorkItem(1107978)]
void GetNameRefAndOutParameters()
{
var source = @"
class C
{
static void M(ref int x, out int y)
{
y = x;
}
}";
Assert.Equal(
"C.M",
GetName(source, "C.M", DkmVariableInfoFlags.None));
Assert.Equal(
"C.M(1, 2)",
GetName(source, "C.M", DkmVariableInfoFlags.None, argumentValues: new[] { "1", "2" }));
Assert.Equal(
"C.M(ref int, out int)",
GetName(source, "C.M", DkmVariableInfoFlags.Types));
Assert.Equal(
"C.M(x, y)",
GetName(source, "C.M", DkmVariableInfoFlags.Names));
Assert.Equal(
"C.M(ref int x, out int y)",
GetName(source, "C.M", DkmVariableInfoFlags.Types | DkmVariableInfoFlags.Names));
}
[Fact]
void GetNameParamsParameters()
{
var source = @"
class C
{
static void M(params int[] x)
{
}
}";
Assert.Equal(
"C.M(int[] x)",
GetName(source, "C.M", DkmVariableInfoFlags.Types | DkmVariableInfoFlags.Names));
}
[Fact]
void GetReturnTypeNamePrimitive()
{
var source = @"
static class C
{
static uint M1() { return 42; }
}";
Assert.Equal("uint", GetReturnTypeName(source, "C.M1"));
}
[Fact]
void GetReturnTypeNameNested()
{
var source = @"
static class C
{
static N.D.E M1() { return default(N.D.E); }
}
namespace N
{
class D
{
internal struct E
{
}
}
}";
Assert.Equal("N.D.E", GetReturnTypeName(source, "C.M1"));
}
[Fact]
void GetReturnTypeNameGenericOfPrimitive()
{
var source = @"
using System;
class C
{
Action<Int32> M1() { return null; }
}";
Assert.Equal("System.Action<int>", GetReturnTypeName(source, "C.M1"));
}
[Fact]
void GetReturnTypeNameGenericOfNested()
{
var source = @"
using System;
class C
{
Action<D> M1() { return null; }
class D
{
}
}";
Assert.Equal("System.Action<C.D>", GetReturnTypeName(source, "C.M1"));
}
[Fact]
void GetReturnTypeNameGenericOfGeneric()
{
var source = @"
using System;
class C
{
Action<Func<T>> M1<T>() { return null; }
}";
Assert.Equal("System.Action<System.Func<object>>", GetReturnTypeName(source, "C.M1", new[] { typeof(object) }));
}
private string GetName(string source, string methodName, DkmVariableInfoFlags argumentFlags, Type[] typeArguments = null, string[] argumentValues = null)
{
var serializedTypeArgumentNames = typeArguments?.Select(t => t?.AssemblyQualifiedName).ToArray();
return GetName(source, methodName, argumentFlags, serializedTypeArgumentNames, argumentValues);
}
private string GetName(string source, string methodName, DkmVariableInfoFlags argumentFlags, string[] typeArguments, string[] argumentValues = null)
{
Debug.Assert((argumentFlags & (DkmVariableInfoFlags.Names | DkmVariableInfoFlags.Types)) == argumentFlags,
"Unexpected argumentFlags", "argumentFlags = {0}", argumentFlags);
var instructionDecoder = CSharpInstructionDecoder.Instance;
var method = GetConstructedMethod(source, methodName, typeArguments, instructionDecoder);
var includeParameterTypes = argumentFlags.Includes(DkmVariableInfoFlags.Types);
var includeParameterNames = argumentFlags.Includes(DkmVariableInfoFlags.Names);
ArrayBuilder<string> builder = null;
if (argumentValues != null)
{
Assert.InRange(argumentValues.Length, 1, int.MaxValue);
builder = ArrayBuilder<string>.GetInstance();
builder.AddRange(argumentValues);
}
var name = instructionDecoder.GetName(method, includeParameterTypes, includeParameterNames, builder);
if (builder != null)
{
builder.Free();
}
return name;
}
private string GetReturnTypeName(string source, string methodName, Type[] typeArguments = null)
{
var instructionDecoder = CSharpInstructionDecoder.Instance;
var serializedTypeArgumentNames = typeArguments?.Select(t => (t != null) ? t.AssemblyQualifiedName : null).ToArray();
var method = GetConstructedMethod(source, methodName, serializedTypeArgumentNames, instructionDecoder);
return instructionDecoder.GetReturnTypeName(method);
}
private MethodSymbol GetConstructedMethod(string source, string methodName, string[] serializedTypeArgumentNames, CSharpInstructionDecoder instructionDecoder)
{
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll, assemblyName: nameof(InstructionDecoderTests));
var runtime = CreateRuntimeInstance(compilation);
var moduleInstances = runtime.Modules;
var blocks = moduleInstances.SelectAsArray(m => m.MetadataBlock);
compilation = blocks.ToCompilation();
var frame = (PEMethodSymbol)GetMethodOrTypeBySignature(compilation, methodName);
// Once we have the method token, we want to look up the method (again)
// using the same helper as the product code. This helper will also map
// async/iterator "MoveNext" methods to the original source method.
MethodSymbol method = compilation.GetSourceMethod(
((PEModuleSymbol)frame.ContainingModule).Module.GetModuleVersionIdOrThrow(),
MetadataTokens.GetToken(frame.Handle));
if (serializedTypeArgumentNames != null)
{
Assert.NotEmpty(serializedTypeArgumentNames);
var typeParameters = instructionDecoder.GetAllTypeParameters(method);
Assert.NotEmpty(typeParameters);
var typeNameDecoder = new EETypeNameDecoder(compilation, (PEModuleSymbol)method.ContainingModule);
// Use the same helper method as the FrameDecoder to get the TypeSymbols for the
// generic type arguments (rather than using EETypeNameDecoder directly).
var typeArguments = instructionDecoder.GetTypeSymbols(compilation, method, serializedTypeArgumentNames);
if (!typeArguments.IsEmpty)
{
method = instructionDecoder.ConstructMethod(method, typeParameters, typeArguments);
}
}
return method;
}
}
}
| |
// 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.
// --------------------------------------------------------------------------------------
//
// A class that provides a simple, lightweight implementation of lazy initialization,
// obviating the need for a developer to implement a custom, thread-safe lazy initialization
// solution.
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
#pragma warning disable 0420
using System.Diagnostics;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Threading;
namespace System
{
internal enum LazyState
{
NoneViaConstructor = 0,
NoneViaFactory = 1,
NoneException = 2,
PublicationOnlyViaConstructor = 3,
PublicationOnlyViaFactory = 4,
PublicationOnlyWait = 5,
PublicationOnlyException = 6,
ExecutionAndPublicationViaConstructor = 7,
ExecutionAndPublicationViaFactory = 8,
ExecutionAndPublicationException = 9,
}
/// <summary>
/// LazyHelper serves multiples purposes
/// - minimizing code size of Lazy<T> by implementing as much of the code that is not generic
/// this reduces generic code bloat, making faster class initialization
/// - contains singleton objects that are used to handle threading primitives for PublicationOnly mode
/// - allows for instantiation for ExecutionAndPublication so as to create an object for locking on
/// - holds exception information.
/// </summary>
internal class LazyHelper
{
internal readonly static LazyHelper NoneViaConstructor = new LazyHelper(LazyState.NoneViaConstructor);
internal readonly static LazyHelper NoneViaFactory = new LazyHelper(LazyState.NoneViaFactory);
internal readonly static LazyHelper PublicationOnlyViaConstructor = new LazyHelper(LazyState.PublicationOnlyViaConstructor);
internal readonly static LazyHelper PublicationOnlyViaFactory = new LazyHelper(LazyState.PublicationOnlyViaFactory);
internal readonly static LazyHelper PublicationOnlyWaitForOtherThreadToPublish = new LazyHelper(LazyState.PublicationOnlyWait);
internal LazyState State { get; }
private readonly ExceptionDispatchInfo _exceptionDispatch;
/// <summary>
/// Constructor that defines the state
/// </summary>
internal LazyHelper(LazyState state)
{
State = state;
}
/// <summary>
/// Constructor used for exceptions
/// </summary>
internal LazyHelper(LazyThreadSafetyMode mode, Exception exception)
{
switch(mode)
{
case LazyThreadSafetyMode.ExecutionAndPublication:
State = LazyState.ExecutionAndPublicationException;
break;
case LazyThreadSafetyMode.None:
State = LazyState.NoneException;
break;
case LazyThreadSafetyMode.PublicationOnly:
State = LazyState.PublicationOnlyException;
break;
default:
Debug.Assert(false, "internal constructor, this should never occur");
break;
}
_exceptionDispatch = ExceptionDispatchInfo.Capture(exception);
}
internal void ThrowException()
{
Debug.Assert(_exceptionDispatch != null, "execution path is invalid");
_exceptionDispatch.Throw();
}
private LazyThreadSafetyMode GetMode()
{
switch (State)
{
case LazyState.NoneViaConstructor:
case LazyState.NoneViaFactory:
case LazyState.NoneException:
return LazyThreadSafetyMode.None;
case LazyState.PublicationOnlyViaConstructor:
case LazyState.PublicationOnlyViaFactory:
case LazyState.PublicationOnlyWait:
case LazyState.PublicationOnlyException:
return LazyThreadSafetyMode.PublicationOnly;
case LazyState.ExecutionAndPublicationViaConstructor:
case LazyState.ExecutionAndPublicationViaFactory:
case LazyState.ExecutionAndPublicationException:
return LazyThreadSafetyMode.ExecutionAndPublication;
default:
Debug.Assert(false, "Invalid logic; State should always have a valid value");
return default(LazyThreadSafetyMode);
}
}
internal static LazyThreadSafetyMode? GetMode(LazyHelper state)
{
if (state == null)
return null; // we don't know the mode anymore
return state.GetMode();
}
internal static bool GetIsValueFaulted(LazyHelper state) => state?._exceptionDispatch != null;
internal static LazyHelper Create(LazyThreadSafetyMode mode, bool useDefaultConstructor)
{
switch (mode)
{
case LazyThreadSafetyMode.None:
return useDefaultConstructor ? NoneViaConstructor : NoneViaFactory;
case LazyThreadSafetyMode.PublicationOnly:
return useDefaultConstructor ? PublicationOnlyViaConstructor : PublicationOnlyViaFactory;
case LazyThreadSafetyMode.ExecutionAndPublication:
// we need to create an object for ExecutionAndPublication because we use Monitor-based locking
var state = useDefaultConstructor ? LazyState.ExecutionAndPublicationViaConstructor : LazyState.ExecutionAndPublicationViaFactory;
return new LazyHelper(state);
default:
throw new ArgumentOutOfRangeException(nameof(mode), SR.Lazy_ctor_ModeInvalid);
}
}
internal static object CreateViaDefaultConstructor(Type type)
{
try
{
return Activator.CreateInstance(type);
}
catch (MissingMethodException)
{
throw new MissingMemberException(SR.Lazy_CreateValue_NoParameterlessCtorForT);
}
}
internal static LazyThreadSafetyMode GetModeFromIsThreadSafe(bool isThreadSafe)
{
return isThreadSafe ? LazyThreadSafetyMode.ExecutionAndPublication : LazyThreadSafetyMode.None;
}
}
/// <summary>
/// Provides support for lazy initialization.
/// </summary>
/// <typeparam name="T">Specifies the type of element being lazily initialized.</typeparam>
/// <remarks>
/// <para>
/// By default, all public and protected members of <see cref="Lazy{T}"/> are thread-safe and may be used
/// concurrently from multiple threads. These thread-safety guarantees may be removed optionally and per instance
/// using parameters to the type's constructors.
/// </para>
/// </remarks>
[Serializable]
[ComVisible(false)]
[DebuggerTypeProxy(typeof(System_LazyDebugView<>))]
[DebuggerDisplay("ThreadSafetyMode={Mode}, IsValueCreated={IsValueCreated}, IsValueFaulted={IsValueFaulted}, Value={ValueForDebugDisplay}")]
public class Lazy<T>
{
private static T CreateViaDefaultConstructor()
{
return (T)LazyHelper.CreateViaDefaultConstructor(typeof(T));
}
// _state, a volatile reference, is set to null after m_value has been set
[NonSerialized]
private volatile LazyHelper _state;
// we ensure that _factory when finished is set to null to allow garbage collector to clean up
// any referenced items
[NonSerialized]
private Func<T> _factory;
// m_value eventually stores the lazily created value. It is valid when _state = null.
private T _value;
/// <summary>
/// Initializes a new instance of the <see cref="T:System.Threading.Lazy{T}"/> class that
/// uses <typeparamref name="T"/>'s default constructor for lazy initialization.
/// </summary>
/// <remarks>
/// An instance created with this constructor may be used concurrently from multiple threads.
/// </remarks>
public Lazy()
: this(null, LazyThreadSafetyMode.ExecutionAndPublication, useDefaultConstructor:true)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="T:System.Threading.Lazy{T}"/> class that
/// uses a pre-initialized specified value.
/// </summary>
/// <remarks>
/// An instance created with this constructor should be usable by multiple threads
// concurrently.
/// </remarks>
public Lazy(T value)
{
_value = value;
}
/// <summary>
/// Initializes a new instance of the <see cref="T:System.Threading.Lazy{T}"/> class that uses a
/// specified initialization function.
/// </summary>
/// <param name="valueFactory">
/// The <see cref="T:System.Func{T}"/> invoked to produce the lazily-initialized value when it is
/// needed.
/// </param>
/// <exception cref="System.ArgumentNullException"><paramref name="valueFactory"/> is a null
/// reference (Nothing in Visual Basic).</exception>
/// <remarks>
/// An instance created with this constructor may be used concurrently from multiple threads.
/// </remarks>
public Lazy(Func<T> valueFactory)
: this(valueFactory, LazyThreadSafetyMode.ExecutionAndPublication, useDefaultConstructor:false)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="T:System.Threading.Lazy{T}"/>
/// class that uses <typeparamref name="T"/>'s default constructor and a specified thread-safety mode.
/// </summary>
/// <param name="isThreadSafe">true if this instance should be usable by multiple threads concurrently; false if the instance will only be used by one thread at a time.
/// </param>
public Lazy(bool isThreadSafe) :
this(null, LazyHelper.GetModeFromIsThreadSafe(isThreadSafe), useDefaultConstructor:true)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="T:System.Threading.Lazy{T}"/>
/// class that uses <typeparamref name="T"/>'s default constructor and a specified thread-safety mode.
/// </summary>
/// <param name="mode">The lazy thread-safety mode mode</param>
/// <exception cref="System.ArgumentOutOfRangeException"><paramref name="mode"/> mode contains an invalid valuee</exception>
public Lazy(LazyThreadSafetyMode mode) :
this(null, mode, useDefaultConstructor:true)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="T:System.Threading.Lazy{T}"/> class
/// that uses a specified initialization function and a specified thread-safety mode.
/// </summary>
/// <param name="valueFactory">
/// The <see cref="T:System.Func{T}"/> invoked to produce the lazily-initialized value when it is needed.
/// </param>
/// <param name="isThreadSafe">true if this instance should be usable by multiple threads concurrently; false if the instance will only be used by one thread at a time.
/// </param>
/// <exception cref="System.ArgumentNullException"><paramref name="valueFactory"/> is
/// a null reference (Nothing in Visual Basic).</exception>
public Lazy(Func<T> valueFactory, bool isThreadSafe) :
this(valueFactory, LazyHelper.GetModeFromIsThreadSafe(isThreadSafe), useDefaultConstructor:false)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="T:System.Threading.Lazy{T}"/> class
/// that uses a specified initialization function and a specified thread-safety mode.
/// </summary>
/// <param name="valueFactory">
/// The <see cref="T:System.Func{T}"/> invoked to produce the lazily-initialized value when it is needed.
/// </param>
/// <param name="mode">The lazy thread-safety mode.</param>
/// <exception cref="System.ArgumentNullException"><paramref name="valueFactory"/> is
/// a null reference (Nothing in Visual Basic).</exception>
/// <exception cref="System.ArgumentOutOfRangeException"><paramref name="mode"/> mode contains an invalid value.</exception>
public Lazy(Func<T> valueFactory, LazyThreadSafetyMode mode)
: this(valueFactory, mode, useDefaultConstructor:false)
{
}
private Lazy(Func<T> valueFactory, LazyThreadSafetyMode mode, bool useDefaultConstructor)
{
if (valueFactory == null && !useDefaultConstructor)
throw new ArgumentNullException(nameof(valueFactory));
_factory = valueFactory;
_state = LazyHelper.Create(mode, useDefaultConstructor);
}
private void ViaConstructor()
{
_value = CreateViaDefaultConstructor();
_state = null; // volatile write, must occur after setting _value
}
private void ViaFactory(LazyThreadSafetyMode mode)
{
try
{
Func<T> factory = _factory;
if (factory == null)
throw new InvalidOperationException(SR.Lazy_Value_RecursiveCallsToValue);
_factory = null;
_value = factory();
_state = null; // volatile write, must occur after setting _value
}
catch (Exception exception)
{
_state = new LazyHelper(mode, exception);
throw;
}
}
private void ExecutionAndPublication(LazyHelper executionAndPublication, bool useDefaultConstructor)
{
lock (executionAndPublication)
{
// it's possible for multiple calls to have piled up behind the lock, so we need to check
// to see if the ExecutionAndPublication object is still the current implementation.
if (ReferenceEquals(_state, executionAndPublication))
{
if (useDefaultConstructor)
{
ViaConstructor();
}
else
{
ViaFactory(LazyThreadSafetyMode.ExecutionAndPublication);
}
}
}
}
private void PublicationOnly(LazyHelper publicationOnly, T possibleValue)
{
LazyHelper previous = Interlocked.CompareExchange(ref _state, LazyHelper.PublicationOnlyWaitForOtherThreadToPublish, publicationOnly);
if (previous == publicationOnly)
{
_factory = null;
_value = possibleValue;
_state = null; // volatile write, must occur after setting _value
}
}
private void PublicationOnlyViaConstructor(LazyHelper initializer)
{
PublicationOnly(initializer, CreateViaDefaultConstructor());
}
private void PublicationOnlyViaFactory(LazyHelper initializer)
{
Func<T> factory = _factory;
if (factory == null)
{
PublicationOnlyWaitForOtherThreadToPublish();
}
else
{
PublicationOnly(initializer, factory());
}
}
private void PublicationOnlyWaitForOtherThreadToPublish()
{
var spinWait = new SpinWait();
while (!ReferenceEquals(_state, null))
{
// We get here when PublicationOnly temporarily sets _state to LazyHelper.PublicationOnlyWaitForOtherThreadToPublish.
// This temporary state should be quickly followed by _state being set to null.
spinWait.SpinOnce();
}
}
private T CreateValue()
{
// we have to create a copy of state here, and use the copy exclusively from here on in
// so as to ensure thread safety.
var state = _state;
if (state != null)
{
switch (state.State)
{
case LazyState.NoneViaConstructor:
ViaConstructor();
break;
case LazyState.NoneViaFactory:
ViaFactory(LazyThreadSafetyMode.None);
break;
case LazyState.PublicationOnlyViaConstructor:
PublicationOnlyViaConstructor(state);
break;
case LazyState.PublicationOnlyViaFactory:
PublicationOnlyViaFactory(state);
break;
case LazyState.PublicationOnlyWait:
PublicationOnlyWaitForOtherThreadToPublish();
break;
case LazyState.ExecutionAndPublicationViaConstructor:
ExecutionAndPublication(state, useDefaultConstructor:true);
break;
case LazyState.ExecutionAndPublicationViaFactory:
ExecutionAndPublication(state, useDefaultConstructor:false);
break;
default:
state.ThrowException();
break;
}
}
return Value;
}
/// <summary>Forces initialization during serialization.</summary>
/// <param name="context">The StreamingContext for the serialization operation.</param>
[OnSerializing]
private void OnSerializing(StreamingContext context)
{
// Force initialization
T dummy = Value;
}
/// <summary>Creates and returns a string representation of this instance.</summary>
/// <returns>The result of calling <see cref="System.Object.ToString"/> on the <see
/// cref="Value"/>.</returns>
/// <exception cref="T:System.NullReferenceException">
/// The <see cref="Value"/> is null.
/// </exception>
public override string ToString()
{
return IsValueCreated ? Value.ToString() : SR.Lazy_ToString_ValueNotCreated;
}
/// <summary>Gets the value of the Lazy<T> for debugging display purposes.</summary>
internal T ValueForDebugDisplay
{
get
{
if (!IsValueCreated)
{
return default(T);
}
return _value;
}
}
/// <summary>
/// Gets a value indicating whether this instance may be used concurrently from multiple threads.
/// </summary>
internal LazyThreadSafetyMode? Mode => LazyHelper.GetMode(_state);
/// <summary>
/// Gets whether the value creation is faulted or not
/// </summary>
internal bool IsValueFaulted => LazyHelper.GetIsValueFaulted(_state);
/// <summary>Gets a value indicating whether the <see cref="T:System.Lazy{T}"/> has been initialized.
/// </summary>
/// <value>true if the <see cref="T:System.Lazy{T}"/> instance has been initialized;
/// otherwise, false.</value>
/// <remarks>
/// The initialization of a <see cref="T:System.Lazy{T}"/> instance may result in either
/// a value being produced or an exception being thrown. If an exception goes unhandled during initialization,
/// <see cref="IsValueCreated"/> will return false.
/// </remarks>
public bool IsValueCreated => _state == null;
/// <summary>Gets the lazily initialized value of the current <see
/// cref="T:System.Threading.Lazy{T}"/>.</summary>
/// <value>The lazily initialized value of the current <see
/// cref="T:System.Threading.Lazy{T}"/>.</value>
/// <exception cref="T:System.MissingMemberException">
/// The <see cref="T:System.Threading.Lazy{T}"/> was initialized to use the default constructor
/// of the type being lazily initialized, and that type does not have a public, parameterless constructor.
/// </exception>
/// <exception cref="T:System.MemberAccessException">
/// The <see cref="T:System.Threading.Lazy{T}"/> was initialized to use the default constructor
/// of the type being lazily initialized, and permissions to access the constructor were missing.
/// </exception>
/// <exception cref="T:System.InvalidOperationException">
/// The <see cref="T:System.Threading.Lazy{T}"/> was constructed with the <see cref="T:System.Threading.LazyThreadSafetyMode.ExecutionAndPublication"/> or
/// <see cref="T:System.Threading.LazyThreadSafetyMode.None"/> and the initialization function attempted to access <see cref="Value"/> on this instance.
/// </exception>
/// <remarks>
/// If <see cref="IsValueCreated"/> is false, accessing <see cref="Value"/> will force initialization.
/// Please <see cref="System.Threading.LazyThreadSafetyMode"> for more information on how <see cref="T:System.Threading.Lazy{T}"/> will behave if an exception is thrown
/// from initialization delegate.
/// </remarks>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public T Value => _state == null ? _value : CreateValue();
}
/// <summary>A debugger view of the Lazy<T> to surface additional debugging properties and
/// to ensure that the Lazy<T> does not become initialized if it was not already.</summary>
internal sealed class System_LazyDebugView<T>
{
//The Lazy object being viewed.
private readonly Lazy<T> _lazy;
/// <summary>Constructs a new debugger view object for the provided Lazy object.</summary>
/// <param name="lazy">A Lazy object to browse in the debugger.</param>
public System_LazyDebugView(Lazy<T> lazy)
{
_lazy = lazy;
}
/// <summary>Returns whether the Lazy object is initialized or not.</summary>
public bool IsValueCreated
{
get { return _lazy.IsValueCreated; }
}
/// <summary>Returns the value of the Lazy object.</summary>
public T Value
{
get
{ return _lazy.ValueForDebugDisplay; }
}
/// <summary>Returns the execution mode of the Lazy object</summary>
public LazyThreadSafetyMode? Mode
{
get { return _lazy.Mode; }
}
/// <summary>Returns the execution mode of the Lazy object</summary>
public bool IsValueFaulted
{
get { return _lazy.IsValueFaulted; }
}
}
}
| |
namespace Nancy.Authentication.Forms
{
using System;
using Bootstrapper;
using Cookies;
using Cryptography;
using Helpers;
using Nancy.Extensions;
/// <summary>
/// Nancy forms authentication implementation
/// </summary>
public static class FormsAuthentication
{
private static string formsAuthenticationCookieName = "_ncfa";
// TODO - would prefer not to hold this here, but the redirect response needs it
private static FormsAuthenticationConfiguration currentConfiguration;
/// <summary>
/// Gets or sets the forms authentication cookie name
/// </summary>
public static string FormsAuthenticationCookieName
{
get
{
return formsAuthenticationCookieName;
}
set
{
formsAuthenticationCookieName = value;
}
}
/// <summary>
/// Enables forms authentication for the application
/// </summary>
/// <param name="pipelines">Pipelines to add handlers to (usually "this")</param>
/// <param name="configuration">Forms authentication configuration</param>
public static void Enable(IPipelines pipelines, FormsAuthenticationConfiguration configuration)
{
if (pipelines == null)
{
throw new ArgumentNullException("pipelines");
}
if (configuration == null)
{
throw new ArgumentNullException("configuration");
}
if (!configuration.IsValid)
{
throw new ArgumentException("Configuration is invalid", "configuration");
}
currentConfiguration = configuration;
pipelines.BeforeRequest.AddItemToStartOfPipeline(GetLoadAuthenticationHook(configuration));
if (!configuration.DisableRedirect)
{
pipelines.AfterRequest.AddItemToEndOfPipeline(GetRedirectToLoginHook(configuration));
}
}
/// <summary>
/// Creates a response that sets the authentication cookie and redirects
/// the user back to where they came from.
/// </summary>
/// <param name="context">Current context</param>
/// <param name="userIdentifier">User identifier guid</param>
/// <param name="cookieExpiry">Optional expiry date for the cookie (for 'Remember me')</param>
/// <param name="fallbackRedirectUrl">Url to redirect to if none in the querystring</param>
/// <returns>Nancy response with redirect.</returns>
public static Response UserLoggedInRedirectResponse(NancyContext context, Guid userIdentifier, DateTime? cookieExpiry = null, string fallbackRedirectUrl = null)
{
var redirectUrl = fallbackRedirectUrl;
if (string.IsNullOrEmpty(redirectUrl))
{
redirectUrl = context.Request.Url.BasePath;
}
if (string.IsNullOrEmpty(redirectUrl))
{
redirectUrl = "/";
}
string redirectQuerystringKey = GetRedirectQuerystringKey(currentConfiguration);
if (context.Request.Query[redirectQuerystringKey].HasValue)
{
var queryUrl = (string)context.Request.Query[redirectQuerystringKey];
if (context.IsLocalUrl(queryUrl))
{
redirectUrl = queryUrl;
}
}
var response = context.GetRedirect(redirectUrl);
var authenticationCookie = BuildCookie(userIdentifier, cookieExpiry, currentConfiguration);
response.AddCookie(authenticationCookie);
return response;
}
/// <summary>
/// Logs the user in.
/// </summary>
/// <param name="userIdentifier">User identifier guid</param>
/// <param name="cookieExpiry">Optional expiry date for the cookie (for 'Remember me')</param>
/// <returns>Nancy response with status <see cref="HttpStatusCode.OK"/></returns>
public static Response UserLoggedInResponse(Guid userIdentifier, DateTime? cookieExpiry = null)
{
var response =
(Response)HttpStatusCode.OK;
var authenticationCookie =
BuildCookie(userIdentifier, cookieExpiry, currentConfiguration);
response.AddCookie(authenticationCookie);
return response;
}
/// <summary>
/// Logs the user out and redirects them to a URL
/// </summary>
/// <param name="context">Current context</param>
/// <param name="redirectUrl">URL to redirect to</param>
/// <returns>Nancy response</returns>
public static Response LogOutAndRedirectResponse(NancyContext context, string redirectUrl)
{
var response = context.GetRedirect(redirectUrl);
var authenticationCookie = BuildLogoutCookie(currentConfiguration);
response.AddCookie(authenticationCookie);
return response;
}
/// <summary>
/// Logs the user out.
/// </summary>
/// <returns>Nancy response</returns>
public static Response LogOutResponse()
{
var response =
(Response)HttpStatusCode.OK;
var authenticationCookie =
BuildLogoutCookie(currentConfiguration);
response.AddCookie(authenticationCookie);
return response;
}
/// <summary>
/// Gets the pre request hook for loading the authenticated user's details
/// from the cookie.
/// </summary>
/// <param name="configuration">Forms authentication configuration to use</param>
/// <returns>Pre request hook delegate</returns>
private static Func<NancyContext, Response> GetLoadAuthenticationHook(FormsAuthenticationConfiguration configuration)
{
if (configuration == null)
{
throw new ArgumentNullException("configuration");
}
return context =>
{
var userGuid = GetAuthenticatedUserFromCookie(context, configuration);
if (userGuid != Guid.Empty)
{
context.CurrentUser = configuration.UserMapper.GetUserFromIdentifier(userGuid, context);
}
return null;
};
}
/// <summary>
/// Gets the post request hook for redirecting to the login page
/// </summary>
/// <param name="configuration">Forms authentication configuration to use</param>
/// <returns>Post request hook delegate</returns>
private static Action<NancyContext> GetRedirectToLoginHook(FormsAuthenticationConfiguration configuration)
{
return context =>
{
if (context.Response.StatusCode == HttpStatusCode.Unauthorized)
{
string redirectQuerystringKey = GetRedirectQuerystringKey(configuration);
context.Response = context.GetRedirect(
string.Format("{0}?{1}={2}",
configuration.RedirectUrl,
redirectQuerystringKey,
context.ToFullPath("~" + context.Request.Path + HttpUtility.UrlEncode(context.Request.Url.Query))));
}
};
}
/// <summary>
/// Gets the authenticated user GUID from the incoming request cookie if it exists
/// and is valid.
/// </summary>
/// <param name="context">Current context</param>
/// <param name="configuration">Current configuration</param>
/// <returns>Returns user guid, or Guid.Empty if not present or invalid</returns>
private static Guid GetAuthenticatedUserFromCookie(NancyContext context, FormsAuthenticationConfiguration configuration)
{
if (!context.Request.Cookies.ContainsKey(formsAuthenticationCookieName))
{
return Guid.Empty;
}
var cookieValueEncrypted = context.Request.Cookies[formsAuthenticationCookieName];
if (string.IsNullOrEmpty(cookieValueEncrypted))
{
return Guid.Empty;
}
var cookieValue = DecryptAndValidateAuthenticationCookie(cookieValueEncrypted, configuration);
Guid returnGuid;
if (String.IsNullOrEmpty(cookieValue) || !Guid.TryParse(cookieValue, out returnGuid))
{
return Guid.Empty;
}
return returnGuid;
}
/// <summary>
/// Build the forms authentication cookie
/// </summary>
/// <param name="userIdentifier">Authenticated user identifier</param>
/// <param name="cookieExpiry">Optional expiry date for the cookie (for 'Remember me')</param>
/// <param name="configuration">Current configuration</param>
/// <returns>Nancy cookie instance</returns>
private static INancyCookie BuildCookie(Guid userIdentifier, DateTime? cookieExpiry, FormsAuthenticationConfiguration configuration)
{
var cookieContents = EncryptAndSignCookie(userIdentifier.ToString(), configuration);
var cookie = new NancyCookie(formsAuthenticationCookieName, cookieContents, true, configuration.RequiresSSL, cookieExpiry);
if(!string.IsNullOrEmpty(configuration.Domain))
{
cookie.Domain = configuration.Domain;
}
if(!string.IsNullOrEmpty(configuration.Path))
{
cookie.Path = configuration.Path;
}
return cookie;
}
/// <summary>
/// Builds a cookie for logging a user out
/// </summary>
/// <param name="configuration">Current configuration</param>
/// <returns>Nancy cookie instance</returns>
private static INancyCookie BuildLogoutCookie(FormsAuthenticationConfiguration configuration)
{
var cookie = new NancyCookie(formsAuthenticationCookieName, String.Empty, true, configuration.RequiresSSL, DateTime.Now.AddDays(-1));
if(!string.IsNullOrEmpty(configuration.Domain))
{
cookie.Domain = configuration.Domain;
}
if(!string.IsNullOrEmpty(configuration.Path))
{
cookie.Path = configuration.Path;
}
return cookie;
}
/// <summary>
/// Encrypt and sign the cookie contents
/// </summary>
/// <param name="cookieValue">Plain text cookie value</param>
/// <param name="configuration">Current configuration</param>
/// <returns>Encrypted and signed string</returns>
private static string EncryptAndSignCookie(string cookieValue, FormsAuthenticationConfiguration configuration)
{
var encryptedCookie = configuration.CryptographyConfiguration.EncryptionProvider.Encrypt(cookieValue);
var hmacBytes = GenerateHmac(encryptedCookie, configuration);
var hmacString = Convert.ToBase64String(hmacBytes);
return String.Format("{1}{0}", encryptedCookie, hmacString);
}
/// <summary>
/// Generate a hmac for the encrypted cookie string
/// </summary>
/// <param name="encryptedCookie">Encrypted cookie string</param>
/// <param name="configuration">Current configuration</param>
/// <returns>Hmac byte array</returns>
private static byte[] GenerateHmac(string encryptedCookie, FormsAuthenticationConfiguration configuration)
{
return configuration.CryptographyConfiguration.HmacProvider.GenerateHmac(encryptedCookie);
}
/// <summary>
/// Decrypt and validate an encrypted and signed cookie value
/// </summary>
/// <param name="cookieValue">Encrypted and signed cookie value</param>
/// <param name="configuration">Current configuration</param>
/// <returns>Decrypted value, or empty on error or if failed validation</returns>
public static string DecryptAndValidateAuthenticationCookie(string cookieValue, FormsAuthenticationConfiguration configuration)
{
// TODO - shouldn't this be automatically decoded by nancy cookie when that change is made?
var decodedCookie = Helpers.HttpUtility.UrlDecode(cookieValue);
var hmacStringLength = Base64Helpers.GetBase64Length(configuration.CryptographyConfiguration.HmacProvider.HmacLength);
var encryptedCookie = decodedCookie.Substring(hmacStringLength);
var hmacString = decodedCookie.Substring(0, hmacStringLength);
var encryptionProvider = configuration.CryptographyConfiguration.EncryptionProvider;
// Check the hmacs, but don't early exit if they don't match
var hmacBytes = Convert.FromBase64String(hmacString);
var newHmac = GenerateHmac(encryptedCookie, configuration);
var hmacValid = HmacComparer.Compare(newHmac, hmacBytes, configuration.CryptographyConfiguration.HmacProvider.HmacLength);
var decrypted = encryptionProvider.Decrypt(encryptedCookie);
// Only return the decrypted result if the hmac was ok
return hmacValid ? decrypted : string.Empty;
}
/// <summary>
/// Gets the redirect query string key from <see cref="FormsAuthenticationConfiguration"/>
/// </summary>
/// <param name="configuration">The forms authentication configuration.</param>
/// <returns>Redirect Querystring key</returns>
private static string GetRedirectQuerystringKey(FormsAuthenticationConfiguration configuration)
{
string redirectQuerystringKey = null;
if (configuration != null)
{
redirectQuerystringKey = configuration.RedirectQuerystringKey;
}
if(string.IsNullOrWhiteSpace(redirectQuerystringKey))
{
redirectQuerystringKey = FormsAuthenticationConfiguration.DefaultRedirectQuerystringKey;
}
return redirectQuerystringKey;
}
}
}
| |
#region License
//
// Copyright (c) 2007-2018, Sean Chambers <schambers80@gmail.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text.RegularExpressions;
using FluentMigrator.Expressions;
using FluentMigrator.Infrastructure;
using FluentMigrator.Runner;
using FluentMigrator.Runner.Exceptions;
using FluentMigrator.Runner.Infrastructure;
using FluentMigrator.Runner.Initialization;
using FluentMigrator.Runner.Processors;
using FluentMigrator.Tests.Integration.Migrations;
using FluentMigrator.Tests.Integration.Migrations.Constrained.Constraints;
using FluentMigrator.Tests.Integration.Migrations.Constrained.ConstraintsMultiple;
using FluentMigrator.Tests.Integration.Migrations.Constrained.ConstraintsSuccess;
using FluentMigrator.Tests.Logging;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Moq;
using NUnit.Framework;
using Shouldly;
namespace FluentMigrator.Tests.Unit
{
[TestFixture]
public class MigrationRunnerTests
{
private Mock<IStopWatch> _stopWatch;
private Mock<IMigrationProcessor> _processorMock;
private Mock<IMigrationInformationLoader> _migrationLoaderMock;
private Mock<IProfileLoader> _profileLoaderMock;
private Mock<IAssemblySource> _assemblySourceMock;
private ICollection<string> _logMessages;
private SortedList<long, IMigrationInfo> _migrationList;
private TestVersionLoader _fakeVersionLoader;
private int _applicationContext;
private IServiceCollection _serviceCollection;
[SetUp]
[MethodImpl(MethodImplOptions.NoInlining)]
public void SetUp()
{
var asm = Assembly.GetExecutingAssembly();
_applicationContext = new Random().Next();
_migrationList = new SortedList<long, IMigrationInfo>();
_processorMock = new Mock<IMigrationProcessor>(MockBehavior.Loose);
_migrationLoaderMock = new Mock<IMigrationInformationLoader>(MockBehavior.Loose);
_profileLoaderMock = new Mock<IProfileLoader>(MockBehavior.Loose);
_stopWatch = new Mock<IStopWatch>();
_stopWatch.Setup(x => x.Time(It.IsAny<Action>())).Returns(new TimeSpan(1)).Callback((Action a) => a.Invoke());
_assemblySourceMock = new Mock<IAssemblySource>();
_assemblySourceMock.SetupGet(x => x.Assemblies).Returns(new[] { asm });
_migrationLoaderMock.Setup(x => x.LoadMigrations()).Returns(()=> _migrationList);
_logMessages = new List<string>();
var connectionString = IntegrationTestOptions.SqlServer2008.ConnectionString;
_serviceCollection = ServiceCollectionExtensions.CreateServices()
.WithProcessor(_processorMock)
.AddSingleton<ILoggerProvider>(new TextLineLoggerProvider(_logMessages, new FluentMigratorLoggerOptions() { ShowElapsedTime = true }))
.AddSingleton(_stopWatch.Object)
.AddSingleton(_assemblySourceMock.Object)
.AddSingleton(_migrationLoaderMock.Object)
.AddScoped<IConnectionStringReader>(_ => new PassThroughConnectionStringReader(connectionString))
.AddScoped(_ => _profileLoaderMock.Object)
#pragma warning disable 612
.Configure<RunnerOptions>(opt => opt.ApplicationContext = _applicationContext)
#pragma warning restore 612
.Configure<ProcessorOptions>(
opt => opt.ConnectionString = connectionString)
.Configure<AssemblySourceOptions>(opt => opt.AssemblyNames = new []{ asm.FullName })
.Configure<TypeFilterOptions>(
opt => opt.Namespace = "FluentMigrator.Tests.Integration.Migrations")
.ConfigureRunner(builder => builder.WithRunnerConventions(new CustomMigrationConventions()));
}
private MigrationRunner CreateRunner(Action<IServiceCollection> initAction = null)
{
initAction?.Invoke(_serviceCollection);
var serviceProvider = _serviceCollection
.BuildServiceProvider();
var runner = (MigrationRunner) serviceProvider.GetRequiredService<IMigrationRunner>();
_fakeVersionLoader = new TestVersionLoader(runner, runner.VersionLoader.VersionTableMetaData);
runner.VersionLoader = _fakeVersionLoader;
var readTableDataResult = new DataSet();
readTableDataResult.Tables.Add(new DataTable());
_processorMock.Setup(x => x.ReadTableData(It.IsAny<string>(), It.IsAny<string>()))
.Returns(readTableDataResult);
_processorMock.Setup(x => x.SchemaExists(It.Is<string>(s => s == runner.VersionLoader.VersionTableMetaData.SchemaName)))
.Returns(true);
_processorMock.Setup(x => x.TableExists(It.Is<string>(s => s == runner.VersionLoader.VersionTableMetaData.SchemaName),
It.Is<string>(t => t == runner.VersionLoader.VersionTableMetaData.TableName)))
.Returns(true);
return runner;
}
private void LoadVersionData(params long[] fakeVersions)
{
_fakeVersionLoader.Versions.Clear();
_migrationList.Clear();
foreach (var version in fakeVersions)
{
_fakeVersionLoader.Versions.Add(version);
_migrationList.Add(version,new MigrationInfo(version, TransactionBehavior.Default, new TestMigration()));
}
_fakeVersionLoader.LoadVersionInfo();
}
[Test]
public void ProfilesAreAppliedWhenMigrateUpIsCalledWithNoVersion()
{
var runner = CreateRunner();
runner.MigrateUp();
_profileLoaderMock.Verify(x => x.ApplyProfiles(runner), Times.Once());
}
[Test]
public void ProfilesAreAppliedWhenMigrateUpIsCalledWithVersionParameter()
{
var runner = CreateRunner();
runner.MigrateUp(2009010101);
_profileLoaderMock.Verify(x => x.ApplyProfiles(runner), Times.Once());
}
[Test]
public void ProfilesAreAppliedWhenMigrateDownIsCalled()
{
var runner = CreateRunner();
runner.MigrateDown(2009010101);
_profileLoaderMock.Verify(x => x.ApplyProfiles(runner), Times.Once());
}
/// <summary>Unit test which ensures that the application context is correctly propagated down to each migration class.</summary>
[Test(Description = "Ensure that the application context is correctly propagated down to each migration class.")]
public void CanPassApplicationContext()
{
var runner = CreateRunner();
IMigration migration = new TestEmptyMigration();
runner.Up(migration);
Assert.AreEqual(_applicationContext, migration.ApplicationContext, "The migration does not have the expected application context.");
}
[Test]
public void CanPassConnectionString()
{
var runner = CreateRunner();
IMigration migration = new TestEmptyMigration();
runner.Up(migration);
Assert.AreEqual(IntegrationTestOptions.SqlServer2008.ConnectionString, migration.ConnectionString, "The migration does not have the expected connection string.");
}
[Test]
public void CanAnnounceUp()
{
var runner = CreateRunner();
runner.Up(new TestMigration());
_logMessages.ShouldContain(l => LineContainsAll(l, "Test", "migrating"));
}
[Test]
public void CanAnnounceUpFinish()
{
var runner = CreateRunner();
runner.Up(new TestMigration());
_logMessages.ShouldContain(l => LineContainsAll(l, "Test", "migrated"));
}
[Test]
public void CanAnnounceDown()
{
var runner = CreateRunner();
runner.Down(new TestMigration());
_logMessages.ShouldContain(l => LineContainsAll(l, "Test", "reverting"));
}
[Test]
public void CanAnnounceDownFinish()
{
var runner = CreateRunner();
runner.Down(new TestMigration());
_logMessages.ShouldContain(l => LineContainsAll(l, "Test", "reverted"));
}
[Test]
public void CanAnnounceUpElapsedTime()
{
var ts = new TimeSpan(0, 0, 0, 1, 3);
_stopWatch.Setup(x => x.ElapsedTime()).Returns(ts);
var runner = CreateRunner();
runner.Up(new TestMigration());
_logMessages.ShouldContain(l => l.Equals($"=> {ts.TotalSeconds}s"));
}
[Test]
public void CanAnnounceDownElapsedTime()
{
var ts = new TimeSpan(0, 0, 0, 1, 3);
_stopWatch.Setup(x => x.ElapsedTime()).Returns(ts);
var runner = CreateRunner();
runner.Down(new TestMigration());
_logMessages.ShouldContain(l => l.Equals($"=> {ts.TotalSeconds}s"));
}
[Test]
public void CanReportExceptions()
{
var runner = CreateRunner();
_processorMock.Setup(x => x.Process(It.IsAny<CreateTableExpression>())).Throws(new Exception("Oops"));
var exception = Assert.Throws<Exception>(() => runner.Up(new TestMigration()));
Assert.That(exception.Message, Does.Contain("Oops"));
}
[Test]
public void CanSayExpression()
{
_stopWatch.Setup(x => x.ElapsedTime()).Returns(new TimeSpan(0, 0, 0, 1, 3));
var runner = CreateRunner();
runner.Up(new TestMigration());
_logMessages.ShouldContain(l => LineContainsAll(l, "CreateTable"));
}
[Test]
public void CanTimeExpression()
{
var ts = new TimeSpan(0, 0, 0, 1, 3);
_stopWatch.Setup(x => x.ElapsedTime()).Returns(ts);
var runner = CreateRunner();
runner.Up(new TestMigration());
_logMessages.ShouldContain(l => l.Equals($"=> {ts.TotalSeconds}s"));
}
[Test]
public void HasMigrationsToApplyUpWhenThereAreMigrations()
{
var runner = CreateRunner();
const long fakeMigrationVersion1 = 2009010101;
const long fakeMigrationVersion2 = 2009010102;
LoadVersionData(fakeMigrationVersion1, fakeMigrationVersion2);
_fakeVersionLoader.Versions.Remove(fakeMigrationVersion2);
_fakeVersionLoader.LoadVersionInfo();
runner.HasMigrationsToApplyUp().ShouldBeTrue();
}
[Test]
public void HasMigrationsToApplyUpWhenThereAreNoNewMigrations()
{
var runner = CreateRunner();
const long fakeMigrationVersion1 = 2009010101;
const long fakeMigrationVersion2 = 2009010102;
LoadVersionData(fakeMigrationVersion1, fakeMigrationVersion2);
runner.HasMigrationsToApplyUp().ShouldBeFalse();
}
[Test]
public void HasMigrationsToApplyUpToSpecificVersionWhenTheSpecificHasNotBeenApplied()
{
var runner = CreateRunner();
const long fakeMigrationVersion1 = 2009010101;
const long fakeMigrationVersion2 = 2009010102;
LoadVersionData(fakeMigrationVersion1, fakeMigrationVersion2);
_fakeVersionLoader.Versions.Remove(fakeMigrationVersion2);
_fakeVersionLoader.LoadVersionInfo();
runner.HasMigrationsToApplyUp(fakeMigrationVersion2).ShouldBeTrue();
}
[Test]
public void HasMigrationsToApplyUpToSpecificVersionWhenTheSpecificHasBeenApplied()
{
var runner = CreateRunner();
const long fakeMigrationVersion1 = 2009010101;
const long fakeMigrationVersion2 = 2009010102;
LoadVersionData(fakeMigrationVersion1, fakeMigrationVersion2);
_fakeVersionLoader.Versions.Remove(fakeMigrationVersion2);
_fakeVersionLoader.LoadVersionInfo();
runner.HasMigrationsToApplyUp(fakeMigrationVersion1).ShouldBeFalse();
}
[Test]
public void HasMigrationsToApplyRollbackWithOneMigrationApplied()
{
var runner = CreateRunner();
const long fakeMigrationVersion1 = 2009010101;
LoadVersionData(fakeMigrationVersion1);
runner.HasMigrationsToApplyRollback().ShouldBeTrue();
}
[Test]
public void HasMigrationsToApplyRollbackWithNoMigrationsApplied()
{
var runner = CreateRunner();
LoadVersionData();
runner.HasMigrationsToApplyRollback().ShouldBeFalse();
}
[Test]
public void HasMigrationsToApplyDownWhenTheVersionHasNotBeenApplied()
{
var runner = CreateRunner();
const long fakeMigrationVersion1 = 2009010101;
const long fakeMigrationVersion2 = 2009010102;
LoadVersionData(fakeMigrationVersion1, fakeMigrationVersion2);
_fakeVersionLoader.Versions.Remove(fakeMigrationVersion2);
_fakeVersionLoader.LoadVersionInfo();
runner.HasMigrationsToApplyDown(fakeMigrationVersion1).ShouldBeFalse();
}
[Test]
public void HasMigrationsToApplyDownWhenTheVersionHasBeenApplied()
{
var runner = CreateRunner();
const long fakeMigrationVersion1 = 2009010101;
const long fakeMigrationVersion2 = 2009010102;
LoadVersionData(fakeMigrationVersion1, fakeMigrationVersion2);
runner.HasMigrationsToApplyDown(fakeMigrationVersion1).ShouldBeTrue();
}
[Test]
public void RollbackOnlyOneStepsOfTwoShouldNotDeleteVersionInfoTable()
{
const long fakeMigrationVersion = 2009010101;
const long fakeMigrationVersion2 = 2009010102;
var runner = CreateRunner();
Assert.NotNull(runner.VersionLoader.VersionTableMetaData.TableName);
LoadVersionData(fakeMigrationVersion, fakeMigrationVersion2);
runner.VersionLoader.LoadVersionInfo();
runner.Rollback(1);
_fakeVersionLoader.DidRemoveVersionTableGetCalled.ShouldBeFalse();
}
[Test]
public void RollbackLastVersionShouldDeleteVersionInfoTable()
{
var runner = CreateRunner();
const long fakeMigrationVersion = 2009010101;
LoadVersionData(fakeMigrationVersion);
Assert.NotNull(runner.VersionLoader.VersionTableMetaData.TableName);
runner.Rollback(1);
_fakeVersionLoader.DidRemoveVersionTableGetCalled.ShouldBeTrue();
}
[Test]
public void RollbackToVersionZeroShouldDeleteVersionInfoTable()
{
var runner = CreateRunner();
Assert.NotNull(runner.VersionLoader.VersionTableMetaData.TableName);
runner.RollbackToVersion(0);
_fakeVersionLoader.DidRemoveVersionTableGetCalled.ShouldBeTrue();
}
[Test]
public void RollbackToVersionZeroShouldNotCreateVersionInfoTableAfterRemoval()
{
var runner = CreateRunner();
var versionInfoTableName = runner.VersionLoader.VersionTableMetaData.TableName;
runner.RollbackToVersion(0);
//Should only be called once in setup
_processorMock.Verify(
pm => pm.Process(It.Is<CreateTableExpression>(
dte => dte.TableName == versionInfoTableName)
),
Times.Once()
);
}
[Test]
public void RollbackToVersionShouldShouldLimitMigrationsToNamespace()
{
const long fakeMigration1 = 2011010101;
const long fakeMigration2 = 2011010102;
const long fakeMigration3 = 2011010103;
var runner = CreateRunner();
LoadVersionData(fakeMigration1,fakeMigration3);
_fakeVersionLoader.Versions.Add(fakeMigration2);
_fakeVersionLoader.LoadVersionInfo();
runner.RollbackToVersion(2011010101);
_fakeVersionLoader.Versions.ShouldContain(fakeMigration1);
_fakeVersionLoader.Versions.ShouldContain(fakeMigration2);
_fakeVersionLoader.Versions.ShouldNotContain(fakeMigration3);
}
[Test]
public void RollbackToVersionZeroShouldShouldLimitMigrationsToNamespace()
{
const long fakeMigration1 = 2011010101;
const long fakeMigration2 = 2011010102;
const long fakeMigration3 = 2011010103;
var runner = CreateRunner();
LoadVersionData(fakeMigration1, fakeMigration2, fakeMigration3);
_migrationList.Remove(fakeMigration1);
_migrationList.Remove(fakeMigration2);
_fakeVersionLoader.LoadVersionInfo();
runner.RollbackToVersion(0);
_fakeVersionLoader.Versions.ShouldContain(fakeMigration1);
_fakeVersionLoader.Versions.ShouldContain(fakeMigration2);
_fakeVersionLoader.Versions.ShouldNotContain(fakeMigration3);
}
[Test]
public void RollbackShouldLimitMigrationsToNamespace()
{
var runner = CreateRunner();
const long fakeMigration1 = 2011010101;
const long fakeMigration2 = 2011010102;
const long fakeMigration3 = 2011010103;
LoadVersionData(fakeMigration1, fakeMigration3);
_fakeVersionLoader.Versions.Add(fakeMigration2);
_fakeVersionLoader.LoadVersionInfo();
runner.Rollback(2);
_fakeVersionLoader.Versions.ShouldNotContain(fakeMigration1);
_fakeVersionLoader.Versions.ShouldContain(fakeMigration2);
_fakeVersionLoader.Versions.ShouldNotContain(fakeMigration3);
_fakeVersionLoader.DidRemoveVersionTableGetCalled.ShouldBeFalse();
}
[Test]
public void RollbackToVersionShouldLoadVersionInfoIfVersionGreaterThanZero()
{
var runner = CreateRunner();
var versionInfoTableName = runner.VersionLoader.VersionTableMetaData.TableName;
runner.RollbackToVersion(1);
_fakeVersionLoader.DidRemoveVersionTableGetCalled.ShouldBeFalse();
//Once in setup
_processorMock.Verify(
pm => pm.Process(It.Is<CreateTableExpression>(
dte => dte.TableName == versionInfoTableName)
),
Times.Exactly(1)
);
//After setup is done, fake version loader owns the proccess
_fakeVersionLoader.DidLoadVersionInfoGetCalled.ShouldBe(true);
}
[Test]
public void ValidateVersionOrderingShouldReturnNothingIfNoUnappliedMigrations()
{
const long version1 = 2011010101;
const long version2 = 2011010102;
var mockMigration1 = new Mock<IMigration>();
var mockMigration2 = new Mock<IMigration>();
var runner = CreateRunner();
LoadVersionData(version1, version2);
_migrationList.Clear();
_migrationList.Add(version1,new MigrationInfo(version1, TransactionBehavior.Default, mockMigration1.Object));
_migrationList.Add(version2, new MigrationInfo(version2, TransactionBehavior.Default, mockMigration2.Object));
Assert.DoesNotThrow(() => runner.ValidateVersionOrder());
_logMessages.ShouldContain(l => LineContainsAll(l, "Version ordering valid."));
_fakeVersionLoader.DidRemoveVersionTableGetCalled.ShouldBeFalse();
}
[Test]
public void ValidateVersionOrderingShouldReturnNothingIfUnappliedMigrationVersionIsGreaterThanLatestAppliedMigration()
{
const long version1 = 2011010101;
const long version2 = 2011010102;
var mockMigration1 = new Mock<IMigration>();
var mockMigration2 = new Mock<IMigration>();
var runner = CreateRunner();
LoadVersionData(version1);
_migrationList.Clear();
_migrationList.Add(version1, new MigrationInfo(version1, TransactionBehavior.Default, mockMigration1.Object));
_migrationList.Add(version2, new MigrationInfo(version2, TransactionBehavior.Default, mockMigration2.Object));
Assert.DoesNotThrow(() => runner.ValidateVersionOrder());
_logMessages.ShouldContain(l => LineContainsAll(l, "Version ordering valid."));
_fakeVersionLoader.DidRemoveVersionTableGetCalled.ShouldBeFalse();
}
[Test]
public void ValidateVersionOrderingShouldThrowExceptionIfUnappliedMigrationVersionIsLessThanGreatestAppliedMigrationVersion()
{
var runner = CreateRunner();
const long version1 = 2011010101;
const long version2 = 2011010102;
const long version3 = 2011010103;
const long version4 = 2011010104;
var mockMigration1 = new Mock<IMigration>();
var mockMigration2 = new Mock<IMigration>();
var mockMigration3 = new Mock<IMigration>();
var mockMigration4 = new Mock<IMigration>();
LoadVersionData(version1, version4);
_migrationList.Clear();
_migrationList.Add(version1, new MigrationInfo(version1, TransactionBehavior.Default, mockMigration1.Object));
_migrationList.Add(version2, new MigrationInfo(version2, TransactionBehavior.Default, mockMigration2.Object));
_migrationList.Add(version3, new MigrationInfo(version3, TransactionBehavior.Default, mockMigration3.Object));
_migrationList.Add(version4, new MigrationInfo(version4, TransactionBehavior.Default, mockMigration4.Object));
var exception = Assert.Throws<VersionOrderInvalidException>(() => runner.ValidateVersionOrder());
var invalidMigrations = exception.InvalidMigrations.ToList();
invalidMigrations.Count.ShouldBe(2);
invalidMigrations.Select(x => x.Key).ShouldContain(version2);
invalidMigrations.Select(x => x.Key).ShouldContain(version3);
_fakeVersionLoader.DidRemoveVersionTableGetCalled.ShouldBeFalse();
}
[Test]
public void CanListVersions()
{
const long version1 = 2011010101;
const long version2 = 2011010102;
const long version3 = 2011010103;
const long version4 = 2011010104;
var mockMigration1 = new Mock<IMigration>();
var mockMigration2 = new Mock<IMigration>();
var mockMigration3 = new Mock<IMigration>();
var mockMigration4 = new Mock<IMigration>();
var runner = CreateRunner();
LoadVersionData(version1, version3);
_migrationList.Clear();
_migrationList.Add(version1, new MigrationInfo(version1, TransactionBehavior.Default, mockMigration1.Object));
_migrationList.Add(version2, new MigrationInfo(version2, TransactionBehavior.Default, mockMigration2.Object));
_migrationList.Add(version3, new MigrationInfo(version3, TransactionBehavior.Default, mockMigration3.Object));
_migrationList.Add(version4, new MigrationInfo(version4, TransactionBehavior.Default, true, mockMigration4.Object));
runner.ListMigrations();
_logMessages.ShouldContain(l => LineContainsAll(l, "2011010101: IMigrationProxy"));
_logMessages.ShouldContain(l => LineContainsAll(l, "2011010102: IMigrationProxy (not applied)"));
_logMessages.ShouldContain(l => LineContainsAll(l, "2011010103: IMigrationProxy (current)"));
_logMessages.ShouldContain(l => LineContainsAll(l, "2011010104: IMigrationProxy (not applied, BREAKING)"));
}
[Test]
public void IfMigrationHasAnInvalidExpressionDuringUpActionShouldThrowAnExceptionAndAnnounceTheError()
{
var invalidMigration = new Mock<IMigration>();
var invalidExpression = new UpdateDataExpression {TableName = "Test"};
invalidMigration.Setup(m => m.GetUpExpressions(It.IsAny<IMigrationContext>())).Callback((IMigrationContext mc) => mc.Expressions.Add(invalidExpression));
var runner = CreateRunner();
Assert.Throws<InvalidMigrationException>(() => runner.Up(invalidMigration.Object));
var expectedErrorMessage = ErrorMessages.UpdateDataExpressionMustSpecifyWhereClauseOrAllRows;
_logMessages.ShouldContain(l => LineContainsAll(l, $"UpdateDataExpression: {expectedErrorMessage}"));
}
[Test]
public void IfMigrationHasAnInvalidExpressionDuringDownActionShouldThrowAnExceptionAndAnnounceTheError()
{
var invalidMigration = new Mock<IMigration>();
var invalidExpression = new UpdateDataExpression { TableName = "Test" };
invalidMigration.Setup(m => m.GetDownExpressions(It.IsAny<IMigrationContext>())).Callback((IMigrationContext mc) => mc.Expressions.Add(invalidExpression));
var runner = CreateRunner();
Assert.Throws<InvalidMigrationException>(() => runner.Down(invalidMigration.Object));
var expectedErrorMessage = ErrorMessages.UpdateDataExpressionMustSpecifyWhereClauseOrAllRows;
_logMessages.ShouldContain(l => LineContainsAll(l, $"UpdateDataExpression: {expectedErrorMessage}"));
}
[Test]
public void IfMigrationHasTwoInvalidExpressionsShouldAnnounceBothErrors()
{
var invalidMigration = new Mock<IMigration>();
var invalidExpression = new UpdateDataExpression { TableName = "Test" };
var secondInvalidExpression = new CreateColumnExpression();
invalidMigration.Setup(m => m.GetUpExpressions(It.IsAny<IMigrationContext>()))
.Callback((IMigrationContext mc) => { mc.Expressions.Add(invalidExpression); mc.Expressions.Add(secondInvalidExpression); });
var runner = CreateRunner();
Assert.Throws<InvalidMigrationException>(() => runner.Up(invalidMigration.Object));
_logMessages.ShouldContain(l => LineContainsAll(l, $"UpdateDataExpression: {ErrorMessages.UpdateDataExpressionMustSpecifyWhereClauseOrAllRows}"));
_logMessages.ShouldContain(l => LineContainsAll(l, $"CreateColumnExpression: {ErrorMessages.TableNameCannotBeNullOrEmpty}"));
}
[Test]
public void CanLoadCustomMigrationConventions()
{
var runner = CreateRunner();
Assert.That(runner.Conventions, Is.TypeOf<CustomMigrationConventions>());
}
[Test]
public void CanLoadDefaultMigrationConventionsIfNoCustomConventionsAreSpecified()
{
var processorMock = new Mock<IMigrationProcessor>(MockBehavior.Loose);
var serviceProvider = ServiceCollectionExtensions.CreateServices(false)
.WithProcessor(processorMock)
.BuildServiceProvider();
var runner = (MigrationRunner) serviceProvider.GetRequiredService<IMigrationRunner>();
Assert.That(runner.Conventions, Is.TypeOf<DefaultMigrationRunnerConventions>());
}
[Test]
public void CanBlockBreakingChangesByDefault()
{
var runner = CreateRunner(sc => sc.Configure<RunnerOptions>(opt => opt.AllowBreakingChange = false));
InvalidOperationException ex = Assert.Throws<InvalidOperationException>(() =>
runner.ApplyMigrationUp(
new MigrationInfo(7, TransactionBehavior.Default, true, new TestBreakingMigration()), true));
Assert.NotNull(ex);
Assert.AreEqual(
"The migration 7: TestBreakingMigration is identified as a breaking change, and will not be executed unless the necessary flag (allow-breaking-changes|abc) is passed to the runner.",
ex.Message);
}
[Test]
public void CanRunBreakingChangesIfSpecified()
{
_serviceCollection
.Configure<RunnerOptions>(opt => opt.AllowBreakingChange = true);
var runner = CreateRunner();
Assert.DoesNotThrow(() =>
runner.ApplyMigrationUp(
new MigrationInfo(7, TransactionBehavior.Default, true, new TestBreakingMigration()), true));
}
[Test]
public void CanRunBreakingChangesInPreview()
{
_serviceCollection
.Configure<RunnerOptions>(opt => opt.AllowBreakingChange = true)
.Configure<ProcessorOptions>(opt => opt.PreviewOnly = true);
var runner = CreateRunner();
Assert.DoesNotThrow(() =>
runner.ApplyMigrationUp(
new MigrationInfo(7, TransactionBehavior.Default, true, new TestBreakingMigration()), true));
}
[Test]
public void DoesRunMigrationsThatMeetConstraints()
{
_migrationList.Clear();
_migrationList.Add(1, new MigrationInfo(1, TransactionBehavior.Default, new Step1Migration()));
_migrationList.Add(2, new MigrationInfo(2, TransactionBehavior.Default, new Step2Migration()));
_migrationList.Add(3, new MigrationInfo(3, TransactionBehavior.Default, new Step2Migration2()));
var runner = CreateRunner();
runner.MigrateUp();
Assert.AreEqual(1, runner.VersionLoader.VersionInfo.Latest());
}
[Test]
public void DoesRunMigrationsThatDoMeetConstraints()
{
_migrationList.Clear();
_migrationList.Add(1, new MigrationInfo(1, TransactionBehavior.Default, new Step1Migration()));
_migrationList.Add(2, new MigrationInfo(2, TransactionBehavior.Default, new Step2Migration()));
_migrationList.Add(3, new MigrationInfo(3, TransactionBehavior.Default, new Step2Migration2()));
var runner = CreateRunner();
runner.MigrateUp();
runner.MigrateUp(); // run migrations second time, this time satisfying constraints
Assert.AreEqual(3, runner.VersionLoader.VersionInfo.Latest());
}
[Test]
public void MultipleConstraintsEachNeedsToReturnTrue()
{
_migrationList.Clear();
_migrationList.Add(1, new MigrationInfo(1, TransactionBehavior.Default, new MultipleConstraintsMigration()));
var runner = CreateRunner();
runner.MigrateUp();
Assert.AreEqual(0, runner.VersionLoader.VersionInfo.Latest());
}
[Test]
public void DoesRunMigrationWithPositiveConstraint()
{
_migrationList.Clear();
_migrationList.Add(1, new MigrationInfo(1, TransactionBehavior.Default, new ConstrainedMigrationSuccess()));
var runner = CreateRunner();
runner.MigrateUp();
Assert.AreEqual(1, runner.VersionLoader.VersionInfo.Latest());
}
private static bool LineContainsAll(string line, params string[] words)
{
var pattern = string.Join(".*?", words.Select(Regex.Escape));
return Regex.IsMatch(line, pattern);
}
public class CustomMigrationConventions : MigrationRunnerConventions
{
}
}
}
| |
using System;
using System.Collections.Generic;
using ServiceStack.ServiceInterface.ServiceModel;
namespace ServiceStack.ServiceHost.Tests.AppData
{
public class Customers { }
public class CustomersResponse : IHasResponseStatus
{
public CustomersResponse()
{
this.ResponseStatus = new ResponseStatus();
this.Customers = new List<Customer>();
}
public List<Customer> Customers { get; set; }
public ResponseStatus ResponseStatus { get; set; }
}
public class CustomerDetails
{
public string Id { get; set; }
}
public class CustomerDetailsResponse : IHasResponseStatus
{
public CustomerDetailsResponse()
{
this.ResponseStatus = new ResponseStatus();
this.CustomerOrders = new List<CustomerOrder>();
}
public Customer Customer { get; set; }
public List<CustomerOrder> CustomerOrders { get; set; }
public ResponseStatus ResponseStatus { get; set; }
}
public class Orders
{
public int? Page { get; set; }
public string CustomerId { get; set; }
}
public class OrdersResponse : IHasResponseStatus
{
public OrdersResponse()
{
this.ResponseStatus = new ResponseStatus();
this.Results = new List<CustomerOrder>();
}
public List<CustomerOrder> Results { get; set; }
public ResponseStatus ResponseStatus { get; set; }
}
public class Category
{
public int Id { get; set; }
public string CategoryName { get; set; }
public string Description { get; set; }
}
public class Customer
{
public string Id { get; set; }
public string CompanyName { get; set; }
public string ContactName { get; set; }
public string ContactTitle { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string Region { get; set; }
public string PostalCode { get; set; }
public string Country { get; set; }
public string Phone { get; set; }
public string Fax { get; set; }
public string Email
{
get { return this.ContactName.Replace(" ", ".").ToLower() + "@gmail.com"; }
}
}
public class CustomerCustomerDemo
{
public string Id { get; set; }
public string CustomerTypeId { get; set; }
}
public class CustomerDemographic
{
public string Id { get; set; }
public string CustomerDesc { get; set; }
}
public class CustomerOrder
{
public CustomerOrder()
{
this.OrderDetails = new List<OrderDetail>();
}
public Order Order { get; set; }
public List<OrderDetail> OrderDetails { get; set; }
}
public class Employee
{
public int Id { get; set; }
public string LastName { get; set; }
public string FirstName { get; set; }
public string Title { get; set; }
public string TitleOfCourtesy { get; set; }
public DateTime? BirthDate { get; set; }
public DateTime? HireDate { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string Region { get; set; }
public string PostalCode { get; set; }
public string Country { get; set; }
public string HomePhone { get; set; }
public string Extension { get; set; }
public byte[] Photo { get; set; }
public string Notes { get; set; }
public int? ReportsTo { get; set; }
public string PhotoPath { get; set; }
}
public class EmployeeTerritory
{
public string Id { get { return this.EmployeeId + "/" + this.TerritoryId; } }
public int EmployeeId { get; set; }
public string TerritoryId { get; set; }
}
public class Order
{
public int Id { get; set; }
public string CustomerId { get; set; }
public int EmployeeId { get; set; }
public DateTime? OrderDate { get; set; }
public DateTime? RequiredDate { get; set; }
public DateTime? ShippedDate { get; set; }
public int? ShipVia { get; set; }
public decimal Freight { get; set; }
public string ShipName { get; set; }
public string ShipAddress { get; set; }
public string ShipCity { get; set; }
public string ShipRegion { get; set; }
public string ShipPostalCode { get; set; }
public string ShipCountry { get; set; }
}
public class OrderDetail
{
public string Id { get { return this.OrderId + "/" + this.ProductId; } }
public int OrderId { get; set; }
public int ProductId { get; set; }
public decimal UnitPrice { get; set; }
public short Quantity { get; set; }
public double Discount { get; set; }
}
public class Product
{
public int Id { get; set; }
public string ProductName { get; set; }
public int SupplierId { get; set; }
public int CategoryId { get; set; }
public string QuantityPerUnit { get; set; }
public decimal UnitPrice { get; set; }
public short UnitsInStock { get; set; }
public short UnitsOnOrder { get; set; }
public short ReorderLevel { get; set; }
public bool Discontinued { get; set; }
}
public class Region
{
public int Id { get; set; }
public string RegionDescription { get; set; }
}
public class Shipper
{
public int Id { get; set; }
public string CompanyName { get; set; }
public string Phone { get; set; }
}
public class Supplier
{
public int Id { get; set; }
public string CompanyName { get; set; }
public string ContactName { get; set; }
public string ContactTitle { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string Region { get; set; }
public string PostalCode { get; set; }
public string Country { get; set; }
public string Phone { get; set; }
public string Fax { get; set; }
public string HomePage { get; set; }
}
public class Territory
{
public string Id { get; set; }
public string TerritoryDescription { get; set; }
public int RegionId { get; set; }
}
}
| |
using UnityEngine;
using System;
public class FRadialWipeSprite : FSprite
{
protected float _baseAngle;
protected float _percentage;
protected bool _isClockwise;
protected Vector2[] _meshVertices = new Vector2[7];
protected Vector2[] _uvVertices = new Vector2[7];
public FRadialWipeSprite (string elementName, bool isClockwise, float baseAngle, float percentage) : base()
{
_isClockwise = isClockwise;
_baseAngle = (baseAngle + 36000000.0f) % 360.0f;
_percentage = Mathf.Clamp01(percentage);
Init(FFacetType.Triangle, Futile.atlasManager.GetElementWithName(elementName),5);
_isAlphaDirty = true;
UpdateLocalVertices();
}
private void CalculateTheRadialVertices ()
{
//TODO: A lot of these calculations could be offloaded to when the element (and maybe anchor?) changes.
float baseAngleToUse;
if(_isClockwise)
{
baseAngleToUse = _baseAngle;
}
else
{
baseAngleToUse = 360.0f-_baseAngle;
}
float startAngle = baseAngleToUse * RXMath.DTOR;
float endAngle = startAngle + _percentage * RXMath.DOUBLE_PI;
float halfWidth = _localRect.width*0.5f;
float halfHeight = _localRect.height*0.5f;
//corner 0 is the top right, the rest go clockwise from there
Vector2 cornerTR = new Vector2(halfHeight, halfWidth);
Vector2 cornerBR = new Vector2(-halfHeight, halfWidth);
Vector2 cornerBL = new Vector2(-halfHeight, -halfWidth);
Vector2 cornerTL = new Vector2(halfHeight, -halfWidth);
float cornerAngleTR = -Mathf.Atan2(cornerTR.x,cornerTR.y) + RXMath.HALF_PI;
float cornerAngleBR = -Mathf.Atan2(cornerBR.x,cornerBR.y) + RXMath.HALF_PI;
float cornerAngleBL = -Mathf.Atan2(cornerBL.x,cornerBL.y) + RXMath.HALF_PI;
float cornerAngleTL = -Mathf.Atan2(cornerTL.x,cornerTL.y) + RXMath.HALF_PI;
cornerAngleTR = (cornerAngleTR + RXMath.DOUBLE_PI*10000.0f) % RXMath.DOUBLE_PI;
cornerAngleBR = (cornerAngleBR + RXMath.DOUBLE_PI*10000.0f) % RXMath.DOUBLE_PI;
cornerAngleBL = (cornerAngleBL + RXMath.DOUBLE_PI*10000.0f) % RXMath.DOUBLE_PI;
cornerAngleTL = (cornerAngleTL + RXMath.DOUBLE_PI*10000.0f) % RXMath.DOUBLE_PI;
float cornerAngle0;
float cornerAngle1;
float cornerAngle2;
float cornerAngle3;
if(startAngle < cornerAngleTR) //top right
{
cornerAngle0 = cornerAngleTR;
cornerAngle1 = cornerAngleBR;
cornerAngle2 = cornerAngleBL;
cornerAngle3 = cornerAngleTL;
}
else if(startAngle >= cornerAngleTR && startAngle < cornerAngleBR) //right
{
cornerAngle0 = cornerAngleBR;
cornerAngle1 = cornerAngleBL;
cornerAngle2 = cornerAngleTL;
cornerAngle3 = cornerAngleTR + RXMath.DOUBLE_PI;
}
else if(startAngle >= cornerAngleBR && startAngle < cornerAngleBL) //left
{
cornerAngle0 = cornerAngleBL;
cornerAngle1 = cornerAngleTL;
cornerAngle2 = cornerAngleTR + RXMath.DOUBLE_PI;
cornerAngle3 = cornerAngleBR + RXMath.DOUBLE_PI;
}
else if(startAngle >= cornerAngleBL && startAngle < cornerAngleTL)
{
cornerAngle0 = cornerAngleTL;
cornerAngle1 = cornerAngleTR + RXMath.DOUBLE_PI;
cornerAngle2 = cornerAngleBR + RXMath.DOUBLE_PI;
cornerAngle3 = cornerAngleBL + RXMath.DOUBLE_PI;
}
//else if(startAngle >= cornerAngleTL)
else //top left
{
cornerAngle0 = cornerAngleTR + RXMath.DOUBLE_PI;
cornerAngle1 = cornerAngleBR + RXMath.DOUBLE_PI;
cornerAngle2 = cornerAngleBL + RXMath.DOUBLE_PI;
cornerAngle3 = cornerAngleTL + RXMath.DOUBLE_PI;
}
float hugeRadius = 1000000.0f;
for(int v = 0; v<6; v++)
{
float angle = 0;
if(v<5)
{
angle = startAngle + ((endAngle - startAngle)/5.0f * v);
if(v == 0)
{
//do nothing, 0 is gooood
}
else if(v == 1 && endAngle > cornerAngle0)
{
angle = cornerAngle0;
}
else if(v == 2 && endAngle > cornerAngle1)
{
angle = cornerAngle1;
}
else if(v == 3 && endAngle > cornerAngle2)
{
angle = cornerAngle2;
}
else if(v == 4 && endAngle > cornerAngle3)
{
angle = cornerAngle3;
}
else if(endAngle > cornerAngle3)
{
angle = Mathf.Max (angle, cornerAngle3);
}
else if(endAngle > cornerAngle2)
{
angle = Mathf.Max (angle, cornerAngle2);
}
else if(endAngle > cornerAngle1)
{
angle = Mathf.Max (angle, cornerAngle1);
}
else if(endAngle > cornerAngle0)
{
angle = Mathf.Max (angle, cornerAngle0);
}
}
else
{
angle = endAngle;
}
angle = (angle + RXMath.DOUBLE_PI*10000.0f) % RXMath.DOUBLE_PI;
float compX = Mathf.Cos(-angle + RXMath.HALF_PI) * hugeRadius;
float compY = Mathf.Sin(-angle + RXMath.HALF_PI) * hugeRadius;
//snap the verts to the edge of the rect
if(angle < cornerAngleTR) //top right
{
compX = compX * (halfHeight / compY);
compY = halfHeight;
}
else if(angle >= cornerAngleTR && angle < cornerAngleBR) //right
{
compY = compY * (halfWidth / compX);
compX = halfWidth;
}
else if(angle >= cornerAngleBR && angle < cornerAngleBL) //bottom
{
compX = compX * (-halfHeight / compY);
compY = -halfHeight;
}
else if(angle >= cornerAngleBL && angle < cornerAngleTL) //left
{
compY = compY * (-halfWidth / compX);
compX = -halfWidth;
}
else if(angle >= cornerAngleTL) //top left
{
compX = compX * (halfHeight / compY);
compY = halfHeight;
}
if(!_isClockwise)
{
compX = -compX;
}
_meshVertices[v] = new Vector2(compX, compY);
}
_meshVertices[6] = new Vector2(0,0); //this last vert is actually the center vert
//create uv vertices
Rect uvRect = _element.uvRect;
Vector2 uvCenter = uvRect.center;
for(int v = 0; v<7; v++)
{
_uvVertices[v].x = uvCenter.x + _meshVertices[v].x / _localRect.width * uvRect.width;
_uvVertices[v].y = uvCenter.y + _meshVertices[v].y / _localRect.height * uvRect.height;
}
//put mesh vertices in the correct position
float offsetX = _localRect.center.x;
float offsetY = _localRect.center.y;
for(int v = 0; v<7; v++)
{
_meshVertices[v].x += offsetX;
_meshVertices[v].y += offsetY;
}
}
override public void PopulateRenderLayer()
{
if(_isOnStage && _firstFacetIndex != -1)
{
_isMeshDirty = false;
CalculateTheRadialVertices();
//now do the actual population
Vector3[] vertices = _renderLayer.vertices;
Vector2[] uvs = _renderLayer.uvs;
Color[] colors = _renderLayer.colors;
int vertexIndex0 = _firstFacetIndex*3;
//set the colors
for(int c = 0; c<15; c++)
{
colors[vertexIndex0 + c] = _alphaColor;
}
//vertex 6 is the center vertex
//set the uvs
uvs[vertexIndex0] = _uvVertices[6];
uvs[vertexIndex0 + 1] = _uvVertices[0];
uvs[vertexIndex0 + 2] = _uvVertices[1];
uvs[vertexIndex0 + 3] = _uvVertices[6];
uvs[vertexIndex0 + 4] = _uvVertices[1];
uvs[vertexIndex0 + 5] = _uvVertices[2];
uvs[vertexIndex0 + 6] = _uvVertices[6];
uvs[vertexIndex0 + 7] = _uvVertices[2];
uvs[vertexIndex0 + 8] = _uvVertices[3];
uvs[vertexIndex0 + 9] = _uvVertices[6];
uvs[vertexIndex0 + 10] = _uvVertices[3];
uvs[vertexIndex0 + 11] = _uvVertices[4];
uvs[vertexIndex0 + 12] = _uvVertices[6];
uvs[vertexIndex0 + 13] = _uvVertices[4];
uvs[vertexIndex0 + 14] = _uvVertices[5];
//set the mesh
_concatenatedMatrix.ApplyVector3FromLocalVector2(ref vertices[vertexIndex0], _meshVertices[6],0);
_concatenatedMatrix.ApplyVector3FromLocalVector2(ref vertices[vertexIndex0 + 1], _meshVertices[0],0);
_concatenatedMatrix.ApplyVector3FromLocalVector2(ref vertices[vertexIndex0 + 2], _meshVertices[1],0);
_concatenatedMatrix.ApplyVector3FromLocalVector2(ref vertices[vertexIndex0 + 3], _meshVertices[6],0);
_concatenatedMatrix.ApplyVector3FromLocalVector2(ref vertices[vertexIndex0 + 4], _meshVertices[1],0);
_concatenatedMatrix.ApplyVector3FromLocalVector2(ref vertices[vertexIndex0 + 5], _meshVertices[2],0);
_concatenatedMatrix.ApplyVector3FromLocalVector2(ref vertices[vertexIndex0 + 6], _meshVertices[6],0);
_concatenatedMatrix.ApplyVector3FromLocalVector2(ref vertices[vertexIndex0 + 7], _meshVertices[2],0);
_concatenatedMatrix.ApplyVector3FromLocalVector2(ref vertices[vertexIndex0 + 8], _meshVertices[3],0);
_concatenatedMatrix.ApplyVector3FromLocalVector2(ref vertices[vertexIndex0 + 9], _meshVertices[6],0);
_concatenatedMatrix.ApplyVector3FromLocalVector2(ref vertices[vertexIndex0 + 10], _meshVertices[3],0);
_concatenatedMatrix.ApplyVector3FromLocalVector2(ref vertices[vertexIndex0 + 11], _meshVertices[4],0);
_concatenatedMatrix.ApplyVector3FromLocalVector2(ref vertices[vertexIndex0 + 12], _meshVertices[6],0);
_concatenatedMatrix.ApplyVector3FromLocalVector2(ref vertices[vertexIndex0 + 13], _meshVertices[4],0);
_concatenatedMatrix.ApplyVector3FromLocalVector2(ref vertices[vertexIndex0 + 14], _meshVertices[5],0);
_renderLayer.HandleVertsChange();
}
}
public float baseAngle
{
get { return _baseAngle;}
set
{
value = (value + 36000000.0f) % 360.0f;
if(_baseAngle != value)
{
_baseAngle = value;
_isMeshDirty = true;
}
}
}
public float percentage
{
get { return _percentage;}
set
{
value = Mathf.Max (0.0f, Mathf.Min(1.0f, value));
if(_percentage != value)
{
_percentage = value;
_isMeshDirty = true;
}
}
}
public bool isClockwise
{
get { return _isClockwise;}
set
{
if(_isClockwise != value)
{
_isClockwise = value;
_isMeshDirty = true;
}
}
}
}
| |
using RootSystem = System;
using System.Linq;
using System.Collections.Generic;
namespace Windows.Kinect
{
//
// Windows.Kinect.Body
//
public sealed partial class Body : Helper.INativeWrapper
{
internal RootSystem.IntPtr _pNative;
RootSystem.IntPtr Helper.INativeWrapper.nativePtr { get { return _pNative; } }
// Constructors and Finalizers
internal Body(RootSystem.IntPtr pNative)
{
_pNative = pNative;
Windows_Kinect_Body_AddRefObject(ref _pNative);
}
~Body()
{
Dispose(false);
}
[RootSystem.Runtime.InteropServices.DllImport("XboxOneUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)]
private static extern void Windows_Kinect_Body_ReleaseObject(ref RootSystem.IntPtr pNative);
[RootSystem.Runtime.InteropServices.DllImport("XboxOneUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)]
private static extern void Windows_Kinect_Body_AddRefObject(ref RootSystem.IntPtr pNative);
private void Dispose(bool disposing)
{
if (_pNative == RootSystem.IntPtr.Zero)
{
return;
}
Helper.NativeObjectCache.RemoveObject<Body>(_pNative);
Windows_Kinect_Body_ReleaseObject(ref _pNative);
_pNative = RootSystem.IntPtr.Zero;
}
// Public Properties
[RootSystem.Runtime.InteropServices.DllImport("XboxOneUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)]
private static extern int Windows_Kinect_Body_get_Activities(RootSystem.IntPtr pNative, [RootSystem.Runtime.InteropServices.Out] Windows.Kinect.Activity[] outKeys, [RootSystem.Runtime.InteropServices.Out] Windows.Kinect.DetectionResult[] outValues, int outCollectionSize);
[RootSystem.Runtime.InteropServices.DllImport("XboxOneUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)]
private static extern int Windows_Kinect_Body_get_Activities_Length(RootSystem.IntPtr pNative);
public RootSystem.Collections.Generic.Dictionary<Windows.Kinect.Activity, Windows.Kinect.DetectionResult> Activities
{
get
{
if (_pNative == RootSystem.IntPtr.Zero)
{
throw new RootSystem.ObjectDisposedException("Body");
}
int outCollectionSize = Windows_Kinect_Body_get_Activities_Length(_pNative);
var outKeys = new Windows.Kinect.Activity[outCollectionSize];
var outValues = new Windows.Kinect.DetectionResult[outCollectionSize];
var managedDictionary = new RootSystem.Collections.Generic.Dictionary<Windows.Kinect.Activity, Windows.Kinect.DetectionResult>();
outCollectionSize = Windows_Kinect_Body_get_Activities(_pNative, outKeys, outValues, outCollectionSize);
for(int i=0;i<outCollectionSize;i++)
{
managedDictionary.Add(outKeys[i], outValues[i]);
}
return managedDictionary;
}
}
[RootSystem.Runtime.InteropServices.DllImport("XboxOneUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)]
private static extern int Windows_Kinect_Body_get_Appearance(RootSystem.IntPtr pNative, [RootSystem.Runtime.InteropServices.Out] Windows.Kinect.Appearance[] outKeys, [RootSystem.Runtime.InteropServices.Out] Windows.Kinect.DetectionResult[] outValues, int outCollectionSize);
[RootSystem.Runtime.InteropServices.DllImport("XboxOneUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)]
private static extern int Windows_Kinect_Body_get_Appearance_Length(RootSystem.IntPtr pNative);
public RootSystem.Collections.Generic.Dictionary<Windows.Kinect.Appearance, Windows.Kinect.DetectionResult> Appearance
{
get
{
if (_pNative == RootSystem.IntPtr.Zero)
{
throw new RootSystem.ObjectDisposedException("Body");
}
int outCollectionSize = Windows_Kinect_Body_get_Appearance_Length(_pNative);
var outKeys = new Windows.Kinect.Appearance[outCollectionSize];
var outValues = new Windows.Kinect.DetectionResult[outCollectionSize];
var managedDictionary = new RootSystem.Collections.Generic.Dictionary<Windows.Kinect.Appearance, Windows.Kinect.DetectionResult>();
outCollectionSize = Windows_Kinect_Body_get_Appearance(_pNative, outKeys, outValues, outCollectionSize);
for(int i=0;i<outCollectionSize;i++)
{
managedDictionary.Add(outKeys[i], outValues[i]);
}
return managedDictionary;
}
}
[RootSystem.Runtime.InteropServices.DllImport("XboxOneUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)]
private static extern Windows.Kinect.FrameEdges Windows_Kinect_Body_get_ClippedEdges(RootSystem.IntPtr pNative);
public Windows.Kinect.FrameEdges ClippedEdges
{
get
{
if (_pNative == RootSystem.IntPtr.Zero)
{
throw new RootSystem.ObjectDisposedException("Body");
}
return Windows_Kinect_Body_get_ClippedEdges(_pNative);
}
}
[RootSystem.Runtime.InteropServices.DllImport("XboxOneUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)]
private static extern Windows.Kinect.DetectionResult Windows_Kinect_Body_get_Engaged(RootSystem.IntPtr pNative);
public Windows.Kinect.DetectionResult Engaged
{
get
{
if (_pNative == RootSystem.IntPtr.Zero)
{
throw new RootSystem.ObjectDisposedException("Body");
}
return Windows_Kinect_Body_get_Engaged(_pNative);
}
}
[RootSystem.Runtime.InteropServices.DllImport("XboxOneUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)]
private static extern int Windows_Kinect_Body_get_Expressions(RootSystem.IntPtr pNative, [RootSystem.Runtime.InteropServices.Out] Windows.Kinect.Expression[] outKeys, [RootSystem.Runtime.InteropServices.Out] Windows.Kinect.DetectionResult[] outValues, int outCollectionSize);
[RootSystem.Runtime.InteropServices.DllImport("XboxOneUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)]
private static extern int Windows_Kinect_Body_get_Expressions_Length(RootSystem.IntPtr pNative);
public RootSystem.Collections.Generic.Dictionary<Windows.Kinect.Expression, Windows.Kinect.DetectionResult> Expressions
{
get
{
if (_pNative == RootSystem.IntPtr.Zero)
{
throw new RootSystem.ObjectDisposedException("Body");
}
int outCollectionSize = Windows_Kinect_Body_get_Expressions_Length(_pNative);
var outKeys = new Windows.Kinect.Expression[outCollectionSize];
var outValues = new Windows.Kinect.DetectionResult[outCollectionSize];
var managedDictionary = new RootSystem.Collections.Generic.Dictionary<Windows.Kinect.Expression, Windows.Kinect.DetectionResult>();
outCollectionSize = Windows_Kinect_Body_get_Expressions(_pNative, outKeys, outValues, outCollectionSize);
for(int i=0;i<outCollectionSize;i++)
{
managedDictionary.Add(outKeys[i], outValues[i]);
}
return managedDictionary;
}
}
[RootSystem.Runtime.InteropServices.DllImport("XboxOneUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)]
private static extern Windows.Kinect.TrackingConfidence Windows_Kinect_Body_get_HandLeftConfidence(RootSystem.IntPtr pNative);
public Windows.Kinect.TrackingConfidence HandLeftConfidence
{
get
{
if (_pNative == RootSystem.IntPtr.Zero)
{
throw new RootSystem.ObjectDisposedException("Body");
}
return Windows_Kinect_Body_get_HandLeftConfidence(_pNative);
}
}
[RootSystem.Runtime.InteropServices.DllImport("XboxOneUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)]
private static extern Windows.Kinect.HandState Windows_Kinect_Body_get_HandLeftState(RootSystem.IntPtr pNative);
public Windows.Kinect.HandState HandLeftState
{
get
{
if (_pNative == RootSystem.IntPtr.Zero)
{
throw new RootSystem.ObjectDisposedException("Body");
}
return Windows_Kinect_Body_get_HandLeftState(_pNative);
}
}
[RootSystem.Runtime.InteropServices.DllImport("XboxOneUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)]
private static extern Windows.Kinect.TrackingConfidence Windows_Kinect_Body_get_HandRightConfidence(RootSystem.IntPtr pNative);
public Windows.Kinect.TrackingConfidence HandRightConfidence
{
get
{
if (_pNative == RootSystem.IntPtr.Zero)
{
throw new RootSystem.ObjectDisposedException("Body");
}
return Windows_Kinect_Body_get_HandRightConfidence(_pNative);
}
}
[RootSystem.Runtime.InteropServices.DllImport("XboxOneUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)]
private static extern Windows.Kinect.HandState Windows_Kinect_Body_get_HandRightState(RootSystem.IntPtr pNative);
public Windows.Kinect.HandState HandRightState
{
get
{
if (_pNative == RootSystem.IntPtr.Zero)
{
throw new RootSystem.ObjectDisposedException("Body");
}
return Windows_Kinect_Body_get_HandRightState(_pNative);
}
}
[RootSystem.Runtime.InteropServices.DllImport("XboxOneUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)]
private static extern bool Windows_Kinect_Body_get_IsRestricted(RootSystem.IntPtr pNative);
public bool IsRestricted
{
get
{
if (_pNative == RootSystem.IntPtr.Zero)
{
throw new RootSystem.ObjectDisposedException("Body");
}
return Windows_Kinect_Body_get_IsRestricted(_pNative);
}
}
[RootSystem.Runtime.InteropServices.DllImport("XboxOneUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)]
private static extern bool Windows_Kinect_Body_get_IsTracked(RootSystem.IntPtr pNative);
public bool IsTracked
{
get
{
if (_pNative == RootSystem.IntPtr.Zero)
{
throw new RootSystem.ObjectDisposedException("Body");
}
return Windows_Kinect_Body_get_IsTracked(_pNative);
}
}
[RootSystem.Runtime.InteropServices.DllImport("XboxOneUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)]
private static extern int Windows_Kinect_Body_get_JointOrientations(RootSystem.IntPtr pNative, [RootSystem.Runtime.InteropServices.Out] Windows.Kinect.JointType[] outKeys, [RootSystem.Runtime.InteropServices.Out] Windows.Kinect.JointOrientation[] outValues, int outCollectionSize);
[RootSystem.Runtime.InteropServices.DllImport("XboxOneUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)]
private static extern int Windows_Kinect_Body_get_JointOrientations_Length(RootSystem.IntPtr pNative);
public RootSystem.Collections.Generic.Dictionary<Windows.Kinect.JointType, Windows.Kinect.JointOrientation> JointOrientations
{
get
{
if (_pNative == RootSystem.IntPtr.Zero)
{
throw new RootSystem.ObjectDisposedException("Body");
}
int outCollectionSize = Windows_Kinect_Body_get_JointOrientations_Length(_pNative);
var outKeys = new Windows.Kinect.JointType[outCollectionSize];
var outValues = new Windows.Kinect.JointOrientation[outCollectionSize];
var managedDictionary = new RootSystem.Collections.Generic.Dictionary<Windows.Kinect.JointType, Windows.Kinect.JointOrientation>();
outCollectionSize = Windows_Kinect_Body_get_JointOrientations(_pNative, outKeys, outValues, outCollectionSize);
for(int i=0;i<outCollectionSize;i++)
{
managedDictionary.Add(outKeys[i], outValues[i]);
}
return managedDictionary;
}
}
[RootSystem.Runtime.InteropServices.DllImport("XboxOneUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)]
private static extern int Windows_Kinect_Body_get_Joints(RootSystem.IntPtr pNative, [RootSystem.Runtime.InteropServices.Out] Windows.Kinect.JointType[] outKeys, [RootSystem.Runtime.InteropServices.Out] Windows.Kinect.Joint[] outValues, int outCollectionSize);
[RootSystem.Runtime.InteropServices.DllImport("XboxOneUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)]
private static extern int Windows_Kinect_Body_get_Joints_Length(RootSystem.IntPtr pNative);
public RootSystem.Collections.Generic.Dictionary<Windows.Kinect.JointType, Windows.Kinect.Joint> Joints
{
get
{
if (_pNative == RootSystem.IntPtr.Zero)
{
throw new RootSystem.ObjectDisposedException("Body");
}
int outCollectionSize = Windows_Kinect_Body_get_Joints_Length(_pNative);
var outKeys = new Windows.Kinect.JointType[outCollectionSize];
var outValues = new Windows.Kinect.Joint[outCollectionSize];
var managedDictionary = new RootSystem.Collections.Generic.Dictionary<Windows.Kinect.JointType, Windows.Kinect.Joint>();
outCollectionSize = Windows_Kinect_Body_get_Joints(_pNative, outKeys, outValues, outCollectionSize);
for(int i=0;i<outCollectionSize;i++)
{
managedDictionary.Add(outKeys[i], outValues[i]);
}
return managedDictionary;
}
}
[RootSystem.Runtime.InteropServices.DllImport("XboxOneUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)]
private static extern Windows.Kinect.TrackingState Windows_Kinect_Body_get_LeanTrackingState(RootSystem.IntPtr pNative);
public Windows.Kinect.TrackingState LeanTrackingState
{
get
{
if (_pNative == RootSystem.IntPtr.Zero)
{
throw new RootSystem.ObjectDisposedException("Body");
}
return Windows_Kinect_Body_get_LeanTrackingState(_pNative);
}
}
[RootSystem.Runtime.InteropServices.DllImport("XboxOneUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)]
private static extern ulong Windows_Kinect_Body_get_TrackingId(RootSystem.IntPtr pNative);
public ulong TrackingId
{
get
{
if (_pNative == RootSystem.IntPtr.Zero)
{
throw new RootSystem.ObjectDisposedException("Body");
}
return Windows_Kinect_Body_get_TrackingId(_pNative);
}
}
[RootSystem.Runtime.InteropServices.DllImport("XboxOneUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)]
private static extern int Windows_Kinect_Body_get_JointCount();
public static int JointCount
{
get
{
return Windows_Kinect_Body_get_JointCount();
}
}
// Public Methods
}
}
| |
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System.Collections.Generic;
using System;
using frame8.Logic.Misc.Visual.UI.ScrollRectItemsAdapter;
/*
BRIEF INSTRUCTIONS (It's recommended to manually go through example code in order to fully understand the mechanism)
1. create your own implementation of BaseItemViewsHolder, let's name it MyItemViewsHolder
2. create your own implementation of BaseParams (if needed), let's name it MyParams
3. create your own implementation of ScrollRectItemsAdapter8<MyParams, MyItemViewsHolder>, let's name it MyScrollRectItemsAdapter
4. instantiate MyScrollRectItemsAdapter
5. call MyScrollRectItemsAdapter.ChangeItemCountTo(int count) once (and any time your dataset is changed) and these two things will happen:
1.
if the scroll rect has vertical scrolling (only top-to-bottom is currently supported), MyScrollRectItemsAdapter.GetItemHeight(int index) will be called <count> times (with index going from 0 to <count-1>)
else if the scroll rect has horizontal scrolling (only left-to-right is currently supported), MyScrollRectItemsAdapter.GetItemWidth(int index) will ...[idem above]...
2. MyScrollRectItemsAdapter.InitOrUpdateItemViewHolder(MyItemViewsHolder newOrRecycledViewsHolder) will be called ONLY for the items currently visible and each time a new one will become visible:
- use newOrRecycledViewsHolder.itemIndex to get the item index, so you can retrieve its associated data model from your data set
- newOrRecycledViewsHolder.root will be null if the item is not recycled. So you need to instantiate your prefab (or whatever), assign it and call newOrRecycledViewsHolder.CollectViews()
- newOrRecycledViewsHolder.root won't be null if the item is recycled. This means that it's assigned a valid object whose UI elements only need their values changed
- update newOrRecycledViewsHolder's views from it's associated data model
*/
public class ScrollRectItemsAdapterExample : MonoBehaviour
{
[SerializeField]
MyParams _ScrollRectAdapterParams;
MyScrollRectItemsAdapter _ScrollRectItemsAdapter;
List<SampleObjectModel> _Data;
public BaseParams Params { get { return _ScrollRectAdapterParams; } }
public MyScrollRectItemsAdapter Adapter { get { return _ScrollRectItemsAdapter; } }
public List<SampleObjectModel> Data { get { return _Data; } }
IEnumerator Start()
{
// Wait for Unity's layout (UI scaling etc.)
yield return null;
yield return null;
yield return null;
yield return null;
_Data = new List<SampleObjectModel>();
int currentItemNum = 0;
_ScrollRectItemsAdapter = new MyScrollRectItemsAdapter(_Data, _ScrollRectAdapterParams);
_ScrollRectAdapterParams.updateItemsButton.onClick.AddListener(() =>
{
_Data.Clear();
int capacity = 0;
int.TryParse(_ScrollRectAdapterParams.numItemsInputField.text, out capacity);
_Data.Capacity = capacity;
for (int i = 0; i < capacity; ++i)
{
_Data.Add(new SampleObjectModel("Item " + i/* + currentItemNum++*/));
}
_ScrollRectItemsAdapter.ChangeItemCountTo(capacity);
});
}
void OnDestroy()
{
if (_ScrollRectItemsAdapter != null)
_ScrollRectItemsAdapter.Dispose();
}
// This is your data model
// this one will generate 5 random colors
public class SampleObjectModel
{
public string objectName;
public Color aColor, bColor, cColor, dColor, eColor;
public bool expanded;
public SampleObjectModel(string name)
{
objectName = name;
aColor = GetRandomColor();
bColor = GetRandomColor();
cColor = GetRandomColor();
dColor = GetRandomColor();
eColor = GetRandomColor();
}
Color GetRandomColor()
{
return new Color(UnityEngine.Random.Range(0f, 1f), UnityEngine.Random.Range(0f, 1f), UnityEngine.Random.Range(0f, 1f), UnityEngine.Random.Range(0f, 1f));
}
}
public sealed class MyItemsViewHolder : BaseItemViewsHolder
{
public Text objectTitle;
public Image a, b, c, d, e;
public ExpandCollapseOnClick expandOnCollapseComponent;
public override void CollectViews()
{
base.CollectViews();
a = root.GetChild(0).GetChild(0).GetComponent<Image>();
b = root.GetChild(0).GetChild(1).GetComponent<Image>();
c = root.GetChild(0).GetChild(2).GetComponent<Image>();
d = root.GetChild(0).GetChild(3).GetComponent<Image>();
e = root.GetChild(0).GetChild(4).GetComponent<Image>();
objectTitle = root.GetChild(0).GetChild(5).GetComponentInChildren<Text>();
expandOnCollapseComponent = root.GetComponent<ExpandCollapseOnClick>();
}
}
[Serializable]
public class MyParams : BaseParams
{
public RectTransform itemPrefab;
public Toggle randomizeSizesToggle;
public InputField numItemsInputField;
public Button updateItemsButton;
}
public sealed class MyScrollRectItemsAdapter : ScrollRectItemsAdapter8<MyParams, MyItemsViewHolder>, ExpandCollapseOnClick.ISizeChangesHandler
{
bool _RandomizeSizes;
float _PrefabSize;
float[] _ItemsSizessToUse;
List<SampleObjectModel> _Data;
public MyScrollRectItemsAdapter(List<SampleObjectModel> data, MyParams parms)
{
_Data = data;
if (parms.scrollRect.horizontal)
_PrefabSize = parms.itemPrefab.rect.width;
else
_PrefabSize = parms.itemPrefab.rect.height;
InitSizes(false);
parms.randomizeSizesToggle.onValueChanged.AddListener((value) => _RandomizeSizes = value);
// Need to call Init(Params) AFTER we init our stuff, because both GetItem[Height|Width]() and InitOrUpdateItemViewHolder() will be called in this method
Init(parms);
}
void InitSizes(bool random)
{
int newCount = _Data.Count;
if (_ItemsSizessToUse == null || newCount != _ItemsSizessToUse.Length)
_ItemsSizessToUse = new float[newCount];
if (random)
for (int i = 0; i < newCount; ++i)
_ItemsSizessToUse[i] = UnityEngine.Random.Range(30, 400);
else
for (int i = 0; i < newCount; ++i)
_ItemsSizessToUse[i] = _PrefabSize;
}
public override void ChangeItemCountTo(int itemsCount)
{
// Keep the mocked heights array's size up to date, so the GetItemHeight(int) callback won't throw an index out of bounds exception
InitSizes(_RandomizeSizes);
base.ChangeItemCountTo(itemsCount);
}
// Remember, only GetItemHeight (for vertical scroll) or GetItemWidth (for horizontal scroll) will be called
protected override float GetItemHeight(int index)
{
return _ItemsSizessToUse[index];
}
// Remember, only GetItemHeight (for vertical scroll) or GetItemWidth (for horizontal scroll) will be called
protected override float GetItemWidth(int index)
{
return _ItemsSizessToUse[index];
}
protected override void InitOrUpdateItemViewHolder(MyItemsViewHolder newOrRecycled)
{
// Recycling process handling
if (newOrRecycled.root == null) // new
{
// Note: you can use whatever prefab you want... you can have multiple prefabs, you can create/change them dynamically etc. it's up to your imagination and needs :)
newOrRecycled.root = (GameObject.Instantiate(_Params.itemPrefab.gameObject) as GameObject).GetComponent<RectTransform>();
newOrRecycled.root.gameObject.SetActive(true); // just in case the prefab started inactive
newOrRecycled.CollectViews();
}
// optionally rename the object
newOrRecycled.root.name = "ListItem " + newOrRecycled.itemIndex;
// Populating with data from associated model
SampleObjectModel dataModel = _Data[newOrRecycled.itemIndex];
newOrRecycled.objectTitle.text = dataModel.objectName + " [Size:" + _ItemsSizessToUse[newOrRecycled.itemIndex] + "]";
newOrRecycled.a.color = dataModel.aColor;
newOrRecycled.b.color = dataModel.bColor;
newOrRecycled.c.color = dataModel.cColor;
newOrRecycled.d.color = dataModel.dColor;
newOrRecycled.e.color = dataModel.eColor;
if (newOrRecycled.expandOnCollapseComponent)
{
newOrRecycled.expandOnCollapseComponent.sizeChangesHandler = this;
newOrRecycled.expandOnCollapseComponent.expanded = dataModel.expanded;
if (!dataModel.expanded)
newOrRecycled.expandOnCollapseComponent.nonExpandedSize = _ItemsSizessToUse[newOrRecycled.itemIndex];
}
}
#region ExpandCollapseOnClick.ISizeChangesHandler implementation
bool ExpandCollapseOnClick.ISizeChangesHandler.HandleSizeChangeRequest(RectTransform rt, float newSize)
{
var vh = GetItemViewsHolderIfVisible(rt);
// If the vh is visible and the request is accepted, we update our list of sizes
if (vh != null)
{
float resolvedSize = RequestChangeItemSizeAndUpdateLayout(vh, newSize);
if (resolvedSize != -1f)
{
_ItemsSizessToUse[vh.itemIndex] = newSize;
return true;
}
}
return false;
}
public void OnExpandedStateChanged(RectTransform rt, bool expanded)
{
var vh = GetItemViewsHolderIfVisible(rt);
// If the vh is visible and the request is accepted, we update the model's "expanded" field
if (vh != null)
_Data[vh.itemIndex].expanded = expanded;
}
#endregion
}
}
| |
using Microsoft.IdentityModel;
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.S2S.Tokens;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.EventReceivers;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.ServiceModel;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Web.Script.Serialization;
using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction;
using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException;
using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration;
using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials;
namespace Provision.Cloud.Async.WebJob.Console.Create
{
public static class TokenHelper
{
#region public fields
/// <summary>
/// SharePoint principal.
/// </summary>
public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000";
/// <summary>
/// Lifetime of HighTrust access token, 12 hours.
/// </summary>
public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0);
#endregion public fields
#region public methods
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequest request)
{
return GetContextTokenFromRequest(new HttpRequestWrapper(request));
}
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequestBase request)
{
string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" };
foreach (string paramName in paramNames)
{
if (!string.IsNullOrEmpty(request.Form[paramName]))
{
return request.Form[paramName];
}
if (!string.IsNullOrEmpty(request.QueryString[paramName]))
{
return request.QueryString[paramName];
}
}
return null;
}
/// <summary>
/// Validate that a specified context token string is intended for this application based on the parameters
/// specified in web.config. Parameters used from web.config used for validation include ClientId,
/// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present,
/// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not
/// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an
/// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents
/// and a JsonWebSecurityToken based on the context token is returned.
/// </summary>
/// <param name="contextTokenString">The context token to validate</param>
/// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation.
/// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used
/// for validation instead of <paramref name="appHostName"/> .</param>
/// <returns>A JsonWebSecurityToken based on the context token.</returns>
public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null)
{
JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler();
SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString);
JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken;
SharePointContextToken token = SharePointContextToken.Create(jsonToken);
string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority;
int firstDot = stsAuthority.IndexOf('.');
GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot);
AcsHostUrl = stsAuthority.Substring(firstDot + 1);
tokenHandler.ValidateToken(jsonToken);
string[] acceptableAudiences;
if (!String.IsNullOrEmpty(HostedAppHostNameOverride))
{
acceptableAudiences = HostedAppHostNameOverride.Split(';');
}
else if (appHostName == null)
{
acceptableAudiences = new[] { HostedAppHostName };
}
else
{
acceptableAudiences = new[] { appHostName };
}
bool validationSuccessful = false;
string realm = Realm ?? token.Realm;
foreach (var audience in acceptableAudiences)
{
string principal = GetFormattedPrincipal(ClientId, audience, realm);
if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal))
{
validationSuccessful = true;
break;
}
}
if (!validationSuccessful)
{
throw new AudienceUriValidationFailedException(
String.Format(CultureInfo.CurrentCulture,
"\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience));
}
return token;
}
/// <summary>
/// Retrieves an access token from ACS to call the source of the specified context token at the specified
/// targetHost. The targetHost must be registered for the principal that sent the context token.
/// </summary>
/// <param name="contextToken">Context token issued by the intended access token audience</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <returns>An access token with an audience matching the context token's source</returns>
public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost)
{
string targetPrincipalName = contextToken.TargetPrincipalName;
// Extract the refreshToken from the context token
string refreshToken = contextToken.RefreshToken;
if (String.IsNullOrEmpty(refreshToken))
{
return null;
}
string targetRealm = Realm ?? contextToken.Realm;
return GetAccessToken(refreshToken,
targetPrincipalName,
targetHost,
targetRealm);
}
/// <summary>
/// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="authorizationCode">Authorization code to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string authorizationCode,
string targetPrincipalName,
string targetHost,
string targetRealm,
Uri redirectUri)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
// Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered
OAuth2AccessTokenRequest oauth2Request =
OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode(
clientId,
ClientSecret,
authorizationCode,
redirectUri,
resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="refreshToken">Refresh token to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string refreshToken,
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Retrieves an app-only access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAppOnlyAccessToken(
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource);
oauth2Request.Resource = resource;
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Creates a client context based on the properties of a remote event receiver
/// </summary>
/// <param name="properties">Properties of a remote event receiver</param>
/// <returns>A ClientContext ready to call the web where the event originated</returns>
public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties)
{
Uri sharepointUrl;
if (properties.ListEventProperties != null)
{
sharepointUrl = new Uri(properties.ListEventProperties.WebUrl);
}
else if (properties.ItemEventProperties != null)
{
sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl);
}
else if (properties.WebEventProperties != null)
{
sharepointUrl = new Uri(properties.WebEventProperties.FullUrl);
}
else
{
return null;
}
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Creates a client context based on the properties of an app event
/// </summary>
/// <param name="properties">Properties of an app event</param>
/// <param name="useAppWeb">True to target the app web, false to target the host web</param>
/// <returns>A ClientContext ready to call the app web or the parent web</returns>
public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb)
{
if (properties.AppEventProperties == null)
{
return null;
}
Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl;
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string authorizationCode,
Uri redirectUri)
{
return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="targetPrincipalName">Name of the target SharePoint principal</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string targetPrincipalName,
string authorizationCode,
string targetRealm,
Uri redirectUri)
{
Uri targetUri = new Uri(targetUrl);
string accessToken =
GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Uses the specified access token to create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="accessToken">Access token to be used when calling the specified targetUrl</param>
/// <returns>A ClientContext ready to call targetUrl with the specified access token</returns>
public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken)
{
ClientContext clientContext = new ClientContext(targetUrl);
clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous;
clientContext.FormDigestHandlingEnabled = false;
clientContext.ExecutingWebRequest +=
delegate(object oSender, WebRequestEventArgs webRequestEventArgs)
{
webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] =
"Bearer " + accessToken;
};
return clientContext;
}
/// <summary>
/// Retrieves an access token from ACS using the specified context token, and uses that access token to create
/// a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="contextTokenString">Context token received from the target SharePoint site</param>
/// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName
/// of web.config will be used instead</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithContextToken(
string targetUrl,
string contextTokenString,
string appHostUrl)
{
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl);
Uri targetUri = new Uri(targetUrl);
string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is
/// granted</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope,
redirectUri);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request a new context token.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param>
/// <returns>Url of the SharePoint site's context token redirect page</returns>
public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri)
{
return string.Format(
"{0}{1}?client_id={2}&redirect_uri={3}",
EnsureTrailingSlash(contextUrl),
RedirectPage,
ClientId,
redirectUri);
}
/// <summary>
/// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified
/// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in
/// web.config, an auth challenge will be issued to the targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>An access token with an audience of the target principal</returns>
public static string GetS2SAccessTokenWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
}
/// <summary>
/// Retrieves an S2S client context with an access token signed by the application's private certificate on
/// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the
/// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the
/// targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>A ClientContext using an access token with an audience of the target application</returns>
public static ClientContext GetS2SClientContextWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken);
}
/// <summary>
/// Get authentication realm from SharePoint
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <returns>String representation of the realm GUID</returns>
public static string GetRealmFromTargetUrl(Uri targetApplicationUri)
{
WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc");
request.Headers.Add("Authorization: Bearer ");
try
{
using (request.GetResponse())
{
}
}
catch (WebException e)
{
if (e.Response == null)
{
return null;
}
string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"];
if (string.IsNullOrEmpty(bearerResponseHeader))
{
return null;
}
const string bearer = "Bearer realm=\"";
int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal);
if (bearerIndex < 0)
{
return null;
}
int realmIndex = bearerIndex + bearer.Length;
if (bearerResponseHeader.Length >= realmIndex + 36)
{
string targetRealm = bearerResponseHeader.Substring(realmIndex, 36);
Guid realmGuid;
if (Guid.TryParse(targetRealm, out realmGuid))
{
return targetRealm;
}
}
}
return null;
}
/// <summary>
/// Determines if this is a high trust app.
/// </summary>
/// <returns>True if this is a high trust app.</returns>
public static bool IsHighTrustApp()
{
return SigningCredentials != null;
}
/// <summary>
/// Ensures that the specified URL ends with '/' if it is not null or empty.
/// </summary>
/// <param name="url">The url.</param>
/// <returns>The url ending with '/' if it is not null or empty.</returns>
public static string EnsureTrailingSlash(string url)
{
if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/')
{
return url + "/";
}
return url;
}
#endregion
#region private fields
//
// Configuration Constants
//
private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx";
private const string RedirectPage = "_layouts/15/AppRedirect.aspx";
private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000";
private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1";
private const string S2SProtocol = "OAuth2";
private const string DelegationIssuance = "DelegationIssuance1.0";
private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier;
private const string TrustedForImpersonationClaimType = "trustedfordelegation";
private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken;
//
// Environment Constants
//
private static string GlobalEndPointPrefix = "accounts";
private static string AcsHostUrl = "accesscontrol.windows.net";
//
// Hosted app configuration
//
private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId");
private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId");
private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride");
private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName");
private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret");
private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret");
private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath");
private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword");
private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword);
private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest);
#endregion
#region private methods
private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl)
{
string contextTokenString = properties.ContextToken;
if (String.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host);
string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken;
return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken);
}
private static string GetAcsMetadataEndpointUrl()
{
return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl);
}
private static string GetFormattedPrincipal(string principalName, string hostName, string realm)
{
if (!String.IsNullOrEmpty(hostName))
{
return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm);
}
return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm);
}
private static string GetAcsPrincipalName(string realm)
{
return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm);
}
private static string GetAcsGlobalEndpointUrl()
{
return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl);
}
private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler()
{
JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler();
handler.Configuration = new SecurityTokenHandlerConfiguration();
handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never);
handler.Configuration.CertificateValidator = X509CertificateValidator.None;
List<byte[]> securityKeys = new List<byte[]>();
securityKeys.Add(Convert.FromBase64String(ClientSecret));
if (!string.IsNullOrEmpty(SecondaryClientSecret))
{
securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret));
}
List<SecurityToken> securityTokens = new List<SecurityToken>();
securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys));
handler.Configuration.IssuerTokenResolver =
SecurityTokenResolver.CreateDefaultSecurityTokenResolver(
new ReadOnlyCollection<SecurityToken>(securityTokens),
false);
SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry();
foreach (byte[] securitykey in securityKeys)
{
issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace));
}
handler.Configuration.IssuerNameRegistry = issuerNameRegistry;
return handler;
}
private static string GetS2SAccessTokenWithClaims(
string targetApplicationHostName,
string targetRealm,
IEnumerable<JsonWebTokenClaim> claims)
{
return IssueToken(
ClientId,
IssuerId,
targetRealm,
SharePointPrincipal,
targetRealm,
targetApplicationHostName,
true,
claims,
claims == null);
}
private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity)
{
JsonWebTokenClaim[] claims = new JsonWebTokenClaim[]
{
new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()),
new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory")
};
return claims;
}
private static string IssueToken(
string sourceApplication,
string issuerApplication,
string sourceRealm,
string targetApplication,
string targetRealm,
string targetApplicationHostName,
bool trustedForDelegation,
IEnumerable<JsonWebTokenClaim> claims,
bool appOnly = false)
{
if (null == SigningCredentials)
{
throw new InvalidOperationException("SigningCredentials was not initialized");
}
#region Actor token
string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm);
string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm);
string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm);
List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>();
actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid));
if (trustedForDelegation && !appOnly)
{
actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true"));
}
// Create token
JsonWebSecurityToken actorToken = new JsonWebSecurityToken(
issuer: issuer,
audience: audience,
validFrom: DateTime.UtcNow,
validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
signingCredentials: SigningCredentials,
claims: actorClaims);
string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken);
if (appOnly)
{
// App-only token is the same as actor token for delegated case
return actorTokenString;
}
#endregion Actor token
#region Outer token
List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims);
outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString));
JsonWebSecurityToken jsonToken = new JsonWebSecurityToken(
nameid, // outer token issuer should match actor token nameid
audience,
DateTime.UtcNow,
DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
outerClaims);
string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken);
#endregion Outer token
return accessToken;
}
#endregion
#region AcsMetadataParser
// This class is used to get MetaData document from the global STS endpoint. It contains
// methods to parse the MetaData document and get endpoints and STS certificate.
public static class AcsMetadataParser
{
public static X509Certificate2 GetAcsSigningCert(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
if (null != document.keys && document.keys.Count > 0)
{
JsonKey signingKey = document.keys[0];
if (null != signingKey && null != signingKey.keyValue)
{
return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value));
}
}
throw new Exception("Metadata document does not contain ACS signing certificate.");
}
public static string GetDelegationServiceUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance);
if (null != delegationEndpoint)
{
return delegationEndpoint.location;
}
throw new Exception("Metadata document does not contain Delegation Service endpoint Url");
}
private static JsonMetadataDocument GetMetadataDocument(string realm)
{
string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}",
GetAcsMetadataEndpointUrl(),
realm);
byte[] acsMetadata;
using (WebClient webClient = new WebClient())
{
acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm);
}
string jsonResponseString = Encoding.UTF8.GetString(acsMetadata);
JavaScriptSerializer serializer = new JavaScriptSerializer();
JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString);
if (null == document)
{
throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm);
}
return document;
}
public static string GetStsUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol);
if (null != s2sEndpoint)
{
return s2sEndpoint.location;
}
throw new Exception("Metadata document does not contain STS endpoint url");
}
private class JsonMetadataDocument
{
public string serviceName { get; set; }
public List<JsonEndpoint> endpoints { get; set; }
public List<JsonKey> keys { get; set; }
}
private class JsonEndpoint
{
public string location { get; set; }
public string protocol { get; set; }
public string usage { get; set; }
}
private class JsonKeyValue
{
public string type { get; set; }
public string value { get; set; }
}
private class JsonKey
{
public string usage { get; set; }
public JsonKeyValue keyValue { get; set; }
}
}
#endregion
}
/// <summary>
/// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token
/// </summary>
public class SharePointContextToken : JsonWebSecurityToken
{
public static SharePointContextToken Create(JsonWebSecurityToken contextToken)
{
return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims);
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims)
: base(issuer, audience, validFrom, validTo, claims)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken)
: base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials)
: base(issuer, audience, validFrom, validTo, claims, signingCredentials)
{
}
public string NameId
{
get
{
return GetClaimValue(this, "nameid");
}
}
/// <summary>
/// The principal name portion of the context token's "appctxsender" claim
/// </summary>
public string TargetPrincipalName
{
get
{
string appctxsender = GetClaimValue(this, "appctxsender");
if (appctxsender == null)
{
return null;
}
return appctxsender.Split('@')[0];
}
}
/// <summary>
/// The context token's "refreshtoken" claim
/// </summary>
public string RefreshToken
{
get
{
return GetClaimValue(this, "refreshtoken");
}
}
/// <summary>
/// The context token's "CacheKey" claim
/// </summary>
public string CacheKey
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string cacheKey = (string)dict["CacheKey"];
return cacheKey;
}
}
/// <summary>
/// The context token's "SecurityTokenServiceUri" claim
/// </summary>
public string SecurityTokenServiceUri
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"];
return securityTokenServiceUri;
}
}
/// <summary>
/// The realm portion of the context token's "audience" claim
/// </summary>
public string Realm
{
get
{
string aud = Audience;
if (aud == null)
{
return null;
}
string tokenRealm = aud.Substring(aud.IndexOf('@') + 1);
return tokenRealm;
}
}
private static string GetClaimValue(JsonWebSecurityToken token, string claimType)
{
if (token == null)
{
throw new ArgumentNullException("token");
}
foreach (JsonWebTokenClaim claim in token.Claims)
{
if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType))
{
return claim.Value;
}
}
return null;
}
}
/// <summary>
/// Represents a security token which contains multiple security keys that are generated using symmetric algorithms.
/// </summary>
public class MultipleSymmetricKeySecurityToken : SecurityToken
{
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys)
: this(UniqueId.CreateUniqueId(), keys)
{
}
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="tokenId">The unique identifier of the security token.</param>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys)
{
if (keys == null)
{
throw new ArgumentNullException("keys");
}
if (String.IsNullOrEmpty(tokenId))
{
throw new ArgumentException("Value cannot be a null or empty string.", "tokenId");
}
foreach (byte[] key in keys)
{
if (key.Length <= 0)
{
throw new ArgumentException("The key length must be greater then zero.", "keys");
}
}
id = tokenId;
effectiveTime = DateTime.UtcNow;
securityKeys = CreateSymmetricSecurityKeys(keys);
}
/// <summary>
/// Gets the unique identifier of the security token.
/// </summary>
public override string Id
{
get
{
return id;
}
}
/// <summary>
/// Gets the cryptographic keys associated with the security token.
/// </summary>
public override ReadOnlyCollection<SecurityKey> SecurityKeys
{
get
{
return securityKeys.AsReadOnly();
}
}
/// <summary>
/// Gets the first instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidFrom
{
get
{
return effectiveTime;
}
}
/// <summary>
/// Gets the last instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidTo
{
get
{
// Never expire
return DateTime.MaxValue;
}
}
/// <summary>
/// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier.
/// </summary>
/// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param>
/// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns>
public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause)
{
if (keyIdentifierClause == null)
{
throw new ArgumentNullException("keyIdentifierClause");
}
// Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the
// presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later
// when the key is matched to the issuer.
if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause)
{
return true;
}
return base.MatchesKeyIdentifierClause(keyIdentifierClause);
}
#region private members
private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys)
{
List<SecurityKey> symmetricKeys = new List<SecurityKey>();
foreach (byte[] key in keys)
{
symmetricKeys.Add(new InMemorySymmetricSecurityKey(key));
}
return symmetricKeys;
}
private string id;
private DateTime effectiveTime;
private List<SecurityKey> securityKeys;
#endregion
}
}
| |
/**
* LookupService.cs
*
* Copyright (C) 2008 MaxMind Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
using System;
using System.IO;
using System.Net;
using System.Runtime.CompilerServices;
namespace LogImporter.GeoIp
{
public class LookupService : IDisposable
{
private FileStream file = null;
private DatabaseInfo databaseInfo = null;
private byte databaseType = Convert.ToByte(DatabaseInfo.COUNTRY_EDITION);
private int[] databaseSegments;
private int recordLength;
private readonly int dboptions;
private byte[] dbbuffer;
private static readonly Country unknownCountry = new Country("--", "N/A");
private const int CountryBegin = 16776960;
private const int StructureInfoMaxSize = 20;
private const int DatabaseInfoMaxSize = 100;
private const int FullRecordLength = 100;//???
private const int SegmentRecordLength = 3;
private const int StandardRecordLength = 3;
private const int OrgRecordLength = 4;
private const int MaxRecordLength = 4;
private const int MaxOrgRecordLength = 1000;//???
private const int FipsRange = 360;
private const int StateBeginRev0 = 16700000;
private const int StateBeginRev1 = 16000000;
private const int USOffset = 1;
private const int CanadaOffset = 677;
private const int WorldOffset = 1353;
public const int GeoipStandard = 0;
public const int GeoipMemoryCache = 1;
public const int GeoipUnknownSpeed = 0;
public const int GeoipDialupSpeed = 1;
public const int GeoipCabledslSpeed = 2;
public const int GeoipCorporateSpeed = 3;
private static readonly String[] countryCode =
{
"--", "AP", "EU", "AD", "AE", "AF", "AG", "AI", "AL", "AM", "AN", "AO", "AQ", "AR",
"AS", "AT", "AU", "AW", "AZ", "BA", "BB", "BD", "BE", "BF", "BG", "BH", "BI", "BJ",
"BM", "BN", "BO", "BR", "BS", "BT", "BV", "BW", "BY", "BZ", "CA", "CC", "CD", "CF",
"CG", "CH", "CI", "CK", "CL", "CM", "CN", "CO", "CR", "CU", "CV", "CX", "CY", "CZ",
"DE", "DJ", "DK", "DM", "DO", "DZ", "EC", "EE", "EG", "EH", "ER", "ES", "ET", "FI",
"FJ", "FK", "FM", "FO", "FR", "FX", "GA", "GB", "GD", "GE", "GF", "GH", "GI", "GL",
"GM", "GN", "GP", "GQ", "GR", "GS", "GT", "GU", "GW", "GY", "HK", "HM", "HN", "HR",
"HT", "HU", "ID", "IE", "IL", "IN", "IO", "IQ", "IR", "IS", "IT", "JM", "JO", "JP",
"KE", "KG", "KH", "KI", "KM", "KN", "KP", "KR", "KW", "KY", "KZ", "LA", "LB", "LC",
"LI", "LK", "LR", "LS", "LT", "LU", "LV", "LY", "MA", "MC", "MD", "MG", "MH", "MK",
"ML", "MM", "MN", "MO", "MP", "MQ", "MR", "MS", "MT", "MU", "MV", "MW", "MX", "MY",
"MZ", "NA", "NC", "NE", "NF", "NG", "NI", "NL", "NO", "NP", "NR", "NU", "NZ", "OM",
"PA", "PE", "PF", "PG", "PH", "PK", "PL", "PM", "PN", "PR", "PS", "PT", "PW", "PY",
"QA", "RE", "RO", "RU", "RW", "SA", "SB", "SC", "SD", "SE", "SG", "SH", "SI", "SJ",
"SK", "SL", "SM", "SN", "SO", "SR", "ST", "SV", "SY", "SZ", "TC", "TD", "TF", "TG",
"TH", "TJ", "TK", "TM", "TN", "TO", "TL", "TR", "TT", "TV", "TW", "TZ", "UA", "UG",
"UM", "US", "UY", "UZ", "VA", "VC", "VE", "VG", "VI", "VN", "VU", "WF", "WS", "YE",
"YT", "RS", "ZA", "ZM", "ME", "ZW", "A1", "A2", "O1", "AX", "GG", "IM", "JE", "BL",
"MF"
};
private static readonly String[] countryName =
{
"N/A", "Asia/Pacific Region", "Europe", "Andorra", "United Arab Emirates",
"Afghanistan", "Antigua and Barbuda", "Anguilla", "Albania", "Armenia",
"Netherlands Antilles", "Angola", "Antarctica", "Argentina", "American Samoa",
"Austria", "Australia", "Aruba", "Azerbaijan", "Bosnia and Herzegovina",
"Barbados", "Bangladesh", "Belgium", "Burkina Faso", "Bulgaria", "Bahrain",
"Burundi", "Benin", "Bermuda", "Brunei Darussalam", "Bolivia", "Brazil", "Bahamas",
"Bhutan", "Bouvet Island", "Botswana", "Belarus", "Belize", "Canada",
"Cocos (Keeling) Islands", "Congo, The Democratic Republic of the",
"Central African Republic", "Congo", "Switzerland", "Cote D'Ivoire",
"Cook Islands", "Chile", "Cameroon", "China", "Colombia", "Costa Rica", "Cuba",
"Cape Verde", "Christmas Island", "Cyprus", "Czech Republic", "Germany",
"Djibouti", "Denmark", "Dominica", "Dominican Republic", "Algeria", "Ecuador",
"Estonia", "Egypt", "Western Sahara", "Eritrea", "Spain", "Ethiopia", "Finland",
"Fiji", "Falkland Islands (Malvinas)", "Micronesia, Federated States of",
"Faroe Islands", "France", "France, Metropolitan", "Gabon", "United Kingdom",
"Grenada", "Georgia", "French Guiana", "Ghana", "Gibraltar", "Greenland", "Gambia",
"Guinea", "Guadeloupe", "Equatorial Guinea", "Greece",
"South Georgia and the South Sandwich Islands", "Guatemala", "Guam",
"Guinea-Bissau", "Guyana", "Hong Kong", "Heard Island and McDonald Islands",
"Honduras", "Croatia", "Haiti", "Hungary", "Indonesia", "Ireland", "Israel", "India",
"British Indian Ocean Territory", "Iraq", "Iran, Islamic Republic of",
"Iceland", "Italy", "Jamaica", "Jordan", "Japan", "Kenya", "Kyrgyzstan", "Cambodia",
"Kiribati", "Comoros", "Saint Kitts and Nevis",
"Korea, Democratic People's Republic of", "Korea, Republic of", "Kuwait",
"Cayman Islands", "Kazakhstan", "Lao People's Democratic Republic", "Lebanon",
"Saint Lucia", "Liechtenstein", "Sri Lanka", "Liberia", "Lesotho", "Lithuania",
"Luxembourg", "Latvia", "Libyan Arab Jamahiriya", "Morocco", "Monaco",
"Moldova, Republic of", "Madagascar", "Marshall Islands",
"Macedonia, the Former Yugoslav Republic of", "Mali", "Myanmar", "Mongolia",
"Macau", "Northern Mariana Islands", "Martinique", "Mauritania", "Montserrat",
"Malta", "Mauritius", "Maldives", "Malawi", "Mexico", "Malaysia", "Mozambique",
"Namibia", "New Caledonia", "Niger", "Norfolk Island", "Nigeria", "Nicaragua",
"Netherlands", "Norway", "Nepal", "Nauru", "Niue", "New Zealand", "Oman", "Panama",
"Peru", "French Polynesia", "Papua New Guinea", "Philippines", "Pakistan",
"Poland", "Saint Pierre and Miquelon", "Pitcairn", "Puerto Rico",
"Palestinian Territory, Occupied", "Portugal", "Palau", "Paraguay", "Qatar",
"Reunion", "Romania", "Russian Federation", "Rwanda", "Saudi Arabia",
"Solomon Islands", "Seychelles", "Sudan", "Sweden", "Singapore", "Saint Helena",
"Slovenia", "Svalbard and Jan Mayen", "Slovakia", "Sierra Leone", "San Marino",
"Senegal", "Somalia", "Suriname", "Sao Tome and Principe", "El Salvador",
"Syrian Arab Republic", "Swaziland", "Turks and Caicos Islands", "Chad",
"French Southern Territories", "Togo", "Thailand", "Tajikistan", "Tokelau",
"Turkmenistan", "Tunisia", "Tonga", "Timor-Leste", "Turkey", "Trinidad and Tobago",
"Tuvalu", "Taiwan", "Tanzania, United Republic of", "Ukraine", "Uganda",
"United States Minor Outlying Islands", "United States", "Uruguay", "Uzbekistan",
"Holy See (Vatican City State)", "Saint Vincent and the Grenadines",
"Venezuela", "Virgin Islands, British", "Virgin Islands, U.S.", "Vietnam",
"Vanuatu", "Wallis and Futuna", "Samoa", "Yemen", "Mayotte", "Serbia",
"South Africa", "Zambia", "Montenegro", "Zimbabwe", "Anonymous Proxy",
"Satellite Provider", "Other",
"Aland Islands", "Guernsey", "Isle of Man", "Jersey", "Saint Barthelemy",
"Saint Martin"
};
private bool disposed;
public LookupService(string databaseFile, int options)
{
try
{
this.file = new FileStream(databaseFile, FileMode.Open, FileAccess.Read);
this.dboptions = options;
this.Init();
}
catch (SystemException)
{
Console.Write("cannot open file " + databaseFile + "\n");
}
}
public LookupService(String databaseFile)
: this(databaseFile, GeoipStandard)
{
}
private void Init()
{
int i, j;
byte[] delim = new byte[3];
byte[] buf = new byte[SegmentRecordLength];
databaseType = (byte)DatabaseInfo.COUNTRY_EDITION;
recordLength = StandardRecordLength;
//file.Seek(file.Length() - 3,SeekOrigin.Begin);
file.Seek(-3, SeekOrigin.End);
for (i = 0; i < StructureInfoMaxSize; i++)
{
file.Read(delim, 0, 3);
if (delim[0] == 255 && delim[1] == 255 && delim[2] == 255)
{
databaseType = Convert.ToByte(file.ReadByte());
if (databaseType >= 106)
{
// Backward compatibility with databases from April 2003 and earlier
databaseType -= 105;
}
// Determine the database type.
if (databaseType == DatabaseInfo.REGION_EDITION_REV0)
{
databaseSegments = new int[1];
databaseSegments[0] = StateBeginRev0;
recordLength = StandardRecordLength;
}
else if (databaseType == DatabaseInfo.REGION_EDITION_REV1)
{
databaseSegments = new int[1];
databaseSegments[0] = StateBeginRev1;
recordLength = StandardRecordLength;
}
else if (databaseType == DatabaseInfo.CITY_EDITION_REV0 ||
databaseType == DatabaseInfo.CITY_EDITION_REV1 ||
databaseType == DatabaseInfo.ORG_EDITION ||
databaseType == DatabaseInfo.ISP_EDITION ||
databaseType == DatabaseInfo.ASNUM_EDITION)
{
databaseSegments = new int[1];
databaseSegments[0] = 0;
if (databaseType == DatabaseInfo.CITY_EDITION_REV0 ||
databaseType == DatabaseInfo.CITY_EDITION_REV1)
{
recordLength = StandardRecordLength;
}
else
{
recordLength = OrgRecordLength;
}
file.Read(buf, 0, SegmentRecordLength);
for (j = 0; j < SegmentRecordLength; j++)
{
databaseSegments[0] += (UnsignedByteToInt(buf[j]) << (j * 8));
}
}
break;
}
else
{
//file.Seek(file.getFilePointer() - 4);
file.Seek(-4, SeekOrigin.Current);
//file.Seek(file.position-4,SeekOrigin.Begin);
}
}
if ((databaseType == DatabaseInfo.COUNTRY_EDITION) |
(databaseType == DatabaseInfo.PROXY_EDITION) |
(databaseType == DatabaseInfo.NETSPEED_EDITION))
{
databaseSegments = new int[1];
databaseSegments[0] = CountryBegin;
recordLength = StandardRecordLength;
}
if ((dboptions & GeoipMemoryCache) == 1)
{
int l = (int) file.Length;
dbbuffer = new byte[l];
file.Seek(0, SeekOrigin.Begin);
file.Read(dbbuffer, 0, l);
}
}
public void Close()
{
try
{
file.Dispose();
file = null;
}
catch (Exception)
{
}
}
public Country GetCountry(IPAddress ipAddress)
{
return GetCountry(BytestoLong(ipAddress.GetAddressBytes()));
}
public Country GetCountry(String ipAddress)
{
IPAddress addr;
try
{
addr = IPAddress.Parse(ipAddress);
}
//catch (UnknownHostException e) {
catch (Exception e)
{
Console.Write(e.Message);
return unknownCountry;
}
// return getCountry(bytestoLong(addr.GetAddressBytes()));
return GetCountry(BytestoLong(addr.GetAddressBytes()));
}
public Country GetCountry(long ipAddress)
{
if (file == null)
{
//throw new IllegalStateException("Database has been closed.");
throw new Exception("Database has been closed.");
}
if ((databaseType == DatabaseInfo.CITY_EDITION_REV1) |
(databaseType == DatabaseInfo.CITY_EDITION_REV0))
{
Location l = GetLocation(ipAddress);
if (l == null)
{
return unknownCountry;
}
else
{
return new Country(l.countryCode, l.countryName);
}
}
else
{
int ret = SeekCountry(ipAddress) - CountryBegin;
if (ret == 0)
{
return unknownCountry;
}
else
{
return new Country(countryCode[ret], countryName[ret]);
}
}
}
public int GetID(String ipAddress)
{
IPAddress addr;
try
{
addr = IPAddress.Parse(ipAddress);
}
catch (Exception e)
{
Console.Write(e.Message);
return 0;
}
return GetID(BytestoLong(addr.GetAddressBytes()));
}
public int GetID(IPAddress ipAddress)
{
return GetID(BytestoLong(ipAddress.GetAddressBytes()));
}
public int GetID(long ipAddress)
{
if (file == null)
{
throw new Exception("Database has been closed.");
}
int ret = SeekCountry(ipAddress) - databaseSegments[0];
return ret;
}
public DatabaseInfo GetDatabaseInfo()
{
if (databaseInfo != null)
{
return databaseInfo;
}
try
{
// Synchronize since we're accessing the database file.
lock (this)
{
bool hasStructureInfo = false;
byte[] delim = new byte[3];
// Advance to part of file where database info is stored.
file.Seek(-3, SeekOrigin.End);
for (int i = 0; i < StructureInfoMaxSize; i++)
{
file.Read(delim, 0, 3);
if (delim[0] == 255 && delim[1] == 255 && delim[2] == 255)
{
hasStructureInfo = true;
break;
}
}
if (hasStructureInfo)
{
file.Seek(-3, SeekOrigin.Current);
}
else
{
// No structure info, must be pre Sep 2002 database, go back to end.
file.Seek(-3, SeekOrigin.End);
}
// Find the database info string.
for (int i = 0; i < DatabaseInfoMaxSize; i++)
{
file.Read(delim, 0, 3);
if (delim[0] == 0 && delim[1] == 0 && delim[2] == 0)
{
byte[] dbInfo = new byte[i];
char[] dbInfo2 = new char[i];
file.Read(dbInfo, 0, i);
for (int a0 = 0;a0 < i;a0++)
{
dbInfo2[a0] = Convert.ToChar(dbInfo[a0]);
}
// Create the database info object using the string.
this.databaseInfo = new DatabaseInfo(new String(dbInfo2));
return databaseInfo;
}
file.Seek(-4, SeekOrigin.Current);
}
}
}
catch (Exception e)
{
Console.Write(e.Message);
//e.printStackTrace();
}
return new DatabaseInfo("");
}
public Region GetRegion(IPAddress ipAddress)
{
return GetRegion(BytestoLong(ipAddress.GetAddressBytes()));
}
public Region GetRegion(String str)
{
IPAddress addr;
try
{
addr = IPAddress.Parse(str);
}
catch (Exception e)
{
Console.Write(e.Message);
return null;
}
return GetRegion(BytestoLong(addr.GetAddressBytes()));
}
[MethodImpl(MethodImplOptions.Synchronized)]
public Region GetRegion(long ipnum)
{
Region record = new Region();
int seek_region = 0;
if (databaseType == DatabaseInfo.REGION_EDITION_REV0)
{
seek_region = SeekCountry(ipnum) - StateBeginRev0;
char[] ch = new char[2];
if (seek_region >= 1000)
{
record.CountryCode = "US";
record.CountryName = "United States";
ch[0] = (char)(((seek_region - 1000) / 26) + 65);
ch[1] = (char)(((seek_region - 1000) % 26) + 65);
record.PRegion = new String(ch);
}
else
{
record.CountryCode = countryCode[seek_region];
record.CountryName = countryName[seek_region];
record.PRegion = "";
}
}
else if (databaseType == DatabaseInfo.REGION_EDITION_REV1)
{
seek_region = SeekCountry(ipnum) - StateBeginRev1;
char[] ch = new char[2];
if (seek_region < USOffset)
{
record.CountryCode = "";
record.CountryName = "";
record.PRegion = "";
}
else if (seek_region < CanadaOffset)
{
record.CountryCode = "US";
record.CountryName = "United States";
ch[0] = (char)(((seek_region - USOffset) / 26) + 65);
ch[1] = (char)(((seek_region - USOffset) % 26) + 65);
record.PRegion = new String(ch);
}
else if (seek_region < WorldOffset)
{
record.CountryCode = "CA";
record.CountryName = "Canada";
ch[0] = (char)(((seek_region - CanadaOffset) / 26) + 65);
ch[1] = (char)(((seek_region - CanadaOffset) % 26) + 65);
record.PRegion = new String(ch);
}
else
{
record.CountryCode = countryCode[(seek_region - WorldOffset) / FipsRange];
record.CountryName = countryName[(seek_region - WorldOffset) / FipsRange];
record.PRegion = "";
}
}
return record;
}
public Location GetLocation(IPAddress addr)
{
return GetLocation(BytestoLong(addr.GetAddressBytes()));
}
public Location GetLocation(String str)
{
IPAddress addr;
try
{
addr = IPAddress.Parse(str);
}
catch (Exception e)
{
Console.Write(e.Message);
return null;
}
return GetLocation(BytestoLong(addr.GetAddressBytes()));
}
[MethodImpl(MethodImplOptions.Synchronized)]
public Location GetLocation(long ipnum)
{
int record_pointer;
byte[] record_buf = new byte[FullRecordLength];
char[] record_buf2 = new char[FullRecordLength];
int record_buf_offset = 0;
Location record = new Location();
int str_length = 0;
int j, Seek_country;
double latitude = 0, longitude = 0;
try
{
Seek_country = SeekCountry(ipnum);
if (Seek_country == databaseSegments[0])
{
return null;
}
record_pointer = Seek_country + ((2 * recordLength - 1) * databaseSegments[0]);
if ((dboptions & GeoipMemoryCache) == 1)
{
Array.Copy(dbbuffer, record_pointer, record_buf, 0, Math.Min(dbbuffer.Length - record_pointer, FullRecordLength));
}
else
{
file.Seek(record_pointer, SeekOrigin.Begin);
file.Read(record_buf, 0, FullRecordLength);
}
for (int a0 = 0;a0 < FullRecordLength;a0++)
{
record_buf2[a0] = Convert.ToChar(record_buf[a0]);
}
// get country
record.countryCode = countryCode[UnsignedByteToInt(record_buf[0])];
record.countryName = countryName[UnsignedByteToInt(record_buf[0])];
record_buf_offset++;
// get region
while (record_buf[record_buf_offset + str_length] != '\0')
str_length++;
if (str_length > 0)
{
record.region = new String(record_buf2, record_buf_offset, str_length);
}
record_buf_offset += str_length + 1;
str_length = 0;
// get region_name
record.regionName = RegionName.getRegionName(record.countryCode, record.region);
// get city
while (record_buf[record_buf_offset + str_length] != '\0')
str_length++;
if (str_length > 0)
{
record.city = new String(record_buf2, record_buf_offset, str_length);
}
record_buf_offset += (str_length + 1);
str_length = 0;
// get postal code
while (record_buf[record_buf_offset + str_length] != '\0')
str_length++;
if (str_length > 0)
{
record.postalCode = new String(record_buf2, record_buf_offset, str_length);
}
record_buf_offset += (str_length + 1);
// get latitude
for (j = 0; j < 3; j++)
latitude += (UnsignedByteToInt(record_buf[record_buf_offset + j]) << (j * 8));
record.latitude = (float) latitude / 10000 - 180;
record_buf_offset += 3;
// get longitude
for (j = 0; j < 3; j++)
longitude += (UnsignedByteToInt(record_buf[record_buf_offset + j]) << (j * 8));
record.longitude = (float) longitude / 10000 - 180;
record.metro_code = record.dma_code = 0;
record.area_code = 0;
if (databaseType == DatabaseInfo.CITY_EDITION_REV1)
{
// get metro_code
int metroarea_combo = 0;
if (record.countryCode == "US")
{
record_buf_offset += 3;
for (j = 0; j < 3; j++)
metroarea_combo += (UnsignedByteToInt(record_buf[record_buf_offset + j]) << (j * 8));
record.metro_code = record.dma_code = metroarea_combo / 1000;
record.area_code = metroarea_combo % 1000;
}
}
}
catch (IOException)
{
Console.Write("IO Exception while seting up segments");
}
return record;
}
public String GetOrg(IPAddress addr)
{
return GetOrg(BytestoLong(addr.GetAddressBytes()));
}
public String GetOrg(String str)
{
IPAddress addr;
try
{
addr = IPAddress.Parse(str);
}
//catch (UnknownHostException e) {
catch (Exception e)
{
Console.Write(e.Message);
return null;
}
return GetOrg(BytestoLong(addr.GetAddressBytes()));
}
[MethodImpl(MethodImplOptions.Synchronized)]
public String GetOrg(long ipnum)
{
int Seek_org;
int record_pointer;
int str_length = 0;
byte[] buf = new byte[MaxOrgRecordLength];
char[] buf2 = new char[MaxOrgRecordLength];
String org_buf;
try
{
Seek_org = SeekCountry(ipnum);
if (Seek_org == databaseSegments[0])
{
return null;
}
record_pointer = Seek_org + (2 * recordLength - 1) * databaseSegments[0];
if ((dboptions & GeoipMemoryCache) == 1)
{
Array.Copy(dbbuffer, record_pointer, buf, 0, Math.Min(dbbuffer.Length - record_pointer, MaxOrgRecordLength));
}
else
{
file.Seek(record_pointer, SeekOrigin.Begin);
file.Read(buf, 0, MaxOrgRecordLength);
}
while (buf[str_length] != 0)
{
buf2[str_length] = Convert.ToChar(buf[str_length]);
str_length++;
}
buf2[str_length] = '\0';
org_buf = new String(buf2,0,str_length);
return org_buf;
}
catch (IOException)
{
Console.Write("IO Exception");
return null;
}
}
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool dispose)
{
if (dispose && !this.disposed)
{
this.Close();
this.disposed = true;
}
}
[MethodImpl(MethodImplOptions.Synchronized)]
private int SeekCountry(long ipAddress)
{
byte[] buf = new byte[2 * MaxRecordLength];
int[] x = new int[2];
int offset = 0;
for (int depth = 31; depth >= 0; depth--)
{
try
{
if ((dboptions & GeoipMemoryCache) == 1)
{
for (int i = 0;i < (2 * MaxRecordLength);i++)
{
buf[i] = dbbuffer[i + (2 * recordLength * offset)];
}
}
else
{
file.Seek(2 * recordLength * offset, SeekOrigin.Begin);
file.Read(buf, 0, 2 * MaxRecordLength);
}
}
catch (IOException)
{
Console.Write("IO Exception");
}
for (int i = 0; i < 2; i++)
{
x[i] = 0;
for (int j = 0; j < recordLength; j++)
{
int y = buf[(i * recordLength) + j];
if (y < 0)
{
y += 256;
}
x[i] += (y << (j * 8));
}
}
if ((ipAddress & (1 << depth)) > 0)
{
if (x[1] >= databaseSegments[0])
{
return x[1];
}
offset = x[1];
}
else
{
if (x[0] >= databaseSegments[0])
{
return x[0];
}
offset = x[0];
}
}
// shouldn't reach here
Console.Write("Error Seeking country while Seeking " + ipAddress);
return 0;
}
private static long SwapBytes(long ipAddress)
{
return (((ipAddress >> 0) & 255) << 24) | (((ipAddress >> 8) & 255) << 16) |
(((ipAddress >> 16) & 255) << 8) | (((ipAddress >> 24) & 255) << 0);
}
private static long BytestoLong(byte[] address)
{
long ipnum = 0;
for (int i = 0; i < 4; ++i)
{
long y = address[i];
if (y < 0)
{
y += 256;
}
ipnum += y << ((3 - i) * 8);
}
return ipnum;
}
private static int UnsignedByteToInt(byte b)
{
return (int) b & 0xFF;
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using osu.Framework.Graphics;
using osu.Framework.Testing;
using osu.Framework.Utils;
using osu.Game.Models;
using osu.Game.Rulesets.Scoring;
using osu.Game.Scoring;
using osu.Game.Screens.Ranking;
using osu.Game.Tests.Resources;
using osuTK.Input;
namespace osu.Game.Tests.Visual.Ranking
{
public class TestSceneScorePanelList : OsuManualInputManagerTestScene
{
private ScorePanelList list;
[Test]
public void TestEmptyList()
{
createListStep(() => new ScorePanelList());
}
[Test]
public void TestEmptyListWithSelectedScore()
{
createListStep(() => new ScorePanelList
{
SelectedScore = { Value = TestResources.CreateTestScoreInfo() }
});
}
[Test]
public void TestAddPanelAfterSelectingScore()
{
var score = TestResources.CreateTestScoreInfo();
createListStep(() => new ScorePanelList
{
SelectedScore = { Value = score }
});
AddStep("add panel", () => list.AddScore(score));
assertScoreState(score, true);
assertExpandedPanelCentred();
}
[Test]
public void TestAddPanelBeforeSelectingScore()
{
var score = TestResources.CreateTestScoreInfo();
createListStep(() => new ScorePanelList());
AddStep("add panel", () => list.AddScore(score));
assertScoreState(score, false);
assertFirstPanelCentred();
AddStep("select score", () => list.SelectedScore.Value = score);
assertScoreState(score, true);
assertExpandedPanelCentred();
}
[Test]
public void TestAddManyNonExpandedPanels()
{
createListStep(() => new ScorePanelList());
AddStep("add many scores", () =>
{
for (int i = 0; i < 20; i++)
list.AddScore(TestResources.CreateTestScoreInfo());
});
assertFirstPanelCentred();
}
[Test]
public void TestAddManyScoresAfterExpandedPanel()
{
var initialScore = TestResources.CreateTestScoreInfo();
createListStep(() => new ScorePanelList());
AddStep("add initial panel and select", () =>
{
list.AddScore(initialScore);
list.SelectedScore.Value = initialScore;
});
AddStep("add many scores", () =>
{
for (int i = 0; i < 20; i++)
list.AddScore(createScoreForTotalScore(initialScore.TotalScore - i - 1));
});
assertScoreState(initialScore, true);
assertExpandedPanelCentred();
}
[Test]
public void TestAddManyScoresBeforeExpandedPanel()
{
var initialScore = TestResources.CreateTestScoreInfo();
createListStep(() => new ScorePanelList());
AddStep("add initial panel and select", () =>
{
list.AddScore(initialScore);
list.SelectedScore.Value = initialScore;
});
AddStep("add scores", () =>
{
for (int i = 0; i < 20; i++)
list.AddScore(createScoreForTotalScore(initialScore.TotalScore + i + 1));
});
assertScoreState(initialScore, true);
assertExpandedPanelCentred();
}
[Test]
public void TestAddManyPanelsOnBothSidesOfExpandedPanel()
{
var initialScore = TestResources.CreateTestScoreInfo();
createListStep(() => new ScorePanelList());
AddStep("add initial panel and select", () =>
{
list.AddScore(initialScore);
list.SelectedScore.Value = initialScore;
});
AddStep("add scores after", () =>
{
for (int i = 0; i < 20; i++)
list.AddScore(createScoreForTotalScore(initialScore.TotalScore - i - 1));
for (int i = 0; i < 20; i++)
list.AddScore(createScoreForTotalScore(initialScore.TotalScore + i + 1));
});
assertScoreState(initialScore, true);
assertExpandedPanelCentred();
}
[Test]
public void TestSelectMultipleScores()
{
var firstScore = TestResources.CreateTestScoreInfo();
firstScore.RealmUser = new RealmUser { Username = "A" };
var secondScore = TestResources.CreateTestScoreInfo();
secondScore.RealmUser = new RealmUser { Username = "B" };
createListStep(() => new ScorePanelList());
AddStep("add scores and select first", () =>
{
list.AddScore(firstScore);
list.AddScore(secondScore);
list.SelectedScore.Value = firstScore;
});
AddUntilStep("wait for load", () => list.AllPanelsVisible);
assertScoreState(firstScore, true);
assertScoreState(secondScore, false);
AddStep("select second score", () =>
{
InputManager.MoveMouseTo(list.ChildrenOfType<ScorePanel>().Single(p => p.Score.Equals(secondScore)));
InputManager.Click(MouseButton.Left);
});
assertScoreState(firstScore, false);
assertScoreState(secondScore, true);
assertExpandedPanelCentred();
}
[Test]
public void TestAddScoreImmediately()
{
var score = TestResources.CreateTestScoreInfo();
createListStep(() =>
{
var newList = new ScorePanelList { SelectedScore = { Value = score } };
newList.AddScore(score);
return newList;
});
assertScoreState(score, true);
assertExpandedPanelCentred();
}
[Test]
public void TestKeyboardNavigation()
{
var lowestScore = TestResources.CreateTestScoreInfo();
lowestScore.OnlineID = 3;
lowestScore.TotalScore = 0;
lowestScore.Statistics = new Dictionary<HitResult, int>();
var middleScore = TestResources.CreateTestScoreInfo();
middleScore.OnlineID = 2;
middleScore.TotalScore = 0;
middleScore.Statistics = new Dictionary<HitResult, int>();
var highestScore = TestResources.CreateTestScoreInfo();
highestScore.OnlineID = 1;
highestScore.TotalScore = 0;
highestScore.Statistics = new Dictionary<HitResult, int>();
createListStep(() => new ScorePanelList());
AddStep("add scores and select middle", () =>
{
// order of addition purposefully scrambled.
list.AddScore(middleScore);
list.AddScore(lowestScore);
list.AddScore(highestScore);
list.SelectedScore.Value = middleScore;
});
AddUntilStep("wait for all scores to be visible", () => list.ChildrenOfType<ScorePanelTrackingContainer>().All(t => t.IsPresent));
assertScoreState(highestScore, false);
assertScoreState(middleScore, true);
assertScoreState(lowestScore, false);
AddStep("press left", () => InputManager.Key(Key.Left));
assertScoreState(highestScore, true);
assertScoreState(middleScore, false);
assertScoreState(lowestScore, false);
assertExpandedPanelCentred();
AddStep("press left at start of list", () => InputManager.Key(Key.Left));
assertScoreState(highestScore, true);
assertScoreState(middleScore, false);
assertScoreState(lowestScore, false);
assertExpandedPanelCentred();
AddStep("press right", () => InputManager.Key(Key.Right));
assertScoreState(highestScore, false);
assertScoreState(middleScore, true);
assertScoreState(lowestScore, false);
assertExpandedPanelCentred();
AddStep("press right again", () => InputManager.Key(Key.Right));
assertScoreState(highestScore, false);
assertScoreState(middleScore, false);
assertScoreState(lowestScore, true);
assertExpandedPanelCentred();
AddStep("press right at end of list", () => InputManager.Key(Key.Right));
assertScoreState(highestScore, false);
assertScoreState(middleScore, false);
assertScoreState(lowestScore, true);
assertExpandedPanelCentred();
AddStep("press left", () => InputManager.Key(Key.Left));
assertScoreState(highestScore, false);
assertScoreState(middleScore, true);
assertScoreState(lowestScore, false);
assertExpandedPanelCentred();
}
private ScoreInfo createScoreForTotalScore(long totalScore)
{
var score = TestResources.CreateTestScoreInfo();
score.TotalScore = totalScore;
return score;
}
private void createListStep(Func<ScorePanelList> creationFunc)
{
AddStep("create list", () => Child = list = creationFunc().With(d =>
{
d.Anchor = Anchor.Centre;
d.Origin = Anchor.Centre;
}));
AddUntilStep("wait for load", () => list.IsLoaded);
}
private void assertExpandedPanelCentred() => AddUntilStep("expanded panel centred", () =>
{
var expandedPanel = list.ChildrenOfType<ScorePanel>().Single(p => p.State == PanelState.Expanded);
return Precision.AlmostEquals(expandedPanel.ScreenSpaceDrawQuad.Centre.X, list.ScreenSpaceDrawQuad.Centre.X, 1);
});
private void assertFirstPanelCentred()
=> AddUntilStep("first panel centred", () => Precision.AlmostEquals(list.ChildrenOfType<ScorePanel>().First().ScreenSpaceDrawQuad.Centre.X, list.ScreenSpaceDrawQuad.Centre.X, 1));
private void assertScoreState(ScoreInfo score, bool expanded)
=> AddUntilStep($"score expanded = {expanded}", () => (list.ChildrenOfType<ScorePanel>().Single(p => p.Score.Equals(score)).State == PanelState.Expanded) == expanded);
}
}
| |
//! \file ArcHibiki.cs
//! \date Fri May 12 19:06:19 2017
//! \brief Hibiki Works resource archive.
//
// Copyright (C) 2017 by morkt
//
// 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.Collections.Generic;
using System.ComponentModel.Composition;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using GameRes.Utility;
namespace GameRes.Formats.YaneSDK
{
[Export(typeof(ArchiveFormat))]
public class HDatOpener : ArchiveFormat
{
public override string Tag { get { return "DAT/hibiki"; } }
public override string Description { get { return "YaneSDK engine resource archive"; } }
public override uint Signature { get { return 0; } }
public override bool IsHierarchic { get { return false; } }
public override bool CanWrite { get { return false; } }
public static readonly string SchemeFileName = "hibiki_works.dat";
public override ArcFile TryOpen (ArcView file)
{
if (!file.Name.HasExtension (".dat"))
return null;
int count = ReadCount (file);
if (!IsSaneCount (count))
return null;
var scheme = QueryScheme (file.Name);
if (null == scheme)
return null;
return TryOpenWithScheme (file, count, scheme);
}
int ReadCount (ArcView file)
{
return (short)(file.View.ReadUInt16 (0) ^ 0x8080);
}
ArcFile TryOpenWithScheme (ArcView file, int count, HibikiDatScheme scheme)
{
var dat_name = Path.GetFileName (file.Name).ToLowerInvariant();
IList<HibikiTocRecord> toc_table = null;
if (scheme.ArcMap != null && scheme.ArcMap.TryGetValue (dat_name, out toc_table))
{
if (toc_table.Count != count)
toc_table = null;
}
using (var input = OpenLstIndex (file, dat_name, scheme))
using (var dec = new XoredStream (input, 0x80))
using (var index = new BinaryReader (dec))
{
const int name_length = 0x100;
int data_offset = 2 + (name_length + 10) * count;
index.BaseStream.Position = 2;
Func<int, Entry> read_entry;
if (null == toc_table)
{
var name_buf = new byte[name_length];
read_entry = i => {
if (name_length != index.Read (name_buf, 0, name_length))
return null;
var name = Binary.GetCString (name_buf, 0);
var entry = FormatCatalog.Instance.Create<Entry> (name);
index.ReadUInt16();
entry.Size = index.ReadUInt32();
entry.Offset = index.ReadUInt32();
return entry;
};
}
else
{
read_entry = i => {
index.BaseStream.Seek (name_length + 6, SeekOrigin.Current);
index.ReadUInt32(); // throws in case of EOF
var toc_entry = toc_table[i];
var entry = FormatCatalog.Instance.Create<Entry> (toc_entry.Name);
entry.Offset = toc_entry.Offset;
entry.Size = toc_entry.Size;
return entry;
};
}
var dir = new List<Entry> (count);
for (int i = 0; i < count; ++i)
{
var entry = read_entry (i);
if (null == entry || string.IsNullOrWhiteSpace (entry.Name)
|| entry.Offset < data_offset || entry.Size > file.MaxOffset)
return null;
dir.Add (entry);
}
return new HibikiArchive (file, this, dir, scheme.ContentKey);
}
}
Stream OpenLstIndex (ArcView file, string dat_name, HibikiDatScheme scheme)
{
var lst_name = Path.ChangeExtension (file.Name, ".lst");
if (VFS.FileExists (lst_name))
return VFS.OpenStream (lst_name);
else if ("init.dat" == dat_name)
return file.CreateStream();
// try to open 'init.dat' archive in the same directory
var dir_name = VFS.GetDirectoryName (file.Name);
var init_dat = VFS.CombinePath (dir_name, "init.dat");
if (!VFS.FileExists (init_dat))
{
init_dat = VFS.CombinePath (VFS.CombinePath (dir_name, "arc"), "init.dat");
if (!VFS.FileExists (init_dat))
return file.CreateStream();
}
try
{
using (var init = VFS.OpenView (init_dat))
using (var init_arc = TryOpenWithScheme (init, ReadCount (init), scheme))
{
lst_name = Path.GetFileName (lst_name);
var lst_entry = init_arc.Dir.First (e => e.Name == lst_name);
return init_arc.OpenEntry (lst_entry);
}
}
catch
{
return file.CreateStream();
}
}
public override Stream OpenEntry (ArcFile arc, Entry entry)
{
var harc = arc as HibikiArchive;
if (null == harc)
return base.OpenEntry (arc, entry);
var key = harc.Key;
uint encrypted = Math.Min (entry.Size, (uint)key.Length);
var header = arc.File.View.ReadBytes (entry.Offset, encrypted);
for (int i = 0; i < header.Length; ++i)
header[i] ^= key[i];
if (encrypted == entry.Size)
return new BinMemoryStream (header);
var rest = arc.File.CreateStream (entry.Offset + encrypted, entry.Size - encrypted);
return new PrefixStream (header, rest);
}
HibikiDatScheme QueryScheme (string arc_name)
{
if (null == KnownSchemes)
return null;
// XXX add GUI widget to select scheme
return KnownSchemes.Values.FirstOrDefault();
}
static Lazy<HibikiScheme> s_Scheme = new Lazy<HibikiScheme> (DeserializeScheme);
internal IDictionary<string, HibikiDatScheme> KnownSchemes {
get { return s_Scheme.Value.KnownSchemes; }
}
static HibikiScheme DeserializeScheme ()
{
try
{
var dir = FormatCatalog.Instance.DataDirectory;
var scheme_file = Path.Combine (dir, SchemeFileName);
using (var input = File.OpenRead (scheme_file))
{
var bin = new BinaryFormatter();
return (HibikiScheme)bin.Deserialize (input);
}
}
catch (Exception X)
{
Trace.WriteLine (X.Message, "hibiki_works scheme deserialization failed");
return new HibikiScheme();
}
}
}
internal class HibikiArchive : ArcFile
{
public readonly byte[] Key;
public HibikiArchive (ArcView arc, ArchiveFormat impl, ICollection<Entry> dir, byte[] key)
: base (arc, impl, dir)
{
Key = key;
}
}
[Serializable]
public class HibikiScheme : ResourceScheme
{
public IDictionary<string, HibikiDatScheme> KnownSchemes;
}
[Serializable]
public class HibikiDatScheme
{
public byte[] ContentKey;
public IDictionary<string, IList<HibikiTocRecord>> ArcMap;
}
[Serializable]
public class HibikiTocRecord
{
public string Name;
public uint Offset;
public uint Size;
public HibikiTocRecord (string name, uint offset, uint size)
{
Name = name;
Offset = offset;
Size = size;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using Google.Analytics;
using Google.GData.Analytics;
using Google.GData.Client.LiveTests;
using NUnit.Framework;
namespace Google.GData.Client.UnitTests.Analytics
{
[TestFixture, Category("Analytics")]
public class AnalyticsDataServiceTest : BaseLiveTestClass
{
private const string DataFeedUrl = "http://www.google.com/analytics/feeds/data";
private const string AccountFeedUrl = "http://www.google.com/analytics/feeds/accounts/default";
private string accountId;
protected override void ReadConfigFile()
{
base.ReadConfigFile();
if (unitTestConfiguration.Contains("analyticsUserName"))
{
userName = (string) unitTestConfiguration["analyticsUserName"];
Tracing.TraceInfo("Read userName value: " + userName);
}
if (unitTestConfiguration.Contains("analyticsPassWord"))
{
passWord = (string) unitTestConfiguration["analyticsPassWord"];
Tracing.TraceInfo("Read passWord value: " + passWord);
}
if (unitTestConfiguration.Contains("accountId"))
{
accountId = (string) unitTestConfiguration["accountId"];
Tracing.TraceInfo("Read accountId value: " + accountId);
}
}
/// <summary>
///Gets or sets the test context which provides
///information about and functionality for the current test run.
///</summary>
public TestContext TestContext { get; set; }
[Test]
public void QueryAccountIds()
{
AnalyticsService service = new AnalyticsService(ApplicationName);
service.Credentials = new GDataCredentials(userName, passWord);
AccountQuery feedQuery = new AccountQuery(AccountFeedUrl);
AccountFeed actual = service.Query(feedQuery);
foreach (AccountEntry entry in actual.Entries)
{
Assert.IsNotNull(entry.Id);
Assert.IsNotNull(entry.ProfileId.Value);
if (accountId == null)
accountId = entry.ProfileId.Value;
}
}
[Test]
public void QueryBrowserMetrics()
{
AnalyticsService service = new AnalyticsService(ApplicationName);
service.Credentials = new GDataCredentials(userName, passWord);
DataQuery query = new DataQuery(DataFeedUrl);
query.Ids = accountId;
query.Metrics = "ga:pageviews";
query.Dimensions = "ga:browser";
query.Sort = "ga:browser,ga:pageviews";
query.GAStartDate = DateTime.Now.AddDays(-14).ToString("yyyy-MM-dd");
query.GAEndDate = DateTime.Now.AddDays(-2).ToString("yyyy-MM-dd");
query.NumberToRetrieve = 200;
DataFeed actual = service.Query(query);
XmlTextWriter writer = new XmlTextWriter("QueryBrowserMetricsOutput.xml", Encoding.UTF8);
writer.Formatting = Formatting.Indented;
writer.Indentation = 2;
actual.SaveToXml(writer);
foreach (DataEntry entry in actual.Entries)
{
Assert.IsNotNull(entry.Id);
}
}
[Test]
public void QueryPageViews()
{
AnalyticsService service = new AnalyticsService(ApplicationName);
service.Credentials = new GDataCredentials(userName, passWord);
DataQuery query = new DataQuery(DataFeedUrl);
query.Ids = accountId;
query.Metrics = "ga:pageviews";
query.Dimensions = "ga:pageTitle";
query.Sort = "-ga:pageviews";
query.GAStartDate = DateTime.Now.AddDays(-14).ToString("yyyy-MM-dd");
query.GAEndDate = DateTime.Now.AddDays(-2).ToString("yyyy-MM-dd");
query.NumberToRetrieve = 200;
DataFeed actual = service.Query(query);
Assert.IsNotNull(actual.Aggregates);
Assert.AreEqual(1, actual.Aggregates.Metrics.Count);
foreach (DataEntry entry in actual.Entries)
{
Assert.IsNotNull(entry.Id);
}
}
[Test]
public void QueryProductCategoryResultForPeriod()
{
AnalyticsService service = new AnalyticsService(ApplicationName);
service.Credentials = new GDataCredentials(userName, passWord);
DataQuery query = new DataQuery(DataFeedUrl);
query.Ids = accountId;
query.Dimensions = "ga:productCategory,ga:productName";
query.Metrics = "ga:itemRevenue,ga:itemQuantity";
query.Sort = "ga:productCategory";
query.GAStartDate = new DateTime(2009, 04, 19).ToString("yyyy-MM-dd");
query.GAEndDate = new DateTime(2009, 04, 25).ToString("yyyy-MM-dd");
DataFeed actual = service.Query(query);
Assert.IsNotNull(actual);
Assert.IsNotNull(actual.Entries);
foreach (DataEntry entry in actual.Entries)
{
Assert.AreEqual(2, entry.Dimensions.Count);
Assert.IsNotNull(entry.Dimensions[0]);
Assert.IsNotNull(entry.Dimensions[0].Name);
Assert.IsNotNull(entry.Dimensions[0].Value);
Assert.IsNotNull(entry.Dimensions[1]);
Assert.IsNotNull(entry.Dimensions[1].Name);
Assert.IsNotNull(entry.Dimensions[1].Value);
Assert.AreEqual(2, entry.Metrics.Count);
Assert.IsNotNull(entry.Metrics[0]);
Assert.IsNotNull(entry.Metrics[0].Name);
Assert.IsNotNull(entry.Metrics[0].Value);
Assert.IsNotNull(entry.Metrics[1]);
Assert.IsNotNull(entry.Metrics[1].Name);
Assert.IsNotNull(entry.Metrics[1].Value);
}
}
[Test]
public void QuerySiteStatsResultForPeriod()
{
AnalyticsService service = new AnalyticsService(ApplicationName);
service.Credentials = new GDataCredentials(userName, passWord);
DataQuery query = new DataQuery(DataFeedUrl);
query.Ids = accountId;
query.Metrics = "ga:pageviews,ga:visits,ga:newVisits,ga:transactions,ga:uniquePageviews";
query.GAStartDate = new DateTime(2009, 04, 19).ToString("yyyy-MM-dd");
query.GAEndDate = new DateTime(2009, 04, 25).ToString("yyyy-MM-dd");
query.StartIndex = 1;
DataFeed actual = service.Query(query);
Assert.IsNotNull(actual.Aggregates);
Assert.AreEqual(5, actual.Aggregates.Metrics.Count);
}
[Test]
public void QueryTransactionIdReturn200Results()
{
AnalyticsService service = new AnalyticsService(ApplicationName);
service.Credentials = new GDataCredentials(userName, passWord);
DataQuery query = new DataQuery(DataFeedUrl);
query.Ids = accountId;
query.Dimensions = "ga:transactionId,ga:date";
query.Metrics = "ga:transactionRevenue";
query.Sort = "ga:date";
query.GAStartDate = new DateTime(2009, 04, 01).ToString("yyyy-MM-dd");
query.GAEndDate = new DateTime(2009, 04, 30).ToString("yyyy-MM-dd");
query.NumberToRetrieve = 200;
DataFeed actual = service.Query(query);
Assert.AreEqual(200, actual.ItemsPerPage);
Assert.IsNotNull(actual.Aggregates);
Assert.AreEqual(1, actual.Aggregates.Metrics.Count);
foreach (DataEntry entry in actual.Entries)
{
Assert.IsNotNull(entry.Id);
}
}
[Test]
public void QueryTransactionIdReturnAllResults()
{
AnalyticsService service = new AnalyticsService(ApplicationName);
service.Credentials = new GDataCredentials(userName, passWord);
int currentIndex = 1;
const int resultsPerPage = 1000;
List<DataFeed> querys = new List<DataFeed>();
DataQuery query = new DataQuery(DataFeedUrl);
query.Ids = accountId;
query.Dimensions = "ga:transactionId,ga:date";
query.Metrics = "ga:transactionRevenue";
query.Sort = "ga:date";
query.GAStartDate = new DateTime(2009, 04, 01).ToString("yyyy-MM-dd");
query.GAEndDate = new DateTime(2009, 04, 30).ToString("yyyy-MM-dd");
query.NumberToRetrieve = resultsPerPage;
query.StartIndex = currentIndex;
DataFeed actual = service.Query(query);
querys.Add(actual);
double totalPages = Math.Round((actual.TotalResults/(double) resultsPerPage) + 0.5);
for (int i = 1; i < totalPages; i++)
{
currentIndex += resultsPerPage;
query.StartIndex = currentIndex;
actual = service.Query(query);
querys.Add(actual);
}
for (int i = 0; i < querys.Count; i++)
{
foreach (DataEntry entry in querys[i].Entries)
{
Assert.IsNotNull(entry.Id);
}
}
}
[Test]
public void QueryVisitorsResultForPeriod()
{
AnalyticsService service = new AnalyticsService(ApplicationName);
service.Credentials = new GDataCredentials(userName, passWord);
DataQuery query = new DataQuery(DataFeedUrl);
query.Ids = accountId;
query.Metrics = "ga:visitors";
query.GAStartDate = new DateTime(2009, 04, 19).ToString("yyyy-MM-dd");
query.GAEndDate = new DateTime(2009, 04, 25).ToString("yyyy-MM-dd");
query.StartIndex = 1;
DataFeed actual = service.Query(query);
Assert.IsNotNull(actual.Aggregates);
Assert.AreEqual(1, actual.Aggregates.Metrics.Count);
}
[Test]
public void TestAnalyticsModel()
{
RequestSettings settings = new RequestSettings("Unittests", userName, passWord);
AnalyticsRequest request = new AnalyticsRequest(settings);
Feed<Account> accounts = request.GetAccounts();
foreach (Account a in accounts.Entries)
{
Assert.IsNotNull(a.AccountId);
Assert.IsNotNull(a.ProfileId);
Assert.IsNotNull(a.WebPropertyId);
if (accountId == null)
accountId = a.TableId;
}
DataQuery q = new DataQuery(accountId, DateTime.Now.AddDays(-14), DateTime.Now.AddDays(-2), "ga:pageviews",
"ga:pageTitle", "ga:pageviews");
Dataset set = request.Get(q);
foreach (Data d in set.Entries)
{
Assert.IsNotNull(d.Id);
Assert.IsNotNull(d.Metrics);
Assert.IsNotNull(d.Dimensions);
}
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: health.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Grpc.Health.V1Alpha {
namespace Proto {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class Health {
#region Descriptor
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static Health() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CgxoZWFsdGgucHJvdG8SE2dycGMuaGVhbHRoLnYxYWxwaGEiMwoSSGVhbHRo",
"Q2hlY2tSZXF1ZXN0EgwKBGhvc3QYASABKAkSDwoHc2VydmljZRgCIAEoCSKZ",
"AQoTSGVhbHRoQ2hlY2tSZXNwb25zZRJGCgZzdGF0dXMYASABKA4yNi5ncnBj",
"LmhlYWx0aC52MWFscGhhLkhlYWx0aENoZWNrUmVzcG9uc2UuU2VydmluZ1N0",
"YXR1cyI6Cg1TZXJ2aW5nU3RhdHVzEgsKB1VOS05PV04QABILCgdTRVJWSU5H",
"EAESDwoLTk9UX1NFUlZJTkcQAjJkCgZIZWFsdGgSWgoFQ2hlY2sSJy5ncnBj",
"LmhlYWx0aC52MWFscGhhLkhlYWx0aENoZWNrUmVxdWVzdBooLmdycGMuaGVh",
"bHRoLnYxYWxwaGEuSGVhbHRoQ2hlY2tSZXNwb25zZUIWqgITR3JwYy5IZWFs",
"dGguVjFBbHBoYWIGcHJvdG8z"));
descriptor = pbr::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedCodeInfo(null, new pbr::GeneratedCodeInfo[] {
new pbr::GeneratedCodeInfo(typeof(global::Grpc.Health.V1Alpha.HealthCheckRequest), new[]{ "Host", "Service" }, null, null, null),
new pbr::GeneratedCodeInfo(typeof(global::Grpc.Health.V1Alpha.HealthCheckResponse), new[]{ "Status" }, null, new[]{ typeof(global::Grpc.Health.V1Alpha.HealthCheckResponse.Types.ServingStatus) }, null)
}));
}
#endregion
}
}
#region Messages
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class HealthCheckRequest : pb::IMessage<HealthCheckRequest> {
private static readonly pb::MessageParser<HealthCheckRequest> _parser = new pb::MessageParser<HealthCheckRequest>(() => new HealthCheckRequest());
public static pb::MessageParser<HealthCheckRequest> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::Grpc.Health.V1Alpha.Proto.Health.Descriptor.MessageTypes[0]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public HealthCheckRequest() {
OnConstruction();
}
partial void OnConstruction();
public HealthCheckRequest(HealthCheckRequest other) : this() {
host_ = other.host_;
service_ = other.service_;
}
public HealthCheckRequest Clone() {
return new HealthCheckRequest(this);
}
public const int HostFieldNumber = 1;
private string host_ = "";
public string Host {
get { return host_; }
set {
host_ = pb::Preconditions.CheckNotNull(value, "value");
}
}
public const int ServiceFieldNumber = 2;
private string service_ = "";
public string Service {
get { return service_; }
set {
service_ = pb::Preconditions.CheckNotNull(value, "value");
}
}
public override bool Equals(object other) {
return Equals(other as HealthCheckRequest);
}
public bool Equals(HealthCheckRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Host != other.Host) return false;
if (Service != other.Service) return false;
return true;
}
public override int GetHashCode() {
int hash = 1;
if (Host.Length != 0) hash ^= Host.GetHashCode();
if (Service.Length != 0) hash ^= Service.GetHashCode();
return hash;
}
public override string ToString() {
return pb::JsonFormatter.Default.Format(this);
}
public void WriteTo(pb::CodedOutputStream output) {
if (Host.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Host);
}
if (Service.Length != 0) {
output.WriteRawTag(18);
output.WriteString(Service);
}
}
public int CalculateSize() {
int size = 0;
if (Host.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Host);
}
if (Service.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Service);
}
return size;
}
public void MergeFrom(HealthCheckRequest other) {
if (other == null) {
return;
}
if (other.Host.Length != 0) {
Host = other.Host;
}
if (other.Service.Length != 0) {
Service = other.Service;
}
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
Host = input.ReadString();
break;
}
case 18: {
Service = input.ReadString();
break;
}
}
}
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class HealthCheckResponse : pb::IMessage<HealthCheckResponse> {
private static readonly pb::MessageParser<HealthCheckResponse> _parser = new pb::MessageParser<HealthCheckResponse>(() => new HealthCheckResponse());
public static pb::MessageParser<HealthCheckResponse> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::Grpc.Health.V1Alpha.Proto.Health.Descriptor.MessageTypes[1]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public HealthCheckResponse() {
OnConstruction();
}
partial void OnConstruction();
public HealthCheckResponse(HealthCheckResponse other) : this() {
status_ = other.status_;
}
public HealthCheckResponse Clone() {
return new HealthCheckResponse(this);
}
public const int StatusFieldNumber = 1;
private global::Grpc.Health.V1Alpha.HealthCheckResponse.Types.ServingStatus status_ = global::Grpc.Health.V1Alpha.HealthCheckResponse.Types.ServingStatus.UNKNOWN;
public global::Grpc.Health.V1Alpha.HealthCheckResponse.Types.ServingStatus Status {
get { return status_; }
set {
status_ = value;
}
}
public override bool Equals(object other) {
return Equals(other as HealthCheckResponse);
}
public bool Equals(HealthCheckResponse other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Status != other.Status) return false;
return true;
}
public override int GetHashCode() {
int hash = 1;
if (Status != global::Grpc.Health.V1Alpha.HealthCheckResponse.Types.ServingStatus.UNKNOWN) hash ^= Status.GetHashCode();
return hash;
}
public override string ToString() {
return pb::JsonFormatter.Default.Format(this);
}
public void WriteTo(pb::CodedOutputStream output) {
if (Status != global::Grpc.Health.V1Alpha.HealthCheckResponse.Types.ServingStatus.UNKNOWN) {
output.WriteRawTag(8);
output.WriteEnum((int) Status);
}
}
public int CalculateSize() {
int size = 0;
if (Status != global::Grpc.Health.V1Alpha.HealthCheckResponse.Types.ServingStatus.UNKNOWN) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Status);
}
return size;
}
public void MergeFrom(HealthCheckResponse other) {
if (other == null) {
return;
}
if (other.Status != global::Grpc.Health.V1Alpha.HealthCheckResponse.Types.ServingStatus.UNKNOWN) {
Status = other.Status;
}
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
status_ = (global::Grpc.Health.V1Alpha.HealthCheckResponse.Types.ServingStatus) input.ReadEnum();
break;
}
}
}
}
#region Nested types
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class Types {
public enum ServingStatus {
UNKNOWN = 0,
SERVING = 1,
NOT_SERVING = 2,
}
}
#endregion
}
#endregion
}
#endregion Designer generated code
| |
using System;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
using UnityStandardAssets.Utility;
using Random = UnityEngine.Random;
namespace UnityStandardAssets.Characters.FirstPerson{
[RequireComponent(typeof (CharacterController))]
[RequireComponent(typeof (AudioSource))]
public class FirstPersonController : MonoBehaviour{
[SerializeField] private bool m_IsWalking;
[SerializeField] private float m_WalkSpeed;
[SerializeField] private float m_RunSpeed;
[SerializeField] [Range(0f, 1f)] private float m_RunstepLenghten;
[SerializeField] private float m_JumpSpeed;
[SerializeField] private float m_StickToGroundForce;
[SerializeField] private float m_GravityMultiplier;
[SerializeField] private bool m_UseFovKick;
[SerializeField] private FOVKick m_FovKick = new FOVKick();
[SerializeField] private bool m_UseHeadBob;
[SerializeField] private CurveControlledBob m_HeadBob = new CurveControlledBob();
[SerializeField] private LerpControlledBob m_JumpBob = new LerpControlledBob();
[SerializeField] private float m_StepInterval;
[SerializeField] private AudioClip[] m_FootstepSounds; // an array of footstep sounds that will be randomly selected from.
[SerializeField] private AudioClip m_JumpSound; // the sound played when character leaves the ground.
[SerializeField] private AudioClip m_LandSound; // the sound played when character touches back on ground.
private Camera m_Camera;
private bool m_Jump;
private float m_YRotation;
private Vector2 m_Input;
private Vector3 m_MoveDir = Vector3.zero;
private CharacterController m_CharacterController;
private CollisionFlags m_CollisionFlags;
private bool m_PreviouslyGrounded;
private Vector3 m_OriginalCameraPosition;
private float m_StepCycle;
private float m_NextStep;
private bool m_Jumping;
private AudioSource m_AudioSource;
// Custom stuff for my own version of this stanard script
[Header("Custom Flags")]
[Tooltip("Toggle jump ability on and off")]
public bool enableJump = false;
[Tooltip("Toggle movement sounds on and off")]
public bool enableMovementSounds = false;
[Tooltip("Toggle movement on and off")]
public bool enableMovement = true;
[Tooltip("Toggle Running ability on and off")]
public bool enableRunning = true;
private void Start(){
m_CharacterController = GetComponent<CharacterController>();
m_Camera = Camera.main;
m_OriginalCameraPosition = m_Camera.transform.localPosition;
m_FovKick.Setup(m_Camera);
m_HeadBob.Setup(m_Camera, m_StepInterval);
m_StepCycle = 0f;
m_NextStep = m_StepCycle/2f;
m_Jumping = false;
m_AudioSource = GetComponent<AudioSource>();
gameObject.GetComponent<MouseLook>().Init(transform , m_Camera.transform);
}
private void Update(){
RotateView();
// the jump state needs to read here to make sure it is not missed
if(enableJump && !m_Jump){
m_Jump = Input.GetButtonDown("Jump");
}
if(!m_PreviouslyGrounded && m_CharacterController.isGrounded){
StartCoroutine(m_JumpBob.DoBobCycle());
PlayLandingSound();
m_MoveDir.y = 0f;
m_Jumping = false;
}
if(!m_CharacterController.isGrounded && !m_Jumping && m_PreviouslyGrounded){
m_MoveDir.y = 0f;
}
m_PreviouslyGrounded = m_CharacterController.isGrounded;
}
private void PlayLandingSound(){
if(enableMovementSounds){
m_AudioSource.clip = m_LandSound;
m_AudioSource.Play ();
m_NextStep = m_StepCycle + .5f;
}
}
private void FixedUpdate(){
float speed;
GetInput(out speed);
// always move along the camera forward as it is the direction that it being aimed at
Vector3 desiredMove = Vector3.zero;
if(enableMovement){
desiredMove = transform.forward * m_Input.y + transform.right * m_Input.x;
}
// get a normal for the surface that is being touched to move along it
RaycastHit hitInfo;
Physics.SphereCast(transform.position, m_CharacterController.radius, Vector3.down, out hitInfo,m_CharacterController.height/2f);
desiredMove = Vector3.ProjectOnPlane(desiredMove, hitInfo.normal).normalized;
m_MoveDir.x = desiredMove.x*speed;
m_MoveDir.z = desiredMove.z*speed;
if(m_CharacterController.isGrounded){
m_MoveDir.y = -m_StickToGroundForce;
if(m_Jump){
m_MoveDir.y = m_JumpSpeed;
PlayJumpSound();
m_Jump = false;
m_Jumping = true;
}
}else{
m_MoveDir += Physics.gravity*m_GravityMultiplier*Time.fixedDeltaTime;
}
m_CollisionFlags = m_CharacterController.Move(m_MoveDir*Time.fixedDeltaTime);
ProgressStepCycle(speed);
UpdateCameraPosition(speed);
}
private void PlayJumpSound(){
if(enableMovementSounds){
m_AudioSource.clip = m_JumpSound;
m_AudioSource.Play ();
}
}
private void ProgressStepCycle(float speed){
if(m_CharacterController.velocity.sqrMagnitude > 0 && (m_Input.x != 0 || m_Input.y != 0)){
m_StepCycle += (m_CharacterController.velocity.magnitude + (speed*(m_IsWalking ? 1f : m_RunstepLenghten)))*Time.fixedDeltaTime;
}
if(!(m_StepCycle > m_NextStep)){
return;
}
m_NextStep = m_StepCycle + m_StepInterval;
PlayFootStepAudio();
}
private void PlayFootStepAudio(){
if(!m_CharacterController.isGrounded){
return;
}
if(enableMovementSounds){
// pick & play a random footstep sound from the array,
// excluding sound at index 0
int n = Random.Range (1, m_FootstepSounds.Length);
m_AudioSource.clip = m_FootstepSounds [n];
m_AudioSource.PlayOneShot (m_AudioSource.clip);
// move picked sound to index 0 so it's not picked next time
m_FootstepSounds [n] = m_FootstepSounds [0];
m_FootstepSounds [0] = m_AudioSource.clip;
}
}
private void UpdateCameraPosition(float speed){
Vector3 newCameraPosition;
if(!m_UseHeadBob){
return;
}
if(m_CharacterController.velocity.magnitude > 0 && m_CharacterController.isGrounded){
m_Camera.transform.localPosition = m_HeadBob.DoHeadBob(m_CharacterController.velocity.magnitude + (speed*(m_IsWalking ? 1f : m_RunstepLenghten)));
newCameraPosition = m_Camera.transform.localPosition;
newCameraPosition.y = m_Camera.transform.localPosition.y - m_JumpBob.Offset();
}else{
newCameraPosition = m_Camera.transform.localPosition;
newCameraPosition.y = m_OriginalCameraPosition.y - m_JumpBob.Offset();
}
m_Camera.transform.localPosition = newCameraPosition;
}
private void GetInput(out float speed){
// Read input
float horizontal = CrossPlatformInputManager.GetAxis("Horizontal");
float vertical = CrossPlatformInputManager.GetAxis("Vertical");
bool waswalking = m_IsWalking;
#if !MOBILE_INPUT
// On standalone builds, walk/run speed is modified by a key press.
// keep track of whether or not the character is walking or running
if(enableRunning){
m_IsWalking = !Input.GetKey(KeyCode.LeftShift);
}
#endif
// set the desired speed to be walking or running
speed = m_IsWalking ? m_WalkSpeed : m_RunSpeed;
m_Input = new Vector2(horizontal, vertical);
// normalize input if it exceeds 1 in combined length:
if(m_Input.sqrMagnitude > 1){
m_Input.Normalize();
}
// handle speed change to give an fov kick
// only if the player is going to a run, is running and the fovkick is to be used
if(m_IsWalking != waswalking && m_UseFovKick && m_CharacterController.velocity.sqrMagnitude > 0){
StopAllCoroutines();
StartCoroutine(!m_IsWalking ? m_FovKick.FOVKickUp() : m_FovKick.FOVKickDown());
}
}
private void RotateView(){
gameObject.GetComponent<MouseLook>().LookRotation(transform, m_Camera.transform);
}
private void OnControllerColliderHit(ControllerColliderHit hit){
Rigidbody body = hit.collider.attachedRigidbody;
//dont move the rigidbody if the character is on top of it
if(m_CollisionFlags == CollisionFlags.Below){
return;
}
if(body == null || body.isKinematic){
return;
}
body.AddForceAtPosition(m_CharacterController.velocity*0.1f, hit.point, ForceMode.Impulse);
}
}
}
| |
// *****************************************************************************
//
// (c) Crownwood Consulting Limited 2002
// All rights reserved. The software and associated documentation
// supplied hereunder are the proprietary information of Crownwood Consulting
// Limited, Haxey, North Lincolnshire, England and are supplied subject to
// licence terms.
//
// IDE Version 1.7 www.dotnetmagic.com
// *****************************************************************************
using System;
using System.IO;
using System.Xml;
using System.Data;
using System.Drawing;
using System.Reflection;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using IDE.Menus;
using IDE.Common;
using IDE.Controls;
using IDE.Collections;
namespace IDE.Controls
{
internal class TabGroupLeaf : TabGroupBase
{
// Class constants
protected const int _imageWidth = 16;
protected const int _imageHeight = 16;
protected const int _imageHorzSplit = 0;
protected const int _imageVertSplit = 1;
// Class state
protected static ImageList _internalImages;
// Instance fields
protected MenuCommand _mcClose;
protected MenuCommand _mcSep1;
protected MenuCommand _mcProm;
protected MenuCommand _mcReba;
protected MenuCommand _mcSep2;
protected MenuCommand _mcPrev;
protected MenuCommand _mcNext;
protected MenuCommand _mcVert;
protected MenuCommand _mcHorz;
protected Cursor _savedCursor;
protected bool _dragEntered;
protected TargetManager _targetManager;
protected Controls.TabControl _tabControl;
static TabGroupLeaf()
{
// Create a strip of images by loading an embedded bitmap resource
_internalImages = ResourceHelper.LoadBitmapStrip(Type.GetType("IDE.Controls.TabbedGroups"),
"IDE.Resources.ImagesTabbedGroups.bmp",
new Size(_imageWidth, _imageHeight),
new Point(0,0));
}
public TabGroupLeaf(TabbedGroups tabbedGroups, TabGroupBase parent)
: base(tabbedGroups, parent)
{
// Create our managed tab control instance
_tabControl = new Controls.TabControl();
// We need page drag to begin when mouse dragged a small distance
_tabControl.DragFromControl = false;
// We need to monitor attempts to drag into the tab control
_dragEntered = false;
_tabControl.AllowDrop = true;
_tabControl.DragDrop += new DragEventHandler(OnControlDragDrop);
_tabControl.DragEnter += new DragEventHandler(OnControlDragEnter);
_tabControl.DragLeave += new EventHandler(OnControlDragLeave);
// Need notification when page drag begins
_tabControl.PageDragStart += new MouseEventHandler(OnPageDragStart);
_tabControl.PageDragMove += new MouseEventHandler(OnPageDragMove);
_tabControl.PageDragEnd += new MouseEventHandler(OnPageDragEnd);
_tabControl.PageDragQuit += new MouseEventHandler(OnPageDragQuit);
// Hook into tab page collection events
_tabControl.TabPages.Cleared += new CollectionClear(OnTabPagesCleared);
_tabControl.TabPages.Inserted += new CollectionChange(OnTabPagesInserted);
_tabControl.TabPages.Removed += new CollectionChange(OnTabPagesRemoved);
// Hook into page level events
_tabControl.GotFocus += new EventHandler(OnGainedFocus);
_tabControl.PageGotFocus += new EventHandler(OnGainedFocus);
_tabControl.ClosePressed += new EventHandler(OnClose);
// Manager only created at start of drag operation
_targetManager = null;
DefinePopupMenuForControl(_tabControl);
// Setup the correct 'HideTabsMode' for the control
Notify(TabGroupBase.NotifyCode.DisplayTabMode);
// Define the default setup of TabControl and allow developer to customize
_tabbedGroups.OnTabControlCreated(_tabControl);
}
protected void DefinePopupMenuForControl(Controls.TabControl tabControl)
{
PopupMenu pm = new PopupMenu();
// Add all the standard menus we manage
_mcClose = new MenuCommand("", new EventHandler(OnClose));
_mcSep1 = new MenuCommand("-");
_mcProm = new MenuCommand("", new EventHandler(OnToggleProminent));
_mcReba = new MenuCommand("", new EventHandler(OnRebalance));
_mcSep2 = new MenuCommand("-");
_mcHorz = new MenuCommand("", _internalImages, _imageHorzSplit, new EventHandler(OnNewVertical));
_mcVert = new MenuCommand("", _internalImages, _imageVertSplit, new EventHandler(OnNewHorizontal));
_mcNext = new MenuCommand("", new EventHandler(OnMoveNext));
_mcPrev = new MenuCommand("", new EventHandler(OnMovePrevious));
// Prominent is a radio checked item
_mcProm.RadioCheck = true;
// Use the provided context menu
tabControl.ContextPopupMenu = pm;
// Update command states when shown
tabControl.PopupMenuDisplay += new CancelEventHandler(OnPopupMenuDisplay);
}
public TabPageCollection TabPages
{
get { return _tabControl.TabPages; }
}
public override void Notify(NotifyCode code)
{
switch(code)
{
case NotifyCode.ImageListChanging:
// Are we using the group level imagelist?
if (_tabbedGroups.ImageList == _tabControl.ImageList)
{
// Then remove its use
_tabControl.ImageList = null;
}
break;
case NotifyCode.ImageListChanged:
// If no imagelist defined
if (_tabControl.ImageList == null)
{
// Then use the group level one
_tabControl.ImageList = _tabbedGroups.ImageList;
}
break;
case NotifyCode.StyleChanged:
// Update tab control with new style
_tabControl.Style = _tabbedGroups.Style;
break;
case NotifyCode.DisplayTabMode:
// Apply the latest mode
switch(_tabbedGroups.DisplayTabMode)
{
case IDE.Controls.TabbedGroups.DisplayTabModes.ShowAll:
_tabControl.HideTabsMode = IDE.Controls.TabControl.HideTabsModes.ShowAlways;
break;
case IDE.Controls.TabbedGroups.DisplayTabModes.HideAll:
_tabControl.HideTabsMode = IDE.Controls.TabControl.HideTabsModes.HideAlways;
break;
case IDE.Controls.TabbedGroups.DisplayTabModes.ShowActiveLeaf:
_tabControl.HideTabsMode = (_tabbedGroups.ActiveLeaf == this ? IDE.Controls.TabControl.HideTabsModes.ShowAlways :
IDE.Controls.TabControl.HideTabsModes.HideAlways);
break;
case IDE.Controls.TabbedGroups.DisplayTabModes.ShowMouseOver:
_tabControl.HideTabsMode = IDE.Controls.TabControl.HideTabsModes.HideWithoutMouse;
break;
case IDE.Controls.TabbedGroups.DisplayTabModes.ShowActiveAndMouseOver:
_tabControl.HideTabsMode = (_tabbedGroups.ActiveLeaf == this ? IDE.Controls.TabControl.HideTabsModes.ShowAlways :
IDE.Controls.TabControl.HideTabsModes.HideWithoutMouse);
break;
}
break;
}
}
public override int Count { get { return _tabControl.TabPages.Count; } }
public override bool IsLeaf { get { return true; } }
public override bool IsSequence { get { return false; } }
public override Control GroupControl { get { return _tabControl; } }
public override bool ContainsProminent(bool recurse)
{
// Cache the currently selected prominent group
TabGroupLeaf prominent = _tabbedGroups.ProminentLeaf;
// Valid value to test against?
if (prominent != null)
return (this == prominent);
else
return false;
}
public override void SaveToXml(XmlTextWriter xmlOut)
{
// Output standard values appropriate for all Sequence instances
xmlOut.WriteStartElement("Leaf");
xmlOut.WriteAttributeString("Count", Count.ToString());
xmlOut.WriteAttributeString("Unique", _unique.ToString());
xmlOut.WriteAttributeString("Space", _space.ToString());
// Output each tab page
foreach(Controls.TabPage tp in _tabControl.TabPages)
{
string controlType = "null";
if (tp.Control != null)
controlType = tp.Control.GetType().AssemblyQualifiedName;
xmlOut.WriteStartElement("Page");
xmlOut.WriteAttributeString("Title", tp.Title);
xmlOut.WriteAttributeString("ImageList", (tp.ImageList != null).ToString());
xmlOut.WriteAttributeString("ImageIndex", tp.ImageIndex.ToString());
xmlOut.WriteAttributeString("Selected", tp.Selected.ToString());
xmlOut.WriteAttributeString("Control", controlType);
// Give handlers chance to reconstruct the page
xmlOut.WriteStartElement("CustomPageData");
_tabbedGroups.OnPageSaving(new TGPageSavingEventArgs(tp, xmlOut));
xmlOut.WriteEndElement();
xmlOut.WriteEndElement();
}
xmlOut.WriteEndElement();
}
public override void LoadFromXml(XmlTextReader xmlIn)
{
// Grab the expected attributes
string rawCount = xmlIn.GetAttribute(0);
string rawUnique = xmlIn.GetAttribute(1);
string rawSpace = xmlIn.GetAttribute(2);
// Convert to correct types
int count = Convert.ToInt32(rawCount);
int unique = Convert.ToInt32(rawUnique);
Decimal space = Convert.ToDecimal(rawSpace);
// Update myself with new values
_unique = unique;
_space = space;
// Load each of the children
for(int i=0; i<count; i++)
{
// Read to the first page element or
if (!xmlIn.Read())
throw new ArgumentException("An element was expected but could not be read in");
// Must always be a page instance
if (xmlIn.Name == "Page")
{
Controls.TabPage tp = new Controls.TabPage();
// Grab the expected attributes
string title = xmlIn.GetAttribute(0);
string rawImageList = xmlIn.GetAttribute(1);
string rawImageIndex = xmlIn.GetAttribute(2);
string rawSelected = xmlIn.GetAttribute(3);
string controlType = xmlIn.GetAttribute(4);
// Convert to correct types
bool imageList = Convert.ToBoolean(rawImageList);
int imageIndex = Convert.ToInt32(rawImageIndex);
bool selected = Convert.ToBoolean(rawSelected);
// Setup new page instance
tp.Title = title;
tp.ImageIndex = imageIndex;
tp.Selected = selected;
if (imageList)
tp.ImageList = _tabbedGroups.ImageList;
// Is there a type description of required control?
if (controlType != "null")
{
try
{
// Get type description, if possible
Type t = Type.GetType(controlType);
// Was a valid, known type?
if (t != null)
{
// Get the assembly this type is defined inside
Assembly a = t.Assembly;
if (a != null)
{
// Create a new instance form the assemnly
object newObj = a.CreateInstance(t.FullName);
Control newControl = newObj as Control;
// Must derive from Control to be of use to us
if (newControl != null)
tp.Control = newControl;
}
}
}
catch
{
// We ignore failure to recreate given control type
}
}
// Read to the custom data element
if (!xmlIn.Read())
throw new ArgumentException("An element was expected but could not be read in");
if (xmlIn.Name != "CustomPageData")
throw new ArgumentException("Expected 'CustomPageData' element was not found");
bool finished = xmlIn.IsEmptyElement;
TGPageLoadingEventArgs e = new TGPageLoadingEventArgs(tp, xmlIn);
// Give handlers chance to reconstruct per-page information
_tabbedGroups.OnPageLoading(e);
// Add into the control unless handler cancelled add operation
if (!e.Cancel)
_tabControl.TabPages.Add(tp);
// Read everything until we get the end of custom data marker
while(!finished)
{
// Check it has the expected name
if (xmlIn.NodeType == XmlNodeType.EndElement)
finished = (xmlIn.Name == "CustomPageData");
if (!finished)
{
if (!xmlIn.Read())
throw new ArgumentException("An element was expected but could not be read in");
}
}
// Read past the end of page element
if (!xmlIn.Read())
throw new ArgumentException("An element was expected but could not be read in");
// Check it has the expected name
if (xmlIn.NodeType != XmlNodeType.EndElement)
throw new ArgumentException("End of 'page' element expected but missing");
}
else
throw new ArgumentException("Unknown element was encountered");
}
}
protected void OnGainedFocus(object sender, EventArgs e)
{
// This tab control has the focus, make it the active leaf
_tabbedGroups.ActiveLeaf = this;
}
protected void OnTabPagesCleared()
{
// All pages removed, do we need to compact?
if (_tabbedGroups.AutoCompact)
_tabbedGroups.Compact();
// Mark layout as dirty
if (_tabbedGroups.AutoCalculateDirty)
_tabbedGroups.Dirty = true;
}
protected void OnTabPagesInserted(int index, object value)
{
// If there is no currently active leaf then make it us
if (_tabbedGroups.ActiveLeaf == null)
_tabbedGroups.ActiveLeaf = this;
// Mark layout as dirty
if (_tabbedGroups.AutoCalculateDirty)
_tabbedGroups.Dirty = true;
}
protected void OnTabPagesRemoved(int index, object value)
{
if (_tabControl.TabPages.Count == 0)
{
// All pages removed, do we need to compact?
if (_tabbedGroups.AutoCompact)
_tabbedGroups.Compact();
}
// Mark layout as dirty
if (_tabbedGroups.AutoCalculateDirty)
_tabbedGroups.Dirty = true;
}
protected void OnPopupMenuDisplay(object sender, CancelEventArgs e)
{
// Remove all existing menu items
_tabControl.ContextPopupMenu.MenuCommands.Clear();
// Add our standard set of menus
_tabControl.ContextPopupMenu.MenuCommands.AddRange(new MenuCommand[]{_mcClose, _mcSep1,
_mcProm, _mcReba,
_mcSep2, _mcHorz,
_mcVert, _mcNext,
_mcPrev});
// Are any pages selected
bool valid = (_tabControl.SelectedIndex != -1);
// Define the latest text string
_mcClose.Text = _tabbedGroups.CloseMenuText;
_mcProm.Text = _tabbedGroups.ProminentMenuText;
_mcReba.Text = _tabbedGroups.RebalanceMenuText;
_mcPrev.Text = _tabbedGroups.MovePreviousMenuText;
_mcNext.Text = _tabbedGroups.MoveNextMenuText;
_mcVert.Text = _tabbedGroups.NewVerticalMenuText;
_mcHorz.Text = _tabbedGroups.NewHorizontalMenuText;
// Only need to close option if the tab has close defined
_mcClose.Visible = _tabControl.ShowClose && valid;
_mcSep1.Visible = _tabControl.ShowClose && valid;
// Update the radio button for prominent
_mcProm.Checked = (_tabbedGroups.ProminentLeaf == this);
// Can only create new group if at least two pages exist
bool split = valid && (_tabControl.TabPages.Count > 1);
bool vertSplit = split;
bool horzSplit = split;
TabGroupSequence tgs = _parent as TabGroupSequence;
// If we are not the only leaf, then can only split in
// the same direction as the group we are in
if (tgs.Count > 1)
{
if (tgs.Direction == Direction.Vertical)
vertSplit = false;
else
horzSplit = false;
}
_mcVert.Visible = vertSplit;
_mcHorz.Visible = horzSplit;
// Can only how movement if group exists in that direction
_mcNext.Visible = valid && (_tabbedGroups.NextLeaf(this) != null);
_mcPrev.Visible = valid && (_tabbedGroups.PreviousLeaf(this) != null);
TGContextMenuEventArgs tge = new TGContextMenuEventArgs(this,
_tabControl,
_tabControl.SelectedTab,
_tabControl.ContextPopupMenu);
// Generate event so handlers can add/remove/cancel menu
_tabbedGroups.OnPageContextMenu(tge);
// Pass back cancel value
e.Cancel = tge.Cancel;
}
internal void OnClose(object sender, EventArgs e)
{
TGCloseRequestEventArgs tge = new TGCloseRequestEventArgs(this, _tabControl, _tabControl.SelectedTab);
// Generate event so handlers can perform appropriate action
_tabbedGroups.OnPageCloseRequested(tge);
// Still want to close the page?
if (!tge.Cancel)
_tabControl.TabPages.Remove(_tabControl.SelectedTab);
}
internal void OnToggleProminent(object sender, EventArgs e)
{
// Toggel the prominent mode
if (_tabbedGroups.ProminentLeaf == this)
_tabbedGroups.ProminentLeaf = null;
else
_tabbedGroups.ProminentLeaf = this;
}
internal void OnRebalance(object sender, EventArgs e)
{
_tabbedGroups.Rebalance();
}
internal void OnMovePrevious(object sender, EventArgs e)
{
// Find the previous leaf node
TabGroupLeaf prev = _tabbedGroups.PreviousLeaf(this);
// Must always be valid!
if (prev != null)
MovePageToLeaf(prev);
}
internal void OnMoveNext(object sender, EventArgs e)
{
// Find the previous leaf node
TabGroupLeaf next = _tabbedGroups.NextLeaf(this);
// Must always be valid!
if (next != null)
MovePageToLeaf(next);
}
internal void OnNewVertical(object sender, EventArgs e)
{
NewVerticalGroup(this, false);
}
protected void OnNewHorizontal(object sender, EventArgs e)
{
NewHorizontalGroup(this, false);
}
internal void NewVerticalGroup(TabGroupLeaf sourceLeaf, bool before)
{
TabGroupSequence tgs = this.Parent as TabGroupSequence;
// We must have a parent sequence!
if (tgs != null)
{
tgs.Direction = Direction.Vertical;
AddGroupToSequence(tgs, sourceLeaf, before);
}
}
internal void NewHorizontalGroup(TabGroupLeaf sourceLeaf, bool before)
{
TabGroupSequence tgs = this.Parent as TabGroupSequence;
// We must have a parent sequence!
if (tgs != null)
{
tgs.Direction = Direction.Horizontal;
AddGroupToSequence(tgs, sourceLeaf, before);
}
}
internal void MovePageToLeaf(TabGroupLeaf leaf)
{
// Remember original auto compact mode
bool autoCompact = _tabbedGroups.AutoCompact;
// Turn mode off as it interferes with reorganisation
_tabbedGroups.AutoCompact = false;
// Get the requested tab page to be moved to new leaf
TabPage tp = _tabControl.SelectedTab;
// Remove page from ourself
_tabControl.TabPages.Remove(tp);
// Add into the new leaf
leaf.TabPages.Add(tp);
// Make new leaf the active one
_tabbedGroups.ActiveLeaf = leaf;
TabControl tc = leaf.GroupControl as Controls.TabControl;
// Select the newly added page
tc.SelectedTab = tp;
// Reset compacting mode as we have updated the structure
_tabbedGroups.AutoCompact = autoCompact;
// Do we need to compact?
if (_tabbedGroups.AutoCompact)
_tabbedGroups.Compact();
}
protected void AddGroupToSequence(TabGroupSequence tgs, TabGroupLeaf sourceLeaf, bool before)
{
// Remember original auto compact mode
bool autoCompact = _tabbedGroups.AutoCompact;
// Turn mode off as it interferes with reorganisation
_tabbedGroups.AutoCompact = false;
// Find our index into parent collection
int pos = tgs.IndexOf(this);
TabGroupLeaf newGroup = null;
// New group inserted before existing one?
if (before)
newGroup = tgs.InsertNewLeaf(pos);
else
{
// No, are we at the end of the collection?
if (pos == (tgs.Count - 1))
newGroup = tgs.AddNewLeaf();
else
newGroup = tgs.InsertNewLeaf(pos + 1);
}
// Get tab control for source leaf
Controls.TabControl tc = sourceLeaf.GroupControl as Controls.TabControl;
TabPage tp = tc.SelectedTab;
// Remove page from ourself
tc.TabPages.Remove(tp);
// Add into the new leaf
newGroup.TabPages.Add(tp);
// Reset compacting mode as we have updated the structure
_tabbedGroups.AutoCompact = autoCompact;
// Do we need to compact?
if (_tabbedGroups.AutoCompact)
_tabbedGroups.Compact();
}
protected void OnPageDragStart(object sender, MouseEventArgs e)
{
// Save the current cursor value
_savedCursor = _tabControl.Cursor;
// Manager will create hot zones and draw dragging rectangle
_targetManager = new TargetManager(_tabbedGroups, this, _tabControl);
}
protected void OnPageDragMove(object sender, MouseEventArgs e)
{
// Convert from Control coordinates to screen coordinates
Point mousePos = _tabControl.PointToScreen(new Point(e.X, e.Y));
// Let manager decide on drawing rectangles and setting cursor
_targetManager.MouseMove(mousePos);
}
protected void OnPageDragEnd(object sender, MouseEventArgs e)
{
// Give manager chance to action request and cleanup
_targetManager.Exit();
// No longer need the manager
_targetManager = null;
// Restore the original cursor
_tabControl.Cursor = _savedCursor;
}
protected void OnPageDragQuit(object sender, MouseEventArgs e)
{
// Give manager chance to cleanup
_targetManager.Quit();
// No longer need the manager
_targetManager = null;
// Restore the original cursor
_tabControl.Cursor = _savedCursor;
}
protected void OnControlDragEnter(object sender, DragEventArgs drgevent)
{
_dragEntered = ValidFormat(drgevent);
// Do we allow the drag to occur?
if (_dragEntered)
{
// Must draw a drag indicator
DrawDragIndicator();
// Update the allowed effects
drgevent.Effect = DragDropEffects.Copy;
}
}
protected void OnControlDragDrop(object sender, DragEventArgs drgevent)
{
// Do we allow the drop to occur?
if (_dragEntered)
{
// Must remove the drag indicator
DrawDragIndicator();
// Generate an event so caller can perform required action
_tabbedGroups.OnExternalDrop(this, _tabControl, GetDragProvider(drgevent));
}
_dragEntered = false;
}
protected void OnControlDragLeave(object sender, EventArgs e)
{
// Do we need to remove the drag indicator?
if (_dragEntered)
DrawDragIndicator();
_dragEntered = false;
}
protected bool ValidFormat(DragEventArgs e)
{
return e.Data.GetDataPresent(typeof(TabbedGroups.DragProvider));
}
protected TabbedGroups.DragProvider GetDragProvider(DragEventArgs e)
{
return (TabbedGroups.DragProvider)e.Data.GetData(typeof(TabbedGroups.DragProvider));
}
protected void DrawDragIndicator()
{
// Create client rectangle
Rectangle clientRect = new Rectangle(new Point(0,0), _tabControl.ClientSize);
// Draw drag indicator around whole control
TargetManager.DrawDragRectangle(_tabControl.RectangleToScreen(clientRect));
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.InteropServices;
internal static partial class Interop
{
internal static partial class Process
{
private const ulong SecondsToNanoSeconds = 1000000000;
// Constants from sys/syslimits.h
private const int PATH_MAX = 1024;
// Constants from sys/user.h
private const int TDNAMLEN = 16;
private const int WMESGLEN = 8;
private const int LOGNAMELEN = 17;
private const int LOCKNAMELEN = 8;
private const int COMMLEN = 19;
private const int KI_EMULNAMELEN = 16;
private const int LOGINCLASSLEN = 17;
private const int KI_NGROUPS = 16;
private const int KI_NSPARE_INT = 4;
private const int KI_NSPARE_LONG = 12;
private const int KI_NSPARE_PTR = 6;
// Constants from sys/_sigset.h
private const int _SIG_WORDS = 4;
// Constants from sys/sysctl.h
private const int CTL_KERN = 1;
private const int KERN_PROC = 14;
private const int KERN_PROC_PATHNAME = 12;
private const int KERN_PROC_PROC = 8;
private const int KERN_PROC_ALL = 0;
private const int KERN_PROC_PID = 1;
private const int KERN_PROC_INC_THREAD = 16;
// Constants from proc_info.h
private const int MAXTHREADNAMESIZE = 64;
private const int PROC_PIDTASKALLINFO = 2;
private const int PROC_PIDTHREADINFO = 5;
private const int PROC_PIDLISTTHREADS = 6;
private const int PROC_PIDPATHINFO_MAXSIZE = 4 * PATH_MAX;
internal struct proc_stats
{
internal long startTime; /* time_t */
internal int nice;
internal ulong userTime; /* in ticks */
internal ulong systemTime; /* in ticks */
}
// From sys/_sigset.h
[StructLayout(LayoutKind.Sequential)]
internal unsafe struct sigset_t
{
private fixed int bits[4];
}
[StructLayout(LayoutKind.Sequential)]
internal struct uid_t
{
public uint id;
}
[StructLayout(LayoutKind.Sequential)]
internal struct gid_t
{
public uint id;
}
[StructLayout(LayoutKind.Sequential)]
public struct timeval
{
public IntPtr tv_sec;
public IntPtr tv_usec;
}
[StructLayout(LayoutKind.Sequential)]
struct vnode
{
public long tv_sec;
public long tv_usec;
}
// sys/resource.h
[StructLayout(LayoutKind.Sequential)]
internal unsafe struct rusage
{
public timeval ru_utime; /* user time used */
public timeval ru_stime; /* system time used */
public long ru_maxrss; /* max resident set size */
private long ru_ixrss; /* integral shared memory size */
private long ru_idrss; /* integral unshared data " */
private long ru_isrss; /* integral unshared stack " */
private long ru_minflt; /* page reclaims */
private long ru_majflt; /* page faults */
private long ru_nswap; /* swaps */
private long ru_inblock; /* block input operations */
private long ru_oublock; /* block output operations */
private long ru_msgsnd; /* messages sent */
private long ru_msgrcv; /* messages received */
private long ru_nsignals; /* signals received */
private long ru_nvcsw; /* voluntary context switches */
private long ru_nivcsw; /* involuntary " */
}
// From sys/user.h
[StructLayout(LayoutKind.Sequential)]
public unsafe struct kinfo_proc
{
public int ki_structsize; /* size of this structure */
private int ki_layout; /* reserved: layout identifier */
private void* ki_args; /* address of command arguments */
private void* ki_paddr; /* address of proc */
private void* ki_addr; /* kernel virtual addr of u-area */
private vnode* ki_tracep; /* pointer to trace file */
private vnode* ki_textvp; /* pointer to executable file */
private void* ki_fd; /* pointer to open file info */
private void* ki_vmspace; /* pointer to kernel vmspace struct */
private void* ki_wchan; /* sleep address */
public int ki_pid; /* Process identifier */
public int ki_ppid; /* parent process id */
private int ki_pgid; /* process group id */
private int ki_tpgid; /* tty process group id */
public int ki_sid; /* Process session ID */
public int ki_tsid; /* Terminal session ID */
private short ki_jobc; /* job control counter */
private short ki_spare_short1; /* unused (just here for alignment) */
private int ki_tdev; /* controlling tty dev */
private sigset_t ki_siglist; /* Signals arrived but not delivered */
private sigset_t ki_sigmask; /* Current signal mask */
private sigset_t ki_sigignore; /* Signals being ignored */
private sigset_t ki_sigcatch; /* Signals being caught by user */
public uid_t ki_uid; /* effective user id */
private uid_t ki_ruid; /* Real user id */
private uid_t ki_svuid; /* Saved effective user id */
private gid_t ki_rgid; /* Real group id */
private gid_t ki_svgid; /* Saved effective group id */
private short ki_ngroups; /* number of groups */
private short ki_spare_short2; /* unused (just here for alignment) */
private fixed uint ki_groups[KI_NGROUPS]; /* groups */
public ulong ki_size; /* virtual size */
public long ki_rssize; /* current resident set size in pages */
private long ki_swrss; /* resident set size before last swap */
private long ki_tsize; /* text size (pages) XXX */
private long ki_dsize; /* data size (pages) XXX */
private long ki_ssize; /* stack size (pages) */
private ushort ki_xstat; /* Exit status for wait & stop signal */
private ushort ki_acflag; /* Accounting flags */
private uint ki_pctcpu; /* %cpu for process during ki_swtime */
private uint ki_estcpu; /* Time averaged value of ki_cpticks */
private uint ki_slptime; /* Time since last blocked */
private uint ki_swtime; /* Time swapped in or out */
private uint ki_cow; /* number of copy-on-write faults */
private ulong ki_runtime; /* Real time in microsec */
public timeval ki_start; /* starting time */
private timeval ki_childtime; /* time used by process children */
private long ki_flag; /* P_* flags */
private long ki_kiflag; /* KI_* flags (below) */
private int ki_traceflag; /* Kernel trace points */
private byte ki_stat; /* S* process status */
public byte ki_nice; /* Process "nice" value */
private byte ki_lock; /* Process lock (prevent swap) count */
private byte ki_rqindex; /* Run queue index */
private byte ki_oncpu_old; /* Which cpu we are on (legacy) */
private byte ki_lastcpu_old; /* Last cpu we were on (legacy) */
public fixed byte ki_tdname[TDNAMLEN+1]; /* thread name */
private fixed byte ki_wmesg[WMESGLEN+1]; /* wchan message */
private fixed byte ki_login[LOGNAMELEN+1]; /* setlogin name */
private fixed byte ki_lockname[LOCKNAMELEN+1]; /* lock name */
public fixed byte ki_comm[COMMLEN+1]; /* command name */
private fixed byte ki_emul[KI_EMULNAMELEN+1]; /* emulation name */
private fixed byte ki_loginclass[LOGINCLASSLEN+1]; /* login class */
private fixed byte ki_sparestrings[50]; /* spare string space */
private fixed int ki_spareints[KI_NSPARE_INT]; /* spare room for growth */
private int ki_oncpu; /* Which cpu we are on */
private int ki_lastcpu; /* Last cpu we were on */
private int ki_tracer; /* Pid of tracing process */
private int ki_flag2; /* P2_* flags */
private int ki_fibnum; /* Default FIB number */
private uint ki_cr_flags; /* Credential flags */
private int ki_jid; /* Process jail ID */
public int ki_numthreads; /* XXXKSE number of threads in total */
public int ki_tid; /* XXXKSE thread id */
private fixed byte ki_pri[4]; /* process priority */
public rusage ki_rusage; /* process rusage statistics */
/* XXX - most fields in ki_rusage_ch are not (yet) filled in */
private rusage ki_rusage_ch; /* rusage of children processes */
private void* ki_pcb; /* kernel virtual addr of pcb */
private void* ki_kstack; /* kernel virtual addr of stack */
private void* ki_udata; /* User convenience pointer */
public void* ki_tdaddr; /* address of thread */
private fixed long ki_spareptrs[KI_NSPARE_PTR]; /* spare room for growth */
private fixed long ki_sparelongs[KI_NSPARE_LONG]; /* spare room for growth */
private long ki_sflag; /* PS_* flags */
private long ki_tdflags; /* XXXKSE kthread flag */
}
/// <summary>
/// Queries the OS for the list of all running processes and returns the PID for each
/// </summary>
/// <returns>Returns a list of PIDs corresponding to all running processes</returns>
internal static unsafe int[] ListAllPids()
{
int numProcesses = 0;
int[] pids;
kinfo_proc * entries = null;
int idx;
try
{
entries = GetProcInfo(0, false, out numProcesses);
if (entries == null || numProcesses <= 0)
{
throw new Win32Exception(SR.CantGetAllPids);
}
var list = new ReadOnlySpan<kinfo_proc>(entries, numProcesses);
pids = new int[numProcesses];
idx = 0;
// walk through process list and skip kernel threads
for (int i = 0; i < list.Length; i++)
{
if (list[i].ki_ppid == 0)
{
// skip kernel threads
numProcesses-=1;
}
else
{
pids[idx] = list[i].ki_pid;
idx += 1;
}
}
// Remove extra elements
Array.Resize<int>(ref pids, numProcesses);
}
finally
{
Marshal.FreeHGlobal((IntPtr)entries);
}
return pids;
}
/// <summary>
/// Gets executable name for process given it's PID
/// </summary>
/// <param name="pid">The PID of the process</param>
public static unsafe string GetProcPath(int pid)
{
Span<int> sysctlName = stackalloc int[4];
byte* pBuffer = null;
int bytesLength = 0;
sysctlName[0] = CTL_KERN;
sysctlName[1] = KERN_PROC;
sysctlName[2] = KERN_PROC_PATHNAME;
sysctlName[3] = pid;
int ret = Interop.Sys.Sysctl(sysctlName, ref pBuffer, ref bytesLength);
if (ret != 0 ) {
return null;
}
return System.Text.Encoding.UTF8.GetString(pBuffer,(int)bytesLength-1);
}
/// <summary>
/// Gets information about process or thread(s)
/// </summary>
/// <param name="pid">The PID of the process. If PID is 0, this will return all processes</param>
public static unsafe kinfo_proc* GetProcInfo(int pid, bool threads, out int count)
{
Span<int> sysctlName = stackalloc int[4];
int bytesLength = 0;
byte* pBuffer = null;
kinfo_proc* kinfo = null;
int ret;
count = -1;
if (pid == 0)
{
// get all processes
sysctlName[3] = 0;
sysctlName[2] = KERN_PROC_PROC;
}
else
{
// get specific process, possibly with threads
sysctlName[3] = pid;
sysctlName[2] = KERN_PROC_PID | (threads ? KERN_PROC_INC_THREAD : 0);
}
sysctlName[1] = KERN_PROC;
sysctlName[0] = CTL_KERN;
try
{
ret = Interop.Sys.Sysctl(sysctlName, ref pBuffer, ref bytesLength);
if (ret != 0 ) {
throw new ArgumentOutOfRangeException(nameof(pid));
}
kinfo = (kinfo_proc*)pBuffer;
if (kinfo->ki_structsize != sizeof(kinfo_proc))
{
// failed consistency check
throw new ArgumentOutOfRangeException(nameof(pid));
}
count = (int)bytesLength / sizeof(kinfo_proc);
}
catch
{
Marshal.FreeHGlobal((IntPtr)pBuffer);
throw;
}
return kinfo;
}
/// <summary>
/// Gets the process information for a given process
/// </summary>
/// <param name="pid">The PID (process ID) of the process</param>
/// <returns>
/// Returns a valid ProcessInfo struct for valid processes that the caller
/// has permission to access; otherwise, returns null
/// </returns>
static public unsafe ProcessInfo GetProcessInfoById(int pid)
{
kinfo_proc* kinfo = null;
int count;
ProcessInfo info;
// Negative PIDs are invalid
if (pid < 0)
{
throw new ArgumentOutOfRangeException(nameof(pid));
}
try
{
kinfo = GetProcInfo(pid, true, out count);
if (kinfo == null || count < 1)
{
throw new ArgumentOutOfRangeException(nameof(pid));
}
var process = new ReadOnlySpan<kinfo_proc>(kinfo, count);
// Get the process information for the specified pid
info = new ProcessInfo();
info.ProcessName = Marshal.PtrToStringAnsi((IntPtr)kinfo->ki_comm);
info.BasePriority = kinfo->ki_nice;
info.VirtualBytes = (long)kinfo->ki_size;
info.WorkingSet = kinfo->ki_rssize;
info.SessionId = kinfo ->ki_sid;
for(int i = 0; i < process.Length; i++)
{
var ti = new ThreadInfo()
{
_processId = pid,
_threadId = (ulong)process[i].ki_tid,
_basePriority = process[i].ki_nice,
_startAddress = (IntPtr)process[i].ki_tdaddr
};
info._threadInfoList.Add(ti);
}
}
finally
{
Marshal.FreeHGlobal((IntPtr)kinfo);
}
return info;
}
/// <summary>
/// Gets the process information for a given process
/// </summary>
/// <param name="pid">The PID (process ID) of the process</param>
/// <param name="tid">The TID (thread ID) of the process</param>
/// <returns>
/// Returns basic info about thread. If tis is 0, it will return
/// info for process e.g. main thread.
/// </returns>
public unsafe static proc_stats GetThreadInfo(int pid, int tid)
{
proc_stats ret = new proc_stats();
kinfo_proc* info = null;
int count;
try
{
info = GetProcInfo(pid, (tid != 0), out count);
if (info != null && count >= 1)
{
if (tid == 0)
{
ret.startTime = (int)info->ki_start.tv_sec;
ret.nice = info->ki_nice;
ret.userTime = (ulong)info->ki_rusage.ru_utime.tv_sec * SecondsToNanoSeconds + (ulong)info->ki_rusage.ru_utime.tv_usec;
ret.systemTime = (ulong)info->ki_rusage.ru_stime.tv_sec * SecondsToNanoSeconds + (ulong)info->ki_rusage.ru_stime.tv_usec;
}
else
{
var list = new ReadOnlySpan<kinfo_proc>(info, count);
for(int i = 0; i < list.Length; i++)
{
if (list[i].ki_tid == tid)
{
ret.startTime = (int)list[i].ki_start.tv_sec;
ret.nice = list[i].ki_nice;
ret.userTime = (ulong)list[i].ki_rusage.ru_utime.tv_sec * SecondsToNanoSeconds + (ulong)list[i].ki_rusage.ru_utime.tv_usec;
ret.systemTime = (ulong)list[i].ki_rusage.ru_stime.tv_sec * SecondsToNanoSeconds + (ulong)list[i].ki_rusage.ru_stime.tv_usec;
break;
}
}
}
}
}
finally
{
Marshal.FreeHGlobal((IntPtr)info);
}
return ret;
}
}
}
| |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
#if !SILVERLIGHT && !__IOS__ && !__ANDROID__
namespace NLog.Targets
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Data.Common;
using System.Globalization;
using System.Reflection;
using System.Text;
using System.Transactions;
using NLog.Common;
using NLog.Config;
using NLog.Internal;
using NLog.Layouts;
using ConfigurationManager = System.Configuration.ConfigurationManager;
/// <summary>
/// Writes log messages to the database using an ADO.NET provider.
/// </summary>
/// <seealso href="https://github.com/nlog/nlog/wiki/Database-target">Documentation on NLog Wiki</seealso>
/// <example>
/// <para>
/// The configuration is dependent on the database type, because
/// there are differnet methods of specifying connection string, SQL
/// command and command parameters.
/// </para>
/// <para>MS SQL Server using System.Data.SqlClient:</para>
/// <code lang="XML" source="examples/targets/Configuration File/Database/MSSQL/NLog.config" height="450" />
/// <para>Oracle using System.Data.OracleClient:</para>
/// <code lang="XML" source="examples/targets/Configuration File/Database/Oracle.Native/NLog.config" height="350" />
/// <para>Oracle using System.Data.OleDBClient:</para>
/// <code lang="XML" source="examples/targets/Configuration File/Database/Oracle.OleDB/NLog.config" height="350" />
/// <para>To set up the log target programmatically use code like this (an equivalent of MSSQL configuration):</para>
/// <code lang="C#" source="examples/targets/Configuration API/Database/MSSQL/Example.cs" height="630" />
/// </example>
[Target("Database")]
public sealed class DatabaseTarget : Target, IInstallable
{
private static Assembly systemDataAssembly = typeof(IDbConnection).Assembly;
private IDbConnection activeConnection = null;
private string activeConnectionString;
/// <summary>
/// Initializes a new instance of the <see cref="DatabaseTarget" /> class.
/// </summary>
public DatabaseTarget()
{
this.Parameters = new List<DatabaseParameterInfo>();
this.InstallDdlCommands = new List<DatabaseCommandInfo>();
this.UninstallDdlCommands = new List<DatabaseCommandInfo>();
this.DBProvider = "sqlserver";
this.DBHost = ".";
this.ConnectionStringsSettings = ConfigurationManager.ConnectionStrings;
this.CommandType = CommandType.Text;
}
/// <summary>
/// Gets or sets the name of the database provider.
/// </summary>
/// <remarks>
/// <para>
/// The parameter name should be a provider invariant name as registered in machine.config or app.config. Common values are:
/// </para>
/// <ul>
/// <li><c>System.Data.SqlClient</c> - <see href="http://msdn.microsoft.com/en-us/library/system.data.sqlclient.aspx">SQL Sever Client</see></li>
/// <li><c>System.Data.SqlServerCe.3.5</c> - <see href="http://www.microsoft.com/sqlserver/2005/en/us/compact.aspx">SQL Sever Compact 3.5</see></li>
/// <li><c>System.Data.OracleClient</c> - <see href="http://msdn.microsoft.com/en-us/library/system.data.oracleclient.aspx">Oracle Client from Microsoft</see> (deprecated in .NET Framework 4)</li>
/// <li><c>Oracle.DataAccess.Client</c> - <see href="http://www.oracle.com/technology/tech/windows/odpnet/index.html">ODP.NET provider from Oracle</see></li>
/// <li><c>System.Data.SQLite</c> - <see href="http://sqlite.phxsoftware.com/">System.Data.SQLite driver for SQLite</see></li>
/// <li><c>Npgsql</c> - <see href="http://npgsql.projects.postgresql.org/">Npgsql driver for PostgreSQL</see></li>
/// <li><c>MySql.Data.MySqlClient</c> - <see href="http://www.mysql.com/downloads/connector/net/">MySQL Connector/Net</see></li>
/// </ul>
/// <para>(Note that provider invariant names are not supported on .NET Compact Framework).</para>
/// <para>
/// Alternatively the parameter value can be be a fully qualified name of the provider
/// connection type (class implementing <see cref="IDbConnection" />) or one of the following tokens:
/// </para>
/// <ul>
/// <li><c>sqlserver</c>, <c>mssql</c>, <c>microsoft</c> or <c>msde</c> - SQL Server Data Provider</li>
/// <li><c>oledb</c> - OLEDB Data Provider</li>
/// <li><c>odbc</c> - ODBC Data Provider</li>
/// </ul>
/// </remarks>
/// <docgen category='Connection Options' order='10' />
[RequiredParameter]
[DefaultValue("sqlserver")]
public string DBProvider { get; set; }
/// <summary>
/// Gets or sets the name of the connection string (as specified in <see href="http://msdn.microsoft.com/en-us/library/bf7sd233.aspx"><connectionStrings> configuration section</see>.
/// </summary>
/// <docgen category='Connection Options' order='10' />
public string ConnectionStringName { get; set; }
/// <summary>
/// Gets or sets the connection string. When provided, it overrides the values
/// specified in DBHost, DBUserName, DBPassword, DBDatabase.
/// </summary>
/// <docgen category='Connection Options' order='10' />
public Layout ConnectionString { get; set; }
/// <summary>
/// Gets or sets the connection string using for installation and uninstallation. If not provided, regular ConnectionString is being used.
/// </summary>
/// <docgen category='Installation Options' order='10' />
public Layout InstallConnectionString { get; set; }
/// <summary>
/// Gets the installation DDL commands.
/// </summary>
/// <docgen category='Installation Options' order='10' />
[ArrayParameter(typeof(DatabaseCommandInfo), "install-command")]
public IList<DatabaseCommandInfo> InstallDdlCommands { get; private set; }
/// <summary>
/// Gets the uninstallation DDL commands.
/// </summary>
/// <docgen category='Installation Options' order='10' />
[ArrayParameter(typeof(DatabaseCommandInfo), "uninstall-command")]
public IList<DatabaseCommandInfo> UninstallDdlCommands { get; private set; }
/// <summary>
/// Gets or sets a value indicating whether to keep the
/// database connection open between the log events.
/// </summary>
/// <docgen category='Connection Options' order='10' />
[DefaultValue(false)]
public bool KeepConnection { get; set; }
/// <summary>
/// Obsolete - value will be ignored! The logging code always runs outside of transaction.
///
/// Gets or sets a value indicating whether to use database transactions.
/// Some data providers require this.
/// </summary>
/// <docgen category='Connection Options' order='10' />
/// <remarks>
/// This option was removed in NLog 4.0 because the logging code always runs outside of transaction.
/// This ensures that the log gets written to the database if you rollback the main transaction because of an error and want to log the error.
/// </remarks>
[Obsolete("Obsolete - value will be ignored - logging code always runs outside of transaction. Will be removed in NLog 6.")]
public bool? UseTransactions { get; set; }
/// <summary>
/// Gets or sets the database host name. If the ConnectionString is not provided
/// this value will be used to construct the "Server=" part of the
/// connection string.
/// </summary>
/// <docgen category='Connection Options' order='10' />
public Layout DBHost { get; set; }
/// <summary>
/// Gets or sets the database user name. If the ConnectionString is not provided
/// this value will be used to construct the "User ID=" part of the
/// connection string.
/// </summary>
/// <docgen category='Connection Options' order='10' />
public Layout DBUserName { get; set; }
/// <summary>
/// Gets or sets the database password. If the ConnectionString is not provided
/// this value will be used to construct the "Password=" part of the
/// connection string.
/// </summary>
/// <docgen category='Connection Options' order='10' />
public Layout DBPassword { get; set; }
/// <summary>
/// Gets or sets the database name. If the ConnectionString is not provided
/// this value will be used to construct the "Database=" part of the
/// connection string.
/// </summary>
/// <docgen category='Connection Options' order='10' />
public Layout DBDatabase { get; set; }
/// <summary>
/// Gets or sets the text of the SQL command to be run on each log level.
/// </summary>
/// <remarks>
/// Typically this is a SQL INSERT statement or a stored procedure call.
/// It should use the database-specific parameters (marked as <c>@parameter</c>
/// for SQL server or <c>:parameter</c> for Oracle, other data providers
/// have their own notation) and not the layout renderers,
/// because the latter is prone to SQL injection attacks.
/// The layout renderers should be specified as <parameter /> elements instead.
/// </remarks>
/// <docgen category='SQL Statement' order='10' />
[RequiredParameter]
public Layout CommandText { get; set; }
/// <summary>
/// Gets or sets the type of the SQL command to be run on each log level.
/// </summary>
/// <remarks>
/// This specifies how the command text is interpreted, as "Text" (default) or as "StoredProcedure".
/// When using the value StoredProcedure, the commandText-property would
/// normally be the name of the stored procedure. TableDirect method is not supported in this context.
/// </remarks>
/// <docgen category='SQL Statement' order='11' />
[DefaultValue(CommandType.Text)]
public CommandType CommandType { get; set; }
/// <summary>
/// Gets the collection of parameters. Each parameter contains a mapping
/// between NLog layout and a database named or positional parameter.
/// </summary>
/// <docgen category='SQL Statement' order='12' />
[ArrayParameter(typeof(DatabaseParameterInfo), "parameter")]
public IList<DatabaseParameterInfo> Parameters { get; private set; }
internal DbProviderFactory ProviderFactory { get; set; }
// this is so we can mock the connection string without creating sub-processes
internal ConnectionStringSettingsCollection ConnectionStringsSettings { get; set; }
internal Type ConnectionType { get; set; }
/// <summary>
/// Performs installation which requires administrative permissions.
/// </summary>
/// <param name="installationContext">The installation context.</param>
public void Install(InstallationContext installationContext)
{
this.RunInstallCommands(installationContext, this.InstallDdlCommands);
}
/// <summary>
/// Performs uninstallation which requires administrative permissions.
/// </summary>
/// <param name="installationContext">The installation context.</param>
public void Uninstall(InstallationContext installationContext)
{
this.RunInstallCommands(installationContext, this.UninstallDdlCommands);
}
/// <summary>
/// Determines whether the item is installed.
/// </summary>
/// <param name="installationContext">The installation context.</param>
/// <returns>
/// Value indicating whether the item is installed or null if it is not possible to determine.
/// </returns>
public bool? IsInstalled(InstallationContext installationContext)
{
return null;
}
internal IDbConnection OpenConnection(string connectionString)
{
IDbConnection connection;
if (this.ProviderFactory != null)
{
connection = this.ProviderFactory.CreateConnection();
}
else
{
connection = (IDbConnection)Activator.CreateInstance(this.ConnectionType);
}
connection.ConnectionString = connectionString;
connection.Open();
return connection;
}
/// <summary>
/// Initializes the target. Can be used by inheriting classes
/// to initialize logging.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "connectionStrings", Justification = "Name of the config file section.")]
protected override void InitializeTarget()
{
base.InitializeTarget();
#pragma warning disable 618
if (UseTransactions.HasValue)
#pragma warning restore 618
{
InternalLogger.Warn("UseTransactions is obsolete and will not be used - will be removed in NLog 6");
}
bool foundProvider = false;
if (!string.IsNullOrEmpty(this.ConnectionStringName))
{
// read connection string and provider factory from the configuration file
var cs = this.ConnectionStringsSettings[this.ConnectionStringName];
if (cs == null)
{
throw new NLogConfigurationException("Connection string '" + this.ConnectionStringName + "' is not declared in <connectionStrings /> section.");
}
this.ConnectionString = SimpleLayout.Escape(cs.ConnectionString);
this.ProviderFactory = DbProviderFactories.GetFactory(cs.ProviderName);
foundProvider = true;
}
if (!foundProvider)
{
foreach (DataRow row in DbProviderFactories.GetFactoryClasses().Rows)
{
if ((string)row["InvariantName"] == this.DBProvider)
{
this.ProviderFactory = DbProviderFactories.GetFactory(this.DBProvider);
foundProvider = true;
}
}
}
if (!foundProvider)
{
switch (this.DBProvider.ToUpper(CultureInfo.InvariantCulture))
{
case "SQLSERVER":
case "MSSQL":
case "MICROSOFT":
case "MSDE":
this.ConnectionType = systemDataAssembly.GetType("System.Data.SqlClient.SqlConnection", true);
break;
case "OLEDB":
this.ConnectionType = systemDataAssembly.GetType("System.Data.OleDb.OleDbConnection", true);
break;
case "ODBC":
this.ConnectionType = systemDataAssembly.GetType("System.Data.Odbc.OdbcConnection", true);
break;
default:
this.ConnectionType = Type.GetType(this.DBProvider, true);
break;
}
}
}
/// <summary>
/// Closes the target and releases any unmanaged resources.
/// </summary>
protected override void CloseTarget()
{
base.CloseTarget();
this.CloseConnection();
}
/// <summary>
/// Writes the specified logging event to the database. It creates
/// a new database command, prepares parameters for it by calculating
/// layouts and executes the command.
/// </summary>
/// <param name="logEvent">The logging event.</param>
protected override void Write(LogEventInfo logEvent)
{
try
{
this.WriteEventToDatabase(logEvent);
}
catch (Exception exception)
{
InternalLogger.Error(exception, "Error when writing to database.");
if (exception.MustBeRethrownImmediately())
{
throw;
}
this.CloseConnection();
throw;
}
finally
{
if (!this.KeepConnection)
{
this.CloseConnection();
}
}
}
/// <summary>
/// Writes an array of logging events to the log target. By default it iterates on all
/// events and passes them to "Write" method. Inheriting classes can use this method to
/// optimize batch writes.
/// </summary>
/// <param name="logEvents">Logging events to be written out.</param>
protected override void Write(AsyncLogEventInfo[] logEvents)
{
var buckets = SortHelpers.BucketSort(logEvents, c => this.BuildConnectionString(c.LogEvent));
try
{
foreach (var kvp in buckets)
{
foreach (AsyncLogEventInfo ev in kvp.Value)
{
try
{
this.WriteEventToDatabase(ev.LogEvent);
ev.Continuation(null);
}
catch (Exception exception)
{
// in case of exception, close the connection and report it
InternalLogger.Error(exception, "Error when writing to database.");
if (exception.MustBeRethrownImmediately())
{
throw;
}
this.CloseConnection();
ev.Continuation(exception);
if (exception.MustBeRethrown())
{
throw;
}
}
}
}
}
finally
{
if (!this.KeepConnection)
{
this.CloseConnection();
}
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2100:Review SQL queries for security vulnerabilities", Justification = "It's up to the user to ensure proper quoting.")]
private void WriteEventToDatabase(LogEventInfo logEvent)
{
//Always suppress transaction so that the caller does not rollback loggin if they are rolling back their transaction.
using (TransactionScope transactionScope = new TransactionScope(TransactionScopeOption.Suppress))
{
this.EnsureConnectionOpen(this.BuildConnectionString(logEvent));
IDbCommand command = this.activeConnection.CreateCommand();
command.CommandText = this.CommandText.Render(logEvent);
command.CommandType = this.CommandType;
InternalLogger.Trace("Executing {0}: {1}", command.CommandType, command.CommandText);
foreach (DatabaseParameterInfo par in this.Parameters)
{
IDbDataParameter p = command.CreateParameter();
p.Direction = ParameterDirection.Input;
if (par.Name != null)
{
p.ParameterName = par.Name;
}
if (par.Size != 0)
{
p.Size = par.Size;
}
if (par.Precision != 0)
{
p.Precision = par.Precision;
}
if (par.Scale != 0)
{
p.Scale = par.Scale;
}
string stringValue = par.Layout.Render(logEvent);
p.Value = stringValue;
command.Parameters.Add(p);
InternalLogger.Trace(" Parameter: '{0}' = '{1}' ({2})", p.ParameterName, p.Value, p.DbType);
}
int result = command.ExecuteNonQuery();
InternalLogger.Trace("Finished execution, result = {0}", result);
//not really needed as there is no transaction at all.
transactionScope.Complete();
}
}
private string BuildConnectionString(LogEventInfo logEvent)
{
if (this.ConnectionString != null)
{
return this.ConnectionString.Render(logEvent);
}
var sb = new StringBuilder();
sb.Append("Server=");
sb.Append(this.DBHost.Render(logEvent));
sb.Append(";");
if (this.DBUserName == null)
{
sb.Append("Trusted_Connection=SSPI;");
}
else
{
sb.Append("User id=");
sb.Append(this.DBUserName.Render(logEvent));
sb.Append(";Password=");
sb.Append(this.DBPassword.Render(logEvent));
sb.Append(";");
}
if (this.DBDatabase != null)
{
sb.Append("Database=");
sb.Append(this.DBDatabase.Render(logEvent));
}
return sb.ToString();
}
private void EnsureConnectionOpen(string connectionString)
{
if (this.activeConnection != null)
{
if (this.activeConnectionString != connectionString)
{
this.CloseConnection();
}
}
if (this.activeConnection != null)
{
return;
}
this.activeConnection = this.OpenConnection(connectionString);
this.activeConnectionString = connectionString;
}
private void CloseConnection()
{
if (this.activeConnection != null)
{
this.activeConnection.Close();
this.activeConnection.Dispose();
this.activeConnection = null;
this.activeConnectionString = null;
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2100:Review SQL queries for security vulnerabilities", Justification = "It's up to the user to ensure proper quoting.")]
private void RunInstallCommands(InstallationContext installationContext, IEnumerable<DatabaseCommandInfo> commands)
{
// create log event that will be used to render all layouts
LogEventInfo logEvent = installationContext.CreateLogEvent();
try
{
foreach (var commandInfo in commands)
{
string cs;
if (commandInfo.ConnectionString != null)
{
// if there is connection string specified on the command info, use it
cs = commandInfo.ConnectionString.Render(logEvent);
}
else if (this.InstallConnectionString != null)
{
// next, try InstallConnectionString
cs = this.InstallConnectionString.Render(logEvent);
}
else
{
// if it's not defined, fall back to regular connection string
cs = this.BuildConnectionString(logEvent);
}
this.EnsureConnectionOpen(cs);
var command = this.activeConnection.CreateCommand();
command.CommandType = commandInfo.CommandType;
command.CommandText = commandInfo.Text.Render(logEvent);
try
{
installationContext.Trace("Executing {0} '{1}'", command.CommandType, command.CommandText);
command.ExecuteNonQuery();
}
catch (Exception exception)
{
if (exception.MustBeRethrownImmediately())
{
throw;
}
if (commandInfo.IgnoreFailures || installationContext.IgnoreFailures)
{
installationContext.Warning(exception.Message);
}
else
{
installationContext.Error(exception.Message);
throw;
}
}
}
}
finally
{
this.CloseConnection();
}
}
}
}
#endif
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Signum.Engine.Basics;
using Signum.Entities;
using Signum.Entities.DynamicQuery;
using Signum.Entities.UserAssets;
using Signum.Utilities;
using Signum.Utilities.ExpressionTrees;
namespace Signum.Engine.UserAssets
{
static class DelayedConsole
{
static List<Action> ToWrite = new List<Action>();
public static IDisposable Delay(Action action)
{
ToWrite.Add(action);
return new Disposable(() => ToWrite.Remove(action));
}
public static void Flush()
{
foreach (var item in ToWrite)
{
item();
}
ToWrite.Clear();
}
}
public static class QueryTokenSynchronizer
{
static void Remember(Replacements replacements, string tokenString, QueryToken token)
{
List<QueryToken> tokenList = token.Follow(a => a.Parent).Reverse().ToList();
string[] oldParts = tokenString.Split('.');
string[] newParts = token.FullKey().Split('.');
List<string> oldPartsList = oldParts.ToList();
List<string> newPartsList = newParts.ToList();
Func<string, string?> rep = str =>
{
if (Replacements.AutoReplacement == null)
return null;
Replacements.Selection? sel = Replacements.AutoReplacement(new Replacements.AutoReplacementContext("QueryToken", oldValue: str, newValues: null));
if (sel == null || sel.Value.NewValue == null)
return null;
return sel.Value.NewValue;
};
int pos = -1;
while (oldPartsList.Count > 0 && newPartsList.Count > 0 &&
(oldPartsList[0] == newPartsList[0] ||
rep(oldPartsList[0]) == newPartsList[0]))
{
oldPartsList.RemoveAt(0);
newPartsList.RemoveAt(0);
pos++;
}
while (oldPartsList.Count > 0 && newPartsList.Count > 0 &&
(oldPartsList[oldPartsList.Count - 1] == newPartsList[newPartsList.Count - 1] ||
rep(oldPartsList[oldPartsList.Count - 1]) == newPartsList[newPartsList.Count - 1]))
{
oldPartsList.RemoveAt(oldPartsList.Count - 1);
newPartsList.RemoveAt(newPartsList.Count - 1);
}
string key = pos == -1 ? QueryKey(tokenList[0].QueryName) : TypeKey(tokenList[pos].Type);
replacements.GetOrCreate(key)[oldPartsList.ToString(".")] = newPartsList.ToString(".");
}
static bool TryParseRemember(Replacements replacements, string tokenString, QueryDescription qd, SubTokensOptions options, out QueryToken? result)
{
string[] parts = tokenString.Split('.');
result = null;
for (int i = 0; i < parts.Length; i++)
{
string part = parts[i];
QueryToken? newResult = QueryUtils.SubToken(result, qd, options, part);
if (newResult != null)
{
result = newResult;
}
else
{
if (i == 0)
{
var entity = QueryUtils.SubToken(result, qd, options, "Entity");
QueryToken? newSubResult = QueryUtils.SubToken(entity, qd, options, part);
if (newSubResult != null)
{
result = newSubResult;
continue;
}
}
if (Replacements.AutoReplacement != null)
{
Replacements.Selection? sel = Replacements.AutoReplacement(new Replacements.AutoReplacementContext(
replacementKey: "QueryToken",
oldValue: part,
newValues: result.SubTokens(qd, options).Select(a => a.Key).ToList()));
if (sel != null && sel.Value.NewValue != null)
{
newResult = QueryUtils.SubToken(result, qd, options, sel.Value.NewValue);
if (newResult != null)
{
result = newResult;
continue;
}
}
}
string key = result == null ? QueryKey(qd.QueryName) : TypeKey(result.Type);
Dictionary<string, string>? dic = replacements.TryGetC(key);
if (dic == null)
return false;
string remainging = parts.Skip(i).ToString(".");
string? old = dic.Keys.OrderByDescending(a => a.Length).FirstOrDefault(s => remainging.StartsWith(s));
if (old == null)
return false;
var subParts = dic[old].Let(s => s.HasText() ? s.Split('.') : new string[0]);
for (int j = 0; j < subParts.Length; j++)
{
string subPart = subParts[j];
QueryToken? subNewResult = QueryUtils.SubToken(result, qd, options, subPart);
if (subNewResult == null)
return false;
result = subNewResult;
}
i += (old == "" ? 0 : old.Split('.').Length) - 1;
}
}
return true;
}
static string QueryKey(object tokenList)
{
return "tokens-Query-" + QueryUtils.GetKey(tokenList);
}
static string TypeKey(Type type)
{
return "tokens-Type-" + type.CleanType().FullName;
}
public static FixTokenResult FixValue(Replacements replacements, Type type, ref string? valueString, bool allowRemoveToken, bool isList)
{
var res = FilterValueConverter.TryParse(valueString, type, isList);
if (res is Result<object>.Success)
return FixTokenResult.Nothing;
DelayedConsole.Flush();
if (isList && valueString!.Contains('|'))
{
List<string?> changes = new List<string?>();
foreach (var str in valueString.Split('|'))
{
string? s = str;
var result = FixValue(replacements, type, ref s, allowRemoveToken, false);
if (result == FixTokenResult.DeleteEntity || result == FixTokenResult.SkipEntity || result == FixTokenResult.RemoveToken)
return result;
changes.Add(s);
}
valueString = changes.ToString("|");
return FixTokenResult.Fix;
}
if (type.IsLite())
{
var m = Lite.ParseRegex.Match(valueString!);
if (m.Success)
{
var typeString = m.Groups["type"].Value;
if (!TypeLogic.NameToType.ContainsKey(typeString))
{
string? newTypeString = AskTypeReplacement(replacements, typeString);
if (newTypeString.HasText())
{
valueString = valueString!.Replace(typeString, newTypeString);
return FixTokenResult.Fix;
}
}
}
}
if (Replacements.AutoReplacement != null)
{
Replacements.Selection? sel = Replacements.AutoReplacement(new Replacements.AutoReplacementContext(replacementKey: "FixValue", oldValue: valueString!, newValues: null));
if (sel != null && sel.Value.NewValue != null)
{
valueString = sel.Value.NewValue;
return FixTokenResult.Fix;
}
}
SafeConsole.WriteLineColor(ConsoleColor.White, "Value '{0}' not convertible to {1}.".FormatWith(valueString, type.TypeName()));
SafeConsole.WriteLineColor(ConsoleColor.Yellow, "- s: Skip entity");
if (allowRemoveToken)
SafeConsole.WriteLineColor(ConsoleColor.DarkRed, "- r: Remove token");
SafeConsole.WriteLineColor(ConsoleColor.Red, "- d: Delete entity");
SafeConsole.WriteLineColor(ConsoleColor.Green, "- freeText: New value");
string answer = Console.ReadLine()!;
if (answer == null)
throw new InvalidOperationException("Impossible to synchronize interactively without Console");
string a = answer.ToLower();
if (a == "s")
return FixTokenResult.SkipEntity;
if (allowRemoveToken && a == "r")
return FixTokenResult.RemoveToken;
if (a == "d")
return FixTokenResult.DeleteEntity;
valueString = answer;
return FixTokenResult.Fix;
}
static string? AskTypeReplacement(Replacements replacements, string type)
{
return replacements.GetOrCreate("cleanNames").GetOrCreate(type, () =>
{
if (Replacements.AutoReplacement != null)
{
Replacements.Selection? sel = Replacements.AutoReplacement(new Replacements.AutoReplacementContext(replacementKey: "FixValue.Type", oldValue: type, newValues: null));
if (sel != null && sel.Value.NewValue != null)
return sel.Value.NewValue;
}
Console.WriteLine("Type {0} has been renamed?".FormatWith(type));
int startingIndex = 0;
StringDistance sd = new StringDistance();
var list = TypeLogic.NameToType.Keys.OrderBy(t => sd.LevenshteinDistance(t, type)).ToList();
retry:
int maxElements = Console.LargestWindowHeight - 11;
list.Skip(startingIndex).Take(maxElements)
.Select((s, i) => "- {1,2}: {2} ".FormatWith(i + startingIndex == 0 ? ">" : " ", i + startingIndex, s)).ToConsole();
Console.WriteLine();
SafeConsole.WriteLineColor(ConsoleColor.White, "- n: None");
int remaining = list.Count - startingIndex - maxElements;
if (remaining > 0)
SafeConsole.WriteLineColor(ConsoleColor.White, "- +: Show more values ({0} remaining)", remaining);
while (true)
{
string answer = Console.ReadLine()!;
if (answer == null)
throw new InvalidOperationException("Impossible to synchronize interactively without Console");
answer = answer.ToLower();
if (answer == "+" && remaining > 0)
{
startingIndex += maxElements;
goto retry;
}
if (answer == "n")
return null!;
if (int.TryParse(answer, out int option))
{
return list[option];
}
Console.WriteLine("Error");
}
});
}
public static FixTokenResult FixToken(Replacements replacements, ref QueryTokenEmbedded token, QueryDescription qd, SubTokensOptions options, string? remainingText, bool allowRemoveToken, bool allowReCreate)
{
var t = token;
using (DelayedConsole.Delay(() => { SafeConsole.WriteColor(t.ParseException == null ? ConsoleColor.Gray : ConsoleColor.Red, " " + t.TokenString); Console.WriteLine(" " + remainingText); }))
{
if (token.ParseException == null)
return FixTokenResult.Nothing;
DelayedConsole.Flush();
FixTokenResult result = FixToken(replacements, token.TokenString, out QueryToken? resultToken, qd, options, remainingText, allowRemoveToken, allowReCreate);
if (result == FixTokenResult.Fix)
token = new QueryTokenEmbedded(resultToken!);
return result;
}
}
public static FixTokenResult FixToken(Replacements replacements, string original, out QueryToken? token, QueryDescription qd, SubTokensOptions options, string? remainingText, bool allowRemoveToken, bool allowReGenerate)
{
string[] parts = original.Split('.');
if (TryParseRemember(replacements, original, qd, options, out QueryToken? current))
{
if (current!.FullKey() != original)
{
SafeConsole.WriteColor(ConsoleColor.DarkRed, " " + original);
Console.Write(" -> ");
SafeConsole.WriteColor(ConsoleColor.DarkGreen, current.FullKey());
}
Console.WriteLine(remainingText);
token = current;
return FixTokenResult.Fix;
}
while (true)
{
var tempToken = current!;
var result = SelectInteractive(ref tempToken, qd, options, remainingText, allowRemoveToken, allowReGenerate);
current = tempToken;
switch (result)
{
case UserAssetTokenAction.DeleteEntity:
SafeConsole.WriteLineColor(ConsoleColor.Red, "Entity deleted");
token = null;
return FixTokenResult.DeleteEntity;
case UserAssetTokenAction.ReGenerateEntity:
if (!allowReGenerate)
throw new InvalidOperationException("Unexpected ReGenerate");
SafeConsole.WriteLineColor(ConsoleColor.Magenta, "Entity Re-Generated");
token = null;
return FixTokenResult.ReGenerateEntity;
case UserAssetTokenAction.RemoveToken:
if (!allowRemoveToken)
throw new InvalidOperationException("Unexpected RemoveToken");
Console.SetCursorPosition(0, Console.CursorTop - 1);
SafeConsole.WriteColor(ConsoleColor.DarkRed, " " + original);
SafeConsole.WriteColor(ConsoleColor.DarkRed, " (token removed)");
Console.WriteLine(remainingText);
token = null;
return FixTokenResult.RemoveToken;
case UserAssetTokenAction.SkipEntity:
SafeConsole.WriteLineColor(ConsoleColor.DarkYellow, "Entity skipped");
token = null;
return FixTokenResult.SkipEntity;
case UserAssetTokenAction.Confirm:
Remember(replacements, original, current);
Console.SetCursorPosition(0, Console.CursorTop - 1);
SafeConsole.WriteColor(ConsoleColor.DarkRed, " " + original);
Console.Write(" -> ");
SafeConsole.WriteColor(ConsoleColor.DarkGreen, current.FullKey());
Console.WriteLine(remainingText);
token = current;
return FixTokenResult.Fix;
}
}
}
static UserAssetTokenAction? SelectInteractive(ref QueryToken token, QueryDescription qd, SubTokensOptions options, string? remainingText, bool allowRemoveToken, bool allowReGenerate)
{
var top = Console.CursorTop;
try
{
if (Console.Out == null)
throw new InvalidOperationException("Unable to ask for renames to synchronize query tokens without interactive Console. Please use your Terminal application.");
var subTokens = token.SubTokens(qd, options).OrderBy(a => a.Parent != null).ThenByDescending(a=>a.Priority).ThenBy(a => a.Key).ToList();
int startingIndex = 0;
SafeConsole.WriteColor(ConsoleColor.Cyan, " " + token?.FullKey());
if (remainingText.HasText())
Console.Write(" " + remainingText);
Console.WriteLine();
bool isRoot = token == null;
retry:
int maxElements = Console.LargestWindowHeight - 11;
subTokens.Skip(startingIndex).Take(maxElements)
.Select((s, i) => "- {1,2}: {2} ".FormatWith(i + " ", i + startingIndex, ((isRoot && s.Parent != null) ? "-" : "") + s.Key)).ToConsole();
Console.WriteLine();
int remaining = subTokens.Count - startingIndex - maxElements;
if (remaining > 0)
SafeConsole.WriteLineColor(ConsoleColor.White, "- +: Show more values ({0} remaining)", remaining);
if (token != null)
{
SafeConsole.WriteLineColor(ConsoleColor.White, "- b: Back");
SafeConsole.WriteLineColor(ConsoleColor.Green, "- c: Confirm");
}
SafeConsole.WriteLineColor(ConsoleColor.Yellow, "- s: Skip entity");
if (allowRemoveToken)
SafeConsole.WriteLineColor(ConsoleColor.DarkRed, "- r: Remove token");
if (allowReGenerate)
SafeConsole.WriteLineColor(ConsoleColor.Magenta, "- g: Generate from default template");
SafeConsole.WriteLineColor(ConsoleColor.Red, "- d: Delete entity");
while (true)
{
string answer = Console.ReadLine()!;
if (answer == null)
throw new InvalidOperationException("Impossible to synchronize interactively without Console");
answer = answer.ToLower();
if (answer == "+" && remaining > 0)
{
startingIndex += maxElements;
goto retry;
}
if (answer == "s")
return UserAssetTokenAction.SkipEntity;
if (answer == "r" && allowRemoveToken)
return UserAssetTokenAction.RemoveToken;
if (answer == "d")
return UserAssetTokenAction.DeleteEntity;
if (answer == "g")
return UserAssetTokenAction.ReGenerateEntity;
if (token != null)
{
if (answer == "c")
return UserAssetTokenAction.Confirm;
if (answer == "b")
{
token = token.Parent!;
return null;
}
}
if (int.TryParse(answer, out int option))
{
token = subTokens[option];
return null;
}
Console.WriteLine("Error");
}
}
finally
{
Clean(top, Console.CursorTop);
}
}
static void Clean(int top, int nextTop)
{
ConsoleColor colorBefore = Console.BackgroundColor;
try
{
for (int i = nextTop - 1; i >= top; i--)
{
Console.BackgroundColor = ConsoleColor.Black;
string spaces = new string(' ', Console.BufferWidth);
Console.SetCursorPosition(0, i);
Console.Write(spaces);
}
Console.SetCursorPosition(0, top);
}
finally
{
Console.BackgroundColor = colorBefore;
}
}
public enum UserAssetTokenAction
{
RemoveToken,
DeleteEntity,
SkipEntity,
Confirm,
ReGenerateEntity,
}
}
public enum FixTokenResult
{
Nothing,
Fix,
RemoveToken,
DeleteEntity,
SkipEntity,
ReGenerateEntity,
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.ServiceModel.Channels
{
using System.Runtime;
using System.Threading;
using System.ServiceModel.Diagnostics.Application;
sealed class Msmq4PoisonHandler : IPoisonHandlingStrategy
{
MsmqQueue mainQueue;
MsmqQueue mainQueueForMove;
MsmqQueue retryQueueForPeek;
MsmqQueue retryQueueForMove;
MsmqQueue poisonQueue;
MsmqQueue lockQueueForReceive;
IOThreadTimer timer;
MsmqReceiveHelper receiver;
bool disposed;
string poisonQueueName;
string retryQueueName;
string mainQueueName;
MsmqRetryQueueMessage retryQueueMessage;
static Action<object> onStartPeek = new Action<object>(StartPeek);
static AsyncCallback onPeekCompleted = Fx.ThunkCallback(OnPeekCompleted);
public Msmq4PoisonHandler(MsmqReceiveHelper receiver)
{
this.receiver = receiver;
this.timer = new IOThreadTimer(new Action<object>(OnTimer), null, false);
this.disposed = false;
this.mainQueueName = this.ReceiveParameters.AddressTranslator.UriToFormatName(this.ListenUri);
this.poisonQueueName = this.ReceiveParameters.AddressTranslator.UriToFormatName(new Uri(this.ListenUri.AbsoluteUri + ";poison"));
this.retryQueueName = this.ReceiveParameters.AddressTranslator.UriToFormatName(new Uri(this.ListenUri.AbsoluteUri + ";retry"));
}
MsmqReceiveParameters ReceiveParameters
{
get { return this.receiver.MsmqReceiveParameters; }
}
Uri ListenUri
{
get { return this.receiver.ListenUri; }
}
public void Open()
{
if (this.ReceiveParameters.ReceiveContextSettings.Enabled)
{
Fx.Assert(this.receiver.Queue is MsmqSubqueueLockingQueue, "Queue must be MsmqSubqueueLockingQueue");
this.lockQueueForReceive = ((MsmqSubqueueLockingQueue)this.receiver.Queue).LockQueueForReceive;
}
this.mainQueue = this.receiver.Queue;
this.mainQueueForMove = new MsmqQueue(this.mainQueueName, UnsafeNativeMethods.MQ_MOVE_ACCESS);
// Open up the poison queue (for handling poison messages).
this.poisonQueue = new MsmqQueue(this.poisonQueueName, UnsafeNativeMethods.MQ_MOVE_ACCESS);
this.retryQueueForMove = new MsmqQueue(this.retryQueueName, UnsafeNativeMethods.MQ_MOVE_ACCESS);
this.retryQueueForPeek = new MsmqQueue(this.retryQueueName, UnsafeNativeMethods.MQ_RECEIVE_ACCESS);
this.retryQueueMessage = new MsmqRetryQueueMessage();
if (Thread.CurrentThread.IsThreadPoolThread)
{
StartPeek(this);
}
else
{
ActionItem.Schedule(Msmq4PoisonHandler.onStartPeek, this);
}
}
static void StartPeek(object state)
{
Msmq4PoisonHandler handler = state as Msmq4PoisonHandler;
lock (handler)
{
if (!handler.disposed)
{
handler.retryQueueForPeek.BeginPeek(handler.retryQueueMessage, TimeSpan.MaxValue, onPeekCompleted, handler);
}
}
}
public bool CheckAndHandlePoisonMessage(MsmqMessageProperty messageProperty)
{
if (this.ReceiveParameters.ReceiveContextSettings.Enabled)
{
return ReceiveContextPoisonHandling(messageProperty);
}
else
{
return NonReceiveContextPoisonHandling(messageProperty);
}
}
public bool ReceiveContextPoisonHandling(MsmqMessageProperty messageProperty)
{
// The basic idea is to use the message move count to get the number of retry attempts the message has been through
// The computation of the retry count and retry cycle count is slightly involved due to fact that the message being processed
// could have been recycled message. (Recycled message is the message that moves from lock queue to retry queue to main queue
// and back to lock queue
//
// Count to tally message recycling (lock queue to retry queue to main queue adds move count of 2 to the message)
const int retryMoveCount = 2;
// Actual number of times message is received before recycling to retry queue
int actualReceiveRetryCount = this.ReceiveParameters.ReceiveRetryCount + 1;
// The message is recycled these many number of times
int maxRetryCycles = this.ReceiveParameters.MaxRetryCycles;
// Max change in message move count between recycling
int maxMovePerCycle = (2 * actualReceiveRetryCount) + 1;
// Number of recycles the message has been through
int messageCyclesCompleted = messageProperty.MoveCount / (maxMovePerCycle + retryMoveCount);
// Total number of moves on the message at the end of the last recycle
int messageMoveCountForCyclesCompleted = messageCyclesCompleted * (maxMovePerCycle + retryMoveCount);
// The differential move count for the current cycle
int messageMoveCountForCurrentCycle = messageProperty.MoveCount - messageMoveCountForCyclesCompleted;
lock (this)
{
if (this.disposed)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ObjectDisposedException(this.GetType().ToString()));
// Check if the message has already completed its max recycle count (MaxRetryCycles)
// and the disposed the message first. Such a message was previously disposed using the ReceiveErrorHandling method
// and the channel/listener would immediately fault
//
if (messageCyclesCompleted > maxRetryCycles)
{
FinalDisposition(messageProperty);
return true;
}
// Check if the message is eligible for recycling/disposition
if (messageMoveCountForCurrentCycle >= maxMovePerCycle)
{
if (TD.ReceiveRetryCountReachedIsEnabled())
{
TD.ReceiveRetryCountReached(messageProperty.MessageId);
}
if (messageCyclesCompleted < maxRetryCycles)
{
// The message is eligible for recycling, move the message the message to retry queue
MsmqReceiveHelper.MoveReceivedMessage(this.lockQueueForReceive, this.retryQueueForMove, messageProperty.LookupId);
MsmqDiagnostics.PoisonMessageMoved(messageProperty.MessageId, false, this.receiver.InstanceId);
}
else
{
if (TD.MaxRetryCyclesExceededMsmqIsEnabled())
{
TD.MaxRetryCyclesExceededMsmq(messageProperty.MessageId);
}
// Dispose the message using ReceiveErrorHandling
FinalDisposition(messageProperty);
}
return true;
}
else
{
return false;
}
}
}
public bool NonReceiveContextPoisonHandling(MsmqMessageProperty messageProperty)
{
if (messageProperty.AbortCount <= this.ReceiveParameters.ReceiveRetryCount)
return false;
int retryCycle = messageProperty.MoveCount / 2;
lock (this)
{
if (this.disposed)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ObjectDisposedException(this.GetType().ToString()));
if (retryCycle >= this.ReceiveParameters.MaxRetryCycles)
{
if (TD.MaxRetryCyclesExceededMsmqIsEnabled())
{
TD.MaxRetryCyclesExceededMsmq(messageProperty.MessageId);
}
FinalDisposition(messageProperty);
}
else
{
MsmqReceiveHelper.MoveReceivedMessage(this.mainQueue, this.retryQueueForMove, messageProperty.LookupId);
MsmqDiagnostics.PoisonMessageMoved(messageProperty.MessageId, false, this.receiver.InstanceId);
}
}
return true;
}
public void FinalDisposition(MsmqMessageProperty messageProperty)
{
if (this.ReceiveParameters.ReceiveContextSettings.Enabled)
{
this.InternalFinalDisposition(this.lockQueueForReceive, messageProperty);
}
else
{
this.InternalFinalDisposition(this.mainQueue, messageProperty);
}
}
private void InternalFinalDisposition(MsmqQueue disposeFromQueue, MsmqMessageProperty messageProperty)
{
switch (this.ReceiveParameters.ReceiveErrorHandling)
{
case ReceiveErrorHandling.Drop:
this.receiver.DropOrRejectReceivedMessage(disposeFromQueue, messageProperty, false);
break;
case ReceiveErrorHandling.Fault:
MsmqReceiveHelper.TryAbortTransactionCurrent();
if (null != this.receiver.ChannelListener)
this.receiver.ChannelListener.FaultListener();
if (null != this.receiver.Channel)
this.receiver.Channel.FaultChannel();
break;
case ReceiveErrorHandling.Reject:
this.receiver.DropOrRejectReceivedMessage(disposeFromQueue, messageProperty, true);
MsmqDiagnostics.PoisonMessageRejected(messageProperty.MessageId, this.receiver.InstanceId);
break;
case ReceiveErrorHandling.Move:
MsmqReceiveHelper.MoveReceivedMessage(disposeFromQueue, this.poisonQueue, messageProperty.LookupId);
MsmqDiagnostics.PoisonMessageMoved(messageProperty.MessageId, true, this.receiver.InstanceId);
break;
default:
Fx.Assert("System.ServiceModel.Channels.Msmq4PoisonHandler.FinalDisposition(): (unexpected ReceiveErrorHandling)");
break;
}
}
public void Dispose()
{
lock (this)
{
if (!this.disposed)
{
this.disposed = true;
this.timer.Cancel();
if (null != this.retryQueueForPeek)
this.retryQueueForPeek.Dispose();
if (null != this.retryQueueForMove)
this.retryQueueForMove.Dispose();
if (null != this.poisonQueue)
this.poisonQueue.Dispose();
if (null != this.mainQueueForMove)
this.mainQueueForMove.Dispose();
}
}
}
static void OnPeekCompleted(IAsyncResult result)
{
Msmq4PoisonHandler handler = result.AsyncState as Msmq4PoisonHandler;
MsmqQueue.ReceiveResult receiveResult = MsmqQueue.ReceiveResult.Unknown;
try
{
receiveResult = handler.retryQueueForPeek.EndPeek(result);
}
catch (MsmqException ex)
{
MsmqDiagnostics.ExpectedException(ex);
}
if (MsmqQueue.ReceiveResult.MessageReceived == receiveResult)
{
lock (handler)
{
if (!handler.disposed)
{
// Check the time - move it, and begin peeking again
// if necessary, or wait for the timeout.
DateTime lastMoveTime = MsmqDateTime.ToDateTime(handler.retryQueueMessage.LastMoveTime.Value);
TimeSpan waitTime = lastMoveTime + handler.ReceiveParameters.RetryCycleDelay - DateTime.UtcNow;
if (waitTime < TimeSpan.Zero)
handler.OnTimer(handler);
else
handler.timer.Set(waitTime);
}
}
}
}
void OnTimer(object state)
{
lock (this)
{
if (!this.disposed)
{
try
{
this.retryQueueForPeek.TryMoveMessage(this.retryQueueMessage.LookupId.Value, this.mainQueueForMove, MsmqTransactionMode.Single);
}
catch (MsmqException ex)
{
MsmqDiagnostics.ExpectedException(ex);
}
this.retryQueueForPeek.BeginPeek(this.retryQueueMessage, TimeSpan.MaxValue, onPeekCompleted, this);
}
}
}
class MsmqRetryQueueMessage : NativeMsmqMessage
{
LongProperty lookupId;
IntProperty lastMoveTime;
public MsmqRetryQueueMessage()
: base(2)
{
this.lookupId = new LongProperty(this, UnsafeNativeMethods.PROPID_M_LOOKUPID);
this.lastMoveTime = new IntProperty(this, UnsafeNativeMethods.PROPID_M_LAST_MOVE_TIME);
}
public LongProperty LookupId
{
get { return this.lookupId; }
}
public IntProperty LastMoveTime
{
get { return this.lastMoveTime; }
}
}
}
}
| |
// Copyright (C) 2014 - 2015 Stephan Bouchard - All Rights Reserved
// This code can only be used under the standard Unity Asset Store End User License Agreement
// A Copy of the EULA APPENDIX 1 is available at http://unity3d.com/company/legal/as_terms
using UnityEngine;
using UnityEditor;
using System.Collections;
namespace TMPro.EditorUtilities
{
[CustomEditor(typeof(TextMeshPro)), CanEditMultipleObjects]
public class TMPro_EditorPanel : Editor
{
private struct m_foldout
{ // Track Inspector foldout panel states, globally.
public static bool textInput = true;
public static bool fontSettings = true;
public static bool extraSettings = false;
public static bool shadowSetting = false;
public static bool materialEditor = true;
}
private static int m_eventID;
private static string[] uiStateLabel = new string[] { "\t- <i>Click to expand</i> -", "\t- <i>Click to collapse</i> -" };
private const string k_UndoRedo = "UndoRedoPerformed";
private GUIStyle toggleStyle;
public int selAlignGrid_A = 0;
public int selAlignGrid_B = 0;
// Serialized Properties
private SerializedProperty text_prop;
// Right to Left properties
private SerializedProperty isRightToLeft_prop;
private string m_RTLText;
private SerializedProperty fontAsset_prop;
private SerializedProperty fontStyle_prop;
// Color Properties
private SerializedProperty fontColor_prop;
private SerializedProperty enableVertexGradient_prop;
private SerializedProperty fontColorGradient_prop;
private SerializedProperty overrideHtmlColor_prop;
private SerializedProperty fontSize_prop;
private SerializedProperty fontSizeBase_prop;
private SerializedProperty autoSizing_prop;
private SerializedProperty fontSizeMin_prop;
private SerializedProperty fontSizeMax_prop;
//private SerializedProperty charSpacingMax_prop;
private SerializedProperty lineSpacingMax_prop;
private SerializedProperty charWidthMaxAdj_prop;
private SerializedProperty characterSpacing_prop;
private SerializedProperty lineSpacing_prop;
private SerializedProperty paragraphSpacing_prop;
private SerializedProperty textAlignment_prop;
//private SerializedProperty textAlignment_prop;
private SerializedProperty horizontalMapping_prop;
private SerializedProperty verticalMapping_prop;
private SerializedProperty uvOffset_prop;
private SerializedProperty uvLineOffset_prop;
private SerializedProperty enableWordWrapping_prop;
private SerializedProperty wordWrappingRatios_prop;
private SerializedProperty textOverflowMode_prop;
private SerializedProperty pageToDisplay_prop;
private SerializedProperty enableKerning_prop;
private SerializedProperty inputSource_prop;
private SerializedProperty havePropertiesChanged_prop;
private SerializedProperty isInputPasingRequired_prop;
//private SerializedProperty isAffectingWordWrapping_prop;
private SerializedProperty isRichText_prop;
private SerializedProperty hasFontAssetChanged_prop;
private SerializedProperty enableExtraPadding_prop;
private SerializedProperty checkPaddingRequired_prop;
private SerializedProperty isOrthographic_prop;
//private SerializedProperty isOverlay_prop;
//private SerializedProperty textRectangle_prop;
//private SerializedProperty isMaskUpdateRequired_prop;
//private SerializedProperty mask_prop;
//private SerializedProperty maskOffset_prop;
//private SerializedProperty maskOffsetMode_prop;
//private SerializedProperty maskSoftness_prop;
//private SerializedProperty vertexOffset_prop;
//private int m_sortingLayerID;
//private int m_sortingOrder;
private bool havePropertiesChanged = false;
private TextMeshPro m_textMeshProScript;
//private Transform m_transform;
private Renderer m_renderer;
//private int m_currentMaterialID;
//private int m_previousMaterialID;
//private Material m_currentMaterial;
//private TMPro_UpdateManager m_updateManager;
//private Vector3[] handlePoints = new Vector3[4]; // { new Vector3(-10, -10, 0), new Vector3(-10, 10, 0), new Vector3(10, 10, 0), new Vector3(10, -10, 0) };
//private float prev_lineLenght;
public void OnEnable()
{
//Debug.Log("OnEnable() for Inspector ID " + this.GetInstanceID() + " has been called.");
// Initialize the Event Listener for Undo Events.
Undo.undoRedoPerformed += OnUndoRedo;
//Undo.postprocessModifications += OnUndoRedoEvent;
text_prop = serializedObject.FindProperty("m_text");
isRightToLeft_prop = serializedObject.FindProperty("m_isRightToLeft");
fontAsset_prop = serializedObject.FindProperty("m_fontAsset");
fontStyle_prop = serializedObject.FindProperty("m_fontStyle");
fontSize_prop = serializedObject.FindProperty("m_fontSize");
fontSizeBase_prop = serializedObject.FindProperty("m_fontSizeBase");
autoSizing_prop = serializedObject.FindProperty("m_enableAutoSizing");
fontSizeMin_prop = serializedObject.FindProperty("m_fontSizeMin");
fontSizeMax_prop = serializedObject.FindProperty("m_fontSizeMax");
//charSpacingMax_prop = serializedObject.FindProperty("m_charSpacingMax");
lineSpacingMax_prop = serializedObject.FindProperty("m_lineSpacingMax");
charWidthMaxAdj_prop = serializedObject.FindProperty("m_charWidthMaxAdj");
// Colors & Gradient
fontColor_prop = serializedObject.FindProperty("m_fontColor");
enableVertexGradient_prop = serializedObject.FindProperty ("m_enableVertexGradient");
fontColorGradient_prop = serializedObject.FindProperty ("m_fontColorGradient");
overrideHtmlColor_prop = serializedObject.FindProperty("m_overrideHtmlColors");
characterSpacing_prop = serializedObject.FindProperty("m_characterSpacing");
lineSpacing_prop = serializedObject.FindProperty("m_lineSpacing");
paragraphSpacing_prop = serializedObject.FindProperty("m_paragraphSpacing");
textAlignment_prop = serializedObject.FindProperty("m_textAlignment");
horizontalMapping_prop = serializedObject.FindProperty("m_horizontalMapping");
verticalMapping_prop = serializedObject.FindProperty("m_verticalMapping");
uvOffset_prop = serializedObject.FindProperty("m_uvOffset");
uvLineOffset_prop = serializedObject.FindProperty("m_uvLineOffset");
enableWordWrapping_prop = serializedObject.FindProperty("m_enableWordWrapping");
wordWrappingRatios_prop = serializedObject.FindProperty("m_wordWrappingRatios");
textOverflowMode_prop = serializedObject.FindProperty("m_overflowMode");
pageToDisplay_prop = serializedObject.FindProperty("m_pageToDisplay");
enableKerning_prop = serializedObject.FindProperty("m_enableKerning");
isOrthographic_prop = serializedObject.FindProperty("m_isOrthographic");
//isOverlay_prop = serializedObject.FindProperty("m_isOverlay");
havePropertiesChanged_prop = serializedObject.FindProperty("havePropertiesChanged");
inputSource_prop = serializedObject.FindProperty("m_inputSource");
isInputPasingRequired_prop = serializedObject.FindProperty("isInputParsingRequired");
//isAffectingWordWrapping_prop = serializedObject.FindProperty("isAffectingWordWrapping");
enableExtraPadding_prop = serializedObject.FindProperty("m_enableExtraPadding");
isRichText_prop = serializedObject.FindProperty("m_isRichText");
checkPaddingRequired_prop = serializedObject.FindProperty("checkPaddingRequired");
//isMaskUpdateRequired_prop = serializedObject.FindProperty("isMaskUpdateRequired");
//mask_prop = serializedObject.FindProperty("m_mask");
//maskOffset_prop= serializedObject.FindProperty("m_maskOffset");
//maskOffsetMode_prop = serializedObject.FindProperty("m_maskOffsetMode");
//maskSoftness_prop = serializedObject.FindProperty("m_maskSoftness");
//vertexOffset_prop = serializedObject.FindProperty("m_vertexOffset");
//m_sortingLayerID = serializedObject.FindProperty("m_sortingLayerID");
//m_sortingOrder = serializedObject.FindProperty("m_sortingOrder");
hasFontAssetChanged_prop = serializedObject.FindProperty("hasFontAssetChanged");
//renderer_prop = serializedObject.FindProperty("m_renderer");
// Get the UI Skin and Styles for the various Editors
TMP_UIStyleManager.GetUIStyles();
m_textMeshProScript = target as TextMeshPro;
//m_transform = Selection.activeGameObject.transform;
m_renderer = m_textMeshProScript.GetComponent<Renderer>();
//m_sortingLayerID = m_renderer.sortingLayerID;
//m_sortingOrder = m_renderer.sortingOrder;
//if (m_renderer.sharedMaterial != null)
// m_currentMaterial = m_renderer.sharedMaterial;
//m_updateManager = Camera.main.gameObject.GetComponent<TMPro_UpdateManager>();
}
public void OnDisable()
{
//Debug.Log("OnDisable() for Inspector ID " + this.GetInstanceID() + " has been called.");
Undo.undoRedoPerformed -= OnUndoRedo;
//Undo.postprocessModifications -= OnUndoRedoEvent;
}
public override void OnInspectorGUI()
{
// Copy Default GUI Toggle Style
if (toggleStyle == null)
{
toggleStyle = new GUIStyle(GUI.skin.label);
toggleStyle.fontSize = 12;
toggleStyle.normal.textColor = TMP_UIStyleManager.Section_Label.normal.textColor;
toggleStyle.richText = true;
}
serializedObject.Update();
Rect rect = EditorGUILayout.GetControlRect(false, 25);
float labelWidth = EditorGUIUtility.labelWidth = 130f;
float fieldWidth = EditorGUIUtility.fieldWidth;
rect.y += 2;
GUI.Label(rect, "<b>TEXT INPUT BOX</b>" + (m_foldout.textInput ? uiStateLabel[1] : uiStateLabel[0]), TMP_UIStyleManager.Section_Label);
if (GUI.Button(new Rect(rect.x, rect.y, rect.width - 150, rect.height), GUIContent.none, GUI.skin.label))
m_foldout.textInput = !m_foldout.textInput;
// Toggle showing Rich Tags
GUI.Label(new Rect(rect.width - 125, rect.y + 4, 125, 24), "<i>Enable RTL Editor</i>", toggleStyle);
isRightToLeft_prop.boolValue = EditorGUI.Toggle(new Rect(rect.width - 10, rect.y + 3, 20, 24), GUIContent.none, isRightToLeft_prop.boolValue);
if (m_foldout.textInput)
{
EditorGUI.BeginChangeCheck();
text_prop.stringValue = EditorGUILayout.TextArea(text_prop.stringValue, TMP_UIStyleManager.TextAreaBoxEditor, GUILayout.Height(125), GUILayout.ExpandWidth(true));
if (EditorGUI.EndChangeCheck() || (isRightToLeft_prop.boolValue && (m_RTLText == null || m_RTLText == string.Empty)))
{
inputSource_prop.enumValueIndex = 0;
isInputPasingRequired_prop.boolValue = true;
havePropertiesChanged = true;
// Handle Left to Right or Right to Left Editor
if (isRightToLeft_prop.boolValue)
{
m_RTLText = string.Empty;
string sourceText = text_prop.stringValue;
// Reverse Text displayed in Text Input Box
for (int i = 0; i < sourceText.Length; i++)
{
m_RTLText += sourceText[sourceText.Length - i - 1];
}
}
}
if (isRightToLeft_prop.boolValue)
{
EditorGUI.BeginChangeCheck();
m_RTLText = EditorGUILayout.TextArea(m_RTLText, TMP_UIStyleManager.TextAreaBoxEditor, GUILayout.Height(125), GUILayout.ExpandWidth(true));
if (EditorGUI.EndChangeCheck())
{
// Convert RTL input
string sourceText = string.Empty;
// Reverse Text displayed in Text Input Box
for (int i = 0; i < m_RTLText.Length; i++)
{
sourceText += m_RTLText[m_RTLText.Length - i - 1];
}
text_prop.stringValue = sourceText;
}
}
}
// FONT SETTINGS SECTION
if (GUILayout.Button("<b>FONT SETTINGS</b>" + (m_foldout.fontSettings ? uiStateLabel[1] : uiStateLabel[0]), TMP_UIStyleManager.Section_Label))
m_foldout.fontSettings = !m_foldout.fontSettings;
if (m_foldout.fontSettings)
{
// FONT ASSET
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(fontAsset_prop);
if (EditorGUI.EndChangeCheck())
{
Undo.RecordObject(m_renderer, "Asset & Material Change");
havePropertiesChanged = true;
hasFontAssetChanged_prop.boolValue = true;
}
// FONT STYLE
EditorGUI.BeginChangeCheck();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel("Font Style");
int styleValue = fontStyle_prop.intValue;
int v1 = GUILayout.Toggle((styleValue & 1) == 1, "B", GUI.skin.button) ? 1 : 0; // Bold
int v2 = GUILayout.Toggle((styleValue & 2) == 2, "I", GUI.skin.button) ? 2 : 0; // Italics
int v3 = GUILayout.Toggle((styleValue & 4) == 4, "U", GUI.skin.button) ? 4 : 0; // Underline
int v7 = GUILayout.Toggle((styleValue & 64) == 64, "S", GUI.skin.button) ? 64 : 0; // Strikethrough
int v4 = GUILayout.Toggle((styleValue & 8) == 8, "ab", GUI.skin.button) ? 8 : 0; // Lowercase
int v5 = GUILayout.Toggle((styleValue & 16) == 16, "AB", GUI.skin.button) ? 16 : 0; // Uppercase
int v6 = GUILayout.Toggle((styleValue & 32) == 32, "SC", GUI.skin.button) ? 32 : 0; // Smallcaps
EditorGUILayout.EndHorizontal();
if (EditorGUI.EndChangeCheck())
{
fontStyle_prop.intValue = v1 + v2 + v3 + v4 + v5 + v6 + v7;
havePropertiesChanged = true;
}
// FACE VERTEX COLOR
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(fontColor_prop, new GUIContent("Color (Vertex)"));
// VERTEX COLOR GRADIENT
EditorGUILayout.BeginHorizontal();
//EditorGUILayout.PrefixLabel("Color Gradient");
EditorGUILayout.PropertyField(enableVertexGradient_prop, new GUIContent("Color Gradient"), GUILayout.MinWidth(140), GUILayout.MaxWidth(200));
EditorGUIUtility.labelWidth = 95;
EditorGUILayout.PropertyField(overrideHtmlColor_prop, new GUIContent("Override Tags"));
EditorGUIUtility.labelWidth = labelWidth;
EditorGUILayout.EndHorizontal();
if (enableVertexGradient_prop.boolValue)
{
EditorGUILayout.PropertyField(fontColorGradient_prop.FindPropertyRelative("topLeft"), new GUIContent("Top Left"));
EditorGUILayout.PropertyField(fontColorGradient_prop.FindPropertyRelative("topRight"), new GUIContent("Top Right"));
EditorGUILayout.PropertyField(fontColorGradient_prop.FindPropertyRelative("bottomLeft"), new GUIContent("Bottom Left"));
EditorGUILayout.PropertyField(fontColorGradient_prop.FindPropertyRelative("bottomRight"), new GUIContent("Bottom Right"));
}
if (EditorGUI.EndChangeCheck())
{
havePropertiesChanged = true;
}
// FONT SIZE
EditorGUI.BeginChangeCheck();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PropertyField(fontSize_prop, new GUIContent("Font Size"), GUILayout.MinWidth(168), GUILayout.MaxWidth(200));
EditorGUIUtility.fieldWidth = fieldWidth;
if (EditorGUI.EndChangeCheck())
{
fontSizeBase_prop.floatValue = fontSize_prop.floatValue;
havePropertiesChanged = true;
//isAffectingWordWrapping_prop.boolValue = true;
}
EditorGUI.BeginChangeCheck();
EditorGUIUtility.labelWidth = 70;
EditorGUILayout.PropertyField(autoSizing_prop, new GUIContent("Auto Size"));
EditorGUILayout.EndHorizontal();
EditorGUIUtility.labelWidth = labelWidth;
if (EditorGUI.EndChangeCheck())
{
if (autoSizing_prop.boolValue == false)
fontSize_prop.floatValue = fontSizeBase_prop.floatValue;
havePropertiesChanged = true;
//isAffectingWordWrapping_prop.boolValue = true;
}
// Show auto sizing options
if (autoSizing_prop.boolValue)
{
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel("Auto Size Options");
EditorGUIUtility.labelWidth = 24;
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(fontSizeMin_prop, new GUIContent("Min"), GUILayout.MinWidth(46));
if (EditorGUI.EndChangeCheck())
{
fontSizeMin_prop.floatValue = Mathf.Min(fontSizeMin_prop.floatValue, fontSizeMax_prop.floatValue);
havePropertiesChanged = true;
}
EditorGUIUtility.labelWidth = 27;
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(fontSizeMax_prop, new GUIContent("Max"), GUILayout.MinWidth(49));
if (EditorGUI.EndChangeCheck())
{
fontSizeMax_prop.floatValue = Mathf.Max(fontSizeMin_prop.floatValue, fontSizeMax_prop.floatValue);
havePropertiesChanged = true;
}
EditorGUI.BeginChangeCheck();
EditorGUIUtility.labelWidth = 36;
//EditorGUILayout.PropertyField(charSpacingMax_prop, new GUIContent("Char"), GUILayout.MinWidth(50));
EditorGUILayout.PropertyField(charWidthMaxAdj_prop, new GUIContent("WD%"), GUILayout.MinWidth(58));
EditorGUIUtility.labelWidth = 28;
EditorGUILayout.PropertyField(lineSpacingMax_prop, new GUIContent("Line"), GUILayout.MinWidth(50));
EditorGUIUtility.labelWidth = labelWidth;
EditorGUILayout.EndHorizontal();
if (EditorGUI.EndChangeCheck())
{
charWidthMaxAdj_prop.floatValue = Mathf.Clamp(charWidthMaxAdj_prop.floatValue, 0, 50);
//charSpacingMax_prop.floatValue = Mathf.Min(0, charSpacingMax_prop.floatValue);
lineSpacingMax_prop.floatValue = Mathf.Min(0, lineSpacingMax_prop.floatValue);
havePropertiesChanged = true;
}
}
// CHARACTER, LINE & PARAGRAPH SPACING
EditorGUI.BeginChangeCheck();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel("Spacing Options");
EditorGUIUtility.labelWidth = 30;
EditorGUILayout.PropertyField(characterSpacing_prop, new GUIContent("Char"), GUILayout.MinWidth(50)); //, GUILayout.MaxWidth(100));
EditorGUILayout.PropertyField(lineSpacing_prop, new GUIContent("Line"), GUILayout.MinWidth(50)); //, GUILayout.MaxWidth(100));
EditorGUILayout.PropertyField(paragraphSpacing_prop, new GUIContent(" Par."), GUILayout.MinWidth(50)); //, GUILayout.MaxWidth(100));
EditorGUIUtility.labelWidth = labelWidth;
EditorGUILayout.EndHorizontal();
if (EditorGUI.EndChangeCheck())
{
havePropertiesChanged = true;
//isAffectingWordWrapping_prop.boolValue = true;
}
// TEXT ALIGNMENT
EditorGUI.BeginChangeCheck();
rect = EditorGUILayout.GetControlRect(false, 17);
GUIStyle btn = new GUIStyle(GUI.skin.button);
btn.margin = new RectOffset(1, 1, 1, 1);
btn.padding = new RectOffset(1, 1, 1, 0);
selAlignGrid_A = textAlignment_prop.enumValueIndex & ~28;
selAlignGrid_B = (textAlignment_prop.enumValueIndex & ~3) / 4;
GUI.Label(new Rect(rect.x, rect.y, 100, rect.height), "Alignment");
float columnB = EditorGUIUtility.labelWidth + 15;
selAlignGrid_A = GUI.SelectionGrid(new Rect(columnB, rect.y, 23 * 4, rect.height), selAlignGrid_A, TMP_UIStyleManager.alignContent_A, 4, btn);
selAlignGrid_B = GUI.SelectionGrid(new Rect(columnB + 23 * 4 + 10, rect.y, 23 * 5, rect.height), selAlignGrid_B, TMP_UIStyleManager.alignContent_B, 5, btn);
if (EditorGUI.EndChangeCheck())
{
textAlignment_prop.enumValueIndex = selAlignGrid_A + selAlignGrid_B * 4;
havePropertiesChanged = true;
}
// WRAPPING RATIOS shown if Justified mode is selected.
EditorGUI.BeginChangeCheck();
if (textAlignment_prop.enumValueIndex == 3 || textAlignment_prop.enumValueIndex == 7 || textAlignment_prop.enumValueIndex == 11 || textAlignment_prop.enumValueIndex == 19)
DrawPropertySlider("Wrap Mix (W <-> C)", wordWrappingRatios_prop);
if (EditorGUI.EndChangeCheck())
havePropertiesChanged = true;
// TEXT WRAPPING & OVERFLOW
EditorGUI.BeginChangeCheck();
rect = EditorGUILayout.GetControlRect(false);
EditorGUI.PrefixLabel(new Rect(rect.x, rect.y, 130, rect.height), new GUIContent("Wrapping & Overflow"));
rect.width = (rect.width - 130) / 2f;
rect.x += 130;
int wrapSelection = EditorGUI.Popup(rect, enableWordWrapping_prop.boolValue ? 1 : 0, new string[] { "Disabled", "Enabled" });
if (EditorGUI.EndChangeCheck())
{
enableWordWrapping_prop.boolValue = wrapSelection == 1 ? true : false;
havePropertiesChanged = true;
isInputPasingRequired_prop.boolValue = true;
}
// TEXT OVERFLOW
EditorGUI.BeginChangeCheck();
if (textOverflowMode_prop.enumValueIndex != 5)
{
rect.x += rect.width + 5f;
rect.width -= 5;
EditorGUI.PropertyField(rect, textOverflowMode_prop, GUIContent.none);
}
else
{
rect.x += rect.width + 5f;
rect.width /= 2;
EditorGUI.PropertyField(rect, textOverflowMode_prop, GUIContent.none);
rect.x += rect.width;
rect.width -= 5;
EditorGUI.PropertyField(rect, pageToDisplay_prop, GUIContent.none);
}
if (EditorGUI.EndChangeCheck())
{
havePropertiesChanged = true;
isInputPasingRequired_prop.boolValue = true;
}
// TEXTURE MAPPING OPTIONS
EditorGUI.BeginChangeCheck();
rect = EditorGUILayout.GetControlRect(false);
EditorGUI.PrefixLabel(new Rect(rect.x, rect.y, 130, rect.height), new GUIContent("UV Mapping Options"));
rect.width = (rect.width - 130) / 2f;
rect.x += 130;
EditorGUI.PropertyField(rect, horizontalMapping_prop, GUIContent.none);
rect.x += rect.width + 5f;
rect.width -= 5;
EditorGUI.PropertyField(rect, verticalMapping_prop, GUIContent.none);
if (EditorGUI.EndChangeCheck())
{
havePropertiesChanged = true;
}
// UV OPTIONS
EditorGUI.BeginChangeCheck();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel("UV Offset");
EditorGUILayout.PropertyField(uvOffset_prop, GUIContent.none, GUILayout.MinWidth(70f));
EditorGUIUtility.labelWidth = 30;
EditorGUILayout.PropertyField(uvLineOffset_prop, new GUIContent("Line"), GUILayout.MinWidth(70f));
EditorGUIUtility.labelWidth = labelWidth;
EditorGUILayout.EndHorizontal();
if (EditorGUI.EndChangeCheck())
{
havePropertiesChanged = true;
}
// KERNING
EditorGUI.BeginChangeCheck();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PropertyField(enableKerning_prop, new GUIContent("Enable Kerning?"));
if (EditorGUI.EndChangeCheck())
{
//isAffectingWordWrapping_prop.boolValue = true;
havePropertiesChanged = true;
}
// EXTRA PADDING
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(enableExtraPadding_prop, new GUIContent("Extra Padding?"));
if (EditorGUI.EndChangeCheck())
{
havePropertiesChanged = true;
checkPaddingRequired_prop.boolValue = true;
}
EditorGUILayout.EndHorizontal();
}
if (GUILayout.Button("<b>EXTRA SETTINGS</b>" + (m_foldout.extraSettings ? uiStateLabel[1] : uiStateLabel[0]), TMP_UIStyleManager.Section_Label))
m_foldout.extraSettings = !m_foldout.extraSettings;
if (m_foldout.extraSettings)
{
EditorGUI.indentLevel = 0;
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel("Sorting Layer");
EditorGUI.BeginChangeCheck();
float old_LabelWidth = EditorGUIUtility.labelWidth;
float old_fieldWidth = EditorGUIUtility.fieldWidth;
// SORTING LAYERS
var sortingLayerNames = SortingLayerHelper.sortingLayerNames;
// Look up the layer name using the current layer ID
string oldName = SortingLayerHelper.GetSortingLayerNameFromID(m_textMeshProScript.sortingLayerID);
// Use the name to look up our array index into the names list
int oldLayerIndex = System.Array.IndexOf(sortingLayerNames, oldName);
// Show the pop-up for the names
EditorGUIUtility.fieldWidth = 0f;
int newLayerIndex = EditorGUILayout.Popup(string.Empty, oldLayerIndex, sortingLayerNames, GUILayout.MinWidth(80f));
// If the index changes, look up the ID for the new index to store as the new ID
if (newLayerIndex != oldLayerIndex)
{
//Undo.RecordObject(renderer, "Edit Sorting Layer");
m_textMeshProScript.sortingLayerID = SortingLayerHelper.GetSortingLayerIDForIndex(newLayerIndex);
//EditorUtility.SetDirty(renderer);
}
// Expose the manual sorting order
EditorGUIUtility.labelWidth = 40f;
EditorGUIUtility.fieldWidth = 80f;
int newSortingLayerOrder = EditorGUILayout.IntField("Order", m_textMeshProScript.sortingOrder);
if (newSortingLayerOrder != m_textMeshProScript.sortingOrder)
{
//Undo.RecordObject(renderer, "Edit Sorting Order");
m_textMeshProScript.sortingOrder = newSortingLayerOrder;
}
EditorGUILayout.EndHorizontal();
EditorGUIUtility.labelWidth = old_LabelWidth;
EditorGUIUtility.fieldWidth = old_fieldWidth;
EditorGUI.BeginChangeCheck();
//EditorGUILayout.PropertyField(isOverlay_prop, new GUIContent("Overlay Mode?"));
EditorGUILayout.PropertyField(isOrthographic_prop, new GUIContent("Orthographic Mode?"));
EditorGUILayout.PropertyField(isRichText_prop, new GUIContent("Enable Rich Text?"));
//EditorGUILayout.PropertyField(textRectangle_prop, true);
if (EditorGUI.EndChangeCheck())
havePropertiesChanged = true;
// EditorGUI.BeginChangeCheck();
//EditorGUILayout.PropertyField(mask_prop);
//EditorGUILayout.PropertyField(maskOffset_prop, true);
//EditorGUILayout.PropertyField(maskSoftness_prop);
//if (EditorGUI.EndChangeCheck())
//{
// isMaskUpdateRequired_prop.boolValue = true;
// havePropertiesChanged = true;
//}
//EditorGUILayout.PropertyField(sortingLayerID_prop);
//EditorGUILayout.PropertyField(sortingOrder_prop);
// Mask Selection
}
/*
if (Event.current.type == EventType.DragExited)
{
m_currentMaterialID = m_renderer.sharedMaterial.GetInstanceID();
if (m_currentMaterialID != m_previousMaterialID)
{
Debug.Log("Material has been changed to " + m_currentMaterialID + ". Previous Material was " + m_previousMaterialID);
//m_targetMaterial = m_renderer.sharedMaterial;
//TMPro_EventManager.ON_MATERIAL_PROPERTY_CHANGED(true, m_targetMaterial);
m_previousMaterialID = m_currentMaterialID;
havePropertiesChanged = true;
}
}
*/
if (havePropertiesChanged)
{
havePropertiesChanged_prop.boolValue = true;
havePropertiesChanged = false;
//m_updateManager.ScheduleObjectForUpdate(m_textMeshProScript);
}
EditorGUILayout.Space();
serializedObject.ApplyModifiedProperties();
/*
Editor materialEditor = Editor.CreateEditor(m_renderer.sharedMaterial);
if (materialEditor != null)
{
if (GUILayout.Button("<b>MATERIAL SETTINGS</b> - <i>Click to expand</i> -", Section_Label))
m_foldout.materialEditor= !m_foldout.materialEditor;
if (m_foldout.materialEditor)
{
materialEditor.OnInspectorGUI();
}
}
*/
}
void DrawPropertySlider(string label, SerializedProperty property)
{
float old_LabelWidth = EditorGUIUtility.labelWidth;
float old_FieldWidth = EditorGUIUtility.fieldWidth;
Rect rect = EditorGUILayout.GetControlRect(false, 17);
//EditorGUIUtility.labelWidth = m_labelWidth;
GUIContent content = label == "" ? GUIContent.none : new GUIContent(label);
EditorGUI.Slider(new Rect(rect.x, rect.y, rect.width, rect.height), property, 0.0f, 1.0f, content);
EditorGUIUtility.labelWidth = old_LabelWidth;
EditorGUIUtility.fieldWidth = old_FieldWidth;
}
private void DrawDimensionProperty(SerializedProperty property, string label)
{
float old_LabelWidth = EditorGUIUtility.labelWidth;
float old_FieldWidth = EditorGUIUtility.fieldWidth;
Rect rect = EditorGUILayout.GetControlRect(false, 18);
Rect pos0 = new Rect(rect.x, rect.y + 2, rect.width, 18);
float width = rect.width + 3;
pos0.width = old_LabelWidth;
GUI.Label(pos0, label);
Rect rectangle = property.rectValue;
float width_B = width - old_LabelWidth;
float fieldWidth = width_B / 4;
pos0.width = fieldWidth - 5;
pos0.x = old_LabelWidth + 15;
GUI.Label(pos0, "Width");
pos0.x += fieldWidth;
rectangle.width = EditorGUI.FloatField(pos0, GUIContent.none, rectangle.width);
pos0.x += fieldWidth;
GUI.Label(pos0, "Height");
pos0.x += fieldWidth;
rectangle.height = EditorGUI.FloatField(pos0, GUIContent.none, rectangle.height);
property.rectValue = rectangle;
EditorGUIUtility.labelWidth = old_LabelWidth;
EditorGUIUtility.fieldWidth = old_FieldWidth;
}
private void DrawDoubleEnumPopup(SerializedProperty property1, SerializedProperty property2, string label)
{
float old_LabelWidth = EditorGUIUtility.labelWidth;
float old_FieldWidth = EditorGUIUtility.fieldWidth;
Rect rect = EditorGUILayout.GetControlRect(false, 17);
Rect pos0 = new Rect(rect.x, rect.y, EditorGUIUtility.labelWidth, rect.height);
EditorGUI.PrefixLabel(pos0, new GUIContent(label));
pos0.x += pos0.width;
pos0.width = (rect.width - pos0.x) / 2 + 5;
EditorGUI.PropertyField(pos0, property1, GUIContent.none);
pos0.x += pos0.width + 5;
EditorGUI.PropertyField(pos0, property2, GUIContent.none);
EditorGUIUtility.labelWidth = old_LabelWidth;
EditorGUIUtility.fieldWidth = old_FieldWidth;
}
void DrawPropertyBlock(string[] labels, SerializedProperty[] properties)
{
float old_LabelWidth = EditorGUIUtility.labelWidth;
float old_FieldWidth = EditorGUIUtility.fieldWidth;
Rect rect = EditorGUILayout.GetControlRect(false, 17);
GUI.Label(new Rect(rect.x, rect.y, old_LabelWidth, rect.height), labels[0]);
rect.x = old_LabelWidth + 15;
rect.width = (rect.width + 20 - rect.x) / labels.Length;
for (int i = 0; i < labels.Length; i++)
{
if (i == 0)
{
EditorGUIUtility.labelWidth = 20;
GUI.enabled = properties[i] == fontSize_prop && autoSizing_prop.boolValue ? GUI.enabled = false : GUI.enabled = true;
EditorGUI.PropertyField(new Rect(rect.x - 20, rect.y, 80, rect.height), properties[i], new GUIContent(" "));
rect.x += rect.width;
GUI.enabled = true;
}
else
{
EditorGUIUtility.labelWidth = GUI.skin.textArea.CalcSize(new GUIContent(labels[i])).x;
EditorGUI.PropertyField(new Rect(rect.x, rect.y, rect.width - 5, rect.height), properties[i], new GUIContent(labels[i]));
rect.x += rect.width;
}
}
EditorGUIUtility.labelWidth = old_LabelWidth;
EditorGUIUtility.fieldWidth = old_FieldWidth;
}
// Special Handling of Undo / Redo Events.
private void OnUndoRedo()
{
int undoEventID = Undo.GetCurrentGroup();
int LastUndoEventID = m_eventID;
if (undoEventID != LastUndoEventID)
{
for (int i = 0; i < targets.Length; i++)
{
//Debug.Log("Undo & Redo Performed detected in Editor Panel. Event ID:" + Undo.GetCurrentGroup());
TMPro_EventManager.ON_TEXTMESHPRO_PROPERTY_CHANGED(true, targets[i] as TextMeshPro);
m_eventID = undoEventID;
}
}
}
/*
private UndoPropertyModification[] OnUndoRedoEvent(UndoPropertyModification[] modifications)
{
int eventID = Undo.GetCurrentGroup();
PropertyModification modifiedProp = modifications[0].propertyModification;
System.Type targetType = modifiedProp.target.GetType();
if (targetType == typeof(Material))
{
//Debug.Log("Undo / Redo Event Registered in Editor Panel on Target: " + targetObject);
//TMPro_EventManager.ON_MATERIAL_PROPERTY_CHANGED(true, targetObject as Material);
//EditorUtility.SetDirty(targetObject);
}
//string propertyPath = modifications[0].propertyModification.propertyPath;
//if (propertyPath == "m_fontAsset")
//{
//int currentEvent = Undo.GetCurrentGroup();
//Undo.RecordObject(Selection.activeGameObject.renderer.sharedMaterial, "Font Asset Changed");
//Undo.CollapseUndoOperations(currentEvent);
//Debug.Log("Undo / Redo Event: Font Asset changed. Event ID:" + Undo.GetCurrentGroup());
//}
//Debug.Log("Undo / Redo Event Registered in Editor Panel on Target: " + modifiedProp.propertyPath + " Undo Event ID:" + eventID + " Stored ID:" + TMPro_EditorUtility.UndoEventID);
//TextMeshPro_EventManager.ON_TEXTMESHPRO_PROPERTY_CHANGED(true, target as TextMeshPro);
return modifications;
}
*/
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Drawing;
using System.IO;
using System.Net;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.Imaging;
using OpenSim.Region.CoreModules.Scripting.DynamicTexture;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using log4net;
using System.Reflection;
using Mono.Addins;
namespace OpenSim.Region.CoreModules.Scripting.LoadImageURL
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "LoadImageURLModule")]
public class LoadImageURLModule : ISharedRegionModule, IDynamicTextureRender
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private string m_name = "LoadImageURL";
private Scene m_scene;
private IDynamicTextureManager m_textureManager;
private string m_proxyurl = "";
private string m_proxyexcepts = "";
#region IDynamicTextureRender Members
public string GetName()
{
return m_name;
}
public string GetContentType()
{
return ("image");
}
public bool SupportsAsynchronous()
{
return true;
}
// public bool AlwaysIdenticalConversion(string bodyData, string extraParams)
// {
// // We don't support conversion of body data.
// return false;
// }
public IDynamicTexture ConvertUrl(string url, string extraParams)
{
return null;
}
public IDynamicTexture ConvertData(string bodyData, string extraParams)
{
return null;
}
public bool AsyncConvertUrl(UUID id, string url, string extraParams)
{
MakeHttpRequest(url, id);
return true;
}
public bool AsyncConvertData(UUID id, string bodyData, string extraParams)
{
return false;
}
public void GetDrawStringSize(string text, string fontName, int fontSize,
out double xSize, out double ySize)
{
xSize = 0;
ySize = 0;
}
#endregion
#region ISharedRegionModule Members
public void Initialise(IConfigSource config)
{
m_proxyurl = config.Configs["Startup"].GetString("HttpProxy");
m_proxyexcepts = config.Configs["Startup"].GetString("HttpProxyExceptions");
}
public void PostInitialise()
{
}
public void AddRegion(Scene scene)
{
if (m_scene == null)
m_scene = scene;
}
public void RemoveRegion(Scene scene)
{
}
public void RegionLoaded(Scene scene)
{
if (m_textureManager == null && m_scene == scene)
{
m_textureManager = m_scene.RequestModuleInterface<IDynamicTextureManager>();
if (m_textureManager != null)
{
m_textureManager.RegisterRender(GetContentType(), this);
}
}
}
public void Close()
{
}
public string Name
{
get { return m_name; }
}
public Type ReplaceableInterface
{
get { return null; }
}
#endregion
private void MakeHttpRequest(string url, UUID requestID)
{
WebRequest request = HttpWebRequest.Create(url);
if (!string.IsNullOrEmpty(m_proxyurl))
{
if (!string.IsNullOrEmpty(m_proxyexcepts))
{
string[] elist = m_proxyexcepts.Split(';');
request.Proxy = new WebProxy(m_proxyurl, true, elist);
}
else
{
request.Proxy = new WebProxy(m_proxyurl, true);
}
}
RequestState state = new RequestState((HttpWebRequest) request, requestID);
// IAsyncResult result = request.BeginGetResponse(new AsyncCallback(HttpRequestReturn), state);
request.BeginGetResponse(new AsyncCallback(HttpRequestReturn), state);
TimeSpan t = (DateTime.UtcNow - new DateTime(1970, 1, 1));
state.TimeOfRequest = (int) t.TotalSeconds;
}
private void HttpRequestReturn(IAsyncResult result)
{
if (m_textureManager == null)
{
m_log.WarnFormat("[LOADIMAGEURLMODULE]: No texture manager. Can't function.");
return;
}
RequestState state = (RequestState) result.AsyncState;
WebRequest request = (WebRequest) state.Request;
Stream stream = null;
byte[] imageJ2000 = new byte[0];
Size newSize = new Size(0, 0);
try
{
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);
if (response != null && response.StatusCode == HttpStatusCode.OK)
{
stream = response.GetResponseStream();
if (stream != null)
{
try
{
Bitmap image = new Bitmap(stream);
// TODO: make this a bit less hard coded
if ((image.Height < 64) && (image.Width < 64))
{
newSize.Width = 32;
newSize.Height = 32;
}
else if ((image.Height < 128) && (image.Width < 128))
{
newSize.Width = 64;
newSize.Height = 64;
}
else if ((image.Height < 256) && (image.Width < 256))
{
newSize.Width = 128;
newSize.Height = 128;
}
else if ((image.Height < 512 && image.Width < 512))
{
newSize.Width = 256;
newSize.Height = 256;
}
else if ((image.Height < 1024 && image.Width < 1024))
{
newSize.Width = 512;
newSize.Height = 512;
}
else
{
newSize.Width = 1024;
newSize.Height = 1024;
}
using (Bitmap resize = new Bitmap(image, newSize))
{
imageJ2000 = OpenJPEG.EncodeFromImage(resize, true);
}
}
catch (Exception)
{
m_log.Error("[LOADIMAGEURLMODULE]: OpenJpeg Conversion Failed. Empty byte data returned!");
}
}
else
{
m_log.WarnFormat("[LOADIMAGEURLMODULE] No data returned");
}
}
}
catch (WebException)
{
}
finally
{
if (stream != null)
{
stream.Close();
}
}
m_log.DebugFormat("[LOADIMAGEURLMODULE]: Returning {0} bytes of image data for request {1}",
imageJ2000.Length, state.RequestID);
m_textureManager.ReturnData(
state.RequestID,
new OpenSim.Region.CoreModules.Scripting.DynamicTexture.DynamicTexture(
request.RequestUri, null, imageJ2000, newSize, false));
}
#region Nested type: RequestState
public class RequestState
{
public HttpWebRequest Request = null;
public UUID RequestID = UUID.Zero;
public int TimeOfRequest = 0;
public RequestState(HttpWebRequest request, UUID requestID)
{
Request = request;
RequestID = requestID;
}
}
#endregion
}
}
| |
using System;
using System.Data;
using System.Data.OleDb;
using PCSComUtils.Common;
using PCSComUtils.DataAccess;
using PCSComUtils.PCSExc;
namespace PCSComUtils.MasterSetup.DS
{
public class MST_MasterLocationDS
{
public MST_MasterLocationDS()
{
}
private const string THIS = "PCSComUtils.MasterSetup.DS.MST_MasterLocationDS";
//**************************************************************************
/// <Description>
/// This method uses to add data to MST_MasterLocation
/// </Description>
/// <Inputs>
/// MST_MasterLocationVO
/// </Inputs>
/// <Outputs>
/// newly inserted primarkey value
/// </Outputs>
/// <Returns>
/// void
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Tuesday, January 25, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void Add(object pobjObjectVO)
{
const string METHOD_NAME = THIS + ".Add()";
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
MST_MasterLocationVO objObject = (MST_MasterLocationVO) pobjObjectVO;
string strSql = String.Empty;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand("", oconPCS);
strSql = "INSERT INTO MST_MasterLocation("
+ MST_MasterLocationTable.CODE_FLD + ","
+ MST_MasterLocationTable.NAME_FLD + ","
+ MST_MasterLocationTable.ADDRESS_FLD + ","
+ MST_MasterLocationTable.STATE_FLD + ","
+ MST_MasterLocationTable.ZIPPOST_FLD + ","
+ MST_MasterLocationTable.CCNID_FLD + ","
+ MST_MasterLocationTable.CITYID_FLD + ","
+ MST_MasterLocationTable.COUNTRYID_FLD + ")"
+ "VALUES(?,?,?,?,?,?,?,?)";
ocmdPCS.Parameters.Add(new OleDbParameter(MST_MasterLocationTable.CODE_FLD, OleDbType.VarWChar));
ocmdPCS.Parameters[MST_MasterLocationTable.CODE_FLD].Value = objObject.Code;
ocmdPCS.Parameters.Add(new OleDbParameter(MST_MasterLocationTable.NAME_FLD, OleDbType.VarWChar));
ocmdPCS.Parameters[MST_MasterLocationTable.NAME_FLD].Value = objObject.Name;
ocmdPCS.Parameters.Add(new OleDbParameter(MST_MasterLocationTable.ADDRESS_FLD, OleDbType.VarWChar));
ocmdPCS.Parameters[MST_MasterLocationTable.ADDRESS_FLD].Value = objObject.Address;
ocmdPCS.Parameters.Add(new OleDbParameter(MST_MasterLocationTable.STATE_FLD, OleDbType.VarWChar));
ocmdPCS.Parameters[MST_MasterLocationTable.STATE_FLD].Value = objObject.State;
ocmdPCS.Parameters.Add(new OleDbParameter(MST_MasterLocationTable.ZIPPOST_FLD, OleDbType.VarWChar));
ocmdPCS.Parameters[MST_MasterLocationTable.ZIPPOST_FLD].Value = objObject.ZipPost;
ocmdPCS.Parameters.Add(new OleDbParameter(MST_MasterLocationTable.CCNID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[MST_MasterLocationTable.CCNID_FLD].Value = objObject.CCNID;
ocmdPCS.Parameters.Add(new OleDbParameter(MST_MasterLocationTable.CITYID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[MST_MasterLocationTable.CITYID_FLD].Value = objObject.CityID;
ocmdPCS.Parameters.Add(new OleDbParameter(MST_MasterLocationTable.COUNTRYID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[MST_MasterLocationTable.COUNTRYID_FLD].Value = objObject.CountryID;
ocmdPCS.CommandText = strSql;
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
}
catch (OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
}
catch (InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS != null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to delete data from MST_MasterLocation
/// </Description>
/// <Inputs>
/// ID
/// </Inputs>
/// <Outputs>
/// void
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// 09-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void Delete(int pintID)
{
const string METHOD_NAME = THIS + ".Delete()";
string strSql = String.Empty;
strSql = "DELETE " + MST_MasterLocationTable.TABLE_NAME + " WHERE " + "MasterLocationID" + "=" + pintID.ToString();
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
ocmdPCS = null;
}
catch (OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE)
{
throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS != null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to get data from MST_MasterLocation
/// </Description>
/// <Inputs>
/// ID
/// </Inputs>
/// <Outputs>
/// MST_MasterLocationVO
/// </Outputs>
/// <Returns>
/// MST_MasterLocationVO
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Tuesday, January 25, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public object GetObjectVO(int pintID)
{
const string METHOD_NAME = THIS + ".GetObjectVO()";
DataSet dstPCS = new DataSet();
OleDbDataReader odrPCS = null;
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql = "SELECT "
+ MST_MasterLocationTable.MASTERLOCATIONID_FLD + ","
+ MST_MasterLocationTable.CODE_FLD + ","
+ MST_MasterLocationTable.NAME_FLD + ","
+ MST_MasterLocationTable.ADDRESS_FLD + ","
+ MST_MasterLocationTable.STATE_FLD + ","
+ MST_MasterLocationTable.ZIPPOST_FLD + ","
+ MST_MasterLocationTable.CCNID_FLD + ","
+ MST_MasterLocationTable.CITYID_FLD + ","
+ MST_MasterLocationTable.COUNTRYID_FLD
+ " FROM " + MST_MasterLocationTable.TABLE_NAME
+ " WHERE " + MST_MasterLocationTable.MASTERLOCATIONID_FLD + "=" + pintID;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
odrPCS = ocmdPCS.ExecuteReader();
MST_MasterLocationVO objObject = new MST_MasterLocationVO();
while (odrPCS.Read())
{
objObject.MasterLocationID = int.Parse(odrPCS[MST_MasterLocationTable.MASTERLOCATIONID_FLD].ToString().Trim());
objObject.Code = odrPCS[MST_MasterLocationTable.CODE_FLD].ToString().Trim();
objObject.Name = odrPCS[MST_MasterLocationTable.NAME_FLD].ToString().Trim();
objObject.Address = odrPCS[MST_MasterLocationTable.ADDRESS_FLD].ToString().Trim();
objObject.State = odrPCS[MST_MasterLocationTable.STATE_FLD].ToString().Trim();
objObject.ZipPost = odrPCS[MST_MasterLocationTable.ZIPPOST_FLD].ToString().Trim();
if (odrPCS[MST_MasterLocationTable.CCNID_FLD] != DBNull.Value)
objObject.CCNID = int.Parse(odrPCS[MST_MasterLocationTable.CCNID_FLD].ToString().Trim());
if (odrPCS[MST_MasterLocationTable.CITYID_FLD] != DBNull.Value)
objObject.CityID = int.Parse(odrPCS[MST_MasterLocationTable.CITYID_FLD].ToString().Trim());
if (odrPCS[MST_MasterLocationTable.COUNTRYID_FLD] != DBNull.Value)
objObject.CountryID = int.Parse(odrPCS[MST_MasterLocationTable.COUNTRYID_FLD].ToString().Trim());
}
return objObject;
}
catch (OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS != null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to update data to MST_MasterLocation
/// </Description>
/// <Inputs>
/// MST_MasterLocationVO
/// </Inputs>
/// <Outputs>
///
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// 09-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void Update(object pobjObjecVO)
{
const string METHOD_NAME = THIS + ".Update()";
MST_MasterLocationVO objObject = (MST_MasterLocationVO) pobjObjecVO;
//prepare value for parameters
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
strSql = "UPDATE MST_MasterLocation SET "
+ MST_MasterLocationTable.CODE_FLD + "= ?" + ","
+ MST_MasterLocationTable.NAME_FLD + "= ?" + ","
+ MST_MasterLocationTable.ADDRESS_FLD + "= ?" + ","
+ MST_MasterLocationTable.STATE_FLD + "= ?" + ","
+ MST_MasterLocationTable.ZIPPOST_FLD + "= ?" + ","
+ MST_MasterLocationTable.CCNID_FLD + "= ?" + ","
+ MST_MasterLocationTable.CITYID_FLD + "= ?" + ","
+ MST_MasterLocationTable.COUNTRYID_FLD + "= ?"
+ " WHERE " + MST_MasterLocationTable.MASTERLOCATIONID_FLD + "= ?";
ocmdPCS.Parameters.Add(new OleDbParameter(MST_MasterLocationTable.CODE_FLD, OleDbType.VarWChar));
ocmdPCS.Parameters[MST_MasterLocationTable.CODE_FLD].Value = objObject.Code;
ocmdPCS.Parameters.Add(new OleDbParameter(MST_MasterLocationTable.NAME_FLD, OleDbType.VarWChar));
ocmdPCS.Parameters[MST_MasterLocationTable.NAME_FLD].Value = objObject.Name;
ocmdPCS.Parameters.Add(new OleDbParameter(MST_MasterLocationTable.ADDRESS_FLD, OleDbType.VarWChar));
ocmdPCS.Parameters[MST_MasterLocationTable.ADDRESS_FLD].Value = objObject.Address;
ocmdPCS.Parameters.Add(new OleDbParameter(MST_MasterLocationTable.STATE_FLD, OleDbType.VarWChar));
ocmdPCS.Parameters[MST_MasterLocationTable.STATE_FLD].Value = objObject.State;
ocmdPCS.Parameters.Add(new OleDbParameter(MST_MasterLocationTable.ZIPPOST_FLD, OleDbType.VarWChar));
ocmdPCS.Parameters[MST_MasterLocationTable.ZIPPOST_FLD].Value = objObject.ZipPost;
ocmdPCS.Parameters.Add(new OleDbParameter(MST_MasterLocationTable.CCNID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[MST_MasterLocationTable.CCNID_FLD].Value = objObject.CCNID;
ocmdPCS.Parameters.Add(new OleDbParameter(MST_MasterLocationTable.CITYID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[MST_MasterLocationTable.CITYID_FLD].Value = objObject.CityID;
ocmdPCS.Parameters.Add(new OleDbParameter(MST_MasterLocationTable.COUNTRYID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[MST_MasterLocationTable.COUNTRYID_FLD].Value = objObject.CountryID;
ocmdPCS.Parameters.Add(new OleDbParameter(MST_MasterLocationTable.MASTERLOCATIONID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[MST_MasterLocationTable.MASTERLOCATIONID_FLD].Value = objObject.MasterLocationID;
ocmdPCS.CommandText = strSql;
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
}
catch (OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
}
catch (InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS != null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to get all data from MST_MasterLocation
/// </Description>
/// <Inputs>
///
/// </Inputs>
/// <Outputs>
/// DataSet
/// </Outputs>
/// <Returns>
/// DataSet
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Tuesday, January 25, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public DataSet List()
{
const string METHOD_NAME = THIS + ".List()";
DataSet dstPCS = new DataSet();
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql = "SELECT "
+ MST_MasterLocationTable.MASTERLOCATIONID_FLD + ","
+ MST_MasterLocationTable.CODE_FLD + ","
+ MST_MasterLocationTable.NAME_FLD + ","
+ MST_MasterLocationTable.ADDRESS_FLD + ","
+ MST_MasterLocationTable.STATE_FLD + ","
+ MST_MasterLocationTable.ZIPPOST_FLD + ","
+ MST_MasterLocationTable.CCNID_FLD + ","
+ MST_MasterLocationTable.CITYID_FLD + ","
+ MST_MasterLocationTable.COUNTRYID_FLD
+ " FROM " + MST_MasterLocationTable.TABLE_NAME;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dstPCS, MST_MasterLocationTable.TABLE_NAME);
return dstPCS;
}
catch (OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS != null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
public DataSet List(string pstrQueryCondition)
{
const string METHOD_NAME = THIS + ".List()";
DataSet dstPCS = new DataSet();
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql = "SELECT "
+ MST_MasterLocationTable.MASTERLOCATIONID_FLD + ","
+ MST_MasterLocationTable.CODE_FLD + ","
+ MST_MasterLocationTable.NAME_FLD + ","
+ MST_MasterLocationTable.ADDRESS_FLD + ","
+ MST_MasterLocationTable.STATE_FLD + ","
+ MST_MasterLocationTable.ZIPPOST_FLD + ","
+ MST_MasterLocationTable.CCNID_FLD + ","
+ MST_MasterLocationTable.CITYID_FLD + ","
+ MST_MasterLocationTable.COUNTRYID_FLD
+ " FROM " + MST_MasterLocationTable.TABLE_NAME
+ " WHERE " + pstrQueryCondition;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dstPCS, MST_MasterLocationTable.TABLE_NAME);
return dstPCS;
}
catch (OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS != null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to update a DataSet
/// </Description>
/// <Inputs>
/// DataSet
/// </Inputs>
/// <Outputs>
///
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// Tuesday, January 25, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void UpdateDataSet(DataSet pData)
{
const string METHOD_NAME = THIS + ".UpdateDataSet()";
string strSql;
OleDbConnection oconPCS = null;
OleDbCommandBuilder odcbPCS;
OleDbDataAdapter odadPCS = new OleDbDataAdapter();
try
{
strSql = "SELECT "
+ MST_MasterLocationTable.MASTERLOCATIONID_FLD + ","
+ MST_MasterLocationTable.CODE_FLD + ","
+ MST_MasterLocationTable.NAME_FLD + ","
+ MST_MasterLocationTable.ADDRESS_FLD + ","
+ MST_MasterLocationTable.STATE_FLD + ","
+ MST_MasterLocationTable.ZIPPOST_FLD + ","
+ MST_MasterLocationTable.CCNID_FLD + ","
+ MST_MasterLocationTable.CITYID_FLD + ","
+ MST_MasterLocationTable.COUNTRYID_FLD
+ " FROM " + MST_MasterLocationTable.TABLE_NAME;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
odadPCS.SelectCommand = new OleDbCommand(strSql, oconPCS);
odcbPCS = new OleDbCommandBuilder(odadPCS);
pData.EnforceConstraints = false;
odadPCS.Update(pData, MST_MasterLocationTable.TABLE_NAME);
}
catch (OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
else if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE)
{
throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
}
catch (InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS != null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to get master location by CCN ID
/// </Description>
/// <Inputs>
/// int
/// </Inputs>
/// <Outputs>
/// DataSet
/// </Outputs>
/// <Returns>
/// DataSet
/// </Returns>
/// <Authors>
/// DungLa
/// </Authors>
/// <History>
/// Feb - 17 - 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public DataSet ListByCCNID(int pintCCNID)
{
const string METHOD_NAME = THIS + ".ListByCCNID()";
DataSet dstPCS = new DataSet();
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql = "SELECT "
+ MST_MasterLocationTable.MASTERLOCATIONID_FLD + ","
+ MST_MasterLocationTable.CODE_FLD + ","
+ MST_MasterLocationTable.NAME_FLD + ","
+ MST_MasterLocationTable.ADDRESS_FLD + ","
+ MST_MasterLocationTable.STATE_FLD + ","
+ MST_MasterLocationTable.ZIPPOST_FLD + ","
+ MST_MasterLocationTable.CCNID_FLD + ","
+ MST_MasterLocationTable.CITYID_FLD + ","
+ MST_MasterLocationTable.COUNTRYID_FLD
+ " FROM " + MST_MasterLocationTable.TABLE_NAME
+ " WHERE " + MST_MasterLocationTable.CCNID_FLD + "=" + pintCCNID;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dstPCS, MST_MasterLocationTable.TABLE_NAME);
return dstPCS;
}
catch (OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS != null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to get data for MasterLocation dropdown
/// </Description>
/// <Inputs>
/// int
/// </Inputs>
/// <Outputs>
/// DataTable
/// </Outputs>
/// <Returns>
/// DataTable
/// </Returns>
/// <Authors>
/// DungLa
/// </Authors>
/// <History>
/// 17-Feb-2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public DataTable GetDataForTrueDBDropDown(int pintCCNID)
{
const string METHOD_NAME = THIS + ".GetDataForMasLocDropDown()";
DataSet dstPCS = new DataSet();
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql = "SELECT "
+ MST_MasterLocationTable.MASTERLOCATIONID_FLD + ","
+ MST_MasterLocationTable.CODE_FLD
+ " FROM " + MST_MasterLocationTable.TABLE_NAME;
if (pintCCNID != 0)
strSql += " WHERE " + MST_MasterLocationTable.CCNID_FLD + "=" + pintCCNID;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dstPCS, MST_MasterLocationTable.TABLE_NAME);
return dstPCS.Tables[MST_MasterLocationTable.TABLE_NAME];
}
catch (OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS != null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
//**************************************************************************
/// <Description>
/// This method uses to get master location code from id
/// </Description>
/// <Inputs>
/// id
/// </Inputs>
/// <Outputs>
/// string Code
/// </Outputs>
/// <Returns>
/// string Code
/// </Returns>
/// <Authors>
/// DungLa
/// </Authors>
/// <History>
/// 21-Apr-2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public string GetCodeFromID(int pintID)
{
const string METHOD_NAME = THIS + ".GetCodeFromID()";
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql= "SELECT "
+ MST_MasterLocationTable.CODE_FLD
+ " FROM " + MST_MasterLocationTable.TABLE_NAME
+" WHERE " + MST_MasterLocationTable.MASTERLOCATIONID_FLD + "=" + pintID;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
object objResult = ocmdPCS.ExecuteScalar();
if (objResult != null)
return objResult.ToString().Trim();
else
return string.Empty;
}
catch(OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS!=null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
}
}
| |
//------------------------------------------------------------------------------
// HTTPClient.cs
// HTTP Client code written in Torque for the new Meltdown 2.
// Note: Requires HTTPClientData.cs
// Copyright (c) 2014 Robert MacGregor
//------------------------------------------------------------------------------
// How long the client waits before deciding that it received everything
// from the target server in milliseconds.
$HTTPClient::TimeoutMS = 2000;
// How many attempts the client will go for when sending packets before
// deciding it can't send it.
$HTTPClient::PacketResendAttempts = 3;
// Load Client Data
logEcho("HTTPClient.cs: Loading Client Data ...");
$HTTPClient::Replicate = "";
$TempFileObject = new FileObject();
$TempFileObject.openForRead("HTTPClientData.cs"); // Point this to wherever the file actually resides
while (!$TempFileObject.isEOF())
$HTTPClient::Replicate = $HTTPClient::Replicate @ $TempFileObject.readLine() @ "\n";
$HTTPClient::Replicate = stripChars($HTTPClient::Replicate, "\t");
$TempFileObject.close();
$TempFileObject.delete();
// Description: A function bound to the HTTPClient script object
// class that connects the game to a given server specified by
// %address.
// Parameter %address: The IP address or the hostname (ie. google.com)
// of the server to connect to.
// Parameter %port: The port # to connect on. If not specified, port
// 80 is assumed.
function HTTPClient::connect(%this, %address, %port)
{
if (%this.isConnected)
return false;
%socketName = %this.getName() @ "Socket";
if (!isObject(%this.socket))
{
// Define the script functions
%evalCode = strReplace($HTTPClient::Replicate, "UNIQUESOCKET", %socketName);
eval(%evalCode);
%this.socket = new TCPObject(%socketName);
%this.socket.owner = %this;
}
if (%port $= "")
%port = 80;
%this.socket.connect(%address @ ":" @ %port);
return true;
}
// Description: A function bound to the HTTPClient script object class
// that acts a sort of macro to quickly get information from a given
// location on a remote server.
// Parameter %address: The IP address or host name (ie. google.com) to
// get a resource from.
// Parameter %port: The port number to connect on. If it is "" then port
// 80 is assumed.
// Parameter %location: The location of the resource you want to attempt
// to grab. (ie. /doku.php) Anything that is valid in the URL bar of
// a web browser is acceptable here.
function HTTPClient::get(%this, %address, %port, %location)
{
%this.connect(%address, %port);
%packet = new ScriptObject() { class = "HTTPResponsePacket"; };
%packet.useHeaderTemplate();
%packet.setHeader("Host", %address);
%packet.setPacketType("GET", %location);
%this.sendPacket(%packet);
}
// Description: A function bound to the HTTPClient script object class
// that acts as a sort of macro to quickly send off a given packet to
// a specified location.
// Parameter %address: The IP address or host name (ie. google.com) to
// get a resource from.
// Parameter %port: The port number to connect on. If it is "" then port
// 80 is assumed.
// Parameter %packet: The instance of the HTTPResponsePacket script
// object to send.
function HTTPClient::sendTo(%this, %address, %port, %packet)
{
%this.connect(%address, %port);
%this.sendPacket(%packet);
}
// Description: A function bound to the HTTPClient script object class
// that sends a given packet to the remote host that we're currently
// connected to.
// Parameter %packet: The instance of a HTTPResponsePacket script object
// type to send to the remote host we're currently connected to.
function HTTPClient::sendPacket(%this, %packet)
{
%this.receiveBuffer = "";
if (!%this.isConnected && %this.resendAttempts < $HTTPClient::PacketResendAttempts)
{
// Wait 500 MS (this assumes we have a connection in progress)
%this.schedule(500, "sendPacket", %packet);
%this.resendAttempts++;
return false;
}
else if (!%this.isConnected)
{
%this.resendAttempts = 0;
%this.onPacketSendFail(%packet);
error("HTTPClient.cs: Failed to send packet " @ %packet @ "!");
return false;
}
%packetData = %packet.statusCodeData @ "\r\n";
// Construct our POST packet if we have to
if (%packet.isPostRequest != 0)
{
%packet.payload = "";
for (%i = 0; %i < %packet.postFieldCount; %i++)
{
%packet.payload = %packet.payload @ %packet.postFieldData[%packet.postFieldName[%i]];
if (%i < %packet.postFieldCount - 1)
%packet.payload = %packet.payload @ "&";
%packet.setPayload(%packet.payload);
}
%packet.setHeader("Content-Type", "application/x-www-form-urlencoded");
%packet.setHeader("Content-Length", strlen(%packet.payload) + 1); // Why is the +1 needed with strlen?
}
for (%i = 0; %i < %packet.headerCount; %i++)
%packetData = %packetData @ %packet.headerData[%packet.headerName[%i]] @ "\r\n";
%packetData = %packetData @ "\r\n";
%packetData = %packetData @ %packet.payLoad @ "\r\n";
%this.socket.send(%packetData);
%this.resendAttempts = 0;
return true;
}
// Callbacks -- make these do whatever you please!
function HTTPClient::onConnected(%this)
{
return true;
}
function HTTPClient::onDisconnected(%this)
{
return true;
}
function HTTPClient::onLine(%this, %line)
{
}
function HTTPClient::onPacketSendFail(%this, %packet)
{
}
function HTTPClient::onReceivedPacket(%this, %packet)
{
%packet.dump();
}
// Description: Sets a given HTTP header.
// Parameter %name: The name of the header to assign a value to.
// Parameter %value: The value to assign to header %name.
function HTTPResponsePacket::setHeader(%this, %name, %value)
{
// Fix for a weird array indexing bug
if (%this.headerCount $="")
%this.headerCount = 0;
if (%this.header[%name] $= "")
{
%this.headerName[%this.headerCount] = %name;
%this.headerCount++;
}
%this.headerData[%name] = %name @ ": " @ %value;
%this.header[%name] = %value;
return true;
}
// Description: Sets the HTTP status code of this packet. This is used
// for server responses.
// Parameter %code: The HTTP code that is to be sent in this packet.
function HTTPResponsePacket::setStatusCode(%this, %code)
{
%this.statusCodeData = "HTTP/1.1 " @ %code SPC "OK";
%this.type = "RESPONSE";
%this.statusCode = %code;
%this.isPostRequest = false;
return true;
}
// Description: Sets the HTTP packet type.
// Parameter %isPOST: Is it a POST request?
// Parameter %destination: The desired destination on the server
// we want to hit.
function HTTPResponsePacket::setPacketType(%this, %isPOST, %destination)
{
%type = "GET";
if (%isPOST)
%type = "POST";
%this.statusCodeData = %type SPC %destination SPC "HTTP/1.1";
%this.type = %type;
%this.statusCode = -1;
%this.isPostRequest = %isPost;
}
// Description: Sets the HTTP Payload.
// Parameter %data: The data that is to be sent in the payload section
// of the packet.
function HTTPResponsePacket::setPayload(%this, %data)
{
%this.payLoad = %data;
%this.payloadSize = strLen(%data) - 1;
%this.setHeader("Content-Length", %this.payloadSize);
return true;
}
// Description: A function that operates almost exactly like setHeader,
// except it is assigning POST fields.
// Parameter %name: The name of the post field to assign a value to.
// Parameter %value: The value to assign to post field %name.
function HTTPResponsePacket::setPOSTField(%this, %name, %value)
{
// Fix for a weird array indexing bug
if (%this.postFieldCount $="")
%this.postFieldCount = 0;
%name = strReplace(%name, " ", "+");
%name = strLwr(%name);
if (%this.postFields[%name] $= "")
{
%this.postFieldName[%this.postFieldCount] = %name;
%this.postFieldCount++;
}
%this.postFieldData[%name] = %name @ "=" @ %value;
%this.postField[%name] = %value;
return true;
}
// Description: A simple macro that assigns common header values
// to the packet.
function HTTPResponsePacket::useHeaderTemplate(%this)
{
%this.setHeader("User-Agent", "Tribes 2");
%this.setHeader("Connection", "close");
%this.setHeader("Cache-Control", "no-cache");
%this.setHeader("Accept-Language", "en");
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
// ReSharper disable ConditionIsAlwaysTrueOrFalse (we're allowing nulls to be passed to the writer where the underlying class doesn't).
// ReSharper disable HeuristicUnreachableCode
namespace osu.Game.IO.Legacy
{
/// <summary> SerializationWriter. Extends BinaryWriter to add additional data types,
/// handle null strings and simplify use with ISerializable. </summary>
public class SerializationWriter : BinaryWriter
{
public SerializationWriter(Stream s, bool leaveOpen = false)
: base(s, Encoding.UTF8, leaveOpen)
{
}
/// <summary> Static method to initialise the writer with a suitable MemoryStream. </summary>
public static SerializationWriter GetWriter()
{
MemoryStream ms = new MemoryStream(1024);
return new SerializationWriter(ms);
}
/// <summary> Writes a string to the buffer. Overrides the base implementation so it can cope with nulls </summary>
public override void Write(string str)
{
if (str == null)
{
Write((byte)ObjType.nullType);
}
else
{
Write((byte)ObjType.stringType);
base.Write(str);
}
}
/// <summary> Writes a byte array to the buffer. Overrides the base implementation to
/// send the length of the array which is needed when it is retrieved </summary>
public override void Write(byte[] b)
{
if (b == null)
{
Write(-1);
}
else
{
int len = b.Length;
Write(len);
if (len > 0) base.Write(b);
}
}
/// <summary> Writes a char array to the buffer. Overrides the base implementation to
/// sends the length of the array which is needed when it is read. </summary>
public override void Write(char[] c)
{
if (c == null)
{
Write(-1);
}
else
{
int len = c.Length;
Write(len);
if (len > 0) base.Write(c);
}
}
/// <summary>
/// Writes DateTime to the buffer.
/// </summary>
/// <param name="dt"></param>
public void Write(DateTime dt)
{
Write(dt.ToUniversalTime().Ticks);
}
/// <summary> Writes a generic ICollection (such as an IList(T)) to the buffer.</summary>
public void Write<T>(List<T> c) where T : ILegacySerializable
{
if (c == null)
{
Write(-1);
}
else
{
int count = c.Count;
Write(count);
for (int i = 0; i < count; i++)
c[i].WriteToStream(this);
}
}
/// <summary> Writes a generic IDictionary to the buffer. </summary>
public void Write<TKey, TValue>(IDictionary<TKey, TValue> d)
{
if (d == null)
{
Write(-1);
}
else
{
Write(d.Count);
foreach (KeyValuePair<TKey, TValue> kvp in d)
{
WriteObject(kvp.Key);
WriteObject(kvp.Value);
}
}
}
/// <summary> Writes an arbitrary object to the buffer. Useful where we have something of type "object"
/// and don't know how to treat it. This works out the best method to use to write to the buffer. </summary>
public void WriteObject(object obj)
{
if (obj == null)
{
Write((byte)ObjType.nullType);
}
else
{
switch (obj)
{
case bool boolObj:
Write((byte)ObjType.boolType);
Write(boolObj);
break;
case byte byteObj:
Write((byte)ObjType.byteType);
Write(byteObj);
break;
case ushort ushortObj:
Write((byte)ObjType.uint16Type);
Write(ushortObj);
break;
case uint uintObj:
Write((byte)ObjType.uint32Type);
Write(uintObj);
break;
case ulong ulongObj:
Write((byte)ObjType.uint64Type);
Write(ulongObj);
break;
case sbyte sbyteObj:
Write((byte)ObjType.sbyteType);
Write(sbyteObj);
break;
case short shortObj:
Write((byte)ObjType.int16Type);
Write(shortObj);
break;
case int intObj:
Write((byte)ObjType.int32Type);
Write(intObj);
break;
case long longObj:
Write((byte)ObjType.int64Type);
Write(longObj);
break;
case char charObj:
Write((byte)ObjType.charType);
base.Write(charObj);
break;
case string stringObj:
Write((byte)ObjType.stringType);
base.Write(stringObj);
break;
case float floatObj:
Write((byte)ObjType.singleType);
Write(floatObj);
break;
case double doubleObj:
Write((byte)ObjType.doubleType);
Write(doubleObj);
break;
case decimal decimalObj:
Write((byte)ObjType.decimalType);
Write(decimalObj);
break;
case DateTime dateTimeObj:
Write((byte)ObjType.dateTimeType);
Write(dateTimeObj);
break;
case byte[] byteArray:
Write((byte)ObjType.byteArrayType);
base.Write(byteArray);
break;
case char[] charArray:
Write((byte)ObjType.charArrayType);
base.Write(charArray);
break;
default:
Write((byte)ObjType.otherType);
BinaryFormatter b = new BinaryFormatter
{
// AssemblyFormat = FormatterAssemblyStyle.Simple,
TypeFormat = FormatterTypeStyle.TypesWhenNeeded
};
b.Serialize(BaseStream, obj);
break;
} // switch
} // if obj==null
} // WriteObject
/// <summary> Adds the SerializationWriter buffer to the SerializationInfo at the end of GetObjectData(). </summary>
public void AddToInfo(SerializationInfo info)
{
byte[] b = ((MemoryStream)BaseStream).ToArray();
info.AddValue("X", b, typeof(byte[]));
}
public void WriteRawBytes(byte[] b)
{
base.Write(b);
}
public void WriteByteArray(byte[] b)
{
if (b == null)
{
Write(-1);
}
else
{
int len = b.Length;
Write(len);
if (len > 0) base.Write(b);
}
}
public void WriteUtf8(string str)
{
WriteRawBytes(Encoding.UTF8.GetBytes(str));
}
}
}
| |
// 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.
//
namespace System.Reflection.Emit
{
using System;
using System.Reflection;
using CultureInfo = System.Globalization.CultureInfo;
using System.Collections.Generic;
using System.Diagnostics.SymbolStore;
using System.Security;
using System.Security.Permissions;
using System.Runtime.InteropServices;
using System.Diagnostics.Contracts;
[HostProtection(MayLeakOnAbort = true)]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(_ConstructorBuilder))]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class ConstructorBuilder : ConstructorInfo, _ConstructorBuilder
{
private readonly MethodBuilder m_methodBuilder;
internal bool m_isDefaultConstructor;
#region Constructor
private ConstructorBuilder()
{
}
[System.Security.SecurityCritical] // auto-generated
internal ConstructorBuilder(String name, MethodAttributes attributes, CallingConventions callingConvention,
Type[] parameterTypes, Type[][] requiredCustomModifiers, Type[][] optionalCustomModifiers, ModuleBuilder mod, TypeBuilder type)
{
int sigLength;
byte[] sigBytes;
MethodToken token;
m_methodBuilder = new MethodBuilder(name, attributes, callingConvention, null, null, null,
parameterTypes, requiredCustomModifiers, optionalCustomModifiers, mod, type, false);
type.m_listMethods.Add(m_methodBuilder);
sigBytes = m_methodBuilder.GetMethodSignature().InternalGetSignature(out sigLength);
token = m_methodBuilder.GetToken();
}
[System.Security.SecurityCritical] // auto-generated
internal ConstructorBuilder(String name, MethodAttributes attributes, CallingConventions callingConvention,
Type[] parameterTypes, ModuleBuilder mod, TypeBuilder type) :
this(name, attributes, callingConvention, parameterTypes, null, null, mod, type)
{
}
#endregion
#region Internal
internal override Type[] GetParameterTypes()
{
return m_methodBuilder.GetParameterTypes();
}
private TypeBuilder GetTypeBuilder()
{
return m_methodBuilder.GetTypeBuilder();
}
internal ModuleBuilder GetModuleBuilder()
{
return GetTypeBuilder().GetModuleBuilder();
}
#endregion
#region Object Overrides
public override String ToString()
{
return m_methodBuilder.ToString();
}
#endregion
#region MemberInfo Overrides
internal int MetadataTokenInternal
{
get { return m_methodBuilder.MetadataTokenInternal; }
}
public override Module Module
{
get { return m_methodBuilder.Module; }
}
public override Type ReflectedType
{
get { return m_methodBuilder.ReflectedType; }
}
public override Type DeclaringType
{
get { return m_methodBuilder.DeclaringType; }
}
public override String Name
{
get { return m_methodBuilder.Name; }
}
#endregion
#region MethodBase Overrides
public override Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule"));
}
[Pure]
public override ParameterInfo[] GetParameters()
{
ConstructorInfo rci = GetTypeBuilder().GetConstructor(m_methodBuilder.m_parameterTypes);
return rci.GetParameters();
}
public override MethodAttributes Attributes
{
get { return m_methodBuilder.Attributes; }
}
public override MethodImplAttributes GetMethodImplementationFlags()
{
return m_methodBuilder.GetMethodImplementationFlags();
}
public override RuntimeMethodHandle MethodHandle
{
get { return m_methodBuilder.MethodHandle; }
}
#endregion
#region ConstructorInfo Overrides
public override Object Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule"));
}
#endregion
#region ICustomAttributeProvider Implementation
public override Object[] GetCustomAttributes(bool inherit)
{
return m_methodBuilder.GetCustomAttributes(inherit);
}
public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
{
return m_methodBuilder.GetCustomAttributes(attributeType, inherit);
}
public override bool IsDefined (Type attributeType, bool inherit)
{
return m_methodBuilder.IsDefined(attributeType, inherit);
}
#endregion
#region Public Members
public MethodToken GetToken()
{
return m_methodBuilder.GetToken();
}
public ParameterBuilder DefineParameter(int iSequence, ParameterAttributes attributes, String strParamName)
{
// Theoretically we shouldn't allow iSequence to be 0 because in reflection ctors don't have
// return parameters. But we'll allow it for backward compatibility with V2. The attributes
// defined on the return parameters won't be very useful but won't do much harm either.
// MD will assert if we try to set the reserved bits explicitly
attributes = attributes & ~ParameterAttributes.ReservedMask;
return m_methodBuilder.DefineParameter(iSequence, attributes, strParamName);
}
public void SetSymCustomAttribute(String name, byte[] data)
{
m_methodBuilder.SetSymCustomAttribute(name, data);
}
public ILGenerator GetILGenerator()
{
if (m_isDefaultConstructor)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_DefaultConstructorILGen"));
return m_methodBuilder.GetILGenerator();
}
public ILGenerator GetILGenerator(int streamSize)
{
if (m_isDefaultConstructor)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_DefaultConstructorILGen"));
return m_methodBuilder.GetILGenerator(streamSize);
}
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
public void SetMethodBody(byte[] il, int maxStack, byte[] localSignature, IEnumerable<ExceptionHandler> exceptionHandlers, IEnumerable<int> tokenFixups)
{
if (m_isDefaultConstructor)
{
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_DefaultConstructorDefineBody"));
}
m_methodBuilder.SetMethodBody(il, maxStack, localSignature, exceptionHandlers, tokenFixups);
}
#if FEATURE_CAS_POLICY
[System.Security.SecuritySafeCritical] // auto-generated
public void AddDeclarativeSecurity(SecurityAction action, PermissionSet pset)
{
if (pset == null)
throw new ArgumentNullException("pset");
#pragma warning disable 618
if (!Enum.IsDefined(typeof(SecurityAction), action) ||
action == SecurityAction.RequestMinimum ||
action == SecurityAction.RequestOptional ||
action == SecurityAction.RequestRefuse)
{
throw new ArgumentOutOfRangeException("action");
}
#pragma warning restore 618
Contract.EndContractBlock();
// Cannot add declarative security after type is created.
if (m_methodBuilder.IsTypeCreated())
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_TypeHasBeenCreated"));
// Translate permission set into serialized format (use standard binary serialization).
byte[] blob = pset.EncodeXml();
// Write the blob into the metadata.
TypeBuilder.AddDeclarativeSecurity(GetModuleBuilder().GetNativeHandle(), GetToken().Token, action, blob, blob.Length);
}
#endif // FEATURE_CAS_POLICY
public override CallingConventions CallingConvention
{
get
{
if (DeclaringType.IsGenericType)
return CallingConventions.HasThis;
return CallingConventions.Standard;
}
}
public Module GetModule()
{
return m_methodBuilder.GetModule();
}
[Obsolete("This property has been deprecated. http://go.microsoft.com/fwlink/?linkid=14202")] //It always returns null.
public Type ReturnType
{
get { return GetReturnType(); }
}
// This always returns null. Is that what we want?
internal override Type GetReturnType()
{
return m_methodBuilder.ReturnType;
}
public String Signature
{
get { return m_methodBuilder.Signature; }
}
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
[System.Runtime.InteropServices.ComVisible(true)]
public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
{
m_methodBuilder.SetCustomAttribute(con, binaryAttribute);
}
public void SetCustomAttribute(CustomAttributeBuilder customBuilder)
{
m_methodBuilder.SetCustomAttribute(customBuilder);
}
public void SetImplementationFlags(MethodImplAttributes attributes)
{
m_methodBuilder.SetImplementationFlags(attributes);
}
public bool InitLocals
{
get { return m_methodBuilder.InitLocals; }
set { m_methodBuilder.InitLocals = value; }
}
#endregion
#if !FEATURE_CORECLR
void _ConstructorBuilder.GetTypeInfoCount(out uint pcTInfo)
{
throw new NotImplementedException();
}
void _ConstructorBuilder.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
{
throw new NotImplementedException();
}
void _ConstructorBuilder.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
{
throw new NotImplementedException();
}
void _ConstructorBuilder.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
{
throw new NotImplementedException();
}
#endif
}
}
| |
// 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.Threading;
interface IGen<T>
{
void Target<U>(object p);
T Dummy(T t);
}
class GenInt : IGen<int>
{
public int Dummy(int t) { return t; }
public void Target<U>(object p)
{
if (Test.Xcounter>=Test.nThreads)
{
ManualResetEvent evt = (ManualResetEvent) p;
evt.Set();
}
else
{
Interlocked.Increment(ref Test.Xcounter);
}
}
public static void ThreadPoolTest<U>()
{
ManualResetEvent evt = new ManualResetEvent(false);
IGen<int> obj = new GenInt();
TimerCallback tcb = new TimerCallback(obj.Target<U>);
Timer timer = new Timer(tcb,evt,Test.delay,Test.period);
evt.WaitOne();
timer.Dispose();
Test.Eval(Test.Xcounter>=Test.nThreads);
Test.Xcounter = 0;
}
}
class GenDouble : IGen<double>
{
public double Dummy(double t) { return t; }
public void Target<U>(object p)
{
if (Test.Xcounter>=Test.nThreads)
{
ManualResetEvent evt = (ManualResetEvent) p;
evt.Set();
}
else
{
Interlocked.Increment(ref Test.Xcounter);
}
}
public static void ThreadPoolTest<U>()
{
ManualResetEvent evt = new ManualResetEvent(false);
IGen<double> obj = new GenDouble();
TimerCallback tcb = new TimerCallback(obj.Target<U>);
Timer timer = new Timer(tcb,evt,Test.delay,Test.period);
evt.WaitOne();
timer.Dispose();
Test.Eval(Test.Xcounter>=Test.nThreads);
Test.Xcounter = 0;
}
}
class GenString : IGen<string>
{
public string Dummy(string t) { return t; }
public void Target<U>(object p)
{
if (Test.Xcounter>=Test.nThreads)
{
ManualResetEvent evt = (ManualResetEvent) p;
evt.Set();
}
else
{
Interlocked.Increment(ref Test.Xcounter);
}
}
public static void ThreadPoolTest<U>()
{
ManualResetEvent evt = new ManualResetEvent(false);
IGen<string> obj = new GenString();
TimerCallback tcb = new TimerCallback(obj.Target<U>);
Timer timer = new Timer(tcb,evt,Test.delay,Test.period);
evt.WaitOne();
timer.Dispose();
Test.Eval(Test.Xcounter>=Test.nThreads);
Test.Xcounter = 0;
}
}
class GenObject : IGen<object>
{
public object Dummy(object t) { return t; }
public void Target<U>(object p)
{
if (Test.Xcounter>=Test.nThreads)
{
ManualResetEvent evt = (ManualResetEvent) p;
evt.Set();
}
else
{
Interlocked.Increment(ref Test.Xcounter);
}
}
public static void ThreadPoolTest<U>()
{
ManualResetEvent evt = new ManualResetEvent(false);
IGen<object> obj = new GenObject();
TimerCallback tcb = new TimerCallback(obj.Target<U>);
Timer timer = new Timer(tcb,evt,Test.delay,Test.period);
evt.WaitOne();
timer.Dispose();
Test.Eval(Test.Xcounter>=Test.nThreads);
Test.Xcounter = 0;
}
}
class GenGuid : IGen<Guid>
{
public Guid Dummy(Guid t) { return t; }
public void Target<U>(object p)
{
if (Test.Xcounter>=Test.nThreads)
{
ManualResetEvent evt = (ManualResetEvent) p;
evt.Set();
}
else
{
Interlocked.Increment(ref Test.Xcounter);
}
}
public static void ThreadPoolTest<U>()
{
ManualResetEvent evt = new ManualResetEvent(false);
IGen<Guid> obj = new GenGuid();
TimerCallback tcb = new TimerCallback(obj.Target<U>);
Timer timer = new Timer(tcb,evt,Test.delay,Test.period);
evt.WaitOne();
timer.Dispose();
Test.Eval(Test.Xcounter>=Test.nThreads);
Test.Xcounter = 0;
}
}
public class Test
{
public static int delay = 0;
public static int period = 2;
public static int nThreads = 5;
public static int counter = 0;
public static int Xcounter = 0;
public static bool result = true;
public static void Eval(bool exp)
{
counter++;
if (!exp)
{
result = exp;
Console.WriteLine("Test Failed at location: " + counter);
}
}
public static int Main()
{
GenInt.ThreadPoolTest<int>();
GenDouble.ThreadPoolTest<int>();
GenString.ThreadPoolTest<int>();
GenObject.ThreadPoolTest<int>();
GenGuid.ThreadPoolTest<int>();
GenInt.ThreadPoolTest<double>();
GenDouble.ThreadPoolTest<double>();
GenString.ThreadPoolTest<double>();
GenObject.ThreadPoolTest<double>();
GenGuid.ThreadPoolTest<double>();
GenInt.ThreadPoolTest<string>();
GenDouble.ThreadPoolTest<string>();
GenString.ThreadPoolTest<string>();
GenObject.ThreadPoolTest<string>();
GenGuid.ThreadPoolTest<string>();
GenInt.ThreadPoolTest<object>();
GenDouble.ThreadPoolTest<object>();
GenString.ThreadPoolTest<object>();
GenObject.ThreadPoolTest<object>();
GenGuid.ThreadPoolTest<object>();
GenInt.ThreadPoolTest<Guid>();
GenDouble.ThreadPoolTest<Guid>();
GenString.ThreadPoolTest<Guid>();
GenObject.ThreadPoolTest<Guid>();
GenGuid.ThreadPoolTest<Guid>();
if (result)
{
Console.WriteLine("Test Passed");
return 100;
}
else
{
Console.WriteLine("Test Failed");
return 1;
}
}
}
| |
namespace Microsoft.Azure.Management.Dns
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Extension methods for RecordSetsOperations.
/// </summary>
public static partial class RecordSetsOperationsExtensions
{
/// <summary>
/// Updates a RecordSet within a DNS zone.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='zoneName'>
/// The name of the zone without a terminating dot.
/// </param>
/// <param name='relativeRecordSetName'>
/// The name of the RecordSet, relative to the name of the zone.
/// </param>
/// <param name='recordType'>
/// The type of DNS record. Possible values include: 'A', 'AAAA', 'CNAME',
/// 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT'
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Update operation.
/// </param>
/// <param name='ifMatch'>
/// The etag of Zone.
/// </param>
/// <param name='ifNoneMatch'>
/// Defines the If-None-Match condition. Set to '*' to force
/// Create-If-Not-Exist. Other values will be ignored.
/// </param>
public static RecordSet Update(this IRecordSetsOperations operations, string resourceGroupName, string zoneName, string relativeRecordSetName, RecordType recordType, RecordSet parameters, string ifMatch = default(string), string ifNoneMatch = default(string))
{
return Task.Factory.StartNew(s => ((IRecordSetsOperations)s).UpdateAsync(resourceGroupName, zoneName, relativeRecordSetName, recordType, parameters, ifMatch, ifNoneMatch), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Updates a RecordSet within a DNS zone.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='zoneName'>
/// The name of the zone without a terminating dot.
/// </param>
/// <param name='relativeRecordSetName'>
/// The name of the RecordSet, relative to the name of the zone.
/// </param>
/// <param name='recordType'>
/// The type of DNS record. Possible values include: 'A', 'AAAA', 'CNAME',
/// 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT'
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the Update operation.
/// </param>
/// <param name='ifMatch'>
/// The etag of Zone.
/// </param>
/// <param name='ifNoneMatch'>
/// Defines the If-None-Match condition. Set to '*' to force
/// Create-If-Not-Exist. Other values will be ignored.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<RecordSet> UpdateAsync(this IRecordSetsOperations operations, string resourceGroupName, string zoneName, string relativeRecordSetName, RecordType recordType, RecordSet parameters, string ifMatch = default(string), string ifNoneMatch = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.UpdateWithHttpMessagesAsync(resourceGroupName, zoneName, relativeRecordSetName, recordType, parameters, ifMatch, ifNoneMatch, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates or Updates a RecordSet within a DNS zone.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='zoneName'>
/// The name of the zone without a terminating dot.
/// </param>
/// <param name='relativeRecordSetName'>
/// The name of the RecordSet, relative to the name of the zone.
/// </param>
/// <param name='recordType'>
/// The type of DNS record. Possible values include: 'A', 'AAAA', 'CNAME',
/// 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT'
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the CreateOrUpdate operation.
/// </param>
/// <param name='ifMatch'>
/// The etag of Recordset.
/// </param>
/// <param name='ifNoneMatch'>
/// Defines the If-None-Match condition. Set to '*' to force
/// Create-If-Not-Exist. Other values will be ignored.
/// </param>
public static RecordSet CreateOrUpdate(this IRecordSetsOperations operations, string resourceGroupName, string zoneName, string relativeRecordSetName, RecordType recordType, RecordSet parameters, string ifMatch = default(string), string ifNoneMatch = default(string))
{
return Task.Factory.StartNew(s => ((IRecordSetsOperations)s).CreateOrUpdateAsync(resourceGroupName, zoneName, relativeRecordSetName, recordType, parameters, ifMatch, ifNoneMatch), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Creates or Updates a RecordSet within a DNS zone.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='zoneName'>
/// The name of the zone without a terminating dot.
/// </param>
/// <param name='relativeRecordSetName'>
/// The name of the RecordSet, relative to the name of the zone.
/// </param>
/// <param name='recordType'>
/// The type of DNS record. Possible values include: 'A', 'AAAA', 'CNAME',
/// 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT'
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the CreateOrUpdate operation.
/// </param>
/// <param name='ifMatch'>
/// The etag of Recordset.
/// </param>
/// <param name='ifNoneMatch'>
/// Defines the If-None-Match condition. Set to '*' to force
/// Create-If-Not-Exist. Other values will be ignored.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<RecordSet> CreateOrUpdateAsync(this IRecordSetsOperations operations, string resourceGroupName, string zoneName, string relativeRecordSetName, RecordType recordType, RecordSet parameters, string ifMatch = default(string), string ifNoneMatch = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, zoneName, relativeRecordSetName, recordType, parameters, ifMatch, ifNoneMatch, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Removes a RecordSet from a DNS zone.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='zoneName'>
/// The name of the zone without a terminating dot.
/// </param>
/// <param name='relativeRecordSetName'>
/// The name of the RecordSet, relative to the name of the zone.
/// </param>
/// <param name='recordType'>
/// The type of DNS record. Possible values include: 'A', 'AAAA', 'CNAME',
/// 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT'
/// </param>
/// <param name='ifMatch'>
/// Defines the If-Match condition. The delete operation will be performed
/// only if the ETag of the zone on the server matches this value.
/// </param>
/// <param name='ifNoneMatch'>
/// Defines the If-None-Match condition. The delete operation will be
/// performed only if the ETag of the zone on the server does not match this
/// value.
/// </param>
public static void Delete(this IRecordSetsOperations operations, string resourceGroupName, string zoneName, string relativeRecordSetName, RecordType recordType, string ifMatch = default(string), string ifNoneMatch = default(string))
{
Task.Factory.StartNew(s => ((IRecordSetsOperations)s).DeleteAsync(resourceGroupName, zoneName, relativeRecordSetName, recordType, ifMatch, ifNoneMatch), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Removes a RecordSet from a DNS zone.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='zoneName'>
/// The name of the zone without a terminating dot.
/// </param>
/// <param name='relativeRecordSetName'>
/// The name of the RecordSet, relative to the name of the zone.
/// </param>
/// <param name='recordType'>
/// The type of DNS record. Possible values include: 'A', 'AAAA', 'CNAME',
/// 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT'
/// </param>
/// <param name='ifMatch'>
/// Defines the If-Match condition. The delete operation will be performed
/// only if the ETag of the zone on the server matches this value.
/// </param>
/// <param name='ifNoneMatch'>
/// Defines the If-None-Match condition. The delete operation will be
/// performed only if the ETag of the zone on the server does not match this
/// value.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this IRecordSetsOperations operations, string resourceGroupName, string zoneName, string relativeRecordSetName, RecordType recordType, string ifMatch = default(string), string ifNoneMatch = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
await operations.DeleteWithHttpMessagesAsync(resourceGroupName, zoneName, relativeRecordSetName, recordType, ifMatch, ifNoneMatch, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets a RecordSet.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='zoneName'>
/// The name of the zone without a terminating dot.
/// </param>
/// <param name='relativeRecordSetName'>
/// The name of the RecordSet, relative to the name of the zone.
/// </param>
/// <param name='recordType'>
/// The type of DNS record. Possible values include: 'A', 'AAAA', 'CNAME',
/// 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT'
/// </param>
public static RecordSet Get(this IRecordSetsOperations operations, string resourceGroupName, string zoneName, string relativeRecordSetName, RecordType recordType)
{
return Task.Factory.StartNew(s => ((IRecordSetsOperations)s).GetAsync(resourceGroupName, zoneName, relativeRecordSetName, recordType), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets a RecordSet.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='zoneName'>
/// The name of the zone without a terminating dot.
/// </param>
/// <param name='relativeRecordSetName'>
/// The name of the RecordSet, relative to the name of the zone.
/// </param>
/// <param name='recordType'>
/// The type of DNS record. Possible values include: 'A', 'AAAA', 'CNAME',
/// 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT'
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<RecordSet> GetAsync(this IRecordSetsOperations operations, string resourceGroupName, string zoneName, string relativeRecordSetName, RecordType recordType, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, zoneName, relativeRecordSetName, recordType, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists the RecordSets of a specified type in a DNS zone.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the zone.
/// </param>
/// <param name='zoneName'>
/// The name of the zone from which to enumerate RecordsSets.
/// </param>
/// <param name='recordType'>
/// The type of record sets to enumerate. Possible values include: 'A',
/// 'AAAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT'
/// </param>
/// <param name='top'>
/// Query parameters. If null is passed returns the default number of zones.
/// </param>
public static IPage<RecordSet> ListByType(this IRecordSetsOperations operations, string resourceGroupName, string zoneName, RecordType recordType, string top = default(string))
{
return Task.Factory.StartNew(s => ((IRecordSetsOperations)s).ListByTypeAsync(resourceGroupName, zoneName, recordType, top), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Lists the RecordSets of a specified type in a DNS zone.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the zone.
/// </param>
/// <param name='zoneName'>
/// The name of the zone from which to enumerate RecordsSets.
/// </param>
/// <param name='recordType'>
/// The type of record sets to enumerate. Possible values include: 'A',
/// 'AAAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT'
/// </param>
/// <param name='top'>
/// Query parameters. If null is passed returns the default number of zones.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<RecordSet>> ListByTypeAsync(this IRecordSetsOperations operations, string resourceGroupName, string zoneName, RecordType recordType, string top = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByTypeWithHttpMessagesAsync(resourceGroupName, zoneName, recordType, top, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists all RecordSets in a DNS zone.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the zone.
/// </param>
/// <param name='zoneName'>
/// The name of the zone from which to enumerate RecordSets.
/// </param>
/// <param name='top'>
/// Query parameters. If null is passed returns the default number of zones.
/// </param>
public static IPage<RecordSet> ListAllInResourceGroup(this IRecordSetsOperations operations, string resourceGroupName, string zoneName, string top = default(string))
{
return Task.Factory.StartNew(s => ((IRecordSetsOperations)s).ListAllInResourceGroupAsync(resourceGroupName, zoneName, top), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Lists all RecordSets in a DNS zone.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the zone.
/// </param>
/// <param name='zoneName'>
/// The name of the zone from which to enumerate RecordSets.
/// </param>
/// <param name='top'>
/// Query parameters. If null is passed returns the default number of zones.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<RecordSet>> ListAllInResourceGroupAsync(this IRecordSetsOperations operations, string resourceGroupName, string zoneName, string top = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListAllInResourceGroupWithHttpMessagesAsync(resourceGroupName, zoneName, top, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists the RecordSets of a specified type in a DNS zone.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<RecordSet> ListByTypeNext(this IRecordSetsOperations operations, string nextPageLink)
{
return Task.Factory.StartNew(s => ((IRecordSetsOperations)s).ListByTypeNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Lists the RecordSets of a specified type in a DNS zone.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<RecordSet>> ListByTypeNextAsync(this IRecordSetsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByTypeNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists all RecordSets in a DNS zone.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<RecordSet> ListAllInResourceGroupNext(this IRecordSetsOperations operations, string nextPageLink)
{
return Task.Factory.StartNew(s => ((IRecordSetsOperations)s).ListAllInResourceGroupNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Lists all RecordSets in a DNS zone.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<RecordSet>> ListAllInResourceGroupNextAsync(this IRecordSetsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListAllInResourceGroupNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Linq;
using System.Reactive.Disposables;
using System.Threading.Tasks;
using FluentAssertions;
using Microsoft.Its.Domain.Serialization;
using Microsoft.Its.Domain.Testing;
using Microsoft.Its.Recipes;
using NUnit.Framework;
using Sample.Domain;
using Sample.Domain.Ordering;
using Sample.Domain.Ordering.Commands;
namespace Microsoft.Its.Domain.Tests
{
[TestFixture]
public abstract class EventSourcedRepositoryTests
{
private CompositeDisposable disposables;
protected abstract void Configure(Configuration configuration, Action onSave = null);
protected abstract IEventSourcedRepository<TAggregate> CreateRepository<TAggregate>(
Action onSave = null)
where TAggregate : class, IEventSourced;
[SetUp]
public virtual void SetUp()
{
// disable authorization checks
Command<Order>.AuthorizeDefault = (order, command) => true;
Command<CustomerAccount>.AuthorizeDefault = (order, command) => true;
var configuration = new Configuration();
Configure(configuration);
disposables = new CompositeDisposable
{
ConfigurationContext.Establish(configuration),
configuration
};
}
[TearDown]
public virtual void TearDown()
{
Clock.Reset();
disposables.Dispose();
}
[Test]
public async Task Serialized_events_are_deserialized_in_their_correct_sequence_and_type()
{
var order = new Order();
var repository = CreateRepository<Order>();
order
.Apply(new AddItem
{
ProductName = "Widget",
Price = 10m,
Quantity = 1
})
.Apply(new ChangeFufillmentMethod { FulfillmentMethod = FulfillmentMethod.DirectShip });
await repository.Save(order);
var rehydratedOrder = await repository.GetLatest(order.Id);
rehydratedOrder.EventHistory.Count().Should().Be(3);
rehydratedOrder.EventHistory.Skip(1).First().Should().BeOfType<Order.ItemAdded>();
rehydratedOrder.EventHistory.Last().Should().BeOfType<Order.FulfillmentMethodSelected>();
}
[Test]
public async Task When_an_aggregate_id_is_not_found_then_GetLatest_returns_null()
{
var aggregate = await CreateRepository<Order>().GetLatest(Any.Guid());
aggregate.Should().BeNull();
}
[Test]
public async Task GetVersion_does_not_pull_versions_after_the_specified_one()
{
var order = new Order();
var repository = CreateRepository<Order>();
Enumerable.Range(1, 10).ForEach(i => order.Apply(new AddItem
{
ProductName = "Widget",
Price = 10m,
Quantity = i
}));
await repository.Save(order);
var rehydratedOrder = await repository.GetVersion(order.Id, 4);
rehydratedOrder.Version().Should().Be(4);
rehydratedOrder.EventHistory.Count().Should().Be(4);
rehydratedOrder.Items.First().Quantity.Should().Be(6);
}
[Test]
public async Task GetAsOfDate_does_not_pull_events_after_the_specified_date()
{
var order = new Order();
var repository = CreateRepository<Order>();
var startTime = DateTimeOffset.UtcNow;
Enumerable.Range(1, 10).ForEach(i =>
{
Clock.Now = () => startTime.AddDays(i);
order.Apply(new AddItem
{
ProductName = "Widget",
Price = 10m,
Quantity = i
});
});
await repository.Save(order);
var rehydratedOrder = await repository.GetAsOfDate(order.Id, startTime.AddDays(3.1));
rehydratedOrder.Version().Should().Be(4);
rehydratedOrder.EventHistory.Count().Should().Be(4);
rehydratedOrder.Items.First().Quantity.Should().Be(6);
}
[Test]
public async Task Deserialized_events_are_used_to_rebuild_the_state_of_the_aggregate()
{
var order = new Order();
var repository = CreateRepository<Order>();
order
.Apply(new AddItem
{
ProductName = "Widget",
Price = 10m,
Quantity = 2
})
.Apply(new AddItem
{
ProductName = "Widget",
Price = 10m,
Quantity = 3
});
await repository.Save(order);
var rehydratedOrder = await repository.GetLatest(order.Id);
rehydratedOrder.Items.Single().Quantity.Should().Be(5);
}
[Test]
public async Task When_Save_is_called_then_each_added_event_is_published()
{
var order = new Order();
var repository = CreateRepository<Order>();
order
.Apply(new AddItem
{
ProductName = "Widget",
Price = 10m,
Quantity = 2
})
.Apply(new ChangeFufillmentMethod
{
FulfillmentMethod = FulfillmentMethod.Delivery
});
await repository.Save(order);
var bus = (FakeEventBus) Configuration.Current.EventBus;
bus.PublishedEvents().Count()
.Should().Be(3);
bus.PublishedEvents().Skip(1).First()
.Should().BeOfType<Order.ItemAdded>();
bus.PublishedEvents().Skip(1).Skip(1).First()
.Should().BeOfType<Order.FulfillmentMethodSelected>();
}
[Test]
public async Task When_Save_is_called_then_published_events_have_incrementing_sequence_ids()
{
// set up the repository so we're not starting from the beginning
var order = new Order();
var bus = (FakeEventBus) Configuration.Current.EventBus;
var repository = CreateRepository<Order>();
order.Apply(new AddItem
{
ProductName = "Widget",
Price = 10m,
Quantity = 2
});
await repository.Save(order);
bus.Clear();
// apply 2 commands
var order2 = await repository.GetLatest(order.Id);
order2
.Apply(new ChangeFufillmentMethod { FulfillmentMethod = FulfillmentMethod.Delivery })
.Apply(new ChangeCustomerInfo { CustomerName = "Wanda" });
await repository.Save(order2);
bus.PublishedEvents().Count().Should().Be(2);
bus.PublishedEvents().First().SequenceNumber.Should().Be(3);
bus.PublishedEvents().Skip(1).First().SequenceNumber.Should().Be(4);
}
[Test]
public abstract Task When_storage_fails_then_no_events_are_published();
[Test]
public async Task Concurrency_on_event_storage_is_optimistic_and_exceptions_have_informative_messages()
{
var repository = CreateRepository<Order>();
var order = new Order()
.Apply(new AddItem
{
Price = .05m,
ProductName = "widget",
Quantity = 100
})
.Apply(new ChangeCustomerInfo
{
CustomerName = "Wanda"
});
await repository.Save(order);
var order2 = (await repository.GetLatest(order.Id))
.Apply(new ChangeCustomerInfo
{
CustomerName = "Alice"
});
var order3 = (await repository.GetLatest(order.Id))
.Apply(new ChangeCustomerInfo
{
CustomerName = "Bob"
});
await repository.Save(order2);
repository.Invoking(r => r.Save(order3).Wait())
.ShouldThrow<ConcurrencyException>()
.And
.Message
.Should()
.Contain("Alice")
.And
.Contain("Bob")
.And
.Contain("Sample.Domain.Ordering.Order+CustomerInfoChanged");
}
[Test]
public abstract Task Events_that_cannot_be_deserialized_due_to_unknown_type_do_not_cause_sourcing_to_fail();
[Test]
public abstract Task Events_at_the_end_of_the_sequence_that_cannot_be_deserialized_due_to_unknown_type_do_not_cause_Version_to_be_incorrect();
[Test]
public abstract Task Events_that_cannot_be_deserialized_due_to_unknown_member_do_not_cause_sourcing_to_fail();
protected abstract Task SaveEventsDirectly(params IStoredEvent[] events);
[Test]
public async Task Save_transfers_pending_events_to_event_history()
{
var order = new Order();
var repository = CreateRepository<Order>();
order.Apply(new AddItem { Price = 1m, ProductName = "Widget" });
await repository.Save(order);
order.EventHistory.Count().Should().Be(2);
}
[Test]
public async Task After_Save_additional_events_continue_in_the_correct_sequence()
{
var order = new Order();
var bus = (FakeEventBus) Configuration.Current.EventBus;
var repository = CreateRepository<Order>();
var addEvent = new Action(() =>
order.Apply(new AddItem { Price = 1m, ProductName = "Widget" }));
addEvent();
await repository.Save(order);
bus.PublishedEvents().Last().SequenceNumber.Should().Be(2);
addEvent();
addEvent();
await repository.Save(order);
bus.PublishedEvents().Last().SequenceNumber.Should().Be(4);
addEvent();
addEvent();
addEvent();
await repository.Save(order);
bus.PublishedEvents().Last().SequenceNumber.Should().Be(7);
}
[Test]
public async Task Refresh_can_be_used_to_update_an_aggregate_in_memory_with_the_latest_events_from_the_stream()
{
// arrange
var order = new Order()
.Apply(new ChangeCustomerInfo
{
CustomerName = Any.FullName()
});
var repository = CreateRepository<Order>();
await repository.Save(order);
await repository.Save(
(await repository.GetLatest(order.Id))
.Apply(new AddItem
{
Price = 1,
ProductName = Any.Word()
}).Apply(new AddItem
{
Price = 2,
ProductName = Any.Word()
}));
// act
await repository.Refresh(order);
// assert
order.Version().Should().Be(4);
}
[Test]
public async Task After_Refresh_is_called_then_future_events_are_added_at_the_correct_sequence_number()
{
// arrange
var order = new Order()
.Apply(new ChangeCustomerInfo
{
CustomerName = Any.FullName()
});
var repository = CreateRepository<Order>();
await repository.Save(order);
await repository.Save(
(await repository.GetLatest(order.Id))
.Apply(new AddItem
{
Price = 1,
ProductName = Any.Word()
}).Apply(new AddItem
{
Price = 2,
ProductName = Any.Word()
}));
await repository.Refresh(order);
// act
order.Apply(new Cancel());
Console.WriteLine(order.Events().ToJson());
// assert
order.Version().Should().Be(5);
order.PendingEvents.Last().SequenceNumber.Should().Be(5);
}
[Test]
public void When_Refresh_is_called_on_an_aggregate_having_pending_events_it_throws()
{
var order = new Order()
.Apply(new ChangeCustomerInfo
{
CustomerName = Any.FullName()
});
var repository = CreateRepository<Order>();
// act
Action refresh = () => repository.Refresh(order).Wait();
// assert
refresh.ShouldThrow<InvalidOperationException>()
.And
.Message
.Should()
.Contain("Aggregates having pending events cannot be updated.");
}
[Test]
public async Task GetAggregate_can_be_used_within_a_consequenter_to_access_an_aggregate_without_having_to_re_source()
{
// arrange
var order = new Order()
.Apply(new ChangeCustomerInfo
{
CustomerName = Any.FullName()
})
.Apply(new AddItem
{
ProductName = "Cog",
Price = 9.99m
})
.Apply(new AddItem
{
ProductName = "Sprocket",
Price = 9.99m
})
.Apply(new ProvideCreditCardInfo
{
CreditCardNumber = Any.String(16, 16, Characters.Digits),
CreditCardCvv2 = "123",
CreditCardExpirationMonth = "12",
CreditCardName = Any.FullName(),
CreditCardExpirationYear = "16"
})
.Apply(new SpecifyShippingInfo())
.Apply(new Place());
var repository = CreateRepository<Order>();
Configuration.Current.UseDependency<IEventSourcedRepository<Order>>(t =>
{
throw new Exception("GetAggregate should not be triggering this call.");
});
Order aggregate = null;
#pragma warning disable 612
var consquenter = Consequenter.Create<Order.Placed>(e => { aggregate = e.GetAggregate(); });
#pragma warning restore 612
var bus = Configuration.Current.EventBus as FakeEventBus;
bus.Subscribe(consquenter);
// act
await repository.Save(order);
// assert
aggregate.Should().Be(order);
}
[Test]
public async Task GetAggregate_can_be_used_when_no_aggregate_was_previously_sourced()
{
var order = new Order()
.Apply(new ChangeCustomerInfo
{
CustomerName = Any.FullName()
});
var repository = CreateRepository<Order>();
await repository.Save(order);
Order aggregate = null;
var consquenter = Consequenter.Create<Order.Placed>(e =>
{
#pragma warning disable 612
aggregate = e.GetAggregate();
#pragma warning restore 612
});
consquenter.HaveConsequences(new Order.Placed
{
AggregateId = order.Id
});
aggregate.Id.Should().Be(order.Id);
}
[Test]
public async Task GetLatest_can_return_an_aggregate_built_from_a_snapshot_projection()
{
// arrange
var snapshotRepository = new InMemorySnapshotRepository();
Configuration.Current.UseDependency<ISnapshotRepository>(_ => snapshotRepository);
var snapshot = new CustomerAccountSnapshot
{
AggregateId = Any.Guid(),
Version = 123,
AggregateTypeName = AggregateType<CustomerAccount>.EventStreamName,
EmailAddress = Any.Email(),
NoSpam = true,
UserName = Any.FullName(),
ETags = new[] { Any.Word(), Any.Word() }
};
await snapshotRepository.SaveSnapshot(snapshot);
// act
var account = await CreateRepository<CustomerAccount>().GetLatest(snapshot.AggregateId);
// assert
account.Id.Should().Be(snapshot.AggregateId);
account.Version.Should().Be(snapshot.Version);
account.EmailAddress.Should().Be(snapshot.EmailAddress);
account.UserName.Should().Be(snapshot.UserName);
account.NoSpam.Should().Be(snapshot.NoSpam);
foreach (var etag in snapshot.ETags)
{
account.HasETag(etag).Should().BeTrue("etags are expected to be loaded from the snapshot");
}
}
[Test]
public async Task When_new_events_are_added_to_an_aggregate_sourced_from_a_fully_current_snapshot_the_version_increments_correctly()
{
// arrange
var snapshotRepository = new InMemorySnapshotRepository();
Configuration.Current.UseDependency<ISnapshotRepository>(_ => snapshotRepository);
var snapshot = new CustomerAccountSnapshot
{
AggregateId = Any.Guid(),
Version = 123,
AggregateTypeName = AggregateType<CustomerAccount>.EventStreamName,
EmailAddress = Any.Email(),
NoSpam = true,
UserName = Any.FullName(),
ETags = new[] { Any.Word(), Any.Word() }
};
await snapshotRepository.SaveSnapshot(snapshot);
// act
var account = await CreateRepository<CustomerAccount>().GetLatest(snapshot.AggregateId);
account.Apply(new RequestSpam());
// assert
account.Version.Should().Be(124);
}
[Test]
public async Task When_new_events_are_added_to_an_aggregate_sourced_from_a_stale_snapshot_the_version_increments_correctly()
{
// arrange
var snapshotRepository = new InMemorySnapshotRepository();
Configuration.Current.UseDependency<ISnapshotRepository>(_ => snapshotRepository);
var snapshot = new CustomerAccountSnapshot
{
AggregateId = Any.Guid(),
Version = 122,
AggregateTypeName = AggregateType<CustomerAccount>.EventStreamName,
EmailAddress = Any.Email(),
NoSpam = true,
UserName = Any.FullName(),
ETags = new[] { Any.Word(), Any.Word() }
};
await snapshotRepository.SaveSnapshot(snapshot);
await SaveEventsDirectly(new CustomerAccount.RequestedSpam
{
AggregateId = snapshot.AggregateId,
SequenceNumber = snapshot.Version + 1
}.ToStoredEvent());
// act
var account = await CreateRepository<CustomerAccount>().GetLatest(snapshot.AggregateId);
account.Apply(new RequestSpam());
// assert
account.Version.Should().Be(124);
}
[Test]
public async Task When_a_snapshot_is_not_up_to_date_then_GetLatest_retrieves_later_events_and_applies_them()
{
// arrange
var snapshotRepository = new InMemorySnapshotRepository();
Configuration.Current.UseDependency<ISnapshotRepository>(_ => snapshotRepository);
var snapshot = new CustomerAccountSnapshot
{
AggregateId = Any.Guid(),
Version = 123,
AggregateTypeName = AggregateType<CustomerAccount>.EventStreamName,
EmailAddress = Any.Email(),
NoSpam = true,
UserName = Any.FullName(),
ETags = new[] { Any.Word(), Any.Word() }
};
await snapshotRepository.SaveSnapshot(snapshot);
await SaveEventsDirectly(new CustomerAccount.RequestedSpam
{
AggregateId = snapshot.AggregateId,
SequenceNumber = 124
}.ToStoredEvent());
// act
var account = await CreateRepository<CustomerAccount>().GetLatest(snapshot.AggregateId);
// assert
account.Version.Should().Be(124);
account.NoSpam.Should().Be(false);
}
[Test]
public async Task Scheduled_Events_that_cannot_be_deserialized_due_to_unknown_command_do_not_cause_sourcing_to_fail()
{
var orderId = Guid.NewGuid();
var goodEvent = new Order.CustomerInfoChanged
{
CustomerName = "Waylon Jennings",
AggregateId = orderId,
SequenceNumber = 1
}.ToStoredEvent();
var badEvent = CreateStoredEvent(
streamName : goodEvent.StreamName,
type : "Scheduled:UNKNOWNCOMMAND",
aggregateId : Guid.Parse(goodEvent.AggregateId),
sequenceNumber : 2,
body : new
{
Command = new
{
CommandName = "UNKNOWNCOMMAND"
}
}.ToJson(),
utcTime : DateTime.UtcNow);
await SaveEventsDirectly(goodEvent, badEvent);
var repository = CreateRepository<Order>();
var order = await repository.GetLatest(orderId);
order.CustomerName.Should().Be("Waylon Jennings");
}
protected abstract IStoredEvent CreateStoredEvent(
string streamName,
string type,
Guid aggregateId,
int sequenceNumber,
string body,
DateTime utcTime);
[Ignore("Scenario under consideration")]
[Test]
public async Task Snapshotting_can_be_bypassed()
{
var snapshotRepository = new InMemorySnapshotRepository();
Configuration.Current.UseDependency<ISnapshotRepository>(_ => snapshotRepository);
var account = new CustomerAccount()
.Apply(new ChangeEmailAddress(Any.Email()))
.Apply(new RequestSpam())
.Apply(new SendMarketingEmail())
.Apply(new SendOrderConfirmationEmail(Any.AlphanumericString(8, 8)));
var eventSourcedRepository = CreateRepository<CustomerAccount>();
await eventSourcedRepository.Save(account);
await snapshotRepository.SaveSnapshot(account);
// act
account = await eventSourcedRepository.GetLatest(account.Id);
// assert
account.Events().Count()
.Should()
.Be(4);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.Security;
using Newtonsoft.Json;
using Umbraco.Core.Configuration;
using Umbraco.Core.Logging;
using Umbraco.Core.Models.EntityBase;
using Umbraco.Core.Models.Membership;
using Umbraco.Core.Models.Rdbms;
using Umbraco.Core.Persistence.DatabaseModelDefinitions;
using Umbraco.Core.Persistence.Factories;
using Umbraco.Core.Persistence.Mappers;
using Umbraco.Core.Persistence.Querying;
using Umbraco.Core.Persistence.Relators;
using Umbraco.Core.Persistence.SqlSyntax;
using Umbraco.Core.Persistence.UnitOfWork;
using Umbraco.Core.Security;
namespace Umbraco.Core.Persistence.Repositories
{
/// <summary>
/// Represents the UserRepository for doing CRUD operations for <see cref="IUser"/>
/// </summary>
internal class UserRepository : PetaPocoRepositoryBase<int, IUser>, IUserRepository
{
private readonly IDictionary<string, string> _passwordConfiguration;
/// <summary>
/// Constructor
/// </summary>
/// <param name="work"></param>
/// <param name="cacheHelper"></param>
/// <param name="logger"></param>
/// <param name="sqlSyntax"></param>
/// <param name="passwordConfiguration">
/// A dictionary specifying the configuration for user passwords. If this is null then no password configuration will be persisted or read.
/// </param>
public UserRepository(IScopeUnitOfWork work, CacheHelper cacheHelper, ILogger logger, ISqlSyntaxProvider sqlSyntax,
IDictionary<string, string> passwordConfiguration = null)
: base(work, cacheHelper, logger, sqlSyntax)
{
_passwordConfiguration = passwordConfiguration;
}
#region Overrides of RepositoryBase<int,IUser>
protected override IUser PerformGet(int id)
{
var sql = GetQueryWithGroups();
sql.Where(GetBaseWhereClause(), new { Id = id });
sql //must be included for relator to work
.OrderBy<UserDto>(d => d.Id, SqlSyntax)
.OrderBy<UserGroupDto>(d => d.Id, SqlSyntax)
.OrderBy<UserStartNodeDto>(d => d.Id, SqlSyntax);
var dto = Database.Fetch<UserDto, UserGroupDto, UserGroup2AppDto, UserStartNodeDto, UserDto>(new UserGroupRelator().Map, sql)
.FirstOrDefault();
if (dto == null)
return null;
var user = UserFactory.BuildEntity(dto);
return user;
}
/// <summary>
/// Returns a user by username
/// </summary>
/// <param name="username"></param>
/// <param name="includeSecurityData">
/// Can be used for slightly faster user lookups if the result doesn't require security data (i.e. groups, apps & start nodes).
/// This is really only used for a shim in order to upgrade to 7.6.
/// </param>
/// <returns>
/// A non cached <see cref="IUser"/> instance
/// </returns>
public IUser GetByUsername(string username, bool includeSecurityData)
{
UserDto dto;
if (includeSecurityData)
{
var sql = GetQueryWithGroups();
sql.Where<UserDto>(userDto => userDto.Login == username, SqlSyntax);
sql //must be included for relator to work
.OrderBy<UserDto>(d => d.Id, SqlSyntax)
.OrderBy<UserGroupDto>(d => d.Id, SqlSyntax)
.OrderBy<UserStartNodeDto>(d => d.Id, SqlSyntax);
dto = Database
.Fetch<UserDto, UserGroupDto, UserGroup2AppDto, UserStartNodeDto, UserDto>(
new UserGroupRelator().Map, sql)
.FirstOrDefault();
}
else
{
var sql = GetBaseQuery("umbracoUser.*");
sql.Where<UserDto>(userDto => userDto.Login == username, SqlSyntax);
dto = Database.FirstOrDefault<UserDto>(sql);
}
if (dto == null)
return null;
var user = UserFactory.BuildEntity(dto);
return user;
}
/// <summary>
/// Returns a user by id
/// </summary>
/// <param name="id"></param>
/// <param name="includeSecurityData">
/// This is really only used for a shim in order to upgrade to 7.6 but could be used
/// for slightly faster user lookups if the result doesn't require security data (i.e. groups, apps & start nodes)
/// </param>
/// <returns>
/// A non cached <see cref="IUser"/> instance
/// </returns>
public IUser Get(int id, bool includeSecurityData)
{
UserDto dto;
if (includeSecurityData)
{
var sql = GetQueryWithGroups();
sql.Where(GetBaseWhereClause(), new { Id = id });
sql //must be included for relator to work
.OrderBy<UserDto>(d => d.Id, SqlSyntax)
.OrderBy<UserGroupDto>(d => d.Id, SqlSyntax)
.OrderBy<UserStartNodeDto>(d => d.Id, SqlSyntax);
dto = Database
.Fetch<UserDto, UserGroupDto, UserGroup2AppDto, UserStartNodeDto, UserDto>(
new UserGroupRelator().Map, sql)
.FirstOrDefault();
}
else
{
var sql = GetBaseQuery("umbracoUser.*");
sql.Where(GetBaseWhereClause(), new { Id = id });
dto = Database.FirstOrDefault<UserDto>(sql);
}
if (dto == null)
return null;
var user = UserFactory.BuildEntity(dto);
return user;
}
public IProfile GetProfile(string username)
{
var sql = GetBaseQuery(false).Where<UserDto>(userDto => userDto.Login == username, SqlSyntax);
var dto = Database.Fetch<UserDto>(sql)
.FirstOrDefault();
if (dto == null)
return null;
return new UserProfile(dto.Id, dto.UserName);
}
public IProfile GetProfile(int id)
{
var sql = GetBaseQuery(false).Where<UserDto>(userDto => userDto.Id == id, SqlSyntax);
var dto = Database.Fetch<UserDto>(sql)
.FirstOrDefault();
if (dto == null)
return null;
return new UserProfile(dto.Id, dto.UserName);
}
public IDictionary<UserState, int> GetUserStates()
{
var sql = @"SELECT '1CountOfAll' AS colName, COUNT(id) AS num FROM umbracoUser
UNION
SELECT '2CountOfActive' AS colName, COUNT(id) AS num FROM umbracoUser WHERE userDisabled = 0 AND userNoConsole = 0 AND lastLoginDate IS NOT NULL
UNION
SELECT '3CountOfDisabled' AS colName, COUNT(id) AS num FROM umbracoUser WHERE userDisabled = 1
UNION
SELECT '4CountOfLockedOut' AS colName, COUNT(id) AS num FROM umbracoUser WHERE userNoConsole = 1
UNION
SELECT '5CountOfInvited' AS colName, COUNT(id) AS num FROM umbracoUser WHERE lastLoginDate IS NULL AND userDisabled = 1 AND invitedDate IS NOT NULL
UNION
SELECT '6CountOfDisabled' AS colName, COUNT(id) AS num FROM umbracoUser WHERE userDisabled = 0 AND userNoConsole = 0 AND lastLoginDate IS NULL
ORDER BY colName";
var result = Database.Fetch<dynamic>(sql);
return new Dictionary<UserState, int>
{
{UserState.All, (int)result[0].num},
{UserState.Active, (int)result[1].num},
{UserState.Disabled, (int)result[2].num},
{UserState.LockedOut, (int)result[3].num},
{UserState.Invited, (int)result[4].num},
{UserState.Inactive, (int) result[5].num}
};
}
public Guid CreateLoginSession(int userId, string requestingIpAddress, bool cleanStaleSessions = true)
{
//TODO: I know this doesn't follow the normal repository conventions which would require us to crete a UserSessionRepository
//and also business logic models for these objects but that's just so overkill for what we are doing
//and now that everything is properly in a transaction (Scope) there doesn't seem to be much reason for using that anymore
var now = DateTime.UtcNow;
var dto = new UserLoginDto
{
UserId = userId,
IpAddress = requestingIpAddress,
LoggedInUtc = now,
LastValidatedUtc = now,
LoggedOutUtc = null,
SessionId = Guid.NewGuid()
};
Database.Insert(dto);
if (cleanStaleSessions)
{
ClearLoginSessions(TimeSpan.FromDays(15));
}
return dto.SessionId;
}
public bool ValidateLoginSession(int userId, Guid sessionId)
{
var found = Database.FirstOrDefault<UserLoginDto>("WHERE sessionId=@sessionId", new {sessionId = sessionId});
if (found == null || found.UserId != userId || found.LoggedOutUtc.HasValue)
return false;
//now detect if there's been a timeout
if (DateTime.UtcNow - found.LastValidatedUtc > TimeSpan.FromMinutes(GlobalSettings.TimeOutInMinutes))
{
//timeout detected, update the record
ClearLoginSession(sessionId);
return false;
}
//update the validate date
found.LastValidatedUtc = DateTime.UtcNow;
Database.Update(found);
return true;
}
public int ClearLoginSessions(int userId)
{
//TODO: I know this doesn't follow the normal repository conventions which would require us to crete a UserSessionRepository
//and also business logic models for these objects but that's just so overkill for what we are doing
//and now that everything is properly in a transaction (Scope) there doesn't seem to be much reason for using that anymore
var count = Database.ExecuteScalar<int>("SELECT COUNT(*) FROM umbracoUserLogin WHERE userId=@userId", new { userId = userId });
Database.Execute("DELETE FROM umbracoUserLogin WHERE userId=@userId", new {userId = userId});
return count;
}
public int ClearLoginSessions(TimeSpan timespan)
{
//TODO: I know this doesn't follow the normal repository conventions which would require us to crete a UserSessionRepository
//and also business logic models for these objects but that's just so overkill for what we are doing
//and now that everything is properly in a transaction (Scope) there doesn't seem to be much reason for using that anymore
var fromDate = DateTime.UtcNow - timespan;
var count = Database.ExecuteScalar<int>("SELECT COUNT(*) FROM umbracoUserLogin WHERE lastValidatedUtc=@fromDate", new { fromDate = fromDate });
Database.Execute("DELETE FROM umbracoUserLogin WHERE lastValidatedUtc=@fromDate", new { fromDate = fromDate });
return count;
}
public void ClearLoginSession(Guid sessionId)
{
//TODO: I know this doesn't follow the normal repository conventions which would require us to crete a UserSessionRepository
//and also business logic models for these objects but that's just so overkill for what we are doing
//and now that everything is properly in a transaction (Scope) there doesn't seem to be much reason for using that anymore
Database.Execute("UPDATE umbracoUserLogin SET loggedOutUtc=@now WHERE sessionId=@sessionId",
new { now = DateTime.UtcNow, sessionId = sessionId });
}
protected override IEnumerable<IUser> PerformGetAll(params int[] ids)
{
var sql = GetQueryWithGroups();
if (ids.Any())
{
sql.Where("umbracoUser.id in (@ids)", new { ids = ids });
}
sql //must be included for relator to work
.OrderBy<UserDto>(d => d.Id, SqlSyntax)
.OrderBy<UserGroupDto>(d => d.Id, SqlSyntax)
.OrderBy<UserStartNodeDto>(d => d.Id, SqlSyntax);
var users = ConvertFromDtos(Database.Fetch<UserDto, UserGroupDto, UserGroup2AppDto, UserStartNodeDto, UserDto>(new UserGroupRelator().Map, sql))
.ToArray(); // important so we don't iterate twice, if we don't do this we can end up with null values in cache if we were caching.
return users;
}
protected override IEnumerable<IUser> PerformGetByQuery(IQuery<IUser> query)
{
var sqlClause = GetQueryWithGroups();
var translator = new SqlTranslator<IUser>(sqlClause, query);
var sql = translator.Translate();
sql //must be included for relator to work
.OrderBy<UserDto>(d => d.Id, SqlSyntax)
.OrderBy<UserGroupDto>(d => d.Id, SqlSyntax)
.OrderBy<UserStartNodeDto>(d => d.Id, SqlSyntax);
var dtos = Database.Fetch<UserDto, UserGroupDto, UserGroup2AppDto, UserStartNodeDto, UserDto>(new UserGroupRelator().Map, sql)
.DistinctBy(x => x.Id);
var users = ConvertFromDtos(dtos)
.ToArray(); // important so we don't iterate twice, if we don't do this we can end up with null values in cache if we were caching.
return users;
}
#endregion
#region Overrides of PetaPocoRepositoryBase<int,IUser>
protected override Sql GetBaseQuery(bool isCount)
{
var sql = new Sql();
if (isCount)
{
sql.Select("COUNT(*)").From<UserDto>();
}
else
{
return GetBaseQuery("*");
}
return sql;
}
/// <summary>
/// A query to return a user with it's groups and with it's groups sections
/// </summary>
/// <returns></returns>
private Sql GetQueryWithGroups()
{
//base query includes user groups
var sql = GetBaseQuery("umbracoUser.*, umbracoUserGroup.*, umbracoUserGroup2App.*, umbracoUserStartNode.*");
AddGroupLeftJoin(sql);
return sql;
}
private void AddGroupLeftJoin(Sql sql)
{
sql.LeftJoin<User2UserGroupDto>(SqlSyntax)
.On<User2UserGroupDto, UserDto>(SqlSyntax, dto => dto.UserId, dto => dto.Id)
.LeftJoin<UserGroupDto>(SqlSyntax)
.On<UserGroupDto, User2UserGroupDto>(SqlSyntax, dto => dto.Id, dto => dto.UserGroupId)
.LeftJoin<UserGroup2AppDto>(SqlSyntax)
.On<UserGroup2AppDto, UserGroupDto>(SqlSyntax, dto => dto.UserGroupId, dto => dto.Id)
.LeftJoin<UserStartNodeDto>(SqlSyntax)
.On<UserStartNodeDto, UserDto>(SqlSyntax, dto => dto.UserId, dto => dto.Id);
}
private Sql GetBaseQuery(string columns)
{
var sql = new Sql();
sql.Select(columns)
.From<UserDto>();
return sql;
}
protected override string GetBaseWhereClause()
{
return "umbracoUser.id = @Id";
}
protected override IEnumerable<string> GetDeleteClauses()
{
var list = new List<string>
{
"DELETE FROM cmsTask WHERE userId = @Id",
"DELETE FROM cmsTask WHERE parentUserId = @Id",
"DELETE FROM umbracoUser2UserGroup WHERE userId = @Id",
"DELETE FROM umbracoUser2NodeNotify WHERE userId = @Id",
"DELETE FROM umbracoUser WHERE id = @Id",
"DELETE FROM umbracoExternalLogin WHERE id = @Id"
};
return list;
}
protected override Guid NodeObjectTypeId
{
get { throw new NotImplementedException(); }
}
protected override void PersistNewItem(IUser entity)
{
((User)entity).AddingEntity();
//ensure security stamp if non
if (entity.SecurityStamp.IsNullOrWhiteSpace())
{
entity.SecurityStamp = Guid.NewGuid().ToString();
}
var userDto = UserFactory.BuildDto(entity);
//Check if we have a known config, we only want to store config for hashing
//TODO: This logic will need to be updated when we do http://issues.umbraco.org/issue/U4-10089
if (_passwordConfiguration != null && _passwordConfiguration.Count > 0)
{
var json = JsonConvert.SerializeObject(_passwordConfiguration);
userDto.PasswordConfig = json;
}
var id = Convert.ToInt32(Database.Insert(userDto));
entity.Id = id;
if (entity.IsPropertyDirty("StartContentIds") || entity.IsPropertyDirty("StartMediaIds"))
{
if (entity.IsPropertyDirty("StartContentIds"))
{
AddingOrUpdateStartNodes(entity, Enumerable.Empty<UserStartNodeDto>(), UserStartNodeDto.StartNodeTypeValue.Content, entity.StartContentIds);
}
if (entity.IsPropertyDirty("StartMediaIds"))
{
AddingOrUpdateStartNodes(entity, Enumerable.Empty<UserStartNodeDto>(), UserStartNodeDto.StartNodeTypeValue.Media, entity.StartMediaIds);
}
}
if (entity.IsPropertyDirty("Groups"))
{
//lookup all assigned
var assigned = entity.Groups == null || entity.Groups.Any() == false
? new List<UserGroupDto>()
: Database.Fetch<UserGroupDto>("SELECT * FROM umbracoUserGroup WHERE userGroupAlias IN (@aliases)", new { aliases = entity.Groups.Select(x => x.Alias) });
foreach (var groupDto in assigned)
{
var dto = new User2UserGroupDto
{
UserGroupId = groupDto.Id,
UserId = entity.Id
};
Database.Insert(dto);
}
}
entity.ResetDirtyProperties();
}
protected override void PersistUpdatedItem(IUser entity)
{
//Updates Modified date
((User)entity).UpdatingEntity();
//ensure security stamp if non
if (entity.SecurityStamp.IsNullOrWhiteSpace())
{
entity.SecurityStamp = Guid.NewGuid().ToString();
}
var userDto = UserFactory.BuildDto(entity);
//build list of columns to check for saving - we don't want to save the password if it hasn't changed!
//List the columns to save, NOTE: would be nice to not have hard coded strings here but no real good way around that
var colsToSave = new Dictionary<string, string>()
{
{"userDisabled", "IsApproved"},
{"userNoConsole", "IsLockedOut"},
{"startStructureID", "StartContentId"},
{"startMediaID", "StartMediaId"},
{"userName", "Name"},
{"userLogin", "Username"},
{"userEmail", "Email"},
{"userLanguage", "Language"},
{"securityStampToken", "SecurityStamp"},
{"lastLockoutDate", "LastLockoutDate"},
{"lastPasswordChangeDate", "LastPasswordChangeDate"},
{"lastLoginDate", "LastLoginDate"},
{"failedLoginAttempts", "FailedPasswordAttempts"},
{"createDate", "CreateDate"},
{"updateDate", "UpdateDate"},
{"avatar", "Avatar"},
{"emailConfirmedDate", "EmailConfirmedDate"},
{"invitedDate", "InvitedDate"},
{"tourData", "TourData"}
};
//create list of properties that have changed
var changedCols = colsToSave
.Where(col => entity.IsPropertyDirty(col.Value))
.Select(col => col.Key)
.ToList();
// DO NOT update the password if it has not changed or if it is null or empty
if (entity.IsPropertyDirty("RawPasswordValue") && entity.RawPasswordValue.IsNullOrWhiteSpace() == false)
{
changedCols.Add("userPassword");
//special case - when using ASP.Net identity the user manager will take care of updating the security stamp, however
// when not using ASP.Net identity (i.e. old membership providers), we'll need to take care of updating this manually
// so we can just detect if that property is dirty, if it's not we'll set it manually
if (entity.IsPropertyDirty("SecurityStamp") == false)
{
userDto.SecurityStampToken = entity.SecurityStamp = Guid.NewGuid().ToString();
changedCols.Add("securityStampToken");
}
//Check if we have a known config, we only want to store config for hashing
//TODO: This logic will need to be updated when we do http://issues.umbraco.org/issue/U4-10089
if (_passwordConfiguration != null && _passwordConfiguration.Count > 0)
{
var json = JsonConvert.SerializeObject(_passwordConfiguration);
userDto.PasswordConfig = json;
changedCols.Add("passwordConfig");
}
}
//only update the changed cols
if (changedCols.Count > 0)
{
Database.Update(userDto, changedCols);
}
if (entity.IsPropertyDirty("StartContentIds") || entity.IsPropertyDirty("StartMediaIds"))
{
var assignedStartNodes = Database.Fetch<UserStartNodeDto>("SELECT * FROM umbracoUserStartNode WHERE userId = @userId", new { userId = entity.Id });
if (entity.IsPropertyDirty("StartContentIds"))
{
AddingOrUpdateStartNodes(entity, assignedStartNodes, UserStartNodeDto.StartNodeTypeValue.Content, entity.StartContentIds);
}
if (entity.IsPropertyDirty("StartMediaIds"))
{
AddingOrUpdateStartNodes(entity, assignedStartNodes, UserStartNodeDto.StartNodeTypeValue.Media, entity.StartMediaIds);
}
}
if (entity.IsPropertyDirty("Groups"))
{
//lookup all assigned
var assigned = entity.Groups == null || entity.Groups.Any() == false
? new List<UserGroupDto>()
: Database.Fetch<UserGroupDto>("SELECT * FROM umbracoUserGroup WHERE userGroupAlias IN (@aliases)", new { aliases = entity.Groups.Select(x => x.Alias) });
//first delete all
//TODO: We could do this a nicer way instead of "Nuke and Pave"
Database.Delete<User2UserGroupDto>("WHERE UserId = @UserId", new { UserId = entity.Id });
foreach (var groupDto in assigned)
{
var dto = new User2UserGroupDto
{
UserGroupId = groupDto.Id,
UserId = entity.Id
};
Database.Insert(dto);
}
}
entity.ResetDirtyProperties();
}
private void AddingOrUpdateStartNodes(IEntity entity, IEnumerable<UserStartNodeDto> current, UserStartNodeDto.StartNodeTypeValue startNodeType, int[] entityStartIds)
{
var assignedIds = current.Where(x => x.StartNodeType == (int)startNodeType).Select(x => x.StartNode).ToArray();
//remove the ones not assigned to the entity
var toDelete = assignedIds.Except(entityStartIds).ToArray();
if (toDelete.Length > 0)
Database.Delete<UserStartNodeDto>("WHERE UserId = @UserId AND startNode IN (@startNodes)", new { UserId = entity.Id, startNodes = toDelete });
//add the ones not currently in the db
var toAdd = entityStartIds.Except(assignedIds).ToArray();
foreach (var i in toAdd)
{
var dto = new UserStartNodeDto
{
StartNode = i,
StartNodeType = (int)startNodeType,
UserId = entity.Id
};
Database.Insert(dto);
}
}
#endregion
#region Implementation of IUserRepository
public int GetCountByQuery(IQuery<IUser> query)
{
var sqlClause = GetBaseQuery("umbracoUser.id");
var translator = new SqlTranslator<IUser>(sqlClause, query);
var subquery = translator.Translate();
//get the COUNT base query
var sql = GetBaseQuery(true)
.Append(new Sql("WHERE umbracoUser.id IN (" + subquery.SQL + ")", subquery.Arguments));
return Database.ExecuteScalar<int>(sql);
}
public bool Exists(string username)
{
var sql = new Sql();
sql.Select("COUNT(*)")
.From<UserDto>()
.Where<UserDto>(x => x.UserName == username);
return Database.ExecuteScalar<int>(sql) > 0;
}
/// <summary>
/// Gets a list of <see cref="IUser"/> objects associated with a given group
/// </summary>
/// <param name="groupId">Id of group</param>
public IEnumerable<IUser> GetAllInGroup(int groupId)
{
return GetAllInOrNotInGroup(groupId, true);
}
/// <summary>
/// Gets a list of <see cref="IUser"/> objects not associated with a given group
/// </summary>
/// <param name="groupId">Id of group</param>
public IEnumerable<IUser> GetAllNotInGroup(int groupId)
{
return GetAllInOrNotInGroup(groupId, false);
}
private IEnumerable<IUser> GetAllInOrNotInGroup(int groupId, bool include)
{
var sql = new Sql();
sql.Select("*")
.From<UserDto>();
var innerSql = new Sql();
innerSql.Select("umbracoUser.id")
.From<UserDto>()
.LeftJoin<User2UserGroupDto>()
.On<UserDto, User2UserGroupDto>(left => left.Id, right => right.UserId)
.Where("umbracoUser2UserGroup.userGroupId = " + groupId);
sql.Where(string.Format("umbracoUser.id {0} ({1})",
include ? "IN" : "NOT IN",
innerSql.SQL));
return ConvertFromDtos(Database.Fetch<UserDto>(sql));
}
[Obsolete("Use the overload with long operators instead")]
[EditorBrowsable(EditorBrowsableState.Never)]
public IEnumerable<IUser> GetPagedResultsByQuery(IQuery<IUser> query, int pageIndex, int pageSize, out int totalRecords, Expression<Func<IUser, string>> orderBy)
{
if (orderBy == null) throw new ArgumentNullException("orderBy");
// get the referenced column name and find the corresp mapped column name
var expressionMember = ExpressionHelper.GetMemberInfo(orderBy);
var mapper = MappingResolver.Current.ResolveMapperByType(typeof(IUser));
var mappedField = mapper.Map(expressionMember.Name);
if (mappedField.IsNullOrWhiteSpace())
throw new ArgumentException("Could not find a mapping for the column specified in the orderBy clause");
long tr;
var results = GetPagedResultsByQuery(query, Convert.ToInt64(pageIndex), pageSize, out tr, mappedField, Direction.Ascending);
totalRecords = Convert.ToInt32(tr);
return results;
}
/// <summary>
/// Gets paged user results
/// </summary>
/// <param name="query"></param>
/// <param name="pageIndex"></param>
/// <param name="pageSize"></param>
/// <param name="totalRecords"></param>
/// <param name="orderBy"></param>
/// <param name="orderDirection"></param>
/// <param name="includeUserGroups">
/// A filter to only include user that belong to these user groups
/// </param>
/// <param name="excludeUserGroups">
/// A filter to only include users that do not belong to these user groups
/// </param>
/// <param name="userState">Optional parameter to filter by specfied user state</param>
/// <param name="filter"></param>
/// <returns></returns>
/// <remarks>
/// The query supplied will ONLY work with data specifically on the umbracoUser table because we are using PetaPoco paging (SQL paging)
/// </remarks>
public IEnumerable<IUser> GetPagedResultsByQuery(IQuery<IUser> query, long pageIndex, int pageSize, out long totalRecords,
Expression<Func<IUser, object>> orderBy, Direction orderDirection,
string[] includeUserGroups = null,
string[] excludeUserGroups = null,
UserState[] userState = null,
IQuery<IUser> filter = null)
{
if (orderBy == null) throw new ArgumentNullException("orderBy");
// get the referenced column name and find the corresp mapped column name
var expressionMember = ExpressionHelper.GetMemberInfo(orderBy);
var mapper = MappingResolver.Current.ResolveMapperByType(typeof(IUser));
var mappedField = mapper.Map(expressionMember.Name);
if (mappedField.IsNullOrWhiteSpace())
throw new ArgumentException("Could not find a mapping for the column specified in the orderBy clause");
return GetPagedResultsByQuery(query, pageIndex, pageSize, out totalRecords, mappedField, orderDirection, includeUserGroups, excludeUserGroups, userState, filter);
}
private IEnumerable<IUser> GetPagedResultsByQuery(IQuery<IUser> query, long pageIndex, int pageSize, out long totalRecords, string orderBy, Direction orderDirection,
string[] includeUserGroups = null,
string[] excludeUserGroups = null,
UserState[] userState = null,
IQuery<IUser> customFilter = null)
{
if (string.IsNullOrWhiteSpace(orderBy)) throw new ArgumentException("Value cannot be null or whitespace.", "orderBy");
Sql filterSql = null;
var customFilterWheres = customFilter != null ? customFilter.GetWhereClauses().ToArray() : null;
var hasCustomFilter = customFilterWheres != null && customFilterWheres.Length > 0;
if (hasCustomFilter
|| (includeUserGroups != null && includeUserGroups.Length > 0) || (excludeUserGroups != null && excludeUserGroups.Length > 0)
|| (userState != null && userState.Length > 0 && userState.Contains(UserState.All) == false))
filterSql = new Sql();
if (hasCustomFilter)
{
foreach (var filterClause in customFilterWheres)
{
filterSql.Append($"AND ({filterClause.Item1})", filterClause.Item2);
}
}
if (includeUserGroups != null && includeUserGroups.Length > 0)
{
const string subQuery = @"AND (umbracoUser.id IN (SELECT DISTINCT umbracoUser.id
FROM umbracoUser
INNER JOIN umbracoUser2UserGroup ON umbracoUser2UserGroup.userId = umbracoUser.id
INNER JOIN umbracoUserGroup ON umbracoUserGroup.id = umbracoUser2UserGroup.userGroupId
WHERE umbracoUserGroup.userGroupAlias IN (@userGroups)))";
filterSql.Append(subQuery, new { userGroups = includeUserGroups });
}
if (excludeUserGroups != null && excludeUserGroups.Length > 0)
{
const string subQuery = @"AND (umbracoUser.id NOT IN (SELECT DISTINCT umbracoUser.id
FROM umbracoUser
INNER JOIN umbracoUser2UserGroup ON umbracoUser2UserGroup.userId = umbracoUser.id
INNER JOIN umbracoUserGroup ON umbracoUserGroup.id = umbracoUser2UserGroup.userGroupId
WHERE umbracoUserGroup.userGroupAlias IN (@userGroups)))";
filterSql.Append(subQuery, new { userGroups = excludeUserGroups });
}
if (userState != null && userState.Length > 0)
{
//the "ALL" state doesn't require any filtering so we ignore that, if it exists in the list we don't do any filtering
if (userState.Contains(UserState.All) == false)
{
var sb = new StringBuilder("(");
var appended = false;
if (userState.Contains(UserState.Active))
{
sb.Append("(userDisabled = 0 AND userNoConsole = 0 AND lastLoginDate IS NOT NULL)");
appended = true;
}
if (userState.Contains(UserState.Inactive))
{
if (appended) sb.Append(" OR ");
sb.Append("(userDisabled = 0 AND userNoConsole = 0 AND lastLoginDate IS NULL)");
appended = true;
}
if (userState.Contains(UserState.Disabled))
{
if (appended) sb.Append(" OR ");
sb.Append("(userDisabled = 1)");
appended = true;
}
if (userState.Contains(UserState.LockedOut))
{
if (appended) sb.Append(" OR ");
sb.Append("(userNoConsole = 1)");
appended = true;
}
if (userState.Contains(UserState.Invited))
{
if (appended) sb.Append(" OR ");
sb.Append("(lastLoginDate IS NULL AND userDisabled = 1 AND invitedDate IS NOT NULL)");
appended = true;
}
sb.Append(")");
filterSql.Append("AND " + sb);
}
}
// Get base query for returning IDs
var sqlBaseIds = GetBaseQuery("id");
if (query == null) query = new Query<IUser>();
var queryHasWhereClause = query.GetWhereClauses().Any();
var translatorIds = new SqlTranslator<IUser>(sqlBaseIds, query);
var sqlQueryIds = translatorIds.Translate();
var sqlBaseFull = GetBaseQuery("umbracoUser.*, umbracoUserGroup.*, umbracoUserGroup2App.*, umbracoUserStartNode.*");
var translatorFull = new SqlTranslator<IUser>(sqlBaseFull, query);
//get sorted and filtered sql
var sqlNodeIdsWithSort = GetSortedSqlForPagedResults(
GetFilteredSqlForPagedResults(sqlQueryIds, filterSql, queryHasWhereClause),
orderDirection, orderBy);
// Get page of results and total count
var pagedResult = Database.Page<UserDto>(pageIndex + 1, pageSize, sqlNodeIdsWithSort);
totalRecords = Convert.ToInt32(pagedResult.TotalItems);
//NOTE: We need to check the actual items returned, not the 'totalRecords', that is because if you request a page number
// that doesn't actually have any data on it, the totalRecords will still indicate there are records but there are none in
// the pageResult.
if (pagedResult.Items.Any())
{
//Create the inner paged query that was used above to get the paged result, we'll use that as the inner sub query
var args = sqlNodeIdsWithSort.Arguments;
string sqlStringCount, sqlStringPage;
Database.BuildPageQueries<UserDto>(pageIndex * pageSize, pageSize, sqlNodeIdsWithSort.SQL, ref args, out sqlStringCount, out sqlStringPage);
var sqlQueryFull = translatorFull.Translate();
//We need to make this FULL query an inner join on the paged ID query
var splitQuery = sqlQueryFull.SQL.Split(new[] { "WHERE " }, StringSplitOptions.None);
var fullQueryWithPagedInnerJoin = new Sql(splitQuery[0])
.Append("INNER JOIN (")
//join the paged query with the paged query arguments
.Append(sqlStringPage, args)
.Append(") temp ")
.Append("ON umbracoUser.id = temp.id");
AddGroupLeftJoin(fullQueryWithPagedInnerJoin);
if (splitQuery.Length > 1)
{
//add the original where clause back with the original arguments
fullQueryWithPagedInnerJoin.Where(splitQuery[1], sqlQueryIds.Arguments);
}
//get sorted and filtered sql
var fullQuery = GetSortedSqlForPagedResults(
GetFilteredSqlForPagedResults(fullQueryWithPagedInnerJoin, filterSql, queryHasWhereClause),
orderDirection, orderBy);
var users = ConvertFromDtos(Database.Fetch<UserDto, UserGroupDto, UserGroup2AppDto, UserStartNodeDto, UserDto>(new UserGroupRelator().Map, fullQuery))
.ToArray(); // important so we don't iterate twice, if we don't do this we can end up with null values in cache if we were caching.
return users;
}
return Enumerable.Empty<IUser>();
}
private Sql GetFilteredSqlForPagedResults(Sql sql, Sql filterSql, bool hasWhereClause)
{
Sql filteredSql;
// Apply filter
if (filterSql != null)
{
//ensure we don't append a WHERE if there is already one
var sqlFilter = hasWhereClause
? filterSql.SQL
: " WHERE " + filterSql.SQL.TrimStart("AND ");
//NOTE: this is certainly strange - NPoco handles this much better but we need to re-create the sql
// instance a couple of times to get the parameter order correct, for some reason the first
// time the arguments don't show up correctly but the SQL argument parameter names are actually updated
// accordingly - so we re-create it again. In v8 we don't need to do this and it's already taken care of.
filteredSql = new Sql(sql.SQL, sql.Arguments);
var args = filteredSql.Arguments.Concat(filterSql.Arguments).ToArray();
filteredSql = new Sql(
string.Format("{0} {1}", filteredSql.SQL, sqlFilter),
args);
filteredSql = new Sql(filteredSql.SQL, args);
}
else
{
//copy to var so that the original isn't changed
filteredSql = new Sql(sql.SQL, sql.Arguments);
}
return filteredSql;
}
private Sql GetSortedSqlForPagedResults(Sql sql, Direction orderDirection, string orderBy)
{
//copy to var so that the original isn't changed
var sortedSql = new Sql(sql.SQL, sql.Arguments);
// Apply order according to parameters
if (string.IsNullOrEmpty(orderBy) == false)
{
//each order by param needs to be in a bracket! see: https://github.com/toptensoftware/PetaPoco/issues/177
var orderByParams = new[] { string.Format("({0})", orderBy) };
if (orderDirection == Direction.Ascending)
{
sortedSql.OrderBy(orderByParams);
}
else
{
sortedSql.OrderByDescending(orderByParams);
}
}
return sortedSql;
}
internal IEnumerable<IUser> GetNextUsers(int id, int count)
{
var idsQuery = new Sql()
.Select("umbracoUser.id")
.From<UserDto>(SqlSyntax)
.Where<UserDto>(x => x.Id >= id)
.OrderBy<UserDto>(x => x.Id, SqlSyntax);
// first page is index 1, not zero
var ids = Database.Page<int>(1, count, idsQuery).Items.ToArray();
// now get the actual users and ensure they are ordered properly (same clause)
return ids.Length == 0 ? Enumerable.Empty<IUser>() : GetAll(ids).OrderBy(x => x.Id);
}
#endregion
private IEnumerable<IUser> ConvertFromDtos(IEnumerable<UserDto> dtos)
{
return dtos.Select(UserFactory.BuildEntity);
}
}
}
| |
// ----------------------------------------------------------------------------------
//
// FXMaker
// Created by ismoon - 2012 - ismoonto@gmail.com
//
// ----------------------------------------------------------------------------------
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class NsEffectManager : MonoBehaviour
{
// Attribute ------------------------------------------------------------------------
// Property -------------------------------------------------------------------------
// Control Function -----------------------------------------------------------------
//
public static Texture[] PreloadResource(GameObject tarObj)
{
if (tarObj == null)
return new Texture[0];
List<GameObject> parentPrefabList = new List<GameObject>();
parentPrefabList.Add(tarObj);
return PreloadResource(tarObj, parentPrefabList);
}
public static Component GetComponentInChildren(GameObject tarObj, System.Type findType)
{
if (tarObj == null)
return null;
List<GameObject> parentPrefabList = new List<GameObject>();
parentPrefabList.Add(tarObj);
return GetComponentInChildren(tarObj, findType, parentPrefabList);
}
// Replay Function
public static GameObject CreateReplayEffect(GameObject tarPrefab)
{
if (tarPrefab == null)
return null;
if (NcEffectBehaviour.IsSafe() == false)
return null;
GameObject instanceObj = (GameObject)Instantiate(tarPrefab);
SetReplayEffect(instanceObj);
return instanceObj;
}
public static void SetReplayEffect(GameObject instanceObj)
{
PreloadResource(instanceObj);
SetActiveRecursively(instanceObj, false);
NcEffectBehaviour[] ncComs = instanceObj.GetComponentsInChildren<NcEffectBehaviour>(true);
foreach (NcEffectBehaviour ncCom in ncComs)
{
ncCom.OnSetReplayState();
}
}
public static void RunReplayEffect(GameObject instanceObj, bool bClearOldParticle)
{
SetActiveRecursively(instanceObj, true);
NcEffectBehaviour[] ncComs = instanceObj.GetComponentsInChildren<NcEffectBehaviour>(true);
foreach (NcEffectBehaviour ncCom in ncComs)
{
ncCom.OnResetReplayStage(bClearOldParticle);
}
}
// ----------------------------------------------------------------------------------
#if UNITY_EDITOR
public static void AdjustSpeedEditor(GameObject target, float fSpeedRate) // support shuriken, legancy, mesh
{
NcEffectBehaviour[] coms = target.GetComponentsInChildren<NcEffectBehaviour>(true);
foreach (NcEffectBehaviour com in coms)
com.OnUpdateEffectSpeed(fSpeedRate, false);
}
#endif
public static void AdjustSpeedRuntime(GameObject target, float fSpeedRate) // support legancy/mesh , not support shuriken
{
NcEffectBehaviour[] coms = target.GetComponentsInChildren<NcEffectBehaviour>(true);
foreach (NcEffectBehaviour com in coms)
com.OnUpdateEffectSpeed(fSpeedRate, true);
}
// ----------------------------------------------------------------------------------
public static void SetActiveRecursively(GameObject target, bool bActive)
{
#if (UNITY_4_0 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7 || UNITY_4_8 || UNITY_4_9)
for (int n = target.transform.childCount-1; 0 <= n; n--)
if (n < target.transform.childCount)
SetActiveRecursively(target.transform.GetChild(n).gameObject, bActive);
target.SetActive(bActive);
#else
target.SetActiveRecursively(bActive);
#endif
// SetActiveRecursivelyEffect(target, bActive);
}
public static bool IsActive(GameObject target)
{
#if (UNITY_4_0 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7 || UNITY_4_8 || UNITY_4_9)
return (target.activeInHierarchy && target.activeSelf);
#else
return target.active;
#endif
}
protected static void SetActiveRecursivelyEffect(GameObject target, bool bActive)
{
NcEffectBehaviour[] coms = target.GetComponentsInChildren<NcEffectBehaviour>(true);
foreach (NcEffectBehaviour com in coms)
com.OnSetActiveRecursively(bActive);
}
// ----------------------------------------------------------------------------------
protected static Texture[] PreloadResource(GameObject tarObj, List<GameObject> parentPrefabList)
{
if (NcEffectBehaviour.IsSafe() == false)
return null;
// texture
Renderer[] rens = tarObj.GetComponentsInChildren<Renderer>(true);
List<Texture> texList = new List<Texture>();
foreach (Renderer ren in rens)
{
if (ren.sharedMaterials == null || ren.sharedMaterials.Length <= 0)
continue;
foreach (Material mat in ren.sharedMaterials)
if (mat != null && mat.mainTexture != null)
texList.Add(mat.mainTexture);
}
// prefab
NcAttachPrefab[] prefabs = tarObj.GetComponentsInChildren<NcAttachPrefab>(true);
foreach (NcAttachPrefab obj in prefabs)
if (obj.m_AttachPrefab != null)
{
Texture[] ret = PreloadPrefab(obj.m_AttachPrefab, parentPrefabList, true);
if (ret == null)
obj.m_AttachPrefab = null; // clear
else texList.AddRange(ret);
}
NcParticleSystem[] pss = tarObj.GetComponentsInChildren<NcParticleSystem>(true);
foreach (NcParticleSystem ps in pss)
if (ps.m_AttachPrefab != null)
{
Texture[] ret = PreloadPrefab(ps.m_AttachPrefab, parentPrefabList, true);
if (ret == null)
ps.m_AttachPrefab = null; // clear
else texList.AddRange(ret);
}
NcSpriteTexture[] sts = tarObj.GetComponentsInChildren<NcSpriteTexture>(true);
foreach (NcSpriteTexture st in sts)
if (st.m_NcSpriteFactoryPrefab != null)
{
Texture[] ret = PreloadPrefab(st.m_NcSpriteFactoryPrefab, parentPrefabList, false);
if (ret != null)
texList.AddRange(ret);
}
NcParticleSpiral[] sps = tarObj.GetComponentsInChildren<NcParticleSpiral>(true);
foreach (NcParticleSpiral sp in sps)
if (sp.m_ParticlePrefab != null)
{
Texture[] ret = PreloadPrefab(sp.m_ParticlePrefab, parentPrefabList, false);
if (ret != null)
texList.AddRange(ret);
}
NcParticleEmit[] ses = tarObj.GetComponentsInChildren<NcParticleEmit>(true);
foreach (NcParticleEmit se in ses)
if (se.m_ParticlePrefab != null)
{
Texture[] ret = PreloadPrefab(se.m_ParticlePrefab, parentPrefabList, false);
if (ret != null)
texList.AddRange(ret);
}
// sound
NcAttachSound[] ass = tarObj.GetComponentsInChildren<NcAttachSound>(true);
foreach (NcAttachSound ncas in ass)
if (ncas.m_AudioClip != null)
continue;
// prefab & sound
NcSpriteFactory[] sprites = tarObj.GetComponentsInChildren<NcSpriteFactory>(true);
foreach (NcSpriteFactory sp in sprites)
if (sp.m_SpriteList != null)
for (int n = 0; n < sp.m_SpriteList.Count; n++)
if (sp.m_SpriteList[n].m_EffectPrefab != null)
{
Texture[] ret = PreloadPrefab(sp.m_SpriteList[n].m_EffectPrefab, parentPrefabList, true);
if (ret == null)
sp.m_SpriteList[n].m_EffectPrefab = null; // clear
else texList.AddRange(ret);
if (sp.m_SpriteList[n].m_AudioClip != null)
continue;
}
return texList.ToArray();
}
protected static Texture[] PreloadPrefab(GameObject tarObj, List<GameObject> parentPrefabList, bool bCheckDup)
{
if (parentPrefabList.Contains(tarObj))
{
if (bCheckDup)
{
string str = "";
for (int n = 0; n < parentPrefabList.Count; n++)
str += parentPrefabList[n].name + "/";
Debug.LogWarning("LoadError : Recursive Prefab - " + str + tarObj.name);
return null; // error
} else return null;
}
parentPrefabList.Add(tarObj);
Texture[] ret = PreloadResource(tarObj, parentPrefabList);
parentPrefabList.Remove(tarObj);
return ret;
}
// ----------------------------------------------------------------------------------
protected static Component GetComponentInChildren(GameObject tarObj, System.Type findType, List<GameObject> parentPrefabList)
{
Component[] coms = tarObj.GetComponentsInChildren(findType, true);
foreach (Component com in coms)
{
if (com.GetComponent<NcDontActive>() == null)
return com;
}
// prefab
Component findCom;
NcAttachPrefab[] prefabs = tarObj.GetComponentsInChildren<NcAttachPrefab>(true);
foreach (NcAttachPrefab obj in prefabs)
if (obj.m_AttachPrefab != null)
{
findCom = GetValidComponentInChildren(obj.m_AttachPrefab, findType, parentPrefabList, true);
if (findCom != null)
return findCom;
}
NcParticleSystem[] pss = tarObj.GetComponentsInChildren<NcParticleSystem>(true);
foreach (NcParticleSystem ps in pss)
if (ps.m_AttachPrefab != null)
{
findCom = GetValidComponentInChildren(ps.m_AttachPrefab, findType, parentPrefabList, true);
if (findCom != null)
return findCom;
}
NcSpriteTexture[] sts = tarObj.GetComponentsInChildren<NcSpriteTexture>(true);
foreach (NcSpriteTexture st in sts)
if (st.m_NcSpriteFactoryPrefab != null)
{
findCom = GetValidComponentInChildren(st.m_NcSpriteFactoryPrefab, findType, parentPrefabList, false);
if (findCom != null)
return findCom;
}
NcParticleSpiral[] sps = tarObj.GetComponentsInChildren<NcParticleSpiral>(true);
foreach (NcParticleSpiral sp in sps)
if (sp.m_ParticlePrefab != null)
{
findCom = GetValidComponentInChildren(sp.m_ParticlePrefab, findType, parentPrefabList, false);
if (findCom != null)
return findCom;
}
NcParticleEmit[] ses = tarObj.GetComponentsInChildren<NcParticleEmit>(true);
foreach (NcParticleEmit se in ses)
if (se.m_ParticlePrefab != null)
{
findCom = GetValidComponentInChildren(se.m_ParticlePrefab, findType, parentPrefabList, false);
if (findCom != null)
return findCom;
}
// prefab & sound
NcSpriteFactory[] sprites = tarObj.GetComponentsInChildren<NcSpriteFactory>(true);
foreach (NcSpriteFactory sp in sprites)
if (sp.m_SpriteList != null)
for (int n = 0; n < sp.m_SpriteList.Count; n++)
if (sp.m_SpriteList[n].m_EffectPrefab != null)
{
findCom = GetValidComponentInChildren(sp.m_SpriteList[n].m_EffectPrefab, findType, parentPrefabList, true);
if (findCom != null)
return findCom;
}
return null;
}
protected static Component GetValidComponentInChildren(GameObject tarObj, System.Type findType, List<GameObject> parentPrefabList, bool bCheckDup)
{
if (parentPrefabList.Contains(tarObj))
{
if (bCheckDup)
{
string str = "";
for (int n = 0; n < parentPrefabList.Count; n++)
str += parentPrefabList[n].name + "/";
Debug.LogWarning("LoadError : Recursive Prefab - " + str + tarObj.name);
return null; // error
} else return null;
}
parentPrefabList.Add(tarObj);
Component com = GetComponentInChildren(tarObj, findType, parentPrefabList);
parentPrefabList.Remove(tarObj);
return com;
}
}
| |
// Author: abi
// Project: DungeonQuest
// Path: C:\code\Xna\DungeonQuest\Helpers
// Creation date: 28.03.2007 01:01
// Last modified: 31.07.2007 04:41
#region Using directives
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using DungeonQuest.Helpers;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using DungeonQuest.Game;
using DungeonQuest.Graphics;
using DungeonQuest.Properties;
#endregion
namespace DungeonQuest.Helpers
{
/// <summary>
/// Input helper class, captures all the mouse, keyboard and XBox 360
/// controller input and provides some nice helper methods and properties.
/// Will also keep track of the last frame states for comparison if
/// a button was just pressed this frame, but not already in the last frame.
/// </summary>
class Input
{
#region Variables
#if !XBOX360
/// <summary>
/// Mouse state, set every frame in the Update method.
/// </summary>
private static MouseState mouseState,
mouseStateLastFrame;
#else
/// <summary>
/// Just save the mouse position here, it is just virtual on the Xbox.
/// Clicking is not possible .. we got no mouse support on the Xbox.
/// </summary>
private static Point mouseState,
mouseStateLastFrame;
#endif
/// <summary>
/// Was a mouse detected? Returns true if the user moves the mouse.
/// On the Xbox 360 there will be no mouse movement and theirfore we
/// know that we don't have to display the mouse.
/// </summary>
private static bool mouseDetected = false;
/// <summary>
/// Keyboard state, set every frame in the Update method.
/// Note: KeyboardState is a class and not a struct,
/// we have to initialize it here, else we might run into trouble when
/// accessing any keyboardState data before BaseGame.Update() is called.
/// We can also NOT use the last state because everytime we call
/// Keyboard.GetState() the old state is useless (see XNA help for more
/// information, section Input). We store our own array of keys from
/// the last frame for comparing stuff.
/// </summary>
private static KeyboardState keyboardState =
Microsoft.Xna.Framework.Input.Keyboard.GetState();
/// <summary>
/// Keys pressed last frame, for comparison if a key was just pressed.
/// </summary>
private static List<Keys> keysPressedLastFrame = new List<Keys>();
/// <summary>
/// GamePad state, set every frame in the Update method.
/// </summary>
private static GamePadState gamePadState,
gamePadStateLastFrame;
/// <summary>
/// Mouse wheel delta this frame. XNA does report only the total
/// scroll value, but we usually need the current delta!
/// </summary>
/// <returns>0</returns>
#if XBOX360
private static int mouseWheelDelta = 0;
#else
private static int mouseWheelDelta = 0, mouseWheelValue = 0;
#endif
/// <summary>
/// Start dragging pos, will be set when we just pressed the left
/// mouse button. Used for the MouseDraggingAmount property.
/// </summary>
private static Point startDraggingPos;
#endregion
#region Mouse Properties
/// <summary>
/// Was a mouse detected? Returns true if the user moves the mouse.
/// On the Xbox 360 there will be no mouse movement and theirfore we
/// know that we don't have to display the mouse.
/// </summary>
/// <returns>Bool</returns>
public static bool MouseDetected
{
get
{
return mouseDetected;
} // get
} // MouseDetected
/// <summary>
/// Mouse position
/// </summary>
/// <returns>Point</returns>
public static Point MousePos
{
get
{
#if XBOX360
return mouseState;
#else
return new Point(mouseState.X, mouseState.Y);
#endif
} // get
set
{
#if XBOX360
mouseState = value;
#else
Mouse.SetPosition(value.X, value.Y);
#endif
} // set
} // MousePos
#if !XBOX360
private static bool mouseWasCentered = false;
#endif
/// <summary>
/// Center mouse on screen for optimal mouse movement.
/// This is required because mouse movement is absolute and
/// relative mode is not supported like in DirectX.
/// We have to make sure in the next frame the relative movement will
/// still be correct!
/// </summary>
public static void CenterMouse()
{
#if !XBOX360
mouseWasCentered = true;
#endif
} // CenterMouse()
#if !XBOX360
/// <summary>
/// X and y movements of the mouse this frame
/// </summary>
private static float mouseXMovement, mouseYMovement,
lastMouseXMovement, lastMouseYMovement;
#endif
/// <summary>
/// Mouse x movement
/// </summary>
/// <returns>Float</returns>
public static float MouseXMovement
{
get
{
#if XBOX360
return 0;
#else
return mouseXMovement;
#endif
} // get
} // MouseXMovement
/// <summary>
/// Mouse y movement
/// </summary>
/// <returns>Float</returns>
public static float MouseYMovement
{
get
{
#if XBOX360
return 0;
#else
return mouseYMovement;
#endif
} // get
} // MouseYMovement
/// <summary>
/// Mouse left button pressed
/// </summary>
/// <returns>Bool</returns>
public static bool MouseLeftButtonPressed
{
get
{
#if XBOX360
return false;
#else
return mouseState.LeftButton == ButtonState.Pressed;
#endif
} // get
} // MouseLeftButtonPressed
/// <summary>
/// Mouse right button pressed
/// </summary>
/// <returns>Bool</returns>
public static bool MouseRightButtonPressed
{
get
{
#if XBOX360
return false;
#else
return mouseState.RightButton == ButtonState.Pressed;
#endif
} // get
} // MouseRightButtonPressed
/// <summary>
/// Mouse middle button pressed
/// </summary>
/// <returns>Bool</returns>
public static bool MouseMiddleButtonPressed
{
get
{
#if XBOX360
return false;
#else
return mouseState.MiddleButton == ButtonState.Pressed;
#endif
} // get
} // MouseMiddleButtonPressed
/// <summary>
/// Mouse left button just pressed
/// </summary>
/// <returns>Bool</returns>
public static bool MouseLeftButtonJustPressed
{
get
{
#if XBOX360
return false;
#else
return mouseState.LeftButton == ButtonState.Pressed &&
mouseStateLastFrame.LeftButton == ButtonState.Released;
#endif
} // get
} // MouseLeftButtonJustPressed
/// <summary>
/// Mouse right button just pressed
/// </summary>
/// <returns>Bool</returns>
public static bool MouseRightButtonJustPressed
{
get
{
#if XBOX360
return false;
#else
return mouseState.RightButton == ButtonState.Pressed &&
mouseStateLastFrame.RightButton == ButtonState.Released;
#endif
} // get
} // MouseRightButtonJustPressed
/// <summary>
/// Mouse dragging amount
/// </summary>
/// <returns>Point</returns>
public static Point MouseDraggingAmount
{
get
{
return new Point(
startDraggingPos.X - MousePos.X,
startDraggingPos.Y - MousePos.Y);
} // get
} // MouseDraggingAmount
/// <summary>
/// Reset mouse dragging amount
/// </summary>
public static void ResetMouseDraggingAmount()
{
startDraggingPos = MousePos;
} // ResetMouseDraggingAmount()
/// <summary>
/// Mouse wheel delta
/// </summary>
/// <returns>Int</returns>
public static int MouseWheelDelta
{
get
{
return mouseWheelDelta;
} // get
} // MouseWheelDelta
/// <summary>
/// Mouse in box
/// </summary>
/// <param name="rect">Rectangle</param>
/// <returns>Bool</returns>
public static bool MouseInBox(Rectangle rect)
{
bool ret = mouseState.X >= rect.X &&
mouseState.Y >= rect.Y &&
mouseState.X < rect.Right &&
mouseState.Y < rect.Bottom;
return ret;
} // MouseInBox(rect)
/// <summary>
/// Mouse was not in rectangle last frame
/// </summary>
/// <param name="rect">Rectangle</param>
public static bool MouseWasNotInRectLastFrame(Rectangle rect)
{
// Check the opposite of MouseInBox.
bool lastRet = mouseStateLastFrame.X >= rect.X &&
mouseStateLastFrame.Y >= rect.Y &&
mouseStateLastFrame.X < rect.Right &&
mouseStateLastFrame.Y < rect.Bottom;
return !lastRet;
} // MouseWasNotInRectLastFrame(rect)
#endregion
#region Keyboard Properties
/// <summary>
/// Keyboard
/// </summary>
/// <returns>Keyboard state</returns>
public static KeyboardState Keyboard
{
get
{
return keyboardState;
} // get
} // Keyboard
public static bool IsSpecialKey(Keys key)
{
// All keys except A-Z, 0-9 and `-\[];',./= (and space) are special keys.
// With shift pressed this also results in this keys:
// ~_|{}:"<>? !@#$%^&*().
int keyNum = (int)key;
if ((keyNum >= (int)Keys.A && keyNum <= (int)Keys.Z) ||
(keyNum >= (int)Keys.D0 && keyNum <= (int)Keys.D9) ||
key == Keys.Space || // well, space ^^
key == Keys.OemTilde || // `~
key == Keys.OemMinus || // -_
key == Keys.OemPipe || // \|
key == Keys.OemOpenBrackets || // [{
key == Keys.OemCloseBrackets || // ]}
key == Keys.OemSemicolon || // ;:
key == Keys.OemQuotes || // '"
key == Keys.OemComma || // ,<
key == Keys.OemPeriod || // .>
key == Keys.OemQuestion || // /?
key == Keys.OemPlus) // =+
return false;
// Else is is a special key
return true;
} // static bool IsSpecialKey(Keys key)
/// <summary>
/// Keys to char helper conversion method.
/// Note: If the keys are mapped other than on a default QWERTY
/// keyboard, this method will not work properly. Most keyboards
/// will return the same for A-Z and 0-9, but the special keys
/// might be different. Sorry, no easy way to fix this with XNA ...
/// For a game with chat (windows) you should implement the
/// windows events for catching keyboard input, which are much better!
/// </summary>
/// <param name="key">Keys</param>
/// <returns>Char</returns>
public static char KeyToChar(Keys key, bool shiftPressed)
{
// If key will not be found, just return space
char ret = ' ';
int keyNum = (int)key;
if (keyNum >= (int)Keys.A && keyNum <= (int)Keys.Z)
{
if (shiftPressed)
ret = key.ToString()[0];
else
ret = key.ToString().ToLower()[0];
} // if (keyNum)
else if (keyNum >= (int)Keys.D0 && keyNum <= (int)Keys.D9 &&
shiftPressed == false)
{
ret = (char)((int)'0' + (keyNum - Keys.D0));
} // else if
else if (key == Keys.D1 && shiftPressed)
ret = '!';
else if (key == Keys.D2 && shiftPressed)
ret = '@';
else if (key == Keys.D3 && shiftPressed)
ret = '#';
else if (key == Keys.D4 && shiftPressed)
ret = '$';
else if (key == Keys.D5 && shiftPressed)
ret = '%';
else if (key == Keys.D6 && shiftPressed)
ret = '^';
else if (key == Keys.D7 && shiftPressed)
ret = '&';
else if (key == Keys.D8 && shiftPressed)
ret = '*';
else if (key == Keys.D9 && shiftPressed)
ret = '(';
else if (key == Keys.D0 && shiftPressed)
ret = ')';
else if (key == Keys.OemTilde)
ret = shiftPressed ? '~' : '`';
else if (key == Keys.OemMinus)
ret = shiftPressed ? '_' : '-';
else if (key == Keys.OemPipe)
ret = shiftPressed ? '|' : '\\';
else if (key == Keys.OemOpenBrackets)
ret = shiftPressed ? '{' : '[';
else if (key == Keys.OemCloseBrackets)
ret = shiftPressed ? '}' : ']';
else if (key == Keys.OemSemicolon)
ret = shiftPressed ? ':' : ';';
else if (key == Keys.OemQuotes)
ret = shiftPressed ? '"' : '\'';
else if (key == Keys.OemComma)
ret = shiftPressed ? '<' : '.';
else if (key == Keys.OemPeriod)
ret = shiftPressed ? '>' : ',';
else if (key == Keys.OemQuestion)
ret = shiftPressed ? '?' : '/';
else if (key == Keys.OemPlus)
ret = shiftPressed ? '+' : '=';
// Return result
return ret;
} // KeyToChar(key)
/// <summary>
/// Handle keyboard input helper method to catch keyboard input
/// for an input text. Only used to enter the player name in the game.
/// </summary>
/// <param name="inputText">Input text</param>
public static void HandleKeyboardInput(ref string inputText)
{
// Is a shift key pressed (we have to check both, left and right)
bool isShiftPressed =
keyboardState.IsKeyDown(Keys.LeftShift) ||
keyboardState.IsKeyDown(Keys.RightShift);
// Go through all pressed keys
foreach (Keys pressedKey in keyboardState.GetPressedKeys())
// Only process if it was not pressed last frame
if (keysPressedLastFrame.Contains(pressedKey) == false)
{
// No special key?
if (IsSpecialKey(pressedKey) == false &&
// Max. allow 32 chars
inputText.Length < 32)
{
// Then add the letter to our inputText.
// Check also the shift state!
inputText += KeyToChar(pressedKey, isShiftPressed);
} // if (IsSpecialKey)
else if (pressedKey == Keys.Back &&
inputText.Length > 0)
{
// Remove 1 character at end
inputText = inputText.Substring(0, inputText.Length - 1);
} // else if
} // foreach if (WasKeyPressedLastFrame)
} // HandleKeyboardInput(inputText)
/// <summary>
/// Keyboard key just pressed
/// </summary>
/// <returns>Bool</returns>
public static bool KeyboardKeyJustPressed(Keys key)
{
return keyboardState.IsKeyDown(key) &&
keysPressedLastFrame.Contains(key) == false;
} // KeyboardSpaceJustPressed
/// <summary>
/// Keyboard space just pressed
/// </summary>
/// <returns>Bool</returns>
public static bool KeyboardSpaceJustPressed
{
get
{
return keyboardState.IsKeyDown(Keys.Space) &&
keysPressedLastFrame.Contains(Keys.Space) == false;
} // get
} // KeyboardSpaceJustPressed
/// <summary>
/// Keyboard enter just pressed
/// </summary>
/// <returns>Bool</returns>
public static bool KeyboardEnterJustPressed
{
get
{
return keyboardState.IsKeyDown(Keys.Enter) &&
keysPressedLastFrame.Contains(Keys.Enter) == false;
} // get
} // KeyboardEnterJustPressed
/// <summary>
/// Keyboard F1 just pressed
/// </summary>
/// <returns>Bool</returns>
public static bool KeyboardF1JustPressed
{
get
{
return keyboardState.IsKeyDown(Keys.F1) &&
keysPressedLastFrame.Contains(Keys.F1) == false;
} // get
} // KeyboardF1JustPressed
/// <summary>
/// Keyboard F2 just pressed
/// </summary>
/// <returns>Bool</returns>
public static bool KeyboardF2JustPressed
{
get
{
return keyboardState.IsKeyDown(Keys.F2) &&
keysPressedLastFrame.Contains(Keys.F2) == false;
} // get
} // KeyboardF2JustPressed
/// <summary>
/// Keyboard escape just pressed
/// </summary>
/// <returns>Bool</returns>
public static bool KeyboardEscapeJustPressed
{
get
{
return keyboardState.IsKeyDown(Keys.Escape) &&
keysPressedLastFrame.Contains(Keys.Escape) == false;
} // get
} // KeyboardEscapeJustPressed
/// <summary>
/// Keyboard left just pressed
/// </summary>
/// <returns>Bool</returns>
public static bool KeyboardLeftJustPressed
{
get
{
return keyboardState.IsKeyDown(Keys.Left) &&
keysPressedLastFrame.Contains(Keys.Left) == false;
} // get
} // KeyboardLeftJustPressed
/// <summary>
/// Keyboard right just pressed
/// </summary>
/// <returns>Bool</returns>
public static bool KeyboardRightJustPressed
{
get
{
return keyboardState.IsKeyDown(Keys.Right) &&
keysPressedLastFrame.Contains(Keys.Right) == false;
} // get
} // KeyboardRightJustPressed
/// <summary>
/// Keyboard up just pressed
/// </summary>
/// <returns>Bool</returns>
public static bool KeyboardUpJustPressed
{
get
{
return keyboardState.IsKeyDown(Keys.Up) &&
keysPressedLastFrame.Contains(Keys.Up) == false;
} // get
} // KeyboardUpJustPressed
/// <summary>
/// Keyboard down just pressed
/// </summary>
/// <returns>Bool</returns>
public static bool KeyboardDownJustPressed
{
get
{
return keyboardState.IsKeyDown(Keys.Down) &&
keysPressedLastFrame.Contains(Keys.Down) == false;
} // get
} // KeyboardDownJustPressed
/// <summary>
/// Keyboard left pressed
/// </summary>
/// <returns>Bool</returns>
public static bool KeyboardLeftPressed
{
get
{
return keyboardState.IsKeyDown(Keys.Left);
} // get
} // KeyboardLeftPressed
/// <summary>
/// Keyboard right pressed
/// </summary>
/// <returns>Bool</returns>
public static bool KeyboardRightPressed
{
get
{
return keyboardState.IsKeyDown(Keys.Right);
} // get
} // KeyboardRightPressed
/// <summary>
/// Keyboard up pressed
/// </summary>
/// <returns>Bool</returns>
public static bool KeyboardUpPressed
{
get
{
return keyboardState.IsKeyDown(Keys.Up);
} // get
} // KeyboardUpPressed
/// <summary>
/// Keyboard down pressed
/// </summary>
/// <returns>Bool</returns>
public static bool KeyboardDownPressed
{
get
{
return keyboardState.IsKeyDown(Keys.Down);
} // get
} // KeyboardDownPressed
#endregion
#region GamePad Properties
/// <summary>
/// Game pad
/// </summary>
/// <returns>Game pad state</returns>
public static GamePadState GamePad
{
get
{
return gamePadState;
} // get
} // GamePad
/// <summary>
/// Is game pad connected
/// </summary>
/// <returns>Bool</returns>
public static bool IsGamePadConnected
{
get
{
return gamePadState.IsConnected;
} // get
} // IsGamePadConnected
/// <summary>
/// Game pad start pressed
/// </summary>
/// <returns>Bool</returns>
public static bool GamePadStartPressed
{
get
{
return gamePadState.Buttons.Start == ButtonState.Pressed;
} // get
} // GamePadStartPressed
/// <summary>
/// Game pad a pressed
/// </summary>
/// <returns>Bool</returns>
public static bool GamePadAPressed
{
get
{
return gamePadState.Buttons.A == ButtonState.Pressed;
} // get
} // GamePadAPressed
/// <summary>
/// Game pad b pressed
/// </summary>
/// <returns>Bool</returns>
public static bool GamePadBPressed
{
get
{
return gamePadState.Buttons.B == ButtonState.Pressed;
} // get
} // GamePadBPressed
/// <summary>
/// Game pad x pressed
/// </summary>
/// <returns>Bool</returns>
public static bool GamePadXPressed
{
get
{
return gamePadState.Buttons.X == ButtonState.Pressed;
} // get
} // GamePadXPressed
/// <summary>
/// Game pad y pressed
/// </summary>
/// <returns>Bool</returns>
public static bool GamePadYPressed
{
get
{
return gamePadState.Buttons.Y == ButtonState.Pressed;
} // get
} // GamePadYPressed
/// <summary>
/// Game pad left pressed
/// </summary>
/// <returns>Bool</returns>
public static bool GamePadLeftPressed
{
get
{
return gamePadState.DPad.Left == ButtonState.Pressed ||
gamePadState.ThumbSticks.Left.X < -0.75f;
} // get
} // GamePadLeftPressed
/// <summary>
/// Game pad right pressed
/// </summary>
/// <returns>Bool</returns>
public static bool GamePadRightPressed
{
get
{
return gamePadState.DPad.Left == ButtonState.Pressed ||
gamePadState.ThumbSticks.Left.X > 0.75f;
} // get
} // GamePadRightPressed
/// <summary>
/// Game pad left just pressed
/// </summary>
/// <returns>Bool</returns>
public static bool GamePadLeftJustPressed
{
get
{
return (gamePadState.DPad.Left == ButtonState.Pressed &&
gamePadStateLastFrame.DPad.Left == ButtonState.Released) ||
(gamePadState.ThumbSticks.Left.X < -0.75f &&
gamePadStateLastFrame.ThumbSticks.Left.X > -0.75f);
} // get
} // GamePadLeftJustPressed
/// <summary>
/// Game pad right just pressed
/// </summary>
/// <returns>Bool</returns>
public static bool GamePadRightJustPressed
{
get
{
return (gamePadState.DPad.Right == ButtonState.Pressed &&
gamePadStateLastFrame.DPad.Right == ButtonState.Released) ||
(gamePadState.ThumbSticks.Left.X > 0.75f &&
gamePadStateLastFrame.ThumbSticks.Left.X < 0.75f);
} // get
} // GamePadRightJustPressed
/// <summary>
/// Game pad up just pressed
/// </summary>
/// <returns>Bool</returns>
public static bool GamePadUpJustPressed
{
get
{
return (gamePadState.DPad.Up == ButtonState.Pressed &&
gamePadStateLastFrame.DPad.Up == ButtonState.Released) ||
(gamePadState.ThumbSticks.Left.Y > 0.75f &&
gamePadStateLastFrame.ThumbSticks.Left.Y < 0.75f);
} // get
} // GamePadUpJustPressed
/// <summary>
/// Game pad down just pressed
/// </summary>
/// <returns>Bool</returns>
public static bool GamePadDownJustPressed
{
get
{
return (gamePadState.DPad.Down == ButtonState.Pressed &&
gamePadStateLastFrame.DPad.Down == ButtonState.Released) ||
(gamePadState.ThumbSticks.Left.Y < -0.75f &&
gamePadStateLastFrame.ThumbSticks.Left.Y > -0.75f);
} // get
} // GamePadDownJustPressed
/// <summary>
/// Game pad up pressed
/// </summary>
/// <returns>Bool</returns>
public static bool GamePadUpPressed
{
get
{
return gamePadState.DPad.Down == ButtonState.Pressed ||
gamePadState.ThumbSticks.Left.Y > 0.75f;
} // get
} // GamePadUpPressed
/// <summary>
/// Game pad down pressed
/// </summary>
/// <returns>Bool</returns>
public static bool GamePadDownPressed
{
get
{
return gamePadState.DPad.Up == ButtonState.Pressed ||
gamePadState.ThumbSticks.Left.Y < -0.75f;
} // get
} // GamePadDownPressed
/// <summary>
/// Game pad a just pressed
/// </summary>
/// <returns>Bool</returns>
public static bool GamePadAJustPressed
{
get
{
return gamePadState.Buttons.A == ButtonState.Pressed &&
gamePadStateLastFrame.Buttons.A == ButtonState.Released;
} // get
} // GamePadAJustPressed
/// <summary>
/// Game pad b just pressed
/// </summary>
/// <returns>Bool</returns>
public static bool GamePadBJustPressed
{
get
{
return gamePadState.Buttons.B == ButtonState.Pressed &&
gamePadStateLastFrame.Buttons.B == ButtonState.Released;
} // get
} // GamePadBJustPressed
/// <summary>
/// Game pad x just pressed
/// </summary>
/// <returns>Bool</returns>
public static bool GamePadXJustPressed
{
get
{
return gamePadState.Buttons.X == ButtonState.Pressed &&
gamePadStateLastFrame.Buttons.X == ButtonState.Released;
} // get
} // GamePadXJustPressed
/// <summary>
/// Game pad y just pressed
/// </summary>
/// <returns>Bool</returns>
public static bool GamePadYJustPressed
{
get
{
return gamePadState.Buttons.Y == ButtonState.Pressed &&
gamePadStateLastFrame.Buttons.Y == ButtonState.Released;
} // get
} // GamePadYJustPressed
/// <summary>
/// Game pad back just pressed
/// </summary>
/// <returns>Bool</returns>
public static bool GamePadBackJustPressed
{
get
{
return gamePadState.Buttons.Back == ButtonState.Pressed &&
gamePadStateLastFrame.Buttons.Back == ButtonState.Released;
} // get
} // GamePadBackJustPressed
/// <summary>
/// GamePadLeftShoulderJustPressed
/// </summary>
/// <returns>Bool</returns>
public static bool GamePadLeftShoulderJustPressed
{
get
{
return gamePadState.Buttons.LeftShoulder == ButtonState.Pressed &&
gamePadStateLastFrame.Buttons.LeftShoulder == ButtonState.Released;
} // get
} // GamePadLeftShoulderJustPressed
/// <summary>
/// GamePadRightShoulderJustPressed
/// </summary>
/// <returns>Bool</returns>
public static bool GamePadRightShoulderJustPressed
{
get
{
return gamePadState.Buttons.RightShoulder == ButtonState.Pressed &&
gamePadStateLastFrame.Buttons.RightShoulder == ButtonState.Released;
} // get
} // GamePadRightShoulderJustPressed
private static float leftRumble = 0,
rightRumble = 0;
/// <summary>
/// Game pad rumble
/// </summary>
/// <param name="setLeftRumble">Set left rumble</param>
/// <param name="setRightRumble">Set right rumble</param>
public static void GamePadRumble(float setLeftRumble, float setRightRumble)
{
if (setLeftRumble > leftRumble)
leftRumble = setLeftRumble;
if (setRightRumble > rightRumble)
rightRumble = setRightRumble;
} // GamePadRumble(setLeftRumble, setRightRumble)
#endregion
#region Update
/// <summary>
/// Update, called from BaseGame.Update().
/// Will catch all new states for keyboard, mouse and the gamepad.
/// </summary>
internal static void Update()
{
#if XBOX360
// No mouse support on the XBox360 yet :(
mouseDetected = false;
// Copy over old mouse state
mouseStateLastFrame = mouseState;
#else
// Handle mouse input variables
mouseStateLastFrame = mouseState;
mouseState = Microsoft.Xna.Framework.Input.Mouse.GetState();
// Update mouseXMovement and mouseYMovement
Point lastMousePos = new Point(
mouseStateLastFrame.X, mouseStateLastFrame.Y);
lastMouseXMovement += (mouseState.X - lastMousePos.X) * GameSettings.Default.ControllerSensibility;
lastMouseYMovement += (mouseState.Y - lastMousePos.Y) * GameSettings.Default.ControllerSensibility;
mouseXMovement = lastMouseXMovement / 2.0f;
mouseYMovement = lastMouseYMovement / 2.0f;
lastMouseXMovement -= lastMouseXMovement / 2.0f;
lastMouseYMovement -= lastMouseYMovement / 2.0f;
if (mouseWasCentered &&
BaseGame.IsWindowActive)
{
mouseWasCentered = false;
MousePos = new Point(BaseGame.Width / 2, BaseGame.Height / 2);
mouseState = Microsoft.Xna.Framework.Input.Mouse.GetState();
} // if
if (MouseLeftButtonPressed == false)
startDraggingPos = MousePos;
mouseWheelDelta = mouseState.ScrollWheelValue - mouseWheelValue;
mouseWheelValue = mouseState.ScrollWheelValue;
// Check if mouse was moved this frame if it is not detected yet.
// This allows us to ignore the mouse even when it is captured
// on a windows machine if just the gamepad or keyboard is used.
if (mouseDetected == false)// &&
//always returns false: Microsoft.Xna.Framework.Input.Mouse.IsCaptured)
mouseDetected = mouseState.X != mouseStateLastFrame.X ||
mouseState.Y != mouseStateLastFrame.Y ||
mouseState.LeftButton != mouseStateLastFrame.LeftButton;
#endif
// Handle keyboard input
keysPressedLastFrame = new List<Keys>(keyboardState.GetPressedKeys());
keyboardState = Microsoft.Xna.Framework.Input.Keyboard.GetState();
// And finally catch the XBox Controller input (only use 1 player here)
gamePadStateLastFrame = gamePadState;
gamePadState = Microsoft.Xna.Framework.Input.GamePad.GetState(
PlayerIndex.One);
// Try player index two
if (gamePadState.IsConnected == false)
gamePadState = Microsoft.Xna.Framework.Input.GamePad.GetState(
PlayerIndex.Two);
// Handle rumbeling
if (leftRumble > 0 || rightRumble > 0)
{
if (leftRumble > 0)
leftRumble -= 0.85f * BaseGame.MoveFactorPerSecond;
if (rightRumble > 0)
rightRumble -= 0.85f * BaseGame.MoveFactorPerSecond;
if (leftRumble < 0)
leftRumble = 0;
if (rightRumble < 0)
rightRumble = 0;
Microsoft.Xna.Framework.Input.GamePad.SetVibration(
PlayerIndex.One, leftRumble, rightRumble);
} // if (leftRumble)
} // Update()
#endregion
#region Unit testing
#if DEBUG
public static void TestXboxControllerInput()
{
TestGame.Start(
delegate
{
if (Input.GamePadAJustPressed)
Input.GamePadRumble(0.35f, 0.475f);
else if (Input.GamePadBJustPressed)
Input.GamePadRumble(0.85f, 0.95f);
TextureFont.WriteText(30, 60, "Press A for a little gamepad rumble"+
"and B for heavy gamepad rumble effect");
});
} // TestXboxControllerInput()
#endif
#endregion
} // class Input
} // namespace DungeonQuest.Helpers
| |
using System.Collections.Generic;
using NUnit.Framework;
using Assert=ModestTree.Assert;
#pragma warning disable 219
namespace Zenject.Tests.Bindings
{
[TestFixture]
public class TestMemoryPool0 : ZenjectUnitTestFixture
{
[Test]
public void TestFactoryProperties()
{
Container.BindMemoryPool<Foo, Foo.Pool>();
var factory = Container.Resolve<Foo.Pool>();
Assert.IsEqual(factory.NumActive, 0);
Assert.IsEqual(factory.NumTotal, 0);
Assert.IsEqual(factory.NumInactive, 0);
var foo = factory.Spawn();
Assert.IsEqual(factory.NumActive, 1);
Assert.IsEqual(factory.NumTotal, 1);
Assert.IsEqual(factory.NumInactive, 0);
Assert.IsEqual(foo.ResetCount, 1);
factory.Despawn(foo);
Assert.IsEqual(factory.NumActive, 0);
Assert.IsEqual(factory.NumTotal, 1);
Assert.IsEqual(factory.NumInactive, 1);
Assert.IsEqual(foo.ResetCount, 1);
foo = factory.Spawn();
Assert.IsEqual(factory.NumActive, 1);
Assert.IsEqual(factory.NumTotal, 1);
Assert.IsEqual(factory.NumInactive, 0);
Assert.IsEqual(foo.ResetCount, 2);
var foo2 = factory.Spawn();
Assert.IsEqual(factory.NumActive, 2);
Assert.IsEqual(factory.NumTotal, 2);
Assert.IsEqual(factory.NumInactive, 0);
Assert.IsEqual(foo2.ResetCount, 1);
factory.Despawn(foo);
Assert.IsEqual(factory.NumActive, 1);
Assert.IsEqual(factory.NumTotal, 2);
Assert.IsEqual(factory.NumInactive, 1);
Assert.IsEqual(foo.ResetCount, 2);
factory.Despawn(foo2);
Assert.IsEqual(factory.NumActive, 0);
Assert.IsEqual(factory.NumTotal, 2);
Assert.IsEqual(factory.NumInactive, 2);
}
[Test]
public void TestFactoryPropertiesDefault()
{
Container.BindMemoryPool<Foo>();
var factory = Container.Resolve<MemoryPool<Foo>>();
Assert.IsEqual(factory.NumActive, 0);
Assert.IsEqual(factory.NumTotal, 0);
Assert.IsEqual(factory.NumInactive, 0);
var foo = factory.Spawn();
Assert.IsEqual(factory.NumActive, 1);
Assert.IsEqual(factory.NumTotal, 1);
Assert.IsEqual(factory.NumInactive, 0);
factory.Despawn(foo);
Assert.IsEqual(factory.NumActive, 0);
Assert.IsEqual(factory.NumTotal, 1);
Assert.IsEqual(factory.NumInactive, 1);
foo = factory.Spawn();
Assert.IsEqual(factory.NumActive, 1);
Assert.IsEqual(factory.NumTotal, 1);
Assert.IsEqual(factory.NumInactive, 0);
var foo2 = factory.Spawn();
Assert.IsEqual(factory.NumActive, 2);
Assert.IsEqual(factory.NumTotal, 2);
Assert.IsEqual(factory.NumInactive, 0);
factory.Despawn(foo);
Assert.IsEqual(factory.NumActive, 1);
Assert.IsEqual(factory.NumTotal, 2);
Assert.IsEqual(factory.NumInactive, 1);
factory.Despawn(foo2);
Assert.IsEqual(factory.NumActive, 0);
Assert.IsEqual(factory.NumTotal, 2);
Assert.IsEqual(factory.NumInactive, 2);
}
[Test]
public void TestExpandDouble()
{
Container.BindMemoryPool<Foo, Foo.Pool>().ExpandByDoubling();
var factory = Container.Resolve<Foo.Pool>();
Assert.IsEqual(factory.NumActive, 0);
Assert.IsEqual(factory.NumTotal, 0);
Assert.IsEqual(factory.NumInactive, 0);
var foo = factory.Spawn();
Assert.IsEqual(factory.NumActive, 1);
Assert.IsEqual(factory.NumTotal, 1);
Assert.IsEqual(factory.NumInactive, 0);
var foo2 = factory.Spawn();
Assert.IsEqual(factory.NumActive, 2);
Assert.IsEqual(factory.NumTotal, 2);
Assert.IsEqual(factory.NumInactive, 0);
var foo3 = factory.Spawn();
Assert.IsEqual(factory.NumActive, 3);
Assert.IsEqual(factory.NumTotal, 4);
Assert.IsEqual(factory.NumInactive, 1);
factory.Despawn(foo2);
Assert.IsEqual(factory.NumActive, 2);
Assert.IsEqual(factory.NumTotal, 4);
Assert.IsEqual(factory.NumInactive, 2);
var foo4 = factory.Spawn();
Assert.IsEqual(factory.NumActive, 3);
Assert.IsEqual(factory.NumTotal, 4);
Assert.IsEqual(factory.NumInactive, 1);
}
[Test]
public void TestFixedSize()
{
Container.BindMemoryPool<Foo, Foo.Pool>().WithFixedSize(2);
var factory = Container.Resolve<Foo.Pool>();
Assert.IsEqual(factory.NumActive, 0);
Assert.IsEqual(factory.NumTotal, 2);
Assert.IsEqual(factory.NumInactive, 2);
var foo = factory.Spawn();
Assert.IsEqual(factory.NumActive, 1);
Assert.IsEqual(factory.NumTotal, 2);
Assert.IsEqual(factory.NumInactive, 1);
var foo2 = factory.Spawn();
Assert.IsEqual(factory.NumActive, 2);
Assert.IsEqual(factory.NumTotal, 2);
Assert.IsEqual(factory.NumInactive, 0);
Assert.Throws<PoolExceededFixedSizeException>(() => factory.Spawn());
}
[Test]
public void TestInitialSize()
{
Container.BindMemoryPool<Foo, Foo.Pool>().WithInitialSize(5);
var factory = Container.Resolve<Foo.Pool>();
Assert.IsEqual(factory.NumActive, 0);
Assert.IsEqual(factory.NumTotal, 5);
Assert.IsEqual(factory.NumInactive, 5);
}
class Bar
{
public Bar()
{
}
public class Pool : MemoryPool<Bar>
{
}
}
class Foo
{
public Foo()
{
}
public int ResetCount
{
get; private set;
}
public class Pool : MemoryPool<Foo>
{
protected override void OnSpawned(Foo foo)
{
foo.ResetCount++;
}
}
}
[Test]
public void TestSubContainers()
{
Container.BindMemoryPool<Qux, Qux.Pool>()
.FromSubContainerResolve().ByMethod(InstallQux).NonLazy();
var factory = Container.Resolve<Qux.Pool>();
var qux = factory.Spawn();
}
void InstallQux(DiContainer subContainer)
{
subContainer.Bind<Qux>().AsSingle();
}
class Qux
{
public class Pool : MemoryPool<Qux>
{
}
}
[Test]
[ValidateOnly]
public void TestIds()
{
Container.BindMemoryPool<Foo, Foo.Pool>().WithInitialSize(5).WithId("foo");
var pool = Container.ResolveId<Foo.Pool>("foo");
}
}
}
| |
#pragma warning disable 162,108,618
using Casanova.Prelude;
using System.Linq;
using System;
using System.Collections.Generic;
using UnityEngine;
namespace Game {public class World : MonoBehaviour{
public static int frame;
void Update () { Update(Time.deltaTime, this);
frame++; }
public bool JustEntered = true;
public void Start()
{
MainCamera = new MainCamera();
Balls = (
Enumerable.Empty<Ball>()).ToList<Ball>();
}
public List<Ball> __Balls;
public List<Ball> Balls{ get { return __Balls; }
set{ __Balls = value;
foreach(var e in value){if(e.JustEntered){ e.JustEntered = false;
}
} }
}
public MainCamera MainCamera;
System.DateTime init_time = System.DateTime.Now;
public void Update(float dt, World world) {
var t = System.DateTime.Now;
for(int x0 = 0; x0 < Balls.Count; x0++) {
Balls[x0].Update(dt, world);
}
MainCamera.Update(dt, world);
this.Rule0(dt, world);
this.Rule1(dt, world);
}
int s0=-1;
public void Rule0(float dt, World world){
switch (s0)
{
case -1:
Balls = (
(Balls).Select(__ContextSymbol1 => new { ___b00 = __ContextSymbol1 })
.Where(__ContextSymbol2 => ((__ContextSymbol2.___b00.UnityBall.Destroyed) == (false)))
.Select(__ContextSymbol3 => __ContextSymbol3.___b00)
.ToList<Ball>()).ToList<Ball>();
s0 = -1;
return;
default: return;}}
int s1=-1;
public void Rule1(float dt, World world){
switch (s1)
{
case -1:
if(!(UnityEngine.Input.GetKeyDown(KeyCode.Space)))
{
s1 = -1;
return; }else
{
goto case 0; }
case 0:
Balls = new Cons<Ball>(new Ball(MainCamera.Position,MainCamera.Forward), (Balls)).ToList<Ball>();
s1 = -1;
return;
default: return;}}
}
public class MainCamera{
public int frame;
public bool JustEntered = true;
public int ID;
public MainCamera()
{JustEntered = false;
frame = World.frame;
VerticalSpeed = -2f;
UnityCamera = UnityCamera.Find();
MaxVelocity = 2f;
HorizontalSpeed = 2f;
}
public UnityEngine.Vector3 Backward{ get { return UnityCamera.Backward; }
}
public UnityEngine.Vector3 Down{ get { return UnityCamera.Down; }
}
public UnityEngine.Vector3 Forward{ get { return UnityCamera.Forward; }
}
public System.Single HorizontalSpeed;
public UnityEngine.Vector3 Left{ get { return UnityCamera.Left; }
}
public System.Single MaxVelocity;
public UnityEngine.Vector3 Position{ get { return UnityCamera.Position; }
set{UnityCamera.Position = value; }
}
public UnityEngine.Vector3 Right{ get { return UnityCamera.Right; }
}
public UnityEngine.Quaternion Rotation{ get { return UnityCamera.Rotation; }
set{UnityCamera.Rotation = value; }
}
public UnityCamera UnityCamera;
public UnityEngine.Vector3 Up{ get { return UnityCamera.Up; }
}
public System.Single VerticalSpeed;
public System.Boolean enabled{ get { return UnityCamera.enabled; }
set{UnityCamera.enabled = value; }
}
public UnityEngine.GameObject gameObject{ get { return UnityCamera.gameObject; }
}
public UnityEngine.HideFlags hideFlags{ get { return UnityCamera.hideFlags; }
set{UnityCamera.hideFlags = value; }
}
public System.Boolean isActiveAndEnabled{ get { return UnityCamera.isActiveAndEnabled; }
}
public System.String name{ get { return UnityCamera.name; }
set{UnityCamera.name = value; }
}
public System.String tag{ get { return UnityCamera.tag; }
set{UnityCamera.tag = value; }
}
public UnityEngine.Transform transform{ get { return UnityCamera.transform; }
}
public System.Boolean useGUILayout{ get { return UnityCamera.useGUILayout; }
set{UnityCamera.useGUILayout = value; }
}
public void Update(float dt, World world) {
frame = World.frame; this.Rule0(dt, world);
this.Rule1(dt, world);
this.Rule2(dt, world);
this.Rule3(dt, world);
this.Rule4(dt, world);
this.Rule5(dt, world);
this.Rule6(dt, world);
}
public void Rule0(float dt, World world)
{
Rotation = ((UnityEngine.Quaternion.Euler(0f,(UnityEngine.Input.GetAxis("Mouse X")) * (HorizontalSpeed),0f)) * (UnityCamera.Rotation)) * (UnityEngine.Quaternion.Euler((UnityEngine.Input.GetAxis("Mouse Y")) * (VerticalSpeed),0f,0f));
}
int s1=-1;
public void Rule1(float dt, World world){
switch (s1)
{
case -1:
if(!(UnityEngine.Input.GetKey(KeyCode.Q)))
{
s1 = -1;
return; }else
{
goto case 0; }
case 0:
Position = ((Position) + (((((Down) * (dt))) * (MaxVelocity))));
s1 = -1;
return;
default: return;}}
int s2=-1;
public void Rule2(float dt, World world){
switch (s2)
{
case -1:
if(!(UnityEngine.Input.GetKey(KeyCode.E)))
{
s2 = -1;
return; }else
{
goto case 0; }
case 0:
Position = ((Position) + (((((Up) * (dt))) * (MaxVelocity))));
s2 = -1;
return;
default: return;}}
int s3=-1;
public void Rule3(float dt, World world){
switch (s3)
{
case -1:
if(!(UnityEngine.Input.GetKey(KeyCode.S)))
{
s3 = -1;
return; }else
{
goto case 0; }
case 0:
Position = ((Position) + (((((Backward) * (dt))) * (MaxVelocity))));
s3 = -1;
return;
default: return;}}
int s4=-1;
public void Rule4(float dt, World world){
switch (s4)
{
case -1:
if(!(UnityEngine.Input.GetKey(KeyCode.W)))
{
s4 = -1;
return; }else
{
goto case 0; }
case 0:
Position = ((Position) + (((((Forward) * (dt))) * (MaxVelocity))));
s4 = -1;
return;
default: return;}}
int s5=-1;
public void Rule5(float dt, World world){
switch (s5)
{
case -1:
if(!(UnityEngine.Input.GetKey(KeyCode.D)))
{
s5 = -1;
return; }else
{
goto case 0; }
case 0:
Position = ((Position) + (((((Right) * (dt))) * (MaxVelocity))));
s5 = -1;
return;
default: return;}}
int s6=-1;
public void Rule6(float dt, World world){
switch (s6)
{
case -1:
if(!(UnityEngine.Input.GetKey(KeyCode.A)))
{
s6 = -1;
return; }else
{
goto case 0; }
case 0:
Position = ((Position) + (((((Left) * (dt))) * (MaxVelocity))));
s6 = -1;
return;
default: return;}}
}
public class Ball{
public int frame;
public bool JustEntered = true;
private UnityEngine.Vector3 position;
private UnityEngine.Vector3 direction;
public int ID;
public Ball(UnityEngine.Vector3 position, UnityEngine.Vector3 direction)
{JustEntered = false;
frame = World.frame;
UnityBall = UnityBall.Instantiate(direction,position);
}
public System.Boolean Destroyed{ get { return UnityBall.Destroyed; }
set{UnityBall.Destroyed = value; }
}
public UnityEngine.Vector3 Position{ get { return UnityBall.Position; }
set{UnityBall.Position = value; }
}
public UnityBall UnityBall;
public System.Boolean enabled{ get { return UnityBall.enabled; }
set{UnityBall.enabled = value; }
}
public UnityEngine.GameObject gameObject{ get { return UnityBall.gameObject; }
}
public UnityEngine.HideFlags hideFlags{ get { return UnityBall.hideFlags; }
set{UnityBall.hideFlags = value; }
}
public System.Boolean isActiveAndEnabled{ get { return UnityBall.isActiveAndEnabled; }
}
public System.String name{ get { return UnityBall.name; }
set{UnityBall.name = value; }
}
public System.String tag{ get { return UnityBall.tag; }
set{UnityBall.tag = value; }
}
public UnityEngine.Transform transform{ get { return UnityBall.transform; }
}
public System.Boolean useGUILayout{ get { return UnityBall.useGUILayout; }
set{UnityBall.useGUILayout = value; }
}
public void Update(float dt, World world) {
frame = World.frame;
this.Rule0(dt, world);
}
int s0=-1;
public void Rule0(float dt, World world){
switch (s0)
{
case -1:
if(!(((-10f) > (Position.y))))
{
s0 = -1;
return; }else
{
goto case 0; }
case 0:
Destroyed = true;
s0 = -1;
return;
default: return;}}
}
}
| |
using System;
using System.Runtime.InteropServices;
namespace BlackBerry
{
public class Navigator : IDisposable
{
public enum EventType {
NAVIGATOR_INVOKE = 0x01,
NAVIGATOR_EXIT = 0x02,
NAVIGATOR_WINDOW_STATE = 0x03,
NAVIGATOR_SWIPE_DOWN = 0x04,
NAVIGATOR_SWIPE_START = 0x05,
NAVIGATOR_LOW_MEMORY = 0x06,
NAVIGATOR_ORIENTATION_CHECK = 0x07,
NAVIGATOR_ORIENTATION = 0x08,
NAVIGATOR_BACK = 0x09,
NAVIGATOR_WINDOW_ACTIVE = 0x0a,
NAVIGATOR_WINDOW_INACTIVE = 0x0b,
NAVIGATOR_ORIENTATION_DONE = 0x0c,
NAVIGATOR_ORIENTATION_RESULT = 0x0d,
NAVIGATOR_WINDOW_LOCK = 0x0e,
NAVIGATOR_WINDOW_UNLOCK = 0x0f,
NAVIGATOR_INVOKE_TARGET = 0x10,
NAVIGATOR_INVOKE_QUERY_RESULT = 0x11,
NAVIGATOR_INVOKE_VIEWER = 0x12,
NAVIGATOR_INVOKE_TARGET_RESULT = 0x13,
NAVIGATOR_INVOKE_VIEWER_RESULT = 0x14,
NAVIGATOR_INVOKE_VIEWER_RELAY = 0x15,
NAVIGATOR_INVOKE_VIEWER_STOPPED = 0x16,
NAVIGATOR_KEYBOARD_STATE = 0x17,
NAVIGATOR_KEYBOARD_POSITION = 0x18,
NAVIGATOR_INVOKE_VIEWER_RELAY_RESULT = 0x19,
NAVIGATOR_DEVICE_LOCK_STATE = 0x1a,
NAVIGATOR_WINDOW_COVER = 0x1b,
NAVIGATOR_WINDOW_COVER_ENTER = 0x1c,
NAVIGATOR_WINDOW_COVER_EXIT = 0x1d,
NAVIGATOR_CARD_PEEK_STARTED = 0x1e,
NAVIGATOR_CARD_PEEK_STOPPED = 0x1f,
NAVIGATOR_CARD_RESIZE = 0x20,
NAVIGATOR_CHILD_CARD_CLOSED = 0x21,
NAVIGATOR_CARD_CLOSED = 0x22,
NAVIGATOR_INVOKE_GET_FILTERS_RESULT = 0x23,
NAVIGATOR_APP_STATE = 0x24,
NAVIGATOR_INVOKE_SET_FILTERS_RESULT = 0x25,
NAVIGATOR_PEEK_STARTED = 0x26,
NAVIGATOR_PEEK_STOPPED = 0x27,
NAVIGATOR_CARD_READY_CHECK = 0x28,
NAVIGATOR_POOLED = 0x29,
NAVIGATOR_OTHER = 0xff
}
public enum BadgeType {
Splat = 0
}
public enum ScreenOrientation {
Landscape = 0,
Portrait = 1
}
public enum ApplicationOrientation {
TopUp = 0,
RightUp = 90,
BottomUp = 180,
LeftUp = 270
}
[DllImport ("bps")]
static extern int navigator_request_events (int flags);
[DllImport ("bps")]
static extern int navigator_stop_events (int flags);
[DllImport ("bps")]
static extern int navigator_invoke(string uri,
/*out*/ IntPtr err);
[DllImport ("bps")]
static extern int navigator_add_uri(string icon_path,
string icon_label,
string default_category,
string url,
/*out*/ IntPtr err);
[DllImport ("bps")]
static extern int navigator_clear_badge ();
[DllImport ("bps")]
static extern int navigator_set_badge (BadgeType badge);
[DllImport ("bps")]
static extern int navigator_get_domain ();
[DllImport ("bps")]
static extern int navigator_set_orientation (ApplicationOrientation angle, IntPtr id);
[DllImport ("bsp")]
static extern int navigator_set_orientation_mode (ScreenOrientation mode, IntPtr id);
[DllImport ("bsp")]
static extern int navigator_set_lock_mode (bool locked);
private int eventDomain = 0;
private const int ALL_EVENTS = 0;
public Action OnExit;
public Action OnSwipeDown;
public Action<InvokeTargetReply> OnInvokeResult;
public Navigator ()
{
PlatformServices.Initialize ();
RequestEvents = true;
}
public bool RequestEvents {
get {
return eventDomain != 0;
}
set {
if (value && eventDomain == 0) {
navigator_request_events (ALL_EVENTS);
eventDomain = navigator_get_domain ();
PlatformServices.AddEventHandler (eventDomain, HandleEvent);
} else {
navigator_stop_events (ALL_EVENTS);
PlatformServices.RemoveEventHandler (eventDomain);
eventDomain = 0;
}
}
}
public void AddUri (string iconPath, string iconLabel, string defaultCategory, string url)
{
navigator_add_uri (iconPath, iconLabel, defaultCategory, url, IntPtr.Zero);
}
public void Invoke (string uri)
{
navigator_invoke (uri, IntPtr.Zero);
}
public void Invoke (InvokeRequest invocation)
{
InvokeRequest.navigator_invoke_invocation_send (invocation.handle);
}
public bool HasBadge {
set {
if (value) {
navigator_set_badge (BadgeType.Splat);
} else {
navigator_clear_badge ();
}
}
}
void HandleEvent (IntPtr eventHandle)
{
var type = (EventType)new Event (eventHandle).Code;
switch (type) {
case EventType.NAVIGATOR_LOW_MEMORY:
Console.WriteLine ("Navigator is afraid the mem could be too low, running GC.");
GC.Collect();
GC.WaitForPendingFinalizers();
break;
case EventType.NAVIGATOR_EXIT:
if (OnExit != null) {
OnExit ();
}
break;
case EventType.NAVIGATOR_SWIPE_DOWN:
if (OnSwipeDown != null) {
OnSwipeDown ();
}
break;
case EventType.NAVIGATOR_INVOKE_TARGET_RESULT:
if (OnInvokeResult != null) {
OnInvokeResult (new InvokeTargetReply (eventHandle));
}
break;
default:
Console.WriteLine ("UNHANDLED NAVIGATOR EVENT, TYPE: {0}", type);
break;
}
}
public void Dispose ()
{
PlatformServices.RemoveEventHandler (eventDomain);
}
public void SetOrientation (ScreenOrientation mode)
{
navigator_set_orientation_mode (mode, IntPtr.Zero);
}
public void SetOrientation (ApplicationOrientation angle)
{
navigator_set_orientation (angle, IntPtr.Zero);
}
public bool OrientationLock {
set {
navigator_set_lock_mode (value);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using NDesk.Options;
using GitTfs.Core;
using GitTfs.Util;
using StructureMap;
namespace GitTfs.Commands
{
[Pluggable("fetch")]
[Description("fetch [options] [tfs-remote-id]...")]
[RequiresValidGitRepository]
public class Fetch : GitTfsCommand
{
private readonly RemoteOptions _remoteOptions;
private readonly Globals _globals;
private readonly ConfigProperties _properties;
private readonly Labels _labels;
public Fetch(Globals globals, ConfigProperties properties, RemoteOptions remoteOptions, Labels labels)
{
_globals = globals;
_properties = properties;
_remoteOptions = remoteOptions;
_labels = labels;
upToChangeSet = -1;
BranchStrategy = BranchStrategy = BranchStrategy.Auto;
}
private bool FetchAll { get; set; }
private bool FetchLabels { get; set; }
private bool FetchParents { get; set; }
private bool IgnoreRestrictedChangesets { get; set; }
private string BareBranch { get; set; }
private bool ForceFetch { get; set; }
private bool ExportMetadatas { get; set; }
private string ExportMetadatasFile { get; set; }
public BranchStrategy BranchStrategy { get; set; }
private string IgnoreBranchesRegex { get; set; }
private bool IgnoreNotInitBranches { get; set; }
public string BatchSizeOption
{
set
{
int batchSize;
if (!int.TryParse(value, out batchSize))
throw new GitTfsException("error: batch size parameter should be an integer.");
_properties.BatchSize = batchSize;
}
}
private int upToChangeSet { get; set; }
public string UpToChangeSetOption
{
set
{
int changesetIdParsed;
if (!int.TryParse(value, out changesetIdParsed))
throw new GitTfsException("error: 'up-to' parameter should be an integer.");
upToChangeSet = changesetIdParsed;
}
}
protected int? InitialChangeset { get; set; }
public virtual OptionSet OptionSet
{
get
{
return new OptionSet
{
{ "all|fetch-all", "Fetch TFS changesets of all the initialized tfs remotes",
v => FetchAll = v != null },
{ "parents", "Fetch TFS changesets of the parent(s) initialized tfs remotes",
v => FetchParents = v != null },
{ "l|with-labels|fetch-labels", "Fetch the labels also when fetching TFS changesets",
v => FetchLabels = v != null },
{ "b|bare-branch=", "The name of the branch on which the fetch will be done for a bare repository",
v => BareBranch = v },
{ "force", "Force fetch of tfs changesets when there is ahead commits (ahead commits will be lost!)",
v => ForceFetch = v != null },
{ "x|export", "Export metadata",
v => ExportMetadatas = v != null },
{ "export-work-item-mapping=", "Path to Work-items mapping export file",
v => ExportMetadatasFile = v },
{ "branches=", "Strategy to manage branches:"+
Environment.NewLine + "* auto:(default) Manage the encountered merged changesets and initialize only the merged branches"+
Environment.NewLine + "* none: Ignore branches and merge changesets, fetching only the cloned tfs path"+
Environment.NewLine + "* all: Manage merged changesets and initialize all the branches during the clone",
v =>
{
BranchStrategy branchStrategy;
if (Enum.TryParse(v, true, out branchStrategy))
BranchStrategy = branchStrategy;
else
throw new GitTfsException("error: 'branches' parameter should be of value none/auto/all.");
} },
{ "batch-size=", "Size of the batch of tfs changesets fetched (-1 for all in one batch)",
v => BatchSizeOption = v },
{ "c|changeset|from=", "The changeset to clone from (must be a number)",
v => InitialChangeset = Convert.ToInt32(v) },
{ "t|up-to|to=", "up-to changeset # (optional, -1 for up to maximum, must be a number, not prefixed with 'C')",
v => UpToChangeSetOption = v },
{ "ignore-branches-regex=", "Don't initialize branches that match given regex",
v => IgnoreBranchesRegex = v },
{ "ignore-not-init-branches", "Ignore not-initialized branches",
v => IgnoreNotInitBranches = v != null },
{ "ignore-restricted-changesets", "Ignore restricted changesets",
v => IgnoreRestrictedChangesets = v != null }
}.Merge(_remoteOptions.OptionSet);
}
}
public int Run()
{
return Run(_globals.RemoteId);
}
public void Run(bool stopOnFailMergeCommit)
{
Run(stopOnFailMergeCommit, _globals.RemoteId);
}
public int Run(params string[] args)
{
return Run(false, args);
}
private int Run(bool stopOnFailMergeCommit, params string[] args)
{
if (!FetchAll && BranchStrategy == BranchStrategy.None)
_globals.Repository.SetConfig(GitTfsConstants.IgnoreBranches, true);
if(!string.IsNullOrEmpty(IgnoreBranchesRegex))
_globals.Repository.SetConfig(GitTfsConstants.IgnoreBranchesRegex, IgnoreBranchesRegex);
_globals.Repository.SetConfig(GitTfsConstants.IgnoreNotInitBranches, IgnoreNotInitBranches);
var remotesToFetch = GetRemotesToFetch(args).ToList();
foreach (var remote in remotesToFetch)
{
FetchRemote(stopOnFailMergeCommit, remote);
}
return 0;
}
private void FetchRemote(bool stopOnFailMergeCommit, IGitTfsRemote remote)
{
Trace.TraceInformation("Fetching from TFS remote '{0}'...", remote.Id);
DoFetch(remote, stopOnFailMergeCommit);
if (_labels != null && FetchLabels)
{
Trace.TraceInformation("Fetching labels from TFS remote '{0}'...", remote.Id);
_labels.Run(remote);
}
}
protected virtual void DoFetch(IGitTfsRemote remote, bool stopOnFailMergeCommit)
{
if (upToChangeSet != -1 && InitialChangeset.HasValue && InitialChangeset.Value > upToChangeSet)
throw new GitTfsException("error: up-to changeset # must not be less than the initial one");
var bareBranch = string.IsNullOrEmpty(BareBranch) ? remote.Id : BareBranch;
// It is possible that we have outdated refs/remotes/tfs/<id>.
// E.g. someone already fetched changesets from TFS into another git repository and we've pulled it since
// in that case tfs fetch will retrieve same changes again unnecessarily. To prevent it we will scan tree from HEAD and see if newer changesets from
// TFS exists (by checking git-tfs-id mark in commit's comments).
// The process is similar to bootstrapping.
if (!ForceFetch)
{
if (!remote.Repository.IsBare)
remote.Repository.MoveTfsRefForwardIfNeeded(remote);
else
remote.Repository.MoveTfsRefForwardIfNeeded(remote, bareBranch);
}
if (!ForceFetch &&
remote.Repository.IsBare &&
remote.Repository.HasRef(GitRepository.ShortToLocalName(bareBranch)) &&
remote.MaxCommitHash != remote.Repository.GetCommit(bareBranch).Sha)
{
throw new GitTfsException("error : fetch is not allowed when there is ahead commits!",
new[] { "Remove ahead commits and retry", "use the --force option (ahead commits will be lost!)" });
}
var metadataExportInitializer = new ExportMetadatasInitializer(_globals);
bool shouldExport = ExportMetadatas || remote.Repository.GetConfig(GitTfsConstants.ExportMetadatasConfigKey) == "true";
if (ExportMetadatas)
{
metadataExportInitializer.InitializeConfig(remote.Repository, ExportMetadatasFile);
}
metadataExportInitializer.InitializeRemote(remote, shouldExport);
try
{
if (InitialChangeset.HasValue)
{
_properties.InitialChangeset = InitialChangeset.Value;
_properties.PersistAllOverrides();
remote.QuickFetch(InitialChangeset.Value, IgnoreRestrictedChangesets);
remote.Fetch(stopOnFailMergeCommit, upToChangeSet);
}
else
{
remote.Fetch(stopOnFailMergeCommit, upToChangeSet);
}
}
finally
{
Trace.WriteLine("Cleaning...");
remote.CleanupWorkspaceDirectory();
if (remote.Repository.IsBare)
remote.Repository.UpdateRef(GitRepository.ShortToLocalName(bareBranch), remote.MaxCommitHash);
}
}
private IEnumerable<IGitTfsRemote> GetRemotesToFetch(IList<string> args)
{
IEnumerable<IGitTfsRemote> remotesToFetch;
if (FetchParents)
remotesToFetch = _globals.Repository.GetLastParentTfsCommits("HEAD").Select(commit => commit.Remote);
else if (FetchAll)
remotesToFetch = _globals.Repository.ReadAllTfsRemotes();
else
remotesToFetch = args.Select(arg => _globals.Repository.ReadTfsRemote(arg));
return remotesToFetch;
}
}
public enum BranchStrategy
{
None,
Auto,
All
}
}
| |
// 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.Reflection;
using Xunit;
namespace System.Linq.Expressions.Tests
{
public class PreIncrementAssignTests : IncDecAssignTests
{
[Theory]
[PerCompilationType(nameof(Int16sAndIncrements))]
[PerCompilationType(nameof(NullableInt16sAndIncrements))]
[PerCompilationType(nameof(UInt16sAndIncrements))]
[PerCompilationType(nameof(NullableUInt16sAndIncrements))]
[PerCompilationType(nameof(Int32sAndIncrements))]
[PerCompilationType(nameof(NullableInt32sAndIncrements))]
[PerCompilationType(nameof(UInt32sAndIncrements))]
[PerCompilationType(nameof(NullableUInt32sAndIncrements))]
[PerCompilationType(nameof(Int64sAndIncrements))]
[PerCompilationType(nameof(NullableInt64sAndIncrements))]
[PerCompilationType(nameof(UInt64sAndIncrements))]
[PerCompilationType(nameof(NullableUInt64sAndIncrements))]
[PerCompilationType(nameof(DecimalsAndIncrements))]
[PerCompilationType(nameof(NullableDecimalsAndIncrements))]
[PerCompilationType(nameof(SinglesAndIncrements))]
[PerCompilationType(nameof(NullableSinglesAndIncrements))]
[PerCompilationType(nameof(DoublesAndIncrements))]
[PerCompilationType(nameof(NullableDoublesAndIncrements))]
public void ReturnsCorrectValues(Type type, object value, object result, bool useInterpreter)
{
ParameterExpression variable = Expression.Variable(type);
BlockExpression block = Expression.Block(
new[] { variable },
Expression.Assign(variable, Expression.Constant(value, type)),
Expression.PreIncrementAssign(variable)
);
Assert.True(Expression.Lambda<Func<bool>>(Expression.Equal(Expression.Constant(result, type), block)).Compile(useInterpreter)());
}
[Theory]
[PerCompilationType(nameof(Int16sAndIncrements))]
[PerCompilationType(nameof(NullableInt16sAndIncrements))]
[PerCompilationType(nameof(UInt16sAndIncrements))]
[PerCompilationType(nameof(NullableUInt16sAndIncrements))]
[PerCompilationType(nameof(Int32sAndIncrements))]
[PerCompilationType(nameof(NullableInt32sAndIncrements))]
[PerCompilationType(nameof(UInt32sAndIncrements))]
[PerCompilationType(nameof(NullableUInt32sAndIncrements))]
[PerCompilationType(nameof(Int64sAndIncrements))]
[PerCompilationType(nameof(NullableInt64sAndIncrements))]
[PerCompilationType(nameof(UInt64sAndIncrements))]
[PerCompilationType(nameof(NullableUInt64sAndIncrements))]
[PerCompilationType(nameof(DecimalsAndIncrements))]
[PerCompilationType(nameof(NullableDecimalsAndIncrements))]
[PerCompilationType(nameof(SinglesAndIncrements))]
[PerCompilationType(nameof(NullableSinglesAndIncrements))]
[PerCompilationType(nameof(DoublesAndIncrements))]
[PerCompilationType(nameof(NullableDoublesAndIncrements))]
public void AssignsCorrectValues(Type type, object value, object result, bool useInterpreter)
{
ParameterExpression variable = Expression.Variable(type);
LabelTarget target = Expression.Label(type);
BlockExpression block = Expression.Block(
new[] { variable },
Expression.Assign(variable, Expression.Constant(value, type)),
Expression.PreIncrementAssign(variable),
Expression.Return(target, variable),
Expression.Label(target, Expression.Default(type))
);
Assert.True(Expression.Lambda<Func<bool>>(Expression.Equal(Expression.Constant(result, type), block)).Compile(useInterpreter)());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void SingleNanToNan(bool useInterpreter)
{
TestPropertyClass<float> instance = new TestPropertyClass<float>();
instance.TestInstance = float.NaN;
Assert.True(float.IsNaN(
Expression.Lambda<Func<float>>(
Expression.PreIncrementAssign(
Expression.Property(
Expression.Constant(instance),
typeof(TestPropertyClass<float>),
"TestInstance"
)
)
).Compile(useInterpreter)()
));
Assert.True(float.IsNaN(instance.TestInstance));
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void DoubleNanToNan(bool useInterpreter)
{
TestPropertyClass<double> instance = new TestPropertyClass<double>();
instance.TestInstance = double.NaN;
Assert.True(double.IsNaN(
Expression.Lambda<Func<double>>(
Expression.PreIncrementAssign(
Expression.Property(
Expression.Constant(instance),
typeof(TestPropertyClass<double>),
"TestInstance"
)
)
).Compile(useInterpreter)()
));
Assert.True(double.IsNaN(instance.TestInstance));
}
[Theory]
[PerCompilationType(nameof(IncrementOverflowingValues))]
public void OverflowingValuesThrow(object value, bool useInterpreter)
{
ParameterExpression variable = Expression.Variable(value.GetType());
Action overflow = Expression.Lambda<Action>(
Expression.Block(
typeof(void),
new[] { variable },
Expression.Assign(variable, Expression.Constant(value)),
Expression.PreIncrementAssign(variable)
)
).Compile(useInterpreter);
Assert.Throws<OverflowException>(overflow);
}
[Theory]
[MemberData(nameof(UnincrementableAndUndecrementableTypes))]
public void InvalidOperandType(Type type)
{
ParameterExpression variable = Expression.Variable(type);
Assert.Throws<InvalidOperationException>(() => Expression.PreIncrementAssign(variable));
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void MethodCorrectResult(bool useInterpreter)
{
ParameterExpression variable = Expression.Variable(typeof(string));
BlockExpression block = Expression.Block(
new[] { variable },
Expression.Assign(variable, Expression.Constant("hello")),
Expression.PreIncrementAssign(variable, typeof(IncDecAssignTests).GetTypeInfo().GetDeclaredMethod("SillyMethod"))
);
Assert.Equal("Eggplant", Expression.Lambda<Func<string>>(block).Compile(useInterpreter)());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void MethodCorrectAssign(bool useInterpreter)
{
ParameterExpression variable = Expression.Variable(typeof(string));
LabelTarget target = Expression.Label(typeof(string));
BlockExpression block = Expression.Block(
new[] { variable },
Expression.Assign(variable, Expression.Constant("hello")),
Expression.PreIncrementAssign(variable, typeof(IncDecAssignTests).GetTypeInfo().GetDeclaredMethod("SillyMethod")),
Expression.Return(target, variable),
Expression.Label(target, Expression.Default(typeof(string)))
);
Assert.Equal("Eggplant", Expression.Lambda<Func<string>>(block).Compile(useInterpreter)());
}
[Fact]
public void IncorrectMethodType()
{
Expression variable = Expression.Variable(typeof(int));
MethodInfo method = typeof(IncDecAssignTests).GetTypeInfo().GetDeclaredMethod("SillyMethod");
Assert.Throws<InvalidOperationException>(() => Expression.PreIncrementAssign(variable, method));
}
[Fact]
public void IncorrectMethodParameterCount()
{
Expression variable = Expression.Variable(typeof(string));
MethodInfo method = typeof(object).GetTypeInfo().GetDeclaredMethod("ReferenceEquals");
Assert.Throws<ArgumentException>("method", () => Expression.PreIncrementAssign(variable, method));
}
[Fact]
public void IncorrectMethodReturnType()
{
Expression variable = Expression.Variable(typeof(int));
MethodInfo method = typeof(IncDecAssignTests).GetTypeInfo().GetDeclaredMethod("GetString");
Assert.Throws<ArgumentException>(null, () => Expression.PreIncrementAssign(variable, method));
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void StaticMemberAccessCorrect(bool useInterpreter)
{
TestPropertyClass<uint>.TestStatic = 2U;
Assert.Equal(
3U,
Expression.Lambda<Func<uint>>(
Expression.PreIncrementAssign(
Expression.Property(null, typeof(TestPropertyClass<uint>), "TestStatic")
)
).Compile(useInterpreter)()
);
Assert.Equal(3U, TestPropertyClass<uint>.TestStatic);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void InstanceMemberAccessCorrect(bool useInterpreter)
{
TestPropertyClass<int> instance = new TestPropertyClass<int>();
instance.TestInstance = 2;
Assert.Equal(
3,
Expression.Lambda<Func<int>>(
Expression.PreIncrementAssign(
Expression.Property(
Expression.Constant(instance),
typeof(TestPropertyClass<int>),
"TestInstance"
)
)
).Compile(useInterpreter)()
);
Assert.Equal(3, instance.TestInstance);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void ArrayAccessCorrect(bool useInterpreter)
{
int[] array = new int[1];
array[0] = 2;
Assert.Equal(
3,
Expression.Lambda<Func<int>>(
Expression.PreIncrementAssign(
Expression.ArrayAccess(Expression.Constant(array), Expression.Constant(0))
)
).Compile(useInterpreter)()
);
Assert.Equal(3, array[0]);
}
[Fact]
public void CanReduce()
{
ParameterExpression variable = Expression.Variable(typeof(int));
UnaryExpression op = Expression.PreIncrementAssign(variable);
Assert.True(op.CanReduce);
Assert.NotSame(op, op.ReduceAndCheck());
}
[Fact]
public void NullOperand()
{
Assert.Throws<ArgumentNullException>("expression", () => Expression.PreIncrementAssign(null));
}
[Fact]
public void UnwritableOperand()
{
Assert.Throws<ArgumentException>("expression", () => Expression.PreIncrementAssign(Expression.Constant(1)));
}
[Fact]
public void UnreadableOperand()
{
Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly");
Assert.Throws<ArgumentException>("expression", () => Expression.PreIncrementAssign(value));
}
[Fact]
public void UpdateSameOperandSameNode()
{
UnaryExpression op = Expression.PreIncrementAssign(Expression.Variable(typeof(int)));
Assert.Same(op, op.Update(op.Operand));
Assert.Same(op, NoOpVisitor.Instance.Visit(op));
}
[Fact]
public void UpdateDiffOperandDiffNode()
{
UnaryExpression op = Expression.PreIncrementAssign(Expression.Variable(typeof(int)));
Assert.NotSame(op, op.Update(Expression.Variable(typeof(int))));
}
[Fact]
public void ToStringTest()
{
UnaryExpression e = Expression.PreIncrementAssign(Expression.Parameter(typeof(int), "x"));
Assert.Equal("++x", e.ToString());
}
}
}
| |
// 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.
namespace System.Xml.Serialization
{
using System.Reflection;
using System.Collections;
using System.IO;
using System.Xml.Schema;
using System;
using System.Text;
using System.Threading;
using System.Globalization;
using System.Security;
using System.Xml.Serialization.Configuration;
using System.Diagnostics;
using System.Collections.Generic;
using System.Runtime.Versioning;
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlDeserializationEvents"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public struct XmlDeserializationEvents
{
private XmlNodeEventHandler _onUnknownNode;
private XmlAttributeEventHandler _onUnknownAttribute;
private XmlElementEventHandler _onUnknownElement;
private UnreferencedObjectEventHandler _onUnreferencedObject;
internal object sender;
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlDeserializationEvents.OnUnknownNode"]/*' />
public XmlNodeEventHandler OnUnknownNode
{
get
{
return _onUnknownNode;
}
set
{
_onUnknownNode = value;
}
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlDeserializationEvents.OnUnknownAttribute"]/*' />
public XmlAttributeEventHandler OnUnknownAttribute
{
get
{
return _onUnknownAttribute;
}
set
{
_onUnknownAttribute = value;
}
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlDeserializationEvents.OnUnknownElement"]/*' />
public XmlElementEventHandler OnUnknownElement
{
get
{
return _onUnknownElement;
}
set
{
_onUnknownElement = value;
}
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlDeserializationEvents.OnUnreferencedObject"]/*' />
public UnreferencedObjectEventHandler OnUnreferencedObject
{
get
{
return _onUnreferencedObject;
}
set
{
_onUnreferencedObject = value;
}
}
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation"]/*' />
///<internalonly/>
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public abstract class XmlSerializerImplementation
{
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation.Reader"]/*' />
public virtual XmlSerializationReader Reader { get { throw new NotSupportedException(); } }
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation.Writer"]/*' />
public virtual XmlSerializationWriter Writer { get { throw new NotSupportedException(); } }
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation.ReadMethods"]/*' />
public virtual Hashtable ReadMethods { get { throw new NotSupportedException(); } }
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation.WriteMethods"]/*' />
public virtual Hashtable WriteMethods { get { throw new NotSupportedException(); } }
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation.TypedSerializers"]/*' />
public virtual Hashtable TypedSerializers { get { throw new NotSupportedException(); } }
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation.CanSerialize"]/*' />
public virtual bool CanSerialize(Type type) { throw new NotSupportedException(); }
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializerImplementation.GetSerializer"]/*' />
public virtual XmlSerializer GetSerializer(Type type) { throw new NotSupportedException(); }
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public class XmlSerializer
{
internal enum SerializationMode
{
CodeGenOnly,
ReflectionOnly,
ReflectionAsBackup
}
internal static SerializationMode Mode { get; set; } = SerializationMode.ReflectionAsBackup;
private static bool ReflectionMethodEnabled
{
get
{
return Mode == SerializationMode.ReflectionOnly || Mode == SerializationMode.ReflectionAsBackup;
}
}
private TempAssembly _tempAssembly;
#pragma warning disable 0414
private bool _typedSerializer;
#pragma warning restore 0414
private Type _primitiveType;
private XmlMapping _mapping;
private XmlDeserializationEvents _events = new XmlDeserializationEvents();
#if uapaot
private XmlSerializer innerSerializer;
public string DefaultNamespace = null;
#else
internal string DefaultNamespace = null;
#endif
private Type rootType;
private static TempAssemblyCache s_cache = new TempAssemblyCache();
private static volatile XmlSerializerNamespaces s_defaultNamespaces;
private static XmlSerializerNamespaces DefaultNamespaces
{
get
{
if (s_defaultNamespaces == null)
{
XmlSerializerNamespaces nss = new XmlSerializerNamespaces();
nss.AddInternal("xsi", XmlSchema.InstanceNamespace);
nss.AddInternal("xsd", XmlSchema.Namespace);
if (s_defaultNamespaces == null)
{
s_defaultNamespaces = nss;
}
}
return s_defaultNamespaces;
}
}
private static readonly Dictionary<Type, Dictionary<XmlSerializerMappingKey, XmlSerializer>> s_xmlSerializerTable = new Dictionary<Type, Dictionary<XmlSerializerMappingKey, XmlSerializer>>();
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer8"]/*' />
///<internalonly/>
protected XmlSerializer()
{
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public XmlSerializer(Type type, XmlAttributeOverrides overrides, Type[] extraTypes, XmlRootAttribute root, string defaultNamespace) :
this(type, overrides, extraTypes, root, defaultNamespace, null)
{
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer2"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public XmlSerializer(Type type, XmlRootAttribute root) : this(type, null, Array.Empty<Type>(), root, null, null)
{
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer3"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
#if !uapaot
public XmlSerializer(Type type, Type[] extraTypes) : this(type, null, extraTypes, null, null, null)
#else
public XmlSerializer(Type type, Type[] extraTypes) : this(type)
#endif
{
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer4"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public XmlSerializer(Type type, XmlAttributeOverrides overrides) : this(type, overrides, Array.Empty<Type>(), null, null, null)
{
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer5"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public XmlSerializer(XmlTypeMapping xmlTypeMapping)
{
if (xmlTypeMapping == null)
throw new ArgumentNullException(nameof(xmlTypeMapping));
#if !uapaot
_tempAssembly = GenerateTempAssembly(xmlTypeMapping);
#endif
_mapping = xmlTypeMapping;
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer6"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public XmlSerializer(Type type) : this(type, (string)null)
{
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer1"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public XmlSerializer(Type type, string defaultNamespace)
{
if (type == null)
throw new ArgumentNullException(nameof(type));
DefaultNamespace = defaultNamespace;
rootType = type;
_mapping = GetKnownMapping(type, defaultNamespace);
if (_mapping != null)
{
_primitiveType = type;
return;
}
#if !uapaot
_tempAssembly = s_cache[defaultNamespace, type];
if (_tempAssembly == null)
{
lock (s_cache)
{
_tempAssembly = s_cache[defaultNamespace, type];
if (_tempAssembly == null)
{
{
// need to reflect and generate new serialization assembly
XmlReflectionImporter importer = new XmlReflectionImporter(defaultNamespace);
_mapping = importer.ImportTypeMapping(type, null, defaultNamespace);
_tempAssembly = GenerateTempAssembly(_mapping, type, defaultNamespace);
}
}
s_cache.Add(defaultNamespace, type, _tempAssembly);
}
}
if (_mapping == null)
{
_mapping = XmlReflectionImporter.GetTopLevelMapping(type, defaultNamespace);
}
#else
XmlSerializerImplementation contract = GetXmlSerializerContractFromGeneratedAssembly();
if (contract != null)
{
this.innerSerializer = contract.GetSerializer(type);
}
else if (ReflectionMethodEnabled)
{
var importer = new XmlReflectionImporter(defaultNamespace);
_mapping = importer.ImportTypeMapping(type, null, defaultNamespace);
if (_mapping == null)
{
_mapping = XmlReflectionImporter.GetTopLevelMapping(type, defaultNamespace);
}
}
#endif
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer7"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public XmlSerializer(Type type, XmlAttributeOverrides overrides, Type[] extraTypes, XmlRootAttribute root, string defaultNamespace, string location)
{
if (type == null)
throw new ArgumentNullException(nameof(type));
DefaultNamespace = defaultNamespace;
rootType = type;
XmlReflectionImporter importer = new XmlReflectionImporter(overrides, defaultNamespace);
if (extraTypes != null)
{
for (int i = 0; i < extraTypes.Length; i++)
importer.IncludeType(extraTypes[i]);
}
_mapping = importer.ImportTypeMapping(type, root, defaultNamespace);
if (location != null)
{
DemandForUserLocationOrEvidence();
}
#if !uapaot
_tempAssembly = GenerateTempAssembly(_mapping, type, defaultNamespace, location);
#endif
}
private void DemandForUserLocationOrEvidence()
{
// Ensure full trust before asserting full file access to the user-provided location or evidence
}
internal static TempAssembly GenerateTempAssembly(XmlMapping xmlMapping)
{
return GenerateTempAssembly(xmlMapping, null, null);
}
internal static TempAssembly GenerateTempAssembly(XmlMapping xmlMapping, Type type, string defaultNamespace)
{
return GenerateTempAssembly(xmlMapping, type, defaultNamespace, null);
}
internal static TempAssembly GenerateTempAssembly(XmlMapping xmlMapping, Type type, string defaultNamespace, string location)
{
if (xmlMapping == null)
{
throw new ArgumentNullException(nameof(xmlMapping));
}
xmlMapping.CheckShallow();
if (xmlMapping.IsSoap)
{
return null;
}
return new TempAssembly(new XmlMapping[] { xmlMapping }, new Type[] { type }, defaultNamespace, location);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void Serialize(TextWriter textWriter, object o)
{
Serialize(textWriter, o, null);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize1"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void Serialize(TextWriter textWriter, object o, XmlSerializerNamespaces namespaces)
{
XmlTextWriter xmlWriter = new XmlTextWriter(textWriter);
xmlWriter.Formatting = Formatting.Indented;
xmlWriter.Indentation = 2;
Serialize(xmlWriter, o, namespaces);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize2"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void Serialize(Stream stream, object o)
{
Serialize(stream, o, null);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize3"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void Serialize(Stream stream, object o, XmlSerializerNamespaces namespaces)
{
XmlTextWriter xmlWriter = new XmlTextWriter(stream, null);
xmlWriter.Formatting = Formatting.Indented;
xmlWriter.Indentation = 2;
Serialize(xmlWriter, o, namespaces);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize4"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void Serialize(XmlWriter xmlWriter, object o)
{
Serialize(xmlWriter, o, null);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize5"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void Serialize(XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces)
{
Serialize(xmlWriter, o, namespaces, null);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize6"]/*' />
public void Serialize(XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces, string encodingStyle)
{
Serialize(xmlWriter, o, namespaces, encodingStyle, null);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize6"]/*' />
public void Serialize(XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces, string encodingStyle, string id)
{
try
{
if (_primitiveType != null)
{
if (encodingStyle != null && encodingStyle.Length > 0)
{
throw new InvalidOperationException(SR.Format(SR.XmlInvalidEncodingNotEncoded1, encodingStyle));
}
SerializePrimitive(xmlWriter, o, namespaces);
}
#if !uapaot
else if (ShouldUseReflectionBasedSerialization())
{
XmlMapping mapping;
if (_mapping != null && _mapping.GenerateSerializer)
{
mapping = _mapping;
}
else
{
XmlReflectionImporter importer = new XmlReflectionImporter(DefaultNamespace);
mapping = importer.ImportTypeMapping(rootType, null, DefaultNamespace);
}
var writer = new ReflectionXmlSerializationWriter(mapping, xmlWriter, namespaces == null || namespaces.Count == 0 ? DefaultNamespaces : namespaces, encodingStyle, id);
writer.WriteObject(o);
}
else if (_tempAssembly == null || _typedSerializer)
{
// The contion for the block is never true, thus the block is never hit.
XmlSerializationWriter writer = CreateWriter();
writer.Init(xmlWriter, namespaces == null || namespaces.Count == 0 ? DefaultNamespaces : namespaces, encodingStyle, id, _tempAssembly);
try
{
Serialize(o, writer);
}
finally
{
writer.Dispose();
}
}
else
_tempAssembly.InvokeWriter(_mapping, xmlWriter, o, namespaces == null || namespaces.Count == 0 ? DefaultNamespaces : namespaces, encodingStyle, id);
#else
else
{
if (this.innerSerializer != null)
{
if (!string.IsNullOrEmpty(this.DefaultNamespace))
{
this.innerSerializer.DefaultNamespace = this.DefaultNamespace;
}
XmlSerializationWriter writer = this.innerSerializer.CreateWriter();
writer.Init(xmlWriter, namespaces == null || namespaces.Count == 0 ? DefaultNamespaces : namespaces, encodingStyle, id);
try
{
this.innerSerializer.Serialize(o, writer);
}
finally
{
writer.Dispose();
}
}
else if (ReflectionMethodEnabled)
{
XmlMapping mapping;
if (_mapping != null && _mapping.GenerateSerializer)
{
mapping = _mapping;
}
else
{
XmlReflectionImporter importer = new XmlReflectionImporter(DefaultNamespace);
mapping = importer.ImportTypeMapping(rootType, null, DefaultNamespace);
}
var writer = new ReflectionXmlSerializationWriter(mapping, xmlWriter, namespaces == null || namespaces.Count == 0 ? DefaultNamespaces : namespaces, encodingStyle, id);
writer.WriteObject(o);
}
else
{
throw new InvalidOperationException(SR.Format(SR.Xml_MissingSerializationCodeException, this.rootType, typeof(XmlSerializer).Name));
}
}
#endif
}
catch (Exception e)
{
if (e is TargetInvocationException)
e = e.InnerException;
throw new InvalidOperationException(SR.XmlGenError, e);
}
xmlWriter.Flush();
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Deserialize"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public object Deserialize(Stream stream)
{
XmlTextReader xmlReader = new XmlTextReader(stream);
xmlReader.WhitespaceHandling = WhitespaceHandling.Significant;
xmlReader.Normalization = true;
xmlReader.XmlResolver = null;
return Deserialize(xmlReader, null);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Deserialize1"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public object Deserialize(TextReader textReader)
{
XmlTextReader xmlReader = new XmlTextReader(textReader);
xmlReader.WhitespaceHandling = WhitespaceHandling.Significant;
xmlReader.Normalization = true;
xmlReader.XmlResolver = null;
return Deserialize(xmlReader, null);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Deserialize2"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public object Deserialize(XmlReader xmlReader)
{
return Deserialize(xmlReader, null);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Deserialize3"]/*' />
public object Deserialize(XmlReader xmlReader, XmlDeserializationEvents events)
{
return Deserialize(xmlReader, null, events);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Deserialize4"]/*' />
public object Deserialize(XmlReader xmlReader, string encodingStyle)
{
return Deserialize(xmlReader, encodingStyle, _events);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Deserialize5"]/*' />
public object Deserialize(XmlReader xmlReader, string encodingStyle, XmlDeserializationEvents events)
{
events.sender = this;
try
{
if (_primitiveType != null)
{
if (encodingStyle != null && encodingStyle.Length > 0)
{
throw new InvalidOperationException(SR.Format(SR.XmlInvalidEncodingNotEncoded1, encodingStyle));
}
return DeserializePrimitive(xmlReader, events);
}
#if !uapaot
else if (ShouldUseReflectionBasedSerialization())
{
XmlMapping mapping;
if (_mapping != null && _mapping.GenerateSerializer)
{
mapping = _mapping;
}
else
{
XmlReflectionImporter importer = new XmlReflectionImporter(DefaultNamespace);
mapping = importer.ImportTypeMapping(rootType, null, DefaultNamespace);
}
var reader = new ReflectionXmlSerializationReader(mapping, xmlReader, events, encodingStyle);
return reader.ReadObject();
}
else if (_tempAssembly == null || _typedSerializer)
{
XmlSerializationReader reader = CreateReader();
reader.Init(xmlReader, events, encodingStyle, _tempAssembly);
try
{
return Deserialize(reader);
}
finally
{
reader.Dispose();
}
}
else
{
return _tempAssembly.InvokeReader(_mapping, xmlReader, events, encodingStyle);
}
#else
else
{
if (this.innerSerializer != null)
{
if (!string.IsNullOrEmpty(this.DefaultNamespace))
{
this.innerSerializer.DefaultNamespace = this.DefaultNamespace;
}
XmlSerializationReader reader = this.innerSerializer.CreateReader();
reader.Init(xmlReader, encodingStyle);
try
{
return this.innerSerializer.Deserialize(reader);
}
finally
{
reader.Dispose();
}
}
else if (ReflectionMethodEnabled)
{
XmlMapping mapping;
if (_mapping != null && _mapping.GenerateSerializer)
{
mapping = _mapping;
}
else
{
XmlReflectionImporter importer = new XmlReflectionImporter(DefaultNamespace);
mapping = importer.ImportTypeMapping(rootType, null, DefaultNamespace);
}
var reader = new ReflectionXmlSerializationReader(mapping, xmlReader, events, encodingStyle);
return reader.ReadObject();
}
else
{
throw new InvalidOperationException(SR.Format(SR.Xml_MissingSerializationCodeException, this.rootType, typeof(XmlSerializer).Name));
}
}
#endif
}
catch (Exception e)
{
if (e is TargetInvocationException)
e = e.InnerException;
if (xmlReader is IXmlLineInfo)
{
IXmlLineInfo lineInfo = (IXmlLineInfo)xmlReader;
throw new InvalidOperationException(SR.Format(SR.XmlSerializeErrorDetails, lineInfo.LineNumber.ToString(CultureInfo.InvariantCulture), lineInfo.LinePosition.ToString(CultureInfo.InvariantCulture)), e);
}
else
{
throw new InvalidOperationException(SR.XmlSerializeError, e);
}
}
}
private bool ShouldUseReflectionBasedSerialization()
{
return Mode == SerializationMode.ReflectionOnly
|| (_mapping != null && _mapping.IsSoap);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.CanDeserialize"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public virtual bool CanDeserialize(XmlReader xmlReader)
{
if (_primitiveType != null)
{
TypeDesc typeDesc = (TypeDesc)TypeScope.PrimtiveTypes[_primitiveType];
return xmlReader.IsStartElement(typeDesc.DataType.Name, string.Empty);
}
#if !uapaot
else if (_tempAssembly != null)
{
return _tempAssembly.CanRead(_mapping, xmlReader);
}
else
{
return false;
}
#else
if (this.innerSerializer != null)
{
return this.innerSerializer.CanDeserialize(xmlReader);
}
else
{
return ReflectionMethodEnabled;
}
#endif
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.FromMappings"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static XmlSerializer[] FromMappings(XmlMapping[] mappings)
{
return FromMappings(mappings, (Type)null);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.FromMappings1"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static XmlSerializer[] FromMappings(XmlMapping[] mappings, Type type)
{
if (mappings == null || mappings.Length == 0) return Array.Empty<XmlSerializer>();
#if uapaot
var serializers = new XmlSerializer[mappings.Length];
for(int i=0;i<mappings.Length;i++)
{
serializers[i] = new XmlSerializer();
serializers[i].rootType = type;
serializers[i]._mapping = mappings[i];
}
return serializers;
#else
XmlSerializerImplementation contract = null;
Assembly assembly = type == null ? null : TempAssembly.LoadGeneratedAssembly(type, null, out contract);
TempAssembly tempAssembly = null;
if (assembly == null)
{
if (XmlMapping.IsShallow(mappings))
{
return Array.Empty<XmlSerializer>();
}
else
{
if (type == null)
{
tempAssembly = new TempAssembly(mappings, new Type[] { type }, null, null);
XmlSerializer[] serializers = new XmlSerializer[mappings.Length];
contract = tempAssembly.Contract;
for (int i = 0; i < serializers.Length; i++)
{
serializers[i] = (XmlSerializer)contract.TypedSerializers[mappings[i].Key];
serializers[i].SetTempAssembly(tempAssembly, mappings[i]);
}
return serializers;
}
else
{
// Use XmlSerializer cache when the type is not null.
return GetSerializersFromCache(mappings, type);
}
}
}
else
{
XmlSerializer[] serializers = new XmlSerializer[mappings.Length];
for (int i = 0; i < serializers.Length; i++)
serializers[i] = (XmlSerializer)contract.TypedSerializers[mappings[i].Key];
return serializers;
}
#endif
}
private static XmlSerializer[] GetSerializersFromCache(XmlMapping[] mappings, Type type)
{
XmlSerializer[] serializers = new XmlSerializer[mappings.Length];
Dictionary<XmlSerializerMappingKey, XmlSerializer> typedMappingTable = null;
lock (s_xmlSerializerTable)
{
if (!s_xmlSerializerTable.TryGetValue(type, out typedMappingTable))
{
typedMappingTable = new Dictionary<XmlSerializerMappingKey, XmlSerializer>();
s_xmlSerializerTable[type] = typedMappingTable;
}
}
lock (typedMappingTable)
{
var pendingKeys = new Dictionary<XmlSerializerMappingKey, int>();
for (int i = 0; i < mappings.Length; i++)
{
XmlSerializerMappingKey mappingKey = new XmlSerializerMappingKey(mappings[i]);
if (!typedMappingTable.TryGetValue(mappingKey, out serializers[i]))
{
pendingKeys.Add(mappingKey, i);
}
}
if (pendingKeys.Count > 0)
{
XmlMapping[] pendingMappings = new XmlMapping[pendingKeys.Count];
int index = 0;
foreach (XmlSerializerMappingKey mappingKey in pendingKeys.Keys)
{
pendingMappings[index++] = mappingKey.Mapping;
}
TempAssembly tempAssembly = new TempAssembly(pendingMappings, new Type[] { type }, null, null);
XmlSerializerImplementation contract = tempAssembly.Contract;
foreach (XmlSerializerMappingKey mappingKey in pendingKeys.Keys)
{
index = pendingKeys[mappingKey];
serializers[index] = (XmlSerializer)contract.TypedSerializers[mappingKey.Mapping.Key];
serializers[index].SetTempAssembly(tempAssembly, mappingKey.Mapping);
typedMappingTable[mappingKey] = serializers[index];
}
}
}
return serializers;
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.FromTypes"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static XmlSerializer[] FromTypes(Type[] types)
{
if (types == null)
return Array.Empty<XmlSerializer>();
#if uapaot
var serializers = new XmlSerializer[types.Length];
for (int i = 0; i < types.Length; i++)
{
serializers[i] = new XmlSerializer(types[i]);
}
return serializers;
#else
XmlReflectionImporter importer = new XmlReflectionImporter();
XmlTypeMapping[] mappings = new XmlTypeMapping[types.Length];
for (int i = 0; i < types.Length; i++)
{
mappings[i] = importer.ImportTypeMapping(types[i]);
}
return FromMappings(mappings);
#endif
}
#if uapaot
// this the global XML serializer contract introduced for multi-file
private static XmlSerializerImplementation xmlSerializerContract;
internal static XmlSerializerImplementation GetXmlSerializerContractFromGeneratedAssembly()
{
// hack to pull in SetXmlSerializerContract which is only referenced from the
// code injected by MainMethodInjector transform
// there's probably also a way to do this via [DependencyReductionRoot],
// but I can't get the compiler to find that...
if (xmlSerializerContract == null)
SetXmlSerializerContract(null);
// this method body used to be rewritten by an IL transform
// with the restructuring for multi-file, it has become a regular method
return xmlSerializerContract;
}
public static void SetXmlSerializerContract(XmlSerializerImplementation xmlSerializerImplementation)
{
xmlSerializerContract = xmlSerializerImplementation;
}
#endif
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.GetXmlSerializerAssemblyName"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static string GetXmlSerializerAssemblyName(Type type)
{
return GetXmlSerializerAssemblyName(type, null);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.GetXmlSerializerAssemblyName"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static string GetXmlSerializerAssemblyName(Type type, string defaultNamespace)
{
if (type == null)
{
throw new ArgumentNullException(nameof(type));
}
return Compiler.GetTempAssemblyName(type.Assembly.GetName(), defaultNamespace);
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.UnknownNode"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public event XmlNodeEventHandler UnknownNode
{
add
{
_events.OnUnknownNode += value;
}
remove
{
_events.OnUnknownNode -= value;
}
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.UnknownAttribute"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public event XmlAttributeEventHandler UnknownAttribute
{
add
{
_events.OnUnknownAttribute += value;
}
remove
{
_events.OnUnknownAttribute -= value;
}
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.UnknownElement"]/*' />
public event XmlElementEventHandler UnknownElement
{
add
{
_events.OnUnknownElement += value;
}
remove
{
_events.OnUnknownElement -= value;
}
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.UnreferencedObject"]/*' />
public event UnreferencedObjectEventHandler UnreferencedObject
{
add
{
_events.OnUnreferencedObject += value;
}
remove
{
_events.OnUnreferencedObject -= value;
}
}
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.CreateReader"]/*' />
///<internalonly/>
protected virtual XmlSerializationReader CreateReader() { throw new PlatformNotSupportedException(); }
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Deserialize4"]/*' />
///<internalonly/>
protected virtual object Deserialize(XmlSerializationReader reader) { throw new PlatformNotSupportedException(); }
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.CreateWriter"]/*' />
///<internalonly/>
protected virtual XmlSerializationWriter CreateWriter() { throw new PlatformNotSupportedException(); }
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.Serialize7"]/*' />
///<internalonly/>
protected virtual void Serialize(object o, XmlSerializationWriter writer) { throw new PlatformNotSupportedException(); }
internal void SetTempAssembly(TempAssembly tempAssembly, XmlMapping mapping)
{
_tempAssembly = tempAssembly;
_mapping = mapping;
_typedSerializer = true;
}
private static XmlTypeMapping GetKnownMapping(Type type, string ns)
{
if (ns != null && ns != string.Empty)
return null;
TypeDesc typeDesc = (TypeDesc)TypeScope.PrimtiveTypes[type];
if (typeDesc == null)
return null;
ElementAccessor element = new ElementAccessor();
element.Name = typeDesc.DataType.Name;
XmlTypeMapping mapping = new XmlTypeMapping(null, element);
mapping.SetKeyInternal(XmlMapping.GenerateKey(type, null, null));
return mapping;
}
private void SerializePrimitive(XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces)
{
XmlSerializationPrimitiveWriter writer = new XmlSerializationPrimitiveWriter();
writer.Init(xmlWriter, namespaces, null, null, null);
switch (_primitiveType.GetTypeCode())
{
case TypeCode.String:
writer.Write_string(o);
break;
case TypeCode.Int32:
writer.Write_int(o);
break;
case TypeCode.Boolean:
writer.Write_boolean(o);
break;
case TypeCode.Int16:
writer.Write_short(o);
break;
case TypeCode.Int64:
writer.Write_long(o);
break;
case TypeCode.Single:
writer.Write_float(o);
break;
case TypeCode.Double:
writer.Write_double(o);
break;
case TypeCode.Decimal:
writer.Write_decimal(o);
break;
case TypeCode.DateTime:
writer.Write_dateTime(o);
break;
case TypeCode.Char:
writer.Write_char(o);
break;
case TypeCode.Byte:
writer.Write_unsignedByte(o);
break;
case TypeCode.SByte:
writer.Write_byte(o);
break;
case TypeCode.UInt16:
writer.Write_unsignedShort(o);
break;
case TypeCode.UInt32:
writer.Write_unsignedInt(o);
break;
case TypeCode.UInt64:
writer.Write_unsignedLong(o);
break;
default:
if (_primitiveType == typeof(XmlQualifiedName))
{
writer.Write_QName(o);
}
else if (_primitiveType == typeof(byte[]))
{
writer.Write_base64Binary(o);
}
else if (_primitiveType == typeof(Guid))
{
writer.Write_guid(o);
}
else if (_primitiveType == typeof(TimeSpan))
{
writer.Write_TimeSpan(o);
}
else
{
throw new InvalidOperationException(SR.Format(SR.XmlUnxpectedType, _primitiveType.FullName));
}
break;
}
}
private object DeserializePrimitive(XmlReader xmlReader, XmlDeserializationEvents events)
{
XmlSerializationPrimitiveReader reader = new XmlSerializationPrimitiveReader();
reader.Init(xmlReader, events, null, null);
object o;
switch (_primitiveType.GetTypeCode())
{
case TypeCode.String:
o = reader.Read_string();
break;
case TypeCode.Int32:
o = reader.Read_int();
break;
case TypeCode.Boolean:
o = reader.Read_boolean();
break;
case TypeCode.Int16:
o = reader.Read_short();
break;
case TypeCode.Int64:
o = reader.Read_long();
break;
case TypeCode.Single:
o = reader.Read_float();
break;
case TypeCode.Double:
o = reader.Read_double();
break;
case TypeCode.Decimal:
o = reader.Read_decimal();
break;
case TypeCode.DateTime:
o = reader.Read_dateTime();
break;
case TypeCode.Char:
o = reader.Read_char();
break;
case TypeCode.Byte:
o = reader.Read_unsignedByte();
break;
case TypeCode.SByte:
o = reader.Read_byte();
break;
case TypeCode.UInt16:
o = reader.Read_unsignedShort();
break;
case TypeCode.UInt32:
o = reader.Read_unsignedInt();
break;
case TypeCode.UInt64:
o = reader.Read_unsignedLong();
break;
default:
if (_primitiveType == typeof(XmlQualifiedName))
{
o = reader.Read_QName();
}
else if (_primitiveType == typeof(byte[]))
{
o = reader.Read_base64Binary();
}
else if (_primitiveType == typeof(Guid))
{
o = reader.Read_guid();
}
else if (_primitiveType == typeof(TimeSpan))
{
o = reader.Read_TimeSpan();
}
else
{
throw new InvalidOperationException(SR.Format(SR.XmlUnxpectedType, _primitiveType.FullName));
}
break;
}
return o;
}
private class XmlSerializerMappingKey
{
public XmlMapping Mapping;
public XmlSerializerMappingKey(XmlMapping mapping)
{
this.Mapping = mapping;
}
public override bool Equals(object obj)
{
XmlSerializerMappingKey other = obj as XmlSerializerMappingKey;
if (other == null)
return false;
if (this.Mapping.Key != other.Mapping.Key)
return false;
if (this.Mapping.ElementName != other.Mapping.ElementName)
return false;
if (this.Mapping.Namespace != other.Mapping.Namespace)
return false;
if (this.Mapping.IsSoap != other.Mapping.IsSoap)
return false;
return true;
}
public override int GetHashCode()
{
int hashCode = this.Mapping.IsSoap ? 0 : 1;
if (this.Mapping.Key != null)
hashCode ^= this.Mapping.Key.GetHashCode();
if (this.Mapping.ElementName != null)
hashCode ^= this.Mapping.ElementName.GetHashCode();
if (this.Mapping.Namespace != null)
hashCode ^= this.Mapping.Namespace.GetHashCode();
return hashCode;
}
}
}
}
| |
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Copyright (c) 2008 - 2015 Jb Evain
// Copyright (c) 2008 - 2011 Novell, Inc.
//
// Licensed under the MIT/X11 license.
//
using System;
using SquabPie.Mono.Collections.Generic;
namespace SquabPie.Mono.Cecil {
public struct CustomAttributeArgument {
readonly TypeReference type;
readonly object value;
public TypeReference Type {
get { return type; }
}
public object Value {
get { return value; }
}
public CustomAttributeArgument (TypeReference type, object value)
{
Mixin.CheckType (type);
this.type = type;
this.value = value;
}
}
public struct CustomAttributeNamedArgument {
readonly string name;
readonly CustomAttributeArgument argument;
public string Name {
get { return name; }
}
public CustomAttributeArgument Argument {
get { return argument; }
}
public CustomAttributeNamedArgument (string name, CustomAttributeArgument argument)
{
Mixin.CheckName (name);
this.name = name;
this.argument = argument;
}
}
public interface ICustomAttribute {
TypeReference AttributeType { get; }
bool HasFields { get; }
bool HasProperties { get; }
Collection<CustomAttributeNamedArgument> Fields { get; }
Collection<CustomAttributeNamedArgument> Properties { get; }
}
public sealed class CustomAttribute : ICustomAttribute {
readonly internal uint signature;
internal bool resolved;
MethodReference constructor;
byte [] blob;
internal Collection<CustomAttributeArgument> arguments;
internal Collection<CustomAttributeNamedArgument> fields;
internal Collection<CustomAttributeNamedArgument> properties;
public MethodReference Constructor {
get { return constructor; }
set { constructor = value; }
}
public TypeReference AttributeType {
get { return constructor.DeclaringType; }
}
public bool IsResolved {
get { return resolved; }
}
public bool HasConstructorArguments {
get {
Resolve ();
return !arguments.IsNullOrEmpty ();
}
}
public Collection<CustomAttributeArgument> ConstructorArguments {
get {
Resolve ();
return arguments ?? (arguments = new Collection<CustomAttributeArgument> ());
}
}
public bool HasFields {
get {
Resolve ();
return !fields.IsNullOrEmpty ();
}
}
public Collection<CustomAttributeNamedArgument> Fields {
get {
Resolve ();
return fields ?? (fields = new Collection<CustomAttributeNamedArgument> ());
}
}
public bool HasProperties {
get {
Resolve ();
return !properties.IsNullOrEmpty ();
}
}
public Collection<CustomAttributeNamedArgument> Properties {
get {
Resolve ();
return properties ?? (properties = new Collection<CustomAttributeNamedArgument> ());
}
}
internal bool HasImage {
get { return constructor != null && constructor.HasImage; }
}
internal ModuleDefinition Module {
get { return constructor.Module; }
}
internal CustomAttribute (uint signature, MethodReference constructor)
{
this.signature = signature;
this.constructor = constructor;
this.resolved = false;
}
public CustomAttribute (MethodReference constructor)
{
this.constructor = constructor;
this.resolved = true;
}
public CustomAttribute (MethodReference constructor, byte [] blob)
{
this.constructor = constructor;
this.resolved = false;
this.blob = blob;
}
public byte [] GetBlob ()
{
if (blob != null)
return blob;
if (!HasImage)
throw new NotSupportedException ();
return Module.Read (ref blob, this, (attribute, reader) => reader.ReadCustomAttributeBlob (attribute.signature));
}
void Resolve ()
{
if (resolved || !HasImage)
return;
Module.Read (this, (attribute, reader) => {
try {
reader.ReadCustomAttributeSignature (attribute);
resolved = true;
} catch (ResolutionException) {
if (arguments != null)
arguments.Clear ();
if (fields != null)
fields.Clear ();
if (properties != null)
properties.Clear ();
resolved = false;
}
return this;
});
}
}
static partial class Mixin {
public static void CheckName (string name)
{
if (name == null)
throw new ArgumentNullException ("name");
if (name.Length == 0)
throw new ArgumentException ("Empty name");
}
}
}
| |
//
// ItunesPlayerImportSource.cs
//
// Authors:
// Scott Peterson <lunchtimemama@gmail.com>
// Alexander Kojevnikov <alexander@kojevnikov.com>
//
// Copyright (C) 2007 Scott Peterson
// Copyright (C) 2009 Alexander Kojevnikov
//
// 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.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml;
using Mono.Unix;
using Gtk;
using Hyena;
using Banshee.Base;
using Banshee.Collection;
using Banshee.Collection.Database;
using Banshee.IO;
using Banshee.Library;
using Banshee.Playlist;
using Banshee.ServiceStack;
using Banshee.Sources;
using Banshee.Widgets;
using Hyena.Data.Sqlite;
namespace Banshee.PlayerMigration
{
public sealed class ItunesPlayerImportSource : ThreadPoolImportSource
{
// This is its own class so that we don't always load this stuff into memory
private class ItunesImportData
{
public string library_uri, default_query, local_prefix, fallback_dir;
public string[] query_dirs;
public bool get_ratings, get_stats, get_playlists, user_provided_prefix, empty_library;
public int total_songs, total_processed;
public Dictionary<int, int> track_ids = new Dictionary<int, int> (); // key=itunes_id, value=banshee_id
}
private readonly object mutex = new object ();
private volatile bool ok;
public const string LibraryFilename = "iTunes Music Library.xml";
public override string Name {
get { return Catalog.GetString ("iTunes Media Player"); }
}
public override bool CanImport {
get { return true; }
}
private ItunesImportData data;
protected override bool ConfirmImport ()
{
if (data == null) {
data = new ItunesImportData ();
var dialog = new ItunesImportDialog ();
if (!HandleImportDialog (dialog, delegate { data.library_uri = dialog.LibraryUri; })) {
data = null;
return false;
}
}
return true;
}
private delegate void ImportDialogHandler (ItunesImportDialog dialog);
private bool HandleImportDialog (ItunesImportDialog dialog, ImportDialogHandler code)
{
try {
if (dialog.Run () == (int)ResponseType.Ok) {
if(code != null) {
code (dialog);
}
data.get_ratings = dialog.Ratings;
data.get_stats = dialog.Stats;
data.get_playlists = dialog.Playliststs;
} else {
return false;
}
} finally {
dialog.Destroy ();
dialog.Dispose ();
}
if (String.IsNullOrEmpty (data.library_uri)) {
return false;
}
// Make sure the library version is supported (version 1.1)
string message = null;
bool prompt = false;
using (var xml_reader = new XmlTextReader (data.library_uri))
{
xml_reader.ReadToFollowing ("key");
do {
xml_reader.Read ();
string key = xml_reader.ReadContentAsString ();
if (key == "Major Version" || key == "Minor Version") {
xml_reader.Read ();
xml_reader.Read ();
if(xml_reader.ReadContentAsString () != "1") {
message = Catalog.GetString (
"Banshee is not familiar with this version of the iTunes library format." +
" Importing may or may not work as expected, or at all. Would you like to attempt to import anyway?");
prompt = true;
break;
}
}
} while (xml_reader.ReadToNextSibling ("key"));
}
if (prompt) {
bool proceed = false;
using (var message_dialog = new MessageDialog (null, 0, MessageType.Question, ButtonsType.YesNo, message)) {
if (message_dialog.Run () == (int)ResponseType.Yes) {
proceed = true;
}
message_dialog.Destroy ();
}
if (!proceed) {
LogError (data.library_uri, "Unsupported version");
return false;
}
}
return true;
}
protected override void ImportCore ()
{
try {
CountSongs ();
data.empty_library = ServiceManager.SourceManager.MusicLibrary.TrackModel.Count == 0;
var import_manager = ServiceManager.Get<LibraryImportManager> ();
using (var xml_reader = new XmlTextReader (data.library_uri)) {
ProcessLibraryXml (import_manager, xml_reader);
}
import_manager.NotifyAllSources ();
} finally {
data = null;
}
}
private void CountSongs ()
{
using (var xml_reader = new XmlTextReader (data.library_uri)) {
xml_reader.ReadToDescendant("dict");
xml_reader.ReadToDescendant("dict");
xml_reader.ReadToDescendant("dict");
do {
data.total_songs++;
} while (xml_reader.ReadToNextSibling ("dict"));
}
}
private void ProcessLibraryXml (LibraryImportManager import_manager, XmlReader xml_reader)
{
while (xml_reader.ReadToFollowing ("key") && !CheckForCanceled ()) {
xml_reader.Read ();
string key = xml_reader.ReadContentAsString ();
xml_reader.Read ();
xml_reader.Read ();
switch (key) {
case "Music Folder":
if (!ProcessMusicFolderPath (xml_reader.ReadContentAsString ())) {
return;
}
break;
case "Tracks":
ProcessSongs (import_manager, xml_reader.ReadSubtree ());
break;
case "Playlists":
if (data.get_playlists) {
ProcessPlaylists (xml_reader.ReadSubtree ());
}
break;
}
}
}
private bool ProcessMusicFolderPath(string path)
{
string[] itunes_music_uri_parts = ConvertToLocalUriFormat (path).Split (Path.DirectorySeparatorChar);
string[] library_uri_parts = Path.GetDirectoryName (data.library_uri).Split (Path.DirectorySeparatorChar);
string itunes_dir_name = library_uri_parts[library_uri_parts.Length - 1];
int i = 0;
bool found = false;
for (i = itunes_music_uri_parts.Length - 1; i >= 0; i--) {
if (itunes_music_uri_parts[i] == itunes_dir_name) {
found = true;
break;
}
}
if (!found) {
var builder = new StringBuilder (path.Length - 17);
for (int j = 3; j < itunes_music_uri_parts.Length; j++) {
string part = itunes_music_uri_parts[j];
builder.Append (part);
if (part.Length > 0) {
builder.Append (Path.DirectorySeparatorChar);
}
}
string local_path = builder.ToString ();
System.Threading.Monitor.Enter (mutex);
ThreadAssist.ProxyToMain (delegate {
System.Threading.Monitor.Enter (mutex);
using (var dialog = new ItunesMusicDirectoryDialog (local_path)) {
if (dialog.Run () == (int)ResponseType.Ok) {
data.local_prefix = dialog.UserMusicDirectory;
data.user_provided_prefix = true;
data.default_query = local_path;
ok = true;
} else {
ok = false;
}
dialog.Destroy ();
System.Threading.Monitor.Pulse (mutex);
System.Threading.Monitor.Exit (mutex);
}
});
System.Threading.Monitor.Wait (mutex);
System.Threading.Monitor.Exit (mutex);
if (ok) {
return true;
} else {
LogError (data.library_uri, "Unable to locate iTunes directory from iTunes URI");
return false;
}
}
string[] tmp_query_dirs = new string[itunes_music_uri_parts.Length];
string upstream_uri;
string tmp_upstream_uri = null;
int step = 0;
string root = Path.GetPathRoot (data.library_uri);
bool same_root = library_uri_parts[0] == root.Split (Path.DirectorySeparatorChar)[0];
do {
upstream_uri = tmp_upstream_uri;
tmp_upstream_uri = root;
for (int j = same_root ? 1 : 0; j < library_uri_parts.Length - step - 1; j++) {
tmp_upstream_uri = Path.Combine (tmp_upstream_uri, library_uri_parts[j]);
}
tmp_upstream_uri = Path.Combine (tmp_upstream_uri, itunes_music_uri_parts[i - step]);
data.fallback_dir = tmp_query_dirs[step] = itunes_music_uri_parts[i - step];
step++;
} while (Banshee.IO.Directory.Exists (tmp_upstream_uri));
if (upstream_uri == null) {
LogError (data.library_uri, "Unable to resolve iTunes URIs to local URIs");
return false;
}
data.query_dirs = new string[step - 2];
data.default_query = string.Empty;
for (int j = step - 2; j >= 0; j--) {
if (j > 0) {
data.query_dirs[j - 1] = tmp_query_dirs[j];
}
data.default_query += tmp_query_dirs[j] + Path.DirectorySeparatorChar;
}
data.local_prefix = string.Empty;
for (int j = 0; j <= library_uri_parts.Length - step; j++) {
data.local_prefix += library_uri_parts[j] + Path.DirectorySeparatorChar;
}
return true;
}
private void ProcessSongs (LibraryImportManager import_manager, XmlReader xml_reader)
{
using (xml_reader) {
xml_reader.ReadToFollowing ("dict");
while (xml_reader.ReadToFollowing ("dict") && !CheckForCanceled ()) {
ProcessSong (import_manager, xml_reader.ReadSubtree ());
}
}
}
private void ProcessPlaylists (XmlReader xml_reader)
{
using (xml_reader) {
while(xml_reader.ReadToFollowing ("dict") && !CheckForCanceled ()) {
ProcessPlaylist (xml_reader.ReadSubtree ());
}
}
}
private void ProcessSong (LibraryImportManager import_manager, XmlReader xml_reader)
{
data.total_processed++;
var itunes_id = 0;
var title = String.Empty;
var title_sort = String.Empty;
var genre = String.Empty;
var artist = String.Empty;
var artist_sort = String.Empty;
var album_artist = String.Empty;
var album_artist_sort = String.Empty;
var composer = String.Empty;
var album = String.Empty;
var album_sort = String.Empty;
var grouping = String.Empty;
var year = 0;
var rating = 0;
var play_count = 0;
var track_number = 0;
var date_added = DateTime.Now;
var last_played = DateTime.MinValue;
SafeUri uri = null;
using (xml_reader) {
while (xml_reader.ReadToFollowing ("key")) {
xml_reader.Read();
string key = xml_reader.ReadContentAsString ();
xml_reader.Read ();
xml_reader.Read ();
try {
switch (key) {
case "Track ID":
itunes_id = Int32.Parse (xml_reader.ReadContentAsString ());
break;
case "Name":
title = xml_reader.ReadContentAsString ();
break;
case "Sort Name":
title_sort = xml_reader.ReadContentAsString ();
break;
case "Genre":
genre = xml_reader.ReadContentAsString ();
break;
case "Artist":
artist = xml_reader.ReadContentAsString ();
break;
case "Sort Artist":
artist_sort = xml_reader.ReadContentAsString ();
break;
case "Album Artist":
album_artist = xml_reader.ReadContentAsString ();
break;
case "Sort Album Artist":
album_artist_sort = xml_reader.ReadContentAsString ();
break;
case "Composer":
composer = xml_reader.ReadContentAsString ();
break;
case "Album":
album = xml_reader.ReadContentAsString ();
break;
case "Sort Album":
album_sort = xml_reader.ReadContentAsString ();
break;
case "Grouping":
grouping = xml_reader.ReadContentAsString ();
break;
case "Year":
year = Int32.Parse (xml_reader.ReadContentAsString ());
break;
case "Rating":
rating = Int32.Parse (xml_reader.ReadContentAsString ()) / 20;
break;
case "Play Count":
play_count = Int32.Parse (xml_reader.ReadContentAsString ());
break;
case "Track Number":
track_number = Int32.Parse (xml_reader.ReadContentAsString ());
break;
case "Date Added":
date_added = DateTime.Parse (xml_reader.ReadContentAsString (),
DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AssumeUniversal);
break;
case "Play Date UTC":
last_played = DateTime.Parse (xml_reader.ReadContentAsString (),
DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AssumeUniversal);
break;
case "Location":
uri = ConvertToLocalUri (xml_reader.ReadContentAsString ());
break;
}
} catch {
}
}
}
if (uri == null) {
return;
}
UpdateUserJob (data.total_processed, data.total_songs, artist, title);
try {
DatabaseTrackInfo track = import_manager.ImportTrack (uri);
if (track == null) {
LogError (SafeUri.UriToFilename (uri), Catalog.GetString ("Unable to import song."));
return;
}
if (!String.IsNullOrEmpty (title)) {
track.TrackTitle = title;
}
if (!String.IsNullOrEmpty (title_sort)) {
track.TrackTitleSort = title_sort;
}
if (!String.IsNullOrEmpty (artist)) {
track.ArtistName = artist;
}
if (!String.IsNullOrEmpty (artist_sort)) {
track.ArtistNameSort = artist_sort;
}
if (!String.IsNullOrEmpty (genre)) {
track.Genre = genre;
}
if (!String.IsNullOrEmpty (album_artist)) {
track.AlbumArtist = album_artist;
}
if (!String.IsNullOrEmpty (album_artist_sort)) {
track.AlbumArtistSort = album_artist_sort;
}
if (!String.IsNullOrEmpty (composer)) {
track.Composer = composer;
}
if (!String.IsNullOrEmpty (album)) {
track.AlbumTitle = album;
}
if (!String.IsNullOrEmpty (album_sort)) {
track.AlbumTitleSort = album_sort;
}
if (!String.IsNullOrEmpty (grouping)) {
track.Grouping = grouping;
}
if (year > 0) {
track.Year = year;
}
if (data.get_ratings && rating > 0 && rating <= 5) {
track.Rating = rating;
}
if (data.get_stats && play_count > 0) {
track.PlayCount = play_count;
}
if (track_number > 0) {
track.TrackNumber = track_number;
}
if (data.get_stats) {
track.DateAdded = date_added;
}
if (data.get_stats && last_played > DateTime.MinValue) {
track.LastPlayed = last_played;
}
data.track_ids.Add (itunes_id, track.TrackId);
track.Save (false);
} catch (Exception e) {
LogError (SafeUri.UriToFilename (uri), e);
}
}
private void ProcessPlaylist (XmlReader xml_reader)
{
string name = string.Empty;
bool skip = false;
bool processed = false;
using (xml_reader) {
while (xml_reader.ReadToFollowing ("key")) {
xml_reader.Read ();
string key = xml_reader.ReadContentAsString ();
xml_reader.Read ();
switch (key) {
case "Name":
xml_reader.Read ();
name = xml_reader.ReadContentAsString ();
if (name == "Library" ||
name == "Music Videos" ||
name == "Audiobooks" ||
name == "Music" ||
name == "Movies" ||
name == "Party Shuffle" ||
name == "Podcasts" ||
name == "Party Shuffle" ||
name == "Purchased Music" ||
name == "Genius" ||
name == "TV Shows") {
skip = true;
}
break;
case "Smart Info":
skip = true;
break;
case "Smart Criteria":
skip = true;
break;
case "Playlist Items":
xml_reader.Read ();
if(!skip) {
ProcessPlaylist (name, xml_reader.ReadSubtree ());
processed = true;
}
break;
}
}
}
// Empty playlist
if (!processed && !skip) {
ProcessPlaylist (name, null);
}
}
private void ProcessPlaylist (string name, XmlReader xml_reader)
{
UpdateUserJob (1, 1, Catalog.GetString("Playlists"), name);
ProcessRegularPlaylist (name, xml_reader);
if (xml_reader != null) {
xml_reader.Close ();
}
}
private void ProcessRegularPlaylist (string name, XmlReader xml_reader)
{
var playlist_source = new PlaylistSource (name, ServiceManager.SourceManager.MusicLibrary);
playlist_source.Save ();
ServiceManager.SourceManager.MusicLibrary.AddChildSource (playlist_source);
// Get the songs in the playlists
if (xml_reader != null) {
while (xml_reader.ReadToFollowing ("integer") && !CheckForCanceled ()) {
xml_reader.Read ();
int itunes_id = Int32.Parse (xml_reader.ReadContentAsString ());
int track_id;
if (data.track_ids.TryGetValue (itunes_id, out track_id)) {
try {
ServiceManager.DbConnection.Execute (
"INSERT INTO CorePlaylistEntries (PlaylistID, TrackID) VALUES (?, ?)",
playlist_source.DbId, track_id);
} catch {
}
}
}
playlist_source.Reload ();
playlist_source.NotifyUser ();
}
}
private SafeUri ConvertToLocalUri (string raw_uri)
{
if (raw_uri == null) {
return null;
}
string uri = ConvertToLocalUriFormat (raw_uri);
int index = uri.IndexOf (data.default_query);
if (data.user_provided_prefix && index != -1) {
index += data.default_query.Length;
} else if (index == -1 && data.query_dirs.Length > 0) {
int count = 0;
string path = data.query_dirs[data.query_dirs.Length - 1];
do {
for (int k = data.query_dirs.Length - 2; k >= count; k--) {
path = Path.Combine (path, data.query_dirs[k]);
}
index = uri.IndexOf (path);
count++;
} while(index == -1 && count < data.query_dirs.Length);
if (index == -1) {
index = uri.IndexOf(data.fallback_dir);
if (index != -1) {
index += data.fallback_dir.Length + 1;
}
}
}
if (index == -1) {
if (data.empty_library) {
LogError (uri, "Unable to map iTunes URI to local URI");
}
return null;
}
SafeUri safe_uri = CreateSafeUri (Path.Combine(
data.local_prefix, uri.Substring (index, uri.Length - index)), data.empty_library);
if (safe_uri == null && !data.empty_library) {
string local_uri = string.Empty;
string lower_uri = raw_uri.ToLower (CultureInfo.InvariantCulture);
int i = lower_uri.Length;
while (true) {
i = lower_uri.LastIndexOf (Path.DirectorySeparatorChar, i - 1);
if (i == -1) {
break;
}
try {
using (var reader = ServiceManager.DbConnection.Query (String.Format (
@"SELECT Uri FROM CoreTracks WHERE lower(Uri) LIKE ""%{0}""", lower_uri.Substring (i + 1)))) {
bool found = false;
local_uri = string.Empty;
while (reader.Read ()) {
if (found) {
local_uri = string.Empty;
break;
}
found = true;
local_uri = (string)reader[0];
}
if (!found || local_uri.Length > 0) {
break;
}
}
} catch {
break;
}
}
if (local_uri.Length > 0) {
safe_uri = CreateSafeUri (local_uri, true);
} else {
LogError (uri, "Unable to map iTunes URI to local URI");
}
}
return safe_uri;
}
private SafeUri CreateSafeUri (string uri, bool complain)
{
SafeUri safe_uri;
try {
safe_uri = new SafeUri (uri);
} catch {
if (complain) {
LogError (uri, "URI is not a local file path");
}
return null;
}
safe_uri = FindFile (safe_uri);
if (safe_uri == null) {
if (complain) {
LogError (uri, "File does not exist");
}
return null;
}
return safe_uri;
}
// URIs are UTF-8 percent-encoded. Deconding with System.Web.HttpServerUtility
// involves too much overhead, so we do it cheap here.
private static string ConvertToLocalUriFormat (string input)
{
var builder = new StringBuilder (input.Length);
byte[] buffer = new byte[2];
bool using_buffer = false;
for (int i = 0; i < input.Length; i++) {
// If it's a '%', treat the two subsiquent characters as a UTF-8 byte in hex.
if (input[i] == '%') {
byte code = Byte.Parse (input.Substring(i + 1, 2),
System.Globalization.NumberStyles.HexNumber);
// If it's a non-ascii character, or there are already some non-ascii
// characters in the buffer, then queue it for UTF-8 decoding.
if (using_buffer || (code & 0x80) != 0) {
if (using_buffer) {
if (buffer[1] == 0) {
buffer[1] = code;
} else {
byte[] new_buffer = new byte[buffer.Length + 1];
for (int j = 0; j < buffer.Length; j++) {
new_buffer[j] = buffer[j];
}
buffer = new_buffer;
buffer[buffer.Length - 1] = code;
}
} else {
buffer[0] = code;
using_buffer = true;
}
}
// If it's a lone ascii character, there's no need for fancy UTF-8 decoding.
else {
builder.Append ((char)code);
}
i += 2;
} else {
// If we have something in the buffer, decode it.
if (using_buffer) {
builder.Append (Encoding.UTF8.GetString (buffer));
if (buffer.Length > 2) {
buffer = new byte[2];
} else {
buffer[1] = 0;
}
using_buffer = false;
}
// And add our regular characters and convert to local directory separator char.
if (input[i] == '/') {
builder.Append (Path.DirectorySeparatorChar);
} else {
builder.Append (input[i]);
}
}
}
return builder.ToString ();
}
private static SafeUri FindFile (SafeUri uri)
{
// URIs kept by iTunes often contain characters in a case different from the actual
// files and directories. This method tries to find the real file URI.
if (Banshee.IO.File.Exists (uri)) {
return uri;
}
string path = uri.AbsolutePath;
string file = Path.GetFileName (path);
string directory = Path.GetDirectoryName (path);
directory = FindDirectory (directory);
if (directory == null) {
return null;
}
uri = new SafeUri (Path.Combine (directory, file), false);
if (Banshee.IO.File.Exists (uri)) {
return uri;
}
foreach (string item in Banshee.IO.Directory.GetFiles (directory)) {
string name = Path.GetFileName (item);
if (0 != String.Compare (file, name, true)) {
continue;
}
return new SafeUri (Path.Combine (directory, name), false);
}
return null;
}
private static string FindDirectory (string directory)
{
if (Banshee.IO.Directory.Exists (directory)) {
return directory;
}
string current = Path.GetFileName (directory);
directory = Path.GetDirectoryName (directory);
if (String.IsNullOrEmpty (directory)) {
return null;
}
directory = FindDirectory (directory);
if (String.IsNullOrEmpty (directory)) {
return null;
}
foreach (string item in Banshee.IO.Directory.GetDirectories (directory)) {
string name = Path.GetFileName (item);
if (0 != String.Compare (current, name, true)) {
continue;
}
return Path.Combine (directory, name);
}
return null;
}
public override string [] IconNames {
get { return new string [] { "itunes", "system-search" }; }
}
public override int SortOrder {
get { return 40; }
}
}
}
| |
using System;
using System.CodeDom;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Orleans.Runtime;
using Orleans.Runtime.Configuration;
using Orleans.Serialization;
namespace Orleans.Messaging
{
// <summary>
// This class is used on the client only.
// It provides the client counterpart to the Gateway and GatewayAcceptor classes on the silo side.
//
// There is one ProxiedMessageCenter instance per OutsideRuntimeClient. There can be multiple ProxiedMessageCenter instances
// in a single process, but because RuntimeClient keeps a static pointer to a single OutsideRuntimeClient instance, this is not
// generally done in practice.
//
// Each ProxiedMessageCenter keeps a collection of GatewayConnection instances. Each of these represents a bidirectional connection
// to a single gateway endpoint. Requests are assigned to a specific connection based on the target grain ID, so that requests to
// the same grain will go to the same gateway, in sending order. To do this efficiently and scalably, we bucket grains together
// based on their hash code mod a reasonably large number (currently 8192).
//
// When the first message is sent to a bucket, we assign a gateway to that bucket, selecting in round-robin fashion from the known
// gateways. If this is the first message to be sent to the gateway, we will create a new connection for it and assign the bucket to
// the new connection. Either way, all messages to grains in that bucket will be sent to the assigned connection as long as the
// connection is live.
//
// Connections stay live as long as possible. If a socket error or other communications error occurs, then the client will try to
// reconnect twice before giving up on the gateway. If the connection cannot be re-established, then the gateway is deemed (temporarily)
// dead, and any buckets assigned to the connection are unassigned (so that the next message sent will cause a new gateway to be selected).
// There is no assumption that this death is permanent; the system will try to reuse the gateway every 5 minutes.
//
// The list of known gateways is managed by the GatewayManager class. See comments there for details...
// =======================================================================================================================================
// Locking and lock protocol:
// The ProxiedMessageCenter instance itself may be accessed by many client threads simultaneously, and each GatewayConnection instance
// is accessed by its own thread, by the thread for its Receiver, and potentially by client threads from within the ProxiedMessageCenter.
// Thus, we need locks to protect the various data structured from concurrent modifications.
//
// Each GatewayConnection instance has a "lockable" field that is used to lock local information. This lock is used by both the GatewayConnection
// thread and the Receiver thread.
//
// The ProxiedMessageCenter instance also has a "lockable" field. This lock is used by any client thread running methods within the instance.
//
// Note that we take care to ensure that client threads never need locked access to GatewayConnection state and GatewayConnection threads never need
// locked access to ProxiedMessageCenter state. Thus, we don't need to worry about lock ordering across these objects.
//
// Finally, the GatewayManager instance within the ProxiedMessageCenter has two collections, knownGateways and knownDead, that it needs to
// protect with locks. Rather than using a "lockable" field, each collection is lcoked to protect the collection.
// All sorts of threads can run within the GatewayManager, including client threads and GatewayConnection threads, so we need to
// be careful about locks here. The protocol we use is to always take GatewayManager locks last, to only take them within GatewayManager methods,
// and to always release them before returning from the method. In addition, we never simultaneously hold the knownGateways and knownDead locks,
// so there's no need to worry about the order in which we take and release those locks.
// </summary>
internal class ProxiedMessageCenter : IMessageCenter, IDisposable
{
internal readonly SerializationManager SerializationManager;
#region Constants
internal static readonly TimeSpan MINIMUM_INTERCONNECT_DELAY = TimeSpan.FromMilliseconds(100); // wait one tenth of a second between connect attempts
internal const int CONNECT_RETRY_COUNT = 2; // Retry twice before giving up on a gateway server
#endregion
internal GrainId ClientId { get; private set; }
public IRuntimeClient RuntimeClient { get; }
internal bool Running { get; private set; }
internal readonly GatewayManager GatewayManager;
internal readonly BlockingCollection<Message> PendingInboundMessages;
private readonly Dictionary<Uri, GatewayConnection> gatewayConnections;
private int numMessages;
// The grainBuckets array is used to select the connection to use when sending an ordered message to a grain.
// Requests are bucketed by GrainID, so that all requests to a grain get routed through the same bucket.
// Each bucket holds a (possibly null) weak reference to a GatewayConnection object. That connection instance is used
// if the WeakReference is non-null, is alive, and points to a live gateway connection. If any of these conditions is
// false, then a new gateway is selected using the gateway manager, and a new connection established if necessary.
private readonly WeakReference[] grainBuckets;
private readonly Logger logger;
private readonly object lockable;
public SiloAddress MyAddress { get; private set; }
public IMessagingConfiguration MessagingConfiguration { get; private set; }
private readonly QueueTrackingStatistic queueTracking;
private int numberOfConnectedGateways = 0;
private readonly MessageFactory messageFactory;
private readonly IClusterConnectionStatusListener connectionStatusListener;
public ProxiedMessageCenter(
ClientConfiguration config,
IPAddress localAddress,
int gen,
GrainId clientId,
IGatewayListProvider gatewayListProvider,
SerializationManager serializationManager,
IRuntimeClient runtimeClient,
MessageFactory messageFactory,
IClusterConnectionStatusListener connectionStatusListener)
{
this.SerializationManager = serializationManager;
lockable = new object();
MyAddress = SiloAddress.New(new IPEndPoint(localAddress, 0), gen);
ClientId = clientId;
this.RuntimeClient = runtimeClient;
this.messageFactory = messageFactory;
this.connectionStatusListener = connectionStatusListener;
Running = false;
MessagingConfiguration = config;
GatewayManager = new GatewayManager(config, gatewayListProvider);
PendingInboundMessages = new BlockingCollection<Message>();
gatewayConnections = new Dictionary<Uri, GatewayConnection>();
numMessages = 0;
grainBuckets = new WeakReference[config.ClientSenderBuckets];
logger = LogManager.GetLogger("Messaging.ProxiedMessageCenter", LoggerType.Runtime);
if (logger.IsVerbose) logger.Verbose("Proxy grain client constructed");
IntValueStatistic.FindOrCreate(
StatisticNames.CLIENT_CONNECTED_GATEWAY_COUNT,
() =>
{
lock (gatewayConnections)
{
return gatewayConnections.Values.Count(conn => conn.IsLive);
}
});
if (StatisticsCollector.CollectQueueStats)
{
queueTracking = new QueueTrackingStatistic("ClientReceiver");
}
}
public void Start()
{
Running = true;
if (StatisticsCollector.CollectQueueStats)
{
queueTracking.OnStartExecution();
}
if (logger.IsVerbose) logger.Verbose("Proxy grain client started");
}
public void PrepareToStop()
{
// put any pre stop logic here.
}
public void Stop()
{
Running = false;
Utils.SafeExecute(() =>
{
PendingInboundMessages.CompleteAdding();
});
if (StatisticsCollector.CollectQueueStats)
{
queueTracking.OnStopExecution();
}
GatewayManager.Stop();
foreach (var gateway in gatewayConnections.Values.ToArray())
{
gateway.Stop();
}
}
public void SendMessage(Message msg)
{
GatewayConnection gatewayConnection = null;
bool startRequired = false;
// If there's a specific gateway specified, use it
if (msg.TargetSilo != null)
{
Uri addr = msg.TargetSilo.ToGatewayUri();
lock (lockable)
{
if (!gatewayConnections.TryGetValue(addr, out gatewayConnection) || !gatewayConnection.IsLive)
{
gatewayConnection = new GatewayConnection(addr, this, this.messageFactory);
gatewayConnections[addr] = gatewayConnection;
if (logger.IsVerbose) logger.Verbose("Creating gateway to {0} for pre-addressed message", addr);
startRequired = true;
}
}
}
// For untargeted messages to system targets, and for unordered messages, pick a next connection in round robin fashion.
else if (msg.TargetGrain.IsSystemTarget || msg.IsUnordered)
{
// Get the cached list of live gateways.
// Pick a next gateway name in a round robin fashion.
// See if we have a live connection to it.
// If Yes, use it.
// If not, create a new GatewayConnection and start it.
// If start fails, we will mark this connection as dead and remove it from the GetCachedLiveGatewayNames.
lock (lockable)
{
int msgNumber = numMessages;
numMessages = unchecked(numMessages + 1);
IList<Uri> gatewayNames = GatewayManager.GetLiveGateways();
int numGateways = gatewayNames.Count;
if (numGateways == 0)
{
RejectMessage(msg, "No gateways available");
logger.Warn(ErrorCode.ProxyClient_CannotSend, "Unable to send message {0}; gateway manager state is {1}", msg, GatewayManager);
return;
}
Uri addr = gatewayNames[msgNumber % numGateways];
if (!gatewayConnections.TryGetValue(addr, out gatewayConnection) || !gatewayConnection.IsLive)
{
gatewayConnection = new GatewayConnection(addr, this, this.messageFactory);
gatewayConnections[addr] = gatewayConnection;
if (logger.IsVerbose) logger.Verbose(ErrorCode.ProxyClient_CreatedGatewayUnordered, "Creating gateway to {0} for unordered message to grain {1}", addr, msg.TargetGrain);
startRequired = true;
}
// else - Fast path - we've got a live gatewayConnection to use
}
}
// Otherwise, use the buckets to ensure ordering.
else
{
var index = msg.TargetGrain.GetHashCode_Modulo((uint)grainBuckets.Length);
lock (lockable)
{
// Repeated from above, at the declaration of the grainBuckets array:
// Requests are bucketed by GrainID, so that all requests to a grain get routed through the same bucket.
// Each bucket holds a (possibly null) weak reference to a GatewayConnection object. That connection instance is used
// if the WeakReference is non-null, is alive, and points to a live gateway connection. If any of these conditions is
// false, then a new gateway is selected using the gateway manager, and a new connection established if necessary.
var weakRef = grainBuckets[index];
if ((weakRef != null) && weakRef.IsAlive)
{
gatewayConnection = weakRef.Target as GatewayConnection;
}
if ((gatewayConnection == null) || !gatewayConnection.IsLive)
{
var addr = GatewayManager.GetLiveGateway();
if (addr == null)
{
RejectMessage(msg, "No gateways available");
logger.Warn(ErrorCode.ProxyClient_CannotSend_NoGateway, "Unable to send message {0}; gateway manager state is {1}", msg, GatewayManager);
return;
}
if (logger.IsVerbose2) logger.Verbose2(ErrorCode.ProxyClient_NewBucketIndex, "Starting new bucket index {0} for ordered messages to grain {1}", index, msg.TargetGrain);
if (!gatewayConnections.TryGetValue(addr, out gatewayConnection) || !gatewayConnection.IsLive)
{
gatewayConnection = new GatewayConnection(addr, this, this.messageFactory);
gatewayConnections[addr] = gatewayConnection;
if (logger.IsVerbose) logger.Verbose(ErrorCode.ProxyClient_CreatedGatewayToGrain, "Creating gateway to {0} for message to grain {1}, bucket {2}, grain id hash code {3}X", addr, msg.TargetGrain, index,
msg.TargetGrain.GetHashCode().ToString("x"));
startRequired = true;
}
grainBuckets[index] = new WeakReference(gatewayConnection);
}
}
}
if (startRequired)
{
gatewayConnection.Start();
if (!gatewayConnection.IsLive)
{
// if failed to start Gateway connection (failed to connect), try sending this msg to another Gateway.
RejectOrResend(msg);
return;
}
}
try
{
gatewayConnection.QueueRequest(msg);
if (logger.IsVerbose2) logger.Verbose2(ErrorCode.ProxyClient_QueueRequest, "Sending message {0} via gateway {1}", msg, gatewayConnection.Address);
}
catch (InvalidOperationException)
{
// This exception can be thrown if the gateway connection we selected was closed since we checked (i.e., we lost the race)
// If this happens, we reject if the message is targeted to a specific silo, or try again if not
RejectOrResend(msg);
}
}
private void RejectOrResend(Message msg)
{
if (msg.TargetSilo != null)
{
RejectMessage(msg, String.Format("Target silo {0} is unavailable", msg.TargetSilo));
}
else
{
SendMessage(msg);
}
}
public Task<IGrainTypeResolver> GetTypeCodeMap(IInternalGrainFactory grainFactory)
{
var silo = GetLiveGatewaySiloAddress();
return GetTypeManager(silo, grainFactory).GetClusterTypeCodeMap();
}
public Task<Streams.ImplicitStreamSubscriberTable> GetImplicitStreamSubscriberTable(IInternalGrainFactory grainFactory)
{
var silo = GetLiveGatewaySiloAddress();
return GetTypeManager(silo, grainFactory).GetImplicitStreamSubscriberTable(silo);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
public Message WaitMessage(Message.Categories type, CancellationToken ct)
{
try
{
if (ct.IsCancellationRequested)
{
return null;
}
// Don't pass CancellationToken to Take. It causes too much spinning.
Message msg = PendingInboundMessages.Take();
#if TRACK_DETAILED_STATS
if (StatisticsCollector.CollectQueueStats)
{
queueTracking.OnDeQueueRequest(msg);
}
#endif
return msg;
}
#if !NETSTANDARD
catch (ThreadAbortException exc)
{
// Silo may be shutting-down, so downgrade to verbose log
logger.Verbose(ErrorCode.ProxyClient_ThreadAbort, "Received thread abort exception -- exiting. {0}", exc);
Thread.ResetAbort();
return null;
}
#endif
catch (OperationCanceledException exc)
{
logger.Verbose(ErrorCode.ProxyClient_OperationCancelled, "Received operation cancelled exception -- exiting. {0}", exc);
return null;
}
catch (ObjectDisposedException exc)
{
logger.Verbose(ErrorCode.ProxyClient_OperationCancelled, "Received Object Disposed exception -- exiting. {0}", exc);
return null;
}
catch (InvalidOperationException exc)
{
logger.Verbose(ErrorCode.ProxyClient_OperationCancelled, "Received Invalid Operation exception -- exiting. {0}", exc);
return null;
}
catch (Exception ex)
{
logger.Error(ErrorCode.ProxyClient_ReceiveError, "Unexpected error getting an inbound message", ex);
return null;
}
}
internal void QueueIncomingMessage(Message msg)
{
#if TRACK_DETAILED_STATS
if (StatisticsCollector.CollectQueueStats)
{
queueTracking.OnEnQueueRequest(1, PendingInboundMessages.Count, msg);
}
#endif
PendingInboundMessages.Add(msg);
}
private void RejectMessage(Message msg, string reasonFormat, params object[] reasonParams)
{
if (!Running) return;
var reason = String.Format(reasonFormat, reasonParams);
if (msg.Direction != Message.Directions.Request)
{
if (logger.IsVerbose) logger.Verbose(ErrorCode.ProxyClient_DroppingMsg, "Dropping message: {0}. Reason = {1}", msg, reason);
}
else
{
if (logger.IsVerbose) logger.Verbose(ErrorCode.ProxyClient_RejectingMsg, "Rejecting message: {0}. Reason = {1}", msg, reason);
MessagingStatisticsGroup.OnRejectedMessage(msg);
Message error = this.messageFactory.CreateRejectionResponse(msg, Message.RejectionTypes.Unrecoverable, reason);
QueueIncomingMessage(error);
}
}
/// <summary>
/// For testing use only
/// </summary>
public void Disconnect()
{
foreach (var connection in gatewayConnections.Values.ToArray())
{
connection.Stop();
}
}
/// <summary>
/// For testing use only.
/// </summary>
public void Reconnect()
{
throw new NotImplementedException("Reconnect");
}
#region Random IMessageCenter stuff
public int SendQueueLength
{
get { return 0; }
}
public int ReceiveQueueLength
{
get { return 0; }
}
#endregion
private IClusterTypeManager GetTypeManager(SiloAddress destination, IInternalGrainFactory grainFactory)
{
return grainFactory.GetSystemTarget<IClusterTypeManager>(Constants.TypeManagerId, destination);
}
private SiloAddress GetLiveGatewaySiloAddress()
{
var gateway = GatewayManager.GetLiveGateway();
if (gateway == null)
{
throw new OrleansException("Not connected to a gateway");
}
return gateway.ToSiloAddress();
}
internal void UpdateClientId(GrainId clientId)
{
if (ClientId.Category != UniqueKey.Category.Client)
throw new InvalidOperationException("Only handshake client ID can be updated with a cluster ID.");
if (clientId.Category != UniqueKey.Category.GeoClient)
throw new ArgumentException("Handshake client ID can only be updated with a geo client.", nameof(clientId));
ClientId = clientId;
}
internal void OnGatewayConnectionOpen()
{
Interlocked.Increment(ref numberOfConnectedGateways);
}
internal void OnGatewayConnectionClosed()
{
if (Interlocked.Decrement(ref numberOfConnectedGateways) == 0)
{
this.connectionStatusListener.NotifyClusterConnectionLost();
}
}
public void Dispose()
{
PendingInboundMessages.Dispose();
if (gatewayConnections != null)
foreach (var item in gatewayConnections)
{
item.Value.Dispose();
}
GatewayManager.Dispose();
}
}
}
| |
// <copyright file="PlayGamesPlatform.cs" company="Google Inc.">
// Copyright (C) 2014 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 GooglePlayGames
{
using System;
using UnityEngine.SocialPlatforms;
using System.Collections.Generic;
using UnityEngine;
using GooglePlayGames.BasicApi;
using GooglePlayGames.OurUtils;
using GooglePlayGames.BasicApi.Multiplayer;
using GooglePlayGames.BasicApi.SavedGame;
using GooglePlayGames.BasicApi.Quests;
using GooglePlayGames.BasicApi.Events;
using GooglePlayGames.BasicApi.Nearby;
/// <summary>
/// Provides access to the Google Play Games platform. This is an implementation of
/// UnityEngine.SocialPlatforms.ISocialPlatform. Activate this platform by calling
/// the <see cref="Activate" /> method, then authenticate by calling
/// the <see cref="Authenticate" /> method. After authentication
/// completes, you may call the other methods of this class. This is not a complete
/// implementation of the ISocialPlatform interface. Methods lacking an implementation
/// or whose behavior is at variance with the standard are noted as such.
/// </summary>
public class PlayGamesPlatform : ISocialPlatform
{
private static volatile PlayGamesPlatform sInstance = null;
private readonly PlayGamesClientConfiguration mConfiguration;
private PlayGamesLocalUser mLocalUser = null;
private IPlayGamesClient mClient = null;
private volatile static bool sNearbyInitializePending;
private volatile static INearbyConnectionClient sNearbyConnectionClient;
// the default leaderboard we show on ShowLeaderboardUI
private string mDefaultLbUi = null;
// achievement/leaderboard ID mapping table
private Dictionary<string, string> mIdMap = new Dictionary<string, string>();
private PlayGamesPlatform(PlayGamesClientConfiguration configuration)
{
this.mLocalUser = new PlayGamesLocalUser(this);
this.mConfiguration = configuration;
}
internal PlayGamesPlatform(IPlayGamesClient client)
{
this.mClient = Misc.CheckNotNull(client);
this.mLocalUser = new PlayGamesLocalUser(this);
this.mConfiguration = PlayGamesClientConfiguration.DefaultConfiguration;
}
public static void InitializeInstance(PlayGamesClientConfiguration configuration)
{
if (sInstance != null)
{
Logger.w("PlayGamesPlatform already initialized. Ignoring this call.");
return;
}
sInstance = new PlayGamesPlatform(configuration);
}
/// <summary>
/// Gets the singleton instance of the Play Games platform.
/// </summary>
/// <returns>
/// The instance.
/// </returns>
public static PlayGamesPlatform Instance
{
get
{
if (sInstance == null)
{
Logger.d("Instance was not initialized, using default configuration.");
InitializeInstance(PlayGamesClientConfiguration.DefaultConfiguration);
}
return sInstance;
}
}
public static void InitializeNearby(Action<INearbyConnectionClient> callback)
{
Debug.Log("Calling InitializeNearby!");
if (sNearbyConnectionClient == null)
{
#if UNITY_ANDROID && !UNITY_EDITOR
NearbyConnectionClientFactory.Create(client => {
Debug.Log("Nearby Client Created!!");
sNearbyConnectionClient = client;
if (callback != null) {
callback.Invoke(client);
}
else {
Debug.Log("Initialize Nearby callback is null");
}
});
#else
sNearbyConnectionClient = new DummyNearbyConnectionClient();
if (callback != null)
{
callback.Invoke(sNearbyConnectionClient);
}
#endif
}
else if (callback != null)
{
Debug.Log("Nearby Already initialized: calling callback directly");
callback.Invoke(sNearbyConnectionClient);
}
else
{
Debug.Log("Nearby Already initialized");
}
}
/// <summary>
/// Gets the nearby connection client. NOTE: Can be null until the nearby client
/// is initialized. Call InitializeNearby to use callback to be notified when initialization
/// is complete.
/// </summary>
/// <value>The nearby.</value>
public static INearbyConnectionClient Nearby
{
get
{
if (sNearbyConnectionClient == null && !sNearbyInitializePending)
{
sNearbyInitializePending = true;
InitializeNearby(null);
}
return sNearbyConnectionClient;
}
}
/// <summary>
/// Gets or sets a value indicating whether debug logs are enabled. This property
/// may be set before calling <see cref="Activate" /> method.
/// </summary>
/// <returns>
/// <c>true</c> if debug log enabled; otherwise, <c>false</c>.
/// </returns>
public static bool DebugLogEnabled
{
get
{
return Logger.DebugLogEnabled;
}
set
{
Logger.DebugLogEnabled = value;
}
}
/// <summary> Gets the real time multiplayer API object</summary>
public IRealTimeMultiplayerClient RealTime
{
get
{
return mClient.GetRtmpClient();
}
}
/// <summary> Gets the turn based multiplayer API object</summary>
public ITurnBasedMultiplayerClient TurnBased
{
get
{
return mClient.GetTbmpClient();
}
}
public ISavedGameClient SavedGame
{
get
{
return mClient.GetSavedGameClient();
}
}
public IEventsClient Events
{
get
{
return mClient.GetEventsClient();
}
}
public IQuestsClient Quests
{
get
{
return mClient.GetQuestsClient();
}
}
/// <summary>
/// Activates the Play Games platform as the implementation of Social.Active.
/// After calling this method, you can call methods on Social.Active. For
/// example, <c>Social.Active.Authenticate()</c>.
/// </summary>
/// <returns>The singleton <see cref="PlayGamesPlatform" /> instance.</returns>
public static PlayGamesPlatform Activate()
{
Logger.d("Activating PlayGamesPlatform.");
Social.Active = PlayGamesPlatform.Instance;
Logger.d("PlayGamesPlatform activated: " + Social.Active);
return PlayGamesPlatform.Instance;
}
/// <summary>
/// Specifies that the ID <c>fromId</c> should be implicitly replaced by <c>toId</c>
/// on any calls that take a leaderboard or achievement ID. After a mapping is
/// registered, you can use <c>fromId</c> instead of <c>toId</c> when making a call.
/// For example, the following two snippets are equivalent:
///
/// <code>
/// ReportProgress("Cfiwjew894_AQ", 100.0, callback);
/// </code>
/// ...is equivalent to:
/// <code>
/// AddIdMapping("super-combo", "Cfiwjew894_AQ");
/// ReportProgress("super-combo", 100.0, callback);
/// </code>
///
/// </summary>
/// <param name='fromId'>
/// The identifier to map.
/// </param>
/// <param name='toId'>
/// The identifier that <c>fromId</c> will be mapped to.
/// </param>
public void AddIdMapping(string fromId, string toId)
{
mIdMap[fromId] = toId;
}
/// <summary>
/// Authenticate the local user with the Google Play Games service.
/// </summary>
/// <param name='callback'>
/// The callback to call when authentication finishes. It will be called
/// with <c>true</c> if authentication was successful, <c>false</c>
/// otherwise.
/// </param>
public void Authenticate(Action<bool> callback)
{
Authenticate(callback, false);
}
/// <summary>
/// Authenticate the local user with the Google Play Games service.
/// </summary>
/// <param name='callback'>
/// The callback to call when authentication finishes. It will be called
/// with <c>true</c> if authentication was successful, <c>false</c>
/// otherwise.
/// </param>
/// <param name='silent'>
/// Indicates whether authentication should be silent. If <c>false</c>,
/// authentication may show popups and interact with the user to obtain
/// authorization. If <c>true</c>, there will be no popups or interaction with
/// the user, and the authentication will fail instead if such interaction
/// is required. A typical pattern is to try silent authentication on startup
/// and, if that fails, present the user with a "Sign in" button that then
/// triggers normal (not silent) authentication.
/// </param>
public void Authenticate(Action<bool> callback, bool silent)
{
// make a platform-specific Play Games client
if (mClient == null)
{
Logger.d("Creating platform-specific Play Games client.");
mClient = PlayGamesClientFactory.GetPlatformPlayGamesClient(mConfiguration);
}
// authenticate!
mClient.Authenticate(callback, silent);
}
/// <summary>
/// Provided for compatibility with ISocialPlatform.
/// </summary>
/// <seealso cref="Authenticate(Action<bool>,bool)"/>
/// <param name="unused">Unused.</param>
/// <param name="callback">Callback.</param>
public void Authenticate(ILocalUser unused, Action<bool> callback)
{
Authenticate(callback, false);
}
/// <summary>
/// Determines whether the user is authenticated.
/// </summary>
/// <returns>
/// <c>true</c> if the user is authenticated; otherwise, <c>false</c>.
/// </returns>
public bool IsAuthenticated()
{
return mClient != null && mClient.IsAuthenticated();
}
/// <summary>Sign out. After signing out,
/// Authenticate must be called again to sign back in.
/// </summary>
public void SignOut()
{
if (mClient != null)
{
mClient.SignOut();
}
}
/// <summary>
/// Loads the user information if available.
/// <param name="userIds">The user ids to look up</param>
/// <param name="callback">The callback</param>
/// </summary>
public void LoadUsers(string[] userIds, Action<IUserProfile[]> callback)
{
if (!IsAuthenticated())
{
Logger.e("GetUserId() can only be called after authentication.");
callback(new IUserProfile[0]);
}
mClient.LoadUsers(userIds, callback);
}
/// <summary>
/// Returns the user's Google ID.
/// </summary>
/// <returns>
/// The user's Google ID. No guarantees are made as to the meaning or format of
/// this identifier except that it is unique to the user who is signed in.
/// </returns>
public string GetUserId()
{
if (!IsAuthenticated())
{
Logger.e("GetUserId() can only be called after authentication.");
return "0";
}
return mClient.GetUserId();
}
/// <summary>
/// Returns an id token for the user.
/// </summary>
/// <returns>
/// An id token for the user.
/// </returns>
public string GetIdToken()
{
if (mClient != null)
{
return mClient.GetIdToken();
}
return null;
}
/// <summary>
/// Returns an id token for the user.
/// </summary>
/// <returns>
/// An id token for the user.
/// </returns>
public string GetAccessToken()
{
if (mClient != null)
{
return mClient.GetAccessToken();
}
return null;
}
/// <summary>
/// Gets the email of the current user.
/// This requires additional configuration of permissions in order
/// to work.
/// </summary>
/// <returns>The user email.</returns>
public string GetUserEmail()
{
if (mClient != null)
{
return mClient.GetUserEmail();
}
return null;
}
/// <summary>
/// Returns the achievement corresponding to the passed achievement identifier.
/// </summary>
/// <returns>
/// The achievement corresponding to the identifer. <code>null</code> if no such
/// achievement is found or if the user is not authenticated.
/// </returns>
/// <param name="achievementId">
/// The identifier of the achievement.
/// </param>
public Achievement GetAchievement(string achievementId)
{
if (!IsAuthenticated())
{
Logger.e("GetAchievement can only be called after authentication.");
return null;
}
return mClient.GetAchievement(achievementId);
}
/// <summary>
/// Returns the user's display name.
/// </summary>
/// <returns>
/// The user display name (e.g. "Bruno Oliveira")
/// </returns>
public string GetUserDisplayName()
{
if (!IsAuthenticated())
{
Logger.e("GetUserDisplayName can only be called after authentication.");
return string.Empty;
}
return mClient.GetUserDisplayName();
}
/// <summary>
/// Returns the user's avatar URL if they have one.
/// </summary>
/// <returns>
/// The URL, or <code>null</code> if the user is not authenticated or does not have
/// an avatar.
/// </returns>
public string GetUserImageUrl()
{
if (!IsAuthenticated())
{
Logger.e("GetUserImageUrl can only be called after authentication.");
return null;
}
return mClient.GetUserImageUrl();
}
/// <summary>
/// Reports the progress of an achievement (reveal, unlock or increment). This method attempts
/// to implement the expected behavior of ISocialPlatform.ReportProgress as closely as possible,
/// as described below. Although this method works with incremental achievements for compatibility
/// purposes, calling this method for incremental achievements is not recommended,
/// since the Play Games API exposes incremental achievements in a very different way
/// than the interface presented by ISocialPlatform.ReportProgress. The implementation of this
/// method for incremental achievements attempts to produce the correct result, but may be
/// imprecise. If possible, call <see cref="IncrementAchievement" /> instead.
/// </summary>
/// <param name='achievementID'>
/// The ID of the achievement to unlock, reveal or increment. This can be a raw Google Play
/// Games achievement ID (alphanumeric string), or an alias that was previously configured
/// by a call to <see cref="AddIdMapping" />.
/// </param>
/// <param name='progress'>
/// Progress of the achievement. If the achievement is standard (not incremental), then
/// a progress of 0.0 will reveal the achievement and 100.0 will unlock it. Behavior of other
/// values is undefined. If the achievement is incremental, then this value is interpreted
/// as the total percentage of the achievement's progress that the player should have
/// as a result of this call (regardless of the progress they had before). So if the
/// player's previous progress was 30% and this call specifies 50.0, the new progress will
/// be 50% (not 80%).
/// </param>
/// <param name='callback'>
/// Callback that will be called to report the result of the operation: <c>true</c> on
/// success, <c>false</c> otherwise.
/// </param>
public void ReportProgress(string achievementID, double progress, Action<bool> callback)
{
if (!IsAuthenticated())
{
Logger.e("ReportProgress can only be called after authentication.");
if (callback != null)
{
callback.Invoke(false);
}
return;
}
// map ID, if it's in the dictionary
Logger.d("ReportProgress, " + achievementID + ", " + progress);
achievementID = MapId(achievementID);
// if progress is 0.0, we just want to reveal it
if (progress < 0.000001)
{
Logger.d("Progress 0.00 interpreted as request to reveal.");
mClient.RevealAchievement(achievementID, callback);
return;
}
// figure out if it's a standard or incremental achievement
bool isIncremental = false;
int curSteps = 0, totalSteps = 0;
Achievement ach = mClient.GetAchievement(achievementID);
if (ach == null)
{
Logger.w("Unable to locate achievement " + achievementID);
Logger.w("As a quick fix, assuming it's standard.");
isIncremental = false;
}
else
{
isIncremental = ach.IsIncremental;
curSteps = ach.CurrentSteps;
totalSteps = ach.TotalSteps;
Logger.d("Achievement is " + (isIncremental ? "INCREMENTAL" : "STANDARD"));
if (isIncremental)
{
Logger.d("Current steps: " + curSteps + "/" + totalSteps);
}
}
// do the right thing depending on the achievement type
if (isIncremental)
{
// increment it to the target percentage (approximate)
Logger.d("Progress " + progress +
" interpreted as incremental target (approximate).");
if (progress >= 0.0 && progress <= 1.0)
{
// in a previous version, incremental progress was reported by using the range [0-1]
Logger.w("Progress " + progress + " is less than or equal to 1. You might be trying to use values in the range of [0,1], while values are expected to be within the range [0,100]. If you are using the latter, you can safely ignore this message.");
}
int targetSteps = (int)((progress / 100) * totalSteps);
int numSteps = targetSteps - curSteps;
Logger.d("Target steps: " + targetSteps + ", cur steps:" + curSteps);
Logger.d("Steps to increment: " + numSteps);
if (numSteps > 0)
{
mClient.IncrementAchievement(achievementID, numSteps, callback);
}
}
else if (progress >= 100)
{
// unlock it!
Logger.d("Progress " + progress + " interpreted as UNLOCK.");
mClient.UnlockAchievement(achievementID, callback);
}
else
{
// not enough to unlock
Logger.d("Progress " + progress + " not enough to unlock non-incremental achievement.");
}
}
/// <summary>
/// Increments an achievement. This is a Play Games extension of the ISocialPlatform API.
/// </summary>
/// <param name='achievementID'>
/// The ID of the achievement to increment. This can be a raw Google Play
/// Games achievement ID (alphanumeric string), or an alias that was previously configured
/// by a call to <see cref="AddIdMapping" />.
/// </param>
/// <param name='steps'>
/// The number of steps to increment the achievement by.
/// </param>
/// <param name='callback'>
/// The callback to call to report the success or failure of the operation. The callback
/// will be called with <c>true</c> to indicate success or <c>false</c> for failure.
/// </param>
public void IncrementAchievement(string achievementID, int steps, Action<bool> callback)
{
if (!IsAuthenticated())
{
Logger.e("IncrementAchievement can only be called after authentication.");
if (callback != null)
{
callback.Invoke(false);
}
return;
}
// map ID, if it's in the dictionary
Logger.d("IncrementAchievement: " + achievementID + ", steps " + steps);
achievementID = MapId(achievementID);
mClient.IncrementAchievement(achievementID, steps, callback);
}
/// <summary>
/// Set an achievement to have at least the given number of steps completed.
/// Calling this method while the achievement already has more steps than
/// the provided value is a no-op. Once the achievement reaches the
/// maximum number of steps, the achievement is automatically unlocked,
/// and any further mutation operations are ignored.
/// </summary>
/// <param name='achievementID'>
/// The ID of the achievement to increment. This can be a raw Google Play
/// Games achievement ID (alphanumeric string), or an alias that was previously configured
/// by a call to <see cref="AddIdMapping" />.
/// </param>
/// <param name='steps'>
/// The number of steps to increment the achievement by.
/// </param>
/// <param name='callback'>
/// The callback to call to report the success or failure of the operation. The callback
/// will be called with <c>true</c> to indicate success or <c>false</c> for failure.
/// </param>
public void SetStepsAtLeast(string achievementID, int steps, Action<bool> callback)
{
if (!IsAuthenticated())
{
Logger.e("SetStepsAtLeast can only be called after authentication.");
if (callback != null)
{
callback.Invoke(false);
}
return;
}
// map ID, if it's in the dictionary
Logger.d("SetStepsAtLeast: " + achievementID + ", steps " + steps);
achievementID = MapId(achievementID);
mClient.SetStepsAtLeast(achievementID, steps, callback);
}
/// <summary>
/// Loads the Achievement descriptions.
/// <param name="callback">The callback to receive the descriptions</param>
/// </summary>
public void LoadAchievementDescriptions(Action<IAchievementDescription[]> callback)
{
if (!IsAuthenticated())
{
Logger.e("LoadAchievementDescriptions can only be called after authentication.");
callback.Invoke(null);
}
mClient.LoadAchievements(ach =>
{
IAchievementDescription[] data = new IAchievementDescription[ach.Length];
for (int i = 0; i < data.Length; i++)
{
data[i] = new PlayGamesAchievement(ach[i]);
}
callback.Invoke(data);
});
}
/// <summary>
/// Loads the achievement state for the current user.
/// <param name="callback">The callback to receive the achievements</param>
/// </summary>
public void LoadAchievements(Action<IAchievement[]> callback)
{
if (!IsAuthenticated())
{
Logger.e("LoadAchievements can only be called after authentication.");
callback.Invoke(null);
}
mClient.LoadAchievements(ach =>
{
IAchievement[] data = new IAchievement[ach.Length];
for (int i = 0; i < data.Length; i++)
{
data[i] = new PlayGamesAchievement(ach[i]);
}
callback.Invoke(data);
});
}
/// <summary>
/// Creates an achievement object which may be subsequently used to report an
/// achievement.
/// </summary>
/// <returns>
/// The achievement object.
/// </returns>
public IAchievement CreateAchievement()
{
return new PlayGamesAchievement();
}
/// <summary>
/// Reports a score to a leaderboard.
/// </summary>
/// <param name='score'>
/// The score to report.
/// </param>
/// <param name='board'>
/// The ID of the leaderboard on which the score is to be posted. This may be a raw
/// Google Play Games leaderboard ID or an alias configured through a call to
/// <see cref="AddIdMapping" />.
/// </param>
/// <param name='callback'>
/// The callback to call to report the success or failure of the operation. The callback
/// will be called with <c>true</c> to indicate success or <c>false</c> for failure.
/// </param>
public void ReportScore(long score, string board, Action<bool> callback)
{
if (!IsAuthenticated())
{
Logger.e("ReportScore can only be called after authentication.");
if (callback != null)
{
callback.Invoke(false);
}
return;
}
Logger.d("ReportScore: score=" + score + ", board=" + board);
string lbId = MapId(board);
mClient.SubmitScore(lbId, score, callback);
}
/// <summary>
/// Submits the score for the currently signed-in player
/// to the leaderboard associated with a specific id
/// and metadata (such as something the player did to earn the score).
/// </summary>
/// <param name="score">Score.</param>
/// <param name="board">leaderboard id.</param>
/// <param name="metadata">metadata about the score.</param>
/// <param name="callback">Callback upon completion.</param>
public void ReportScore(long score, string board, string metadata, Action<bool> callback)
{
if (!IsAuthenticated())
{
Logger.e("ReportScore can only be called after authentication.");
if (callback != null)
{
callback.Invoke(false);
}
return;
}
Logger.d("ReportScore: score=" + score + ", board=" + board +
" metadata=" + metadata);
string lbId = MapId(board);
mClient.SubmitScore(lbId, score, metadata, callback);
}
/// <summary>
/// Loads the scores relative the player. This returns the 25
/// (which is the max results returned by the SDK per call) scores
/// that are around the player's score on the Social, all time leaderboard.
/// Use the overloaded methods which are specific to GPGS to modify these
/// parameters.
/// </summary>
/// <param name="leaderboardId">Leaderboard Id</param>
/// <param name="callback">Callback.</param>
public void LoadScores(string leaderboardId, Action<IScore[]> callback)
{
LoadScores(leaderboardId, LeaderboardStart.PlayerCentered,
mClient.LeaderboardMaxResults(),
LeaderboardCollection.Public,
LeaderboardTimeSpan.AllTime,
(scoreData) => callback(scoreData.Scores));
}
/// <summary>
/// Loads the scores using the provided parameters.
/// </summary>
/// <param name="leaderboardId">Leaderboard identifier.</param>
/// <param name="start">Start either top scores, or player centered.</param>
/// <param name="rowCount">Row count. the number of rows to return.</param>
/// <param name="collection">Collection. social or public</param>
/// <param name="timeSpan">Time span. daily, weekly, all-time</param>
/// <param name="callback">Callback.</param>
public void LoadScores(string leaderboardId, LeaderboardStart start,
int rowCount, LeaderboardCollection collection,
LeaderboardTimeSpan timeSpan,
Action<LeaderboardScoreData> callback)
{
if (!IsAuthenticated())
{
Logger.e("LoadScores can only be called after authentication.");
callback(new LeaderboardScoreData(leaderboardId,
ResponseStatus.NotAuthorized));
return;
}
mClient.LoadScores(leaderboardId, start,
rowCount, collection, timeSpan, callback);
}
public void LoadMoreScores(ScorePageToken token, int rowCount,
Action<LeaderboardScoreData> callback)
{
if (!IsAuthenticated())
{
Logger.e("LoadMoreScores can only be called after authentication.");
callback(new LeaderboardScoreData(token.LeaderboardId,
ResponseStatus.NotAuthorized));
return;
}
mClient.LoadMoreScores(token, rowCount, callback);
}
/// <summary>
/// Returns a leaderboard object that can be configured to
/// load scores.
/// </summary>
public ILeaderboard CreateLeaderboard()
{
return new PlayGamesLeaderboard(mDefaultLbUi);
}
/// <summary>
/// Shows the standard Google Play Games achievements user interface,
/// which allows the player to browse their achievements.
/// </summary>
public void ShowAchievementsUI()
{
ShowAchievementsUI(null);
}
/// <summary>
/// Shows the standard Google Play Games achievements user interface,
/// which allows the player to browse their achievements.
/// </summary>
/// <param name="callback">If non-null, the callback is invoked when
/// the achievement UI is dismissed</param>
public void ShowAchievementsUI(Action<UIStatus> callback)
{
if (!IsAuthenticated())
{
Logger.e("ShowAchievementsUI can only be called after authentication.");
return;
}
Logger.d("ShowAchievementsUI callback is " + callback);
mClient.ShowAchievementsUI(callback);
}
/// <summary>
/// Shows the standard Google Play Games leaderboards user interface,
/// which allows the player to browse their leaderboards. If you have
/// configured a specific leaderboard as the default through a call to
/// <see cref="SetDefaultLeaderboardForUi" />, the UI will show that
/// specific leaderboard only. Otherwise, a list of all the leaderboards
/// will be shown.
/// </summary>
public void ShowLeaderboardUI()
{
Logger.d("ShowLeaderboardUI with default ID");
ShowLeaderboardUI(MapId(mDefaultLbUi), null);
}
/// <summary>
/// Shows the standard Google Play Games leaderboard UI for the given
/// leaderboard.
/// </summary>
/// <param name='lbId'>
/// The ID of the leaderboard to display. This may be a raw
/// Google Play Games leaderboard ID or an alias configured through a call to
/// <see cref="AddIdMapping" />.
/// </param>
public void ShowLeaderboardUI(string lbId)
{
if (lbId != null)
{
lbId = MapId(lbId);
}
mClient.ShowLeaderboardUI(lbId, LeaderboardTimeSpan.AllTime, null);
}
/// <summary>
/// Shows the leaderboard UI and calls the specified callback upon
/// completion.
/// </summary>
/// <param name="lbId">leaderboard ID, can be null meaning all leaderboards.</param>
/// <param name="callback">Callback to call. If null, nothing is called.</param>
public void ShowLeaderboardUI(string lbId, Action<UIStatus> callback)
{
ShowLeaderboardUI(lbId, LeaderboardTimeSpan.AllTime, callback);
}
/// <summary>
/// Shows the leaderboard UI and calls the specified callback upon
/// completion.
/// </summary>
/// <param name="lbId">leaderboard ID, can be null meaning all leaderboards.</param>
/// <param name="span">Timespan to display scores in the leaderboard.</param>
/// <param name="callback">Callback to call. If null, nothing is called.</param>
public void ShowLeaderboardUI(string lbId, LeaderboardTimeSpan span,
Action<UIStatus> callback)
{
if (!IsAuthenticated())
{
Logger.e("ShowLeaderboardUI can only be called after authentication.");
callback(UIStatus.NotAuthorized);
return;
}
Logger.d("ShowLeaderboardUI, lbId=" + lbId + " callback is " + callback);
mClient.ShowLeaderboardUI(lbId, span, callback);
}
/// <summary>
/// Sets the default leaderboard for the leaderboard UI. After calling this
/// method, a call to <see cref="ShowLeaderboardUI" /> will show only the specified
/// leaderboard instead of showing the list of all leaderboards.
/// </summary>
/// <param name='lbid'>
/// The ID of the leaderboard to display on the default UI. This may be a raw
/// Google Play Games leaderboard ID or an alias configured through a call to
/// <see cref="AddIdMapping" />.
/// </param>
public void SetDefaultLeaderboardForUI(string lbid)
{
Logger.d("SetDefaultLeaderboardForUI: " + lbid);
if (lbid != null)
{
lbid = MapId(lbid);
}
mDefaultLbUi = lbid;
}
/// <summary>
/// Loads the friends that also play this game. See loadConnectedPlayers.
/// </summary>
/// <param name="callback">Callback.</param>
public void LoadFriends(ILocalUser user, Action<bool> callback)
{
if (!IsAuthenticated())
{
Logger.e("LoadScores can only be called after authentication.");
if (callback != null)
{
callback(false);
}
}
mClient.LoadFriends(callback);
}
/// <summary>
/// Loads the leaderboard based on the constraints in the leaderboard
/// object.
/// <param name="board">The leaderboard object. This is created by
/// calling CreateLeaderboard(), and then initialized appropriately.</param>
/// <param name="callback">callback, returning boolean for success</param>
/// </summary>
public void LoadScores(ILeaderboard board, Action<bool> callback)
{
if (!IsAuthenticated())
{
Logger.e("LoadScores can only be called after authentication.");
if (callback != null)
{
callback(false);
}
}
LeaderboardTimeSpan timeSpan;
switch (board.timeScope)
{
case TimeScope.AllTime:
timeSpan = LeaderboardTimeSpan.AllTime;
break;
case TimeScope.Week:
timeSpan = LeaderboardTimeSpan.Weekly;
break;
case TimeScope.Today:
timeSpan = LeaderboardTimeSpan.Daily;
break;
default:
timeSpan = LeaderboardTimeSpan.AllTime;
break;
}
((PlayGamesLeaderboard)board).loading = true;
Logger.d("LoadScores, board=" + board + " callback is " + callback);
mClient.LoadScores(
board.id,
LeaderboardStart.PlayerCentered,
board.range.count > 0 ? board.range.count : mClient.LeaderboardMaxResults(),
board.userScope == UserScope.FriendsOnly ? LeaderboardCollection.Social : LeaderboardCollection.Public,
timeSpan,
(scoreData) => HandleLoadingScores(
(PlayGamesLeaderboard)board, scoreData, callback));
}
internal void HandleLoadingScores(PlayGamesLeaderboard board,
LeaderboardScoreData scoreData, Action<bool> callback)
{
bool ok = board.SetFromData(scoreData);
if (ok && !board.HasAllScores() && scoreData.NextPageToken != null)
{
int rowCount = board.range.count - board.ScoreCount;
// need to load more scores
mClient.LoadMoreScores(scoreData.NextPageToken, rowCount,
(nextScoreData) =>
HandleLoadingScores(board, nextScoreData, callback));
}
else
{
callback(ok);
}
}
/// <summary>
/// Check if the leaderboard is currently loading.
/// <param name="board">The leaderboard of interest.</param>
/// <returns>true if loading.</returns>
/// </summary>
public bool GetLoading(ILeaderboard board)
{
return board != null && board.loading;
}
/// <summary>
/// Gets the local user.
/// </summary>
/// <returns>
/// The local user.
/// </returns>
public ILocalUser localUser
{
get
{
return mLocalUser;
}
}
/// <summary>
/// Register an invitation delegate to be
/// notified when a multiplayer invitation arrives
/// </summary>
public void RegisterInvitationDelegate(BasicApi.InvitationReceivedDelegate deleg)
{
mClient.RegisterInvitationDelegate(deleg);
}
private string MapId(string id)
{
if (id == null)
{
return null;
}
if (mIdMap.ContainsKey(id))
{
string result = mIdMap[id];
Logger.d("Mapping alias " + id + " to ID " + result);
return result;
}
return id;
}
internal IUserProfile[] GetFriends()
{
if (!IsAuthenticated())
{
Logger.d("Cannot get friends when not authenticated!");
return new IUserProfile[0];
}
return mClient.GetFriends();
}
/// <summary>
/// Retrieves a bearer token associated with the current account.
/// </summary>
/// <returns>A bearer token for authorized requests.</returns>
public string GetToken()
{
return mClient.GetToken();
}
}
}
| |
namespace PlayFab.Sockets
{
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using PlayFab.Sockets.Models;
public partial class PlayFabSocketsAPI
{
public static readonly OnConnectEvent OnConnected = new OnConnectEvent();
public static readonly OnDisconnectEvent OnDisconnected = new OnDisconnectEvent();
public static readonly OnConnectionErrorEvent OnConnectionError = new OnConnectionErrorEvent();
public static readonly OnRetryConnectionEvent OnRetryConnection = new OnRetryConnectionEvent();
public static readonly OnTopicResubscriptionFailedEvent OnTopicResubscriptionFailed = new OnTopicResubscriptionFailedEvent();
public static bool Debugging = false;
public class OnConnectEvent : UnityEvent{}
public class OnDisconnectEvent : UnityEvent{}
public class OnConnectionErrorEvent : UnityEvent<PlayFabError>{}
public class OnRetryConnectionEvent : UnityEvent<float,string>{}
public class OnTopicResubscriptionFailedEvent : UnityEvent<Topic>{}
private static PlayFabSocketsBehaviour _transport;
public static bool IsConnected(){ return _transport != null && _transport.IsConnected(); }
/// <summary>
/// Initialize the Sockets API, this will create a Monobehaviour in the scene
/// You must call this before any other API usage.
/// </summary>
/// <param name="autoConnect"> auto connect after initialization</param>
public static void Initialize(bool autoConnect = false)
{
PlayFabSocketsBehaviour.OnConnected += OnInternalConnected;
PlayFabSocketsBehaviour.OnDisconnected += OnInternalDisconnected;
PlayFabSocketsBehaviour.OnConnectionError += OnInternalConnectionError;
PlayFabSocketsBehaviour.OnRetryConnection += OnInternalRetryConnection;
PlayFabSocketsBehaviour.OnTopicResubscriptionFailed += OnInternalTopicResubscribeFailed;
PlayFabSocketsBehaviour.CreateInstance();
_transport = PlayFabSocketsBehaviour.instance;
if (autoConnect)
{
Connect();
}
_transport.Debugging = Debugging;
}
/// <summary>
/// Connect to the SignalR Hub, call after Initialize
/// </summary>
public static void Connect()
{
_transport.InitializeBehaviour();
_transport.Connect();
}
/// <summary>
/// Disconnect from the SignalR Hub.
/// Note: OnDisconnected event only fires when this is called, use OnConnectionError for connection faults
/// </summary>
public static void Disconnect()
{
_transport.Disconnect();
}
/// <summary>
/// Overload for Connect, Connect to the SignalR hub, with some event subscriptions
/// </summary>
/// <param name="onConnect">get notified when connected</param>
/// <param name="onDisconnect">get notified when disconnected</param>
/// <param name="onConnectionError">get notified when a connection fault occurs</param>
public static void Connect(UnityAction onConnect, UnityAction onDisconnect, UnityAction<PlayFabError> onConnectionError)
{
OnConnected.AddListener(onConnect);
OnDisconnected.AddListener(onDisconnect);
OnConnectionError.AddListener(onConnectionError);
Connect();
}
/// <summary>
/// Subscribe to a PlayStream or Message topic
/// </summary>
/// <param name="topic">The topic you wish to subscribe to</param>
/// <param name="successCallback">Fires if subscription was successful</param>
/// <param name="exceptionCallback">Fires if the subscription was unsuccessful</param>
public static void Subscribe(Topic topic, Action successCallback, Action<Exception> exceptionCallback)
{
_transport.InitializeBehaviour();
if (!_transport.IsConnected())
{
Debug.LogError(ErrorStrings.MustBeConnectedSubscribe);
return;
}
_transport.Subscribe(topic, successCallback, exceptionCallback);
}
/// <summary>
/// Subscribe to a PlayStream or Message topic
/// </summary>
/// <param name="topic">The topic you wish to subscribe to</param>
/// <param name="successCallback">Fires if subscription was successful</param>
/// <param name="exceptionCallback">Fires if the subscription was unsuccessful</param>
public static void Subscribe(Topic topic, Action<Topic> successCallback, Action<Exception> exceptionCallback)
{
_transport.InitializeBehaviour();
if (!_transport.IsConnected())
{
Debug.LogError(ErrorStrings.MustBeConnectedSubscribe);
return;
}
_transport.Subscribe(topic, successCallback, exceptionCallback);
}
/// <summary>
/// Subscribe to multiple PlayStream or Message topics at once
/// </summary>
/// <param name="topics">A list of topics you wish to subscribe to</param>
/// <param name="successCallback">Fires upon success, returns a List of topics that were successfully subscribed to. pass null to omit event</param>
/// <param name="exceptionCallback">Fires upon failure to subscribe, returns a list of Exceptions from failed subscriptions. pass null to omit event</param>
public static void Subscribe(List<Topic> topics, Action<List<Topic>> successCallback, Action<List<Exception>> exceptionCallback)
{
_transport.InitializeBehaviour();
if (!_transport.IsConnected())
{
Debug.LogError(ErrorStrings.MustBeConnectedSubscribe);
return;
}
_transport.Subscribe(topics,successCallback,exceptionCallback);
}
/// <summary>
/// Unsubscribe from a topic
/// </summary>
/// <param name="topic">The topic you wish to unsubscribe from</param>
/// <param name="unsubscribeComplete">Fires if unsubscription was successful, pass null to omit event</param>
/// <param name="exceptionCallback">Fires if unsubscription was not successful, pass null to omit event</param>
public static void Unsubscribe(Topic topic, Action unsubscribeComplete, Action<Exception> exceptionCallback)
{
_transport.InitializeBehaviour();
if (!_transport.IsConnected())
{
Debug.LogError(ErrorStrings.MustBeConnectedUnSubscribe);
return;
}
_transport.Unsubscribe(topic,unsubscribeComplete,exceptionCallback);
}
/// <summary>
/// Unsubscribe from multiple topics at onces
/// </summary>
/// <param name="topics">List of topics to unsubscribe from</param>
/// <param name="unsubscribeComplete">List of topics you successfully unsubscribed from. pass null to omit event</param>
/// <param name="exceptionCallback">List of exceptions from failed unsubscriptions. pass null to omit event</param>
public static void Unsubscribe(List<Topic> topics, Action<List<Topic>> unsubscribeComplete,
Action<List<Exception>> exceptionCallback)
{
_transport.InitializeBehaviour();
if (!_transport.IsConnected())
{
Debug.LogError(ErrorStrings.MustBeConnectedUnSubscribe);
return;
}
_transport.Unsubscribe(topics,unsubscribeComplete,exceptionCallback);
}
/// <summary>
/// Register a handler to receive messages on a topic
/// </summary>
/// <param name="topic">Topic you wish to receive a message about</param>
/// <param name="handler">Function (Action) handler that can receive the message</param>
public static void RegisterHandler(Topic topic, Action<PlayFabNetworkMessage> handler)
{
_transport.InitializeBehaviour();
_transport.RegisterHandler(topic, handler);
}
/// <summary>
/// Unregister a handler from receiving messages on a topic
/// </summary>
/// <param name="topic">Topic you no longer wish to handle messages for</param>
/// <param name="handler">Original handler that you previously registered to handle the message</param>
public static void UnRegisterHandler(Topic topic, Action<PlayFabNetworkMessage> handler)
{
_transport.InitializeBehaviour();
_transport.UnregisterHandler(topic, handler);
}
/// <summary>
/// Internal pass through for connected events
/// </summary>
private static void OnInternalConnected()
{
OnConnected.Invoke();
}
/// <summary>
/// Internal pass through for disconnection events
/// </summary>
private static void OnInternalDisconnected()
{
OnDisconnected.Invoke();
}
/// <summary>
/// Internal pass through for Connection error events
/// </summary>
/// <param name="error"></param>
private static void OnInternalConnectionError(PlayFabError error)
{
OnConnectionError.Invoke(error);
}
/// <summary>
/// Internal pass through for Connection retry events
/// </summary>
/// <param name="retryTime"></param>
/// <param name="message"></param>
private static void OnInternalRetryConnection(float retryTime, string message)
{
OnRetryConnection.Invoke(retryTime, message);
}
/// <summary>
/// Internal pass through for topic re-subscription failures
/// </summary>
/// <param name="topic"></param>
private static void OnInternalTopicResubscribeFailed(Topic topic)
{
OnTopicResubscriptionFailed.Invoke(topic);
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
namespace System.Diagnostics
{
using System.Text;
using System.Threading;
using System;
////using System.Security;
////using System.Security.Permissions;
////using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
////using System.Globalization;
////using System.Runtime.Serialization;
////using System.Runtime.Versioning;
////// READ ME:
////// Modifying the order or fields of this object may require other changes
////// to the unmanaged definition of the StackFrameHelper class, in
////// VM\DebugDebugger.h. The binder will catch some of these layout problems.
////[Serializable]
////internal class StackFrameHelper
////{
//// [NonSerialized]
//// private Thread targetThread;
//// private int[] rgiOffset;
//// private int[] rgiILOffset;
//// // this field is here only for backwards compatibility of serialization format
//// private MethodBase[] rgMethodBase;
////
////#pragma warning disable 414 // Field is not used from managed.
//// // dynamicMethods is an array of System.Resolver objects, used to keep
//// // DynamicMethodDescs alive for the lifetime of StackFrameHelper.
//// private Object dynamicMethods;
////#pragma warning restore 414
////
//// [NonSerialized]
//// private RuntimeMethodHandle[] rgMethodHandle;
//// private String[] rgFilename;
//// private int[] rgiLineNumber;
//// private int[] rgiColumnNumber;
//// private int iFrameCount;
//// private bool fNeedFileInfo;
////
////
//// public StackFrameHelper( bool fNeedFileLineColInfo, Thread target )
//// {
//// targetThread = target;
//// rgMethodBase = null;
//// rgMethodHandle = null;
//// rgiOffset = null;
//// rgiILOffset = null;
//// rgFilename = null;
//// rgiLineNumber = null;
//// rgiColumnNumber = null;
//// dynamicMethods = null;
////
//// // 0 means capture all frames. For StackTraces from an Exception, the EE always
//// // captures all frames. For other uses of StackTraces, we can abort stack walking after
//// // some limit if we want to by setting this to a non-zero value. In Whidbey this was
//// // hard-coded to 512, but some customers complained. There shouldn't be any need to limit
//// // this as memory/CPU is no longer allocated up front. If there is some reason to provide a
//// // limit in the future, then we should expose it in the managed API so applications can
//// // override it.
//// iFrameCount = 0;
////
//// fNeedFileInfo = fNeedFileLineColInfo;
//// }
////
//// public virtual MethodBase GetMethodBase( int i )
//// {
//// // There may be a better way to do this.
//// // we got RuntimeMethodHandles here and we need to go to MethodBase
//// // but we don't know whether the reflection info has been initialized
//// // or not. So we call GetMethods and GetConstructors on the type
//// // and then we fetch the proper MethodBase!!
//// RuntimeMethodHandle mh = rgMethodHandle[i];
////
//// if(mh.IsNullHandle())
//// return null;
////
//// mh = mh.GetTypicalMethodDefinition();
////
//// return RuntimeType.GetMethodBase( mh );
//// }
////
//// public virtual int GetOffset( int i ) { return rgiOffset[i]; }
//// public virtual int GetILOffset( int i ) { return rgiILOffset[i]; }
//// public virtual String GetFilename( int i ) { return rgFilename[i]; }
//// public virtual int GetLineNumber( int i ) { return rgiLineNumber[i]; }
//// public virtual int GetColumnNumber( int i ) { return rgiColumnNumber[i]; }
//// public virtual int GetNumberOfFrames() { return iFrameCount; }
//// public virtual void SetNumberOfFrames( int i ) { iFrameCount = i; }
////
//// //
//// // serialization implementation
//// //
//// [OnSerializing]
//// void OnSerializing( StreamingContext context )
//// {
//// // this is called in the process of serializing this object.
//// // For compatibility with Everett we need to assign the rgMethodBase field as that is the field
//// // that will be serialized
//// rgMethodBase = (rgMethodHandle == null) ? null : new MethodBase[rgMethodHandle.Length];
//// if(rgMethodHandle != null)
//// {
//// for(int i = 0; i < rgMethodHandle.Length; i++)
//// {
//// if(!rgMethodHandle[i].IsNullHandle())
//// rgMethodBase[i] = RuntimeType.GetMethodBase( rgMethodHandle[i] );
//// }
//// }
//// }
////
//// [OnSerialized]
//// void OnSerialized( StreamingContext context )
//// {
//// // after we are done serializing null the rgMethodBase field
//// rgMethodBase = null;
//// }
////
//// [OnDeserialized]
//// void OnDeserialized( StreamingContext context )
//// {
//// // after we are done deserializing we need to transform the rgMethodBase in rgMethodHandle
//// rgMethodHandle = (rgMethodBase == null) ? null : new RuntimeMethodHandle[rgMethodBase.Length];
//// if(rgMethodBase != null)
//// {
//// for(int i = 0; i < rgMethodBase.Length; i++)
//// {
//// if(rgMethodBase[i] != null)
//// rgMethodHandle[i] = rgMethodBase[i].MethodHandle;
//// }
//// }
//// rgMethodBase = null;
//// }
////}
// Class which represents a description of a stack trace
// There is no good reason for the methods of this class to be virtual.
// In order to ensure trusted code can trust the data it gets from a
// StackTrace, we use an InheritanceDemand to prevent partially-trusted
// subclasses.
////[SecurityPermission( SecurityAction.InheritanceDemand, UnmanagedCode = true )]
[Serializable]
public class StackTrace
{
//// public const int METHODS_TO_SKIP = 0;
////
//// private StackFrame[] frames;
//// private int m_iNumOfFrames;
//// private int m_iMethodsToSkip;
////
//// // Constructs a stack trace from the current location.
//// public StackTrace()
//// {
//// m_iNumOfFrames = 0;
//// m_iMethodsToSkip = 0;
//// CaptureStackTrace( METHODS_TO_SKIP, false, null, null );
//// }
////
//// // Constructs a stack trace from the current location.
//// //
//// public StackTrace( bool fNeedFileInfo )
//// {
//// m_iNumOfFrames = 0;
//// m_iMethodsToSkip = 0;
//// CaptureStackTrace( METHODS_TO_SKIP, fNeedFileInfo, null, null );
//// }
////
//// // Constructs a stack trace from the current location, in a caller's
//// // frame
//// //
//// public StackTrace( int skipFrames )
//// {
//// if(skipFrames < 0)
//// {
//// throw new ArgumentOutOfRangeException( "skipFrames", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) );
//// }
////
//// m_iNumOfFrames = 0;
//// m_iMethodsToSkip = 0;
////
//// CaptureStackTrace( skipFrames + METHODS_TO_SKIP, false, null, null );
//// }
// Constructs a stack trace from the current location, in a caller's
// frame
//
public StackTrace( int skipFrames, bool fNeedFileInfo )
{
throw new NotImplementedException();
//// if(skipFrames < 0)
//// {
//// throw new ArgumentOutOfRangeException( "skipFrames", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) );
//// }
////
//// m_iNumOfFrames = 0;
//// m_iMethodsToSkip = 0;
////
//// CaptureStackTrace( skipFrames + METHODS_TO_SKIP, fNeedFileInfo, null, null );
}
//// // Constructs a stack trace from the current location.
//// public StackTrace( Exception e )
//// {
//// if(e == null)
//// {
//// throw new ArgumentNullException( "e" );
//// }
////
//// m_iNumOfFrames = 0;
//// m_iMethodsToSkip = 0;
//// CaptureStackTrace( METHODS_TO_SKIP, false, null, e );
//// }
////
//// // Constructs a stack trace from the current location.
//// //
//// public StackTrace( Exception e, bool fNeedFileInfo )
//// {
//// if(e == null)
//// {
//// throw new ArgumentNullException( "e" );
//// }
////
//// m_iNumOfFrames = 0;
//// m_iMethodsToSkip = 0;
//// CaptureStackTrace( METHODS_TO_SKIP, fNeedFileInfo, null, e );
//// }
////
//// // Constructs a stack trace from the current location, in a caller's
//// // frame
//// //
//// public StackTrace( Exception e, int skipFrames )
//// {
//// if(e == null)
//// {
//// throw new ArgumentNullException( "e" );
//// }
////
//// if(skipFrames < 0)
//// {
//// throw new ArgumentOutOfRangeException( "skipFrames", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) );
//// }
////
//// m_iNumOfFrames = 0;
//// m_iMethodsToSkip = 0;
////
//// CaptureStackTrace( skipFrames + METHODS_TO_SKIP, false, null, e );
//// }
////
//// // Constructs a stack trace from the current location, in a caller's
//// // frame
//// //
//// public StackTrace( Exception e, int skipFrames, bool fNeedFileInfo )
//// {
//// if(e == null)
//// {
//// throw new ArgumentNullException( "e" );
//// }
////
//// if(skipFrames < 0)
//// {
//// throw new ArgumentOutOfRangeException( "skipFrames", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) );
//// }
////
//// m_iNumOfFrames = 0;
//// m_iMethodsToSkip = 0;
////
//// CaptureStackTrace( skipFrames + METHODS_TO_SKIP, fNeedFileInfo, null, e );
//// }
////
////
//// // Constructs a "fake" stack trace, just containing a single frame.
//// // Does not have the overhead of a full stack trace.
//// //
//// public StackTrace( StackFrame frame )
//// {
//// frames = new StackFrame[1];
//// frames[0] = frame;
//// m_iMethodsToSkip = 0;
//// m_iNumOfFrames = 1;
//// }
////
////
//// // Constructs a stack trace for the given thread
//// //
//// public StackTrace( Thread targetThread, bool needFileInfo )
//// {
//// m_iNumOfFrames = 0;
//// m_iMethodsToSkip = 0;
////
//// CaptureStackTrace( METHODS_TO_SKIP, needFileInfo, targetThread, null );
////
//// }
////
//// [ResourceExposure( ResourceScope.None )]
//// [MethodImplAttribute( MethodImplOptions.InternalCall )]
//// internal static extern void GetStackFramesInternal( StackFrameHelper sfh, int iSkip, Exception e );
////
//// internal static int CalculateFramesToSkip( StackFrameHelper StackF, int iNumFrames )
//// {
////
//// int iRetVal = 0;
//// String PackageName = "System.Diagnostics";
////
//// // Check if this method is part of the System.Diagnostics
//// // package. If so, increment counter keeping track of
//// // System.Diagnostics functions
//// for(int i = 0; i < iNumFrames; i++)
//// {
//// MethodBase mb = StackF.GetMethodBase( i );
//// if(mb != null)
//// {
//// Type t = mb.DeclaringType;
//// if(t == null)
//// break;
//// String ns = t.Namespace;
//// if(ns == null)
//// break;
//// if(String.Compare( ns, PackageName, StringComparison.Ordinal ) != 0)
//// break;
//// }
//// iRetVal++;
//// }
////
//// return iRetVal;
//// }
////
//// // Retrieves an object with stack trace information encoded.
//// // It leaves out the first "iSkip" lines of the stacktrace.
//// //
//// private void CaptureStackTrace( int iSkip, bool fNeedFileInfo, Thread targetThread,
//// Exception e )
//// {
//// m_iMethodsToSkip += iSkip;
////
//// StackFrameHelper StackF = new StackFrameHelper( fNeedFileInfo, targetThread );
////
//// GetStackFramesInternal( StackF, 0, e );
////
//// m_iNumOfFrames = StackF.GetNumberOfFrames();
////
//// if(m_iMethodsToSkip > m_iNumOfFrames)
//// m_iMethodsToSkip = m_iNumOfFrames;
////
//// if(m_iNumOfFrames != 0)
//// {
//// frames = new StackFrame[m_iNumOfFrames];
////
//// for(int i = 0; i < m_iNumOfFrames; i++)
//// {
//// bool fDummy1 = true;
//// bool fDummy2 = true;
//// StackFrame sfTemp = new StackFrame( fDummy1, fDummy2 );
////
//// sfTemp.SetMethodBase( StackF.GetMethodBase( i ) );
//// sfTemp.SetOffset( StackF.GetOffset( i ) );
//// sfTemp.SetILOffset( StackF.GetILOffset( i ) );
////
//// if(fNeedFileInfo)
//// {
//// sfTemp.SetFileName( StackF.GetFilename( i ) );
//// sfTemp.SetLineNumber( StackF.GetLineNumber( i ) );
//// sfTemp.SetColumnNumber( StackF.GetColumnNumber( i ) );
//// }
////
//// frames[i] = sfTemp;
//// }
////
//// // CalculateFramesToSkip skips all frames in the System.Diagnostics namespace,
//// // but this is not desired if building a stack trace from an exception.
//// if(e == null)
//// m_iMethodsToSkip += CalculateFramesToSkip( StackF, m_iNumOfFrames );
////
//// m_iNumOfFrames -= m_iMethodsToSkip;
//// if(m_iNumOfFrames < 0)
//// {
//// m_iNumOfFrames = 0;
//// }
//// }
////
//// // In case this is the same object being re-used, set frames to null
//// else
//// frames = null;
//// }
////
//// // Property to get the number of frames in the stack trace
//// //
//// public virtual int FrameCount
//// {
//// get
//// {
//// return m_iNumOfFrames;
//// }
//// }
// Returns a given stack frame. Stack frames are numbered starting at
// zero, which is the last stack frame pushed.
//
public virtual StackFrame GetFrame( int index )
{
throw new NotImplementedException();
//// if((frames != null) && (index < m_iNumOfFrames) && (index >= 0))
//// {
//// return frames[index + m_iMethodsToSkip];
//// }
////
//// return null;
}
//// // Returns an array of all stack frames for this stacktrace.
//// // The array is ordered and sized such that GetFrames()[i] == GetFrame(i)
//// // The nth element of this array is the same as GetFrame(n).
//// // The length of the array is the same as FrameCount.
//// //
//// public virtual StackFrame[] GetFrames()
//// {
//// if(frames == null || m_iNumOfFrames <= 0)
//// {
//// return null;
//// }
////
//// // We have to return a subset of the array. Unfortunately this
//// // means we have to allocate a new array and copy over.
//// StackFrame[] array = new StackFrame[m_iNumOfFrames];
//// Array.Copy( frames, m_iMethodsToSkip, array, 0, m_iNumOfFrames );
//// return array;
//// }
////
//// // Builds a readable representation of the stack trace
//// //
//// public override String ToString()
//// {
//// // Include a trailing newline for backwards compatibility
//// return ToString( TraceFormat.TrailingNewLine );
//// }
////
//// // TraceFormat is Used to specify options for how the
//// // string-representation of a StackTrace should be generated.
//// internal enum TraceFormat
//// {
//// Normal,
//// TrailingNewLine, // include a trailing new line character
//// NoResourceLookup // to prevent infinite resource recusion
//// }
////
//// // Builds a readable representation of the stack trace, specifying
//// // the format for backwards compatibility.
//// internal String ToString( TraceFormat traceFormat )
//// {
//// String word_At = "at";
//// String inFileLineNum = "in {0}:line {1}";
////
//// if(traceFormat != TraceFormat.NoResourceLookup)
//// {
//// word_At = Environment.GetResourceString( "Word_At" );
//// inFileLineNum = Environment.GetResourceString( "StackTrace_InFileLineNumber" );
//// }
////
//// bool fFirstFrame = true;
//// StringBuilder sb = new StringBuilder( 255 );
//// for(int iFrameIndex = 0; iFrameIndex < m_iNumOfFrames; iFrameIndex++)
//// {
//// StackFrame sf = GetFrame( iFrameIndex );
//// MethodBase mb = sf.GetMethod();
//// if(mb != null)
//// {
//// // We want a newline at the end of every line except for the last
//// if(fFirstFrame)
//// fFirstFrame = false;
//// else
//// sb.Append( Environment.NewLine );
////
//// sb.AppendFormat( CultureInfo.InvariantCulture, " {0} ", word_At );
////
//// Type t = mb.DeclaringType;
//// // if there is a type (non global method) print it
//// if(t != null)
//// {
//// sb.Append( t.FullName.Replace( '+', '.' ) );
//// sb.Append( "." );
//// }
//// sb.Append( mb.Name );
////
//// // deal with the generic portion of the method
//// if(mb is MethodInfo && ((MethodInfo)mb).IsGenericMethod)
//// {
//// Type[] typars = ((MethodInfo)mb).GetGenericArguments();
//// sb.Append( "[" );
//// int k = 0;
//// bool fFirstTyParam = true;
//// while(k < typars.Length)
//// {
//// if(fFirstTyParam == false)
//// sb.Append( "," );
//// else
//// fFirstTyParam = false;
////
//// sb.Append( typars[k].Name );
//// k++;
//// }
//// sb.Append( "]" );
//// }
////
//// // arguments printing
//// sb.Append( "(" );
//// ParameterInfo[] pi = mb.GetParameters();
//// bool fFirstParam = true;
//// for(int j = 0; j < pi.Length; j++)
//// {
//// if(fFirstParam == false)
//// sb.Append( ", " );
//// else
//// fFirstParam = false;
////
//// String typeName = "<UnknownType>";
//// if(pi[j].ParameterType != null)
//// typeName = pi[j].ParameterType.Name;
//// sb.Append( typeName + " " + pi[j].Name );
//// }
//// sb.Append( ")" );
////
//// // source location printing
//// if(sf.GetILOffset() != -1)
//// {
//// // It's possible we have a debug version of an executable but no PDB. In
//// // this case, the file name will be null.
//// String fileName = null;
////
//// try
//// {
//// fileName = sf.GetFileName();
//// }
//// catch(SecurityException)
//// {
//// }
////
//// if(fileName != null)
//// {
//// // tack on " in c:\tmp\MyFile.cs:line 5"
//// sb.Append( ' ' );
//// sb.AppendFormat( CultureInfo.InvariantCulture, inFileLineNum, fileName, sf.GetFileLineNumber() );
//// }
//// }
////
//// }
//// }
////
//// if(traceFormat == TraceFormat.TrailingNewLine)
//// {
//// sb.Append( Environment.NewLine );
//// }
////
//// return sb.ToString();
//// }
////
//// // This helper is called from within the EE to construct a string representation
//// // of the current stack trace.
//// private static String GetManagedStackTraceStringHelper( bool fNeedFileInfo )
//// {
//// // Note all the frames in System.Diagnostics will be skipped when capturing
//// // a normal stack trace (not from an exception) so we don't need to explicitly
//// // skip the GetManagedStackTraceStringHelper frame.
//// StackTrace st = new StackTrace( 0, fNeedFileInfo );
//// return st.ToString();
//// }
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.
//
// System.Drawing.Bitmap.cs
//
// Copyright (C) 2002 Ximian, Inc. http://www.ximian.com
// Copyright (C) 2004 Novell, Inc. http://www.novell.com
//
// Authors:
// Alexandre Pigolkine (pigolkine@gmx.de)
// Christian Meyer (Christian.Meyer@cs.tum.edu)
// Miguel de Icaza (miguel@ximian.com)
// Jordi Mas i Hernandez (jmas@softcatala.org)
// Ravindra (rkumar@novell.com)
//
//
// Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
//
// 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.IO;
using System.Drawing.Imaging;
using System.Reflection;
using System.Runtime.Serialization;
using System.Runtime.InteropServices;
using System.ComponentModel;
namespace System.Drawing
{
[ComVisible(true)]
[Serializable]
#if !NETCORE
[Editor ("System.Drawing.Design.BitmapEditor, " + Consts.AssemblySystem_Drawing_Design, typeof (System.Drawing.Design.UITypeEditor))]
#endif
public sealed class Bitmap : Image
{
#region constructors
// constructors
// required for XmlSerializer (#323246)
private Bitmap()
{
}
internal Bitmap(IntPtr ptr)
{
nativeObject = ptr;
}
// Usually called when cloning images that need to have
// not only the handle saved, but also the underlying stream
// (when using MS GDI+ and IStream we must ensure the stream stays alive for all the life of the Image)
internal Bitmap(IntPtr ptr, Stream stream)
{
nativeObject = ptr;
}
public Bitmap(int width, int height) : this(width, height, PixelFormat.Format32bppArgb)
{
}
public Bitmap(int width, int height, Graphics g)
{
if (g == null)
throw new ArgumentNullException("g");
IntPtr bmp;
int s = SafeNativeMethods.Gdip.GdipCreateBitmapFromGraphics(width, height, g.nativeObject, out bmp);
SafeNativeMethods.Gdip.CheckStatus(s);
nativeObject = bmp;
}
public Bitmap(int width, int height, PixelFormat format)
{
IntPtr bmp;
int s = SafeNativeMethods.Gdip.GdipCreateBitmapFromScan0(width, height, 0, format, IntPtr.Zero, out bmp);
SafeNativeMethods.Gdip.CheckStatus(s);
nativeObject = bmp;
}
public Bitmap(Image original) : this(original, original.Width, original.Height) { }
public Bitmap(Stream stream) : this(stream, false) { }
public Bitmap(string filename) : this(filename, false) { }
public Bitmap(Image original, Size newSize) : this(original, newSize.Width, newSize.Height) { }
public Bitmap(Stream stream, bool useIcm)
{
// false: stream is owned by user code
nativeObject = InitFromStream(stream);
}
public Bitmap(string filename, bool useIcm)
{
if (filename == null)
throw new ArgumentNullException("filename");
IntPtr imagePtr;
int st;
if (useIcm)
st = SafeNativeMethods.Gdip.GdipCreateBitmapFromFileICM(filename, out imagePtr);
else
st = SafeNativeMethods.Gdip.GdipCreateBitmapFromFile(filename, out imagePtr);
SafeNativeMethods.Gdip.CheckStatus(st);
nativeObject = imagePtr;
}
public Bitmap(Type type, string resource)
{
if (resource == null)
throw new ArgumentException("resource");
// For compatibility with the .NET Framework
if (type == null)
throw new NullReferenceException();
Stream s = type.GetTypeInfo().Assembly.GetManifestResourceStream(type, resource);
if (s == null)
{
string msg = string.Format("Resource '{0}' was not found.", resource);
throw new FileNotFoundException(msg);
}
nativeObject = InitFromStream(s);
}
public Bitmap(Image original, int width, int height) : this(width, height, PixelFormat.Format32bppArgb)
{
Graphics graphics = Graphics.FromImage(this);
graphics.DrawImage(original, 0, 0, width, height);
graphics.Dispose();
}
public Bitmap(int width, int height, int stride, PixelFormat format, IntPtr scan0)
{
IntPtr bmp;
int status = SafeNativeMethods.Gdip.GdipCreateBitmapFromScan0(width, height, stride, format, scan0, out bmp);
SafeNativeMethods.Gdip.CheckStatus(status);
nativeObject = bmp;
}
private Bitmap(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
#endregion
// methods
public Color GetPixel(int x, int y)
{
int argb;
int s = SafeNativeMethods.Gdip.GdipBitmapGetPixel(nativeObject, x, y, out argb);
SafeNativeMethods.Gdip.CheckStatus(s);
return Color.FromArgb(argb);
}
public void SetPixel(int x, int y, Color color)
{
int s = SafeNativeMethods.Gdip.GdipBitmapSetPixel(nativeObject, x, y, color.ToArgb());
if (s == SafeNativeMethods.Gdip.InvalidParameter)
{
// check is done in case of an error only to avoid another
// unmanaged call for normal (successful) calls
if ((this.PixelFormat & PixelFormat.Indexed) != 0)
{
string msg = "SetPixel cannot be called on indexed bitmaps.";
throw new InvalidOperationException(msg);
}
}
SafeNativeMethods.Gdip.CheckStatus(s);
}
public Bitmap Clone(Rectangle rect, PixelFormat format)
{
IntPtr bmp;
int status = SafeNativeMethods.Gdip.GdipCloneBitmapAreaI(rect.X, rect.Y, rect.Width, rect.Height,
format, nativeObject, out bmp);
SafeNativeMethods.Gdip.CheckStatus(status);
return new Bitmap(bmp);
}
public Bitmap Clone(RectangleF rect, PixelFormat format)
{
IntPtr bmp;
int status = SafeNativeMethods.Gdip.GdipCloneBitmapArea(rect.X, rect.Y, rect.Width, rect.Height,
format, nativeObject, out bmp);
SafeNativeMethods.Gdip.CheckStatus(status);
return new Bitmap(bmp);
}
public static Bitmap FromHicon(IntPtr hicon)
{
IntPtr bitmap;
int status = SafeNativeMethods.Gdip.GdipCreateBitmapFromHICON(hicon, out bitmap);
SafeNativeMethods.Gdip.CheckStatus(status);
return new Bitmap(bitmap);
}
public static Bitmap FromResource(IntPtr hinstance, string bitmapName) //TODO: Untested
{
IntPtr bitmap;
int status = SafeNativeMethods.Gdip.GdipCreateBitmapFromResource(hinstance, bitmapName, out bitmap);
SafeNativeMethods.Gdip.CheckStatus(status);
return new Bitmap(bitmap);
}
[EditorBrowsable(EditorBrowsableState.Advanced)]
public IntPtr GetHbitmap()
{
return GetHbitmap(Color.Gray);
}
[EditorBrowsable(EditorBrowsableState.Advanced)]
public IntPtr GetHbitmap(Color background)
{
IntPtr HandleBmp;
int status = SafeNativeMethods.Gdip.GdipCreateHBITMAPFromBitmap(nativeObject, out HandleBmp, background.ToArgb());
SafeNativeMethods.Gdip.CheckStatus(status);
return HandleBmp;
}
[EditorBrowsable(EditorBrowsableState.Advanced)]
public IntPtr GetHicon()
{
IntPtr HandleIcon;
int status = SafeNativeMethods.Gdip.GdipCreateHICONFromBitmap(nativeObject, out HandleIcon);
SafeNativeMethods.Gdip.CheckStatus(status);
return HandleIcon;
}
public BitmapData LockBits(Rectangle rect, ImageLockMode flags, PixelFormat format)
{
BitmapData result = new BitmapData();
return LockBits(rect, flags, format, result);
}
public
BitmapData LockBits(Rectangle rect, ImageLockMode flags, PixelFormat format, BitmapData bitmapData)
{
int status = SafeNativeMethods.Gdip.GdipBitmapLockBits(nativeObject, ref rect, flags, format, bitmapData);
if (status == 7)
{
status = 8; // libgdiplus has the wrong error code mapping for this state.
}
//NOTE: scan0 points to piece of memory allocated in the unmanaged space
SafeNativeMethods.Gdip.CheckStatus(status);
return bitmapData;
}
public void MakeTransparent()
{
Color clr = GetPixel(0, 0);
MakeTransparent(clr);
}
public void MakeTransparent(Color transparentColor)
{
// We have to draw always over a 32-bitmap surface that supports alpha channel
Bitmap bmp = new Bitmap(Width, Height, PixelFormat.Format32bppArgb);
Graphics gr = Graphics.FromImage(bmp);
Rectangle destRect = new Rectangle(0, 0, Width, Height);
ImageAttributes imageAttr = new ImageAttributes();
imageAttr.SetColorKey(transparentColor, transparentColor);
gr.DrawImage(this, destRect, 0, 0, Width, Height, GraphicsUnit.Pixel, imageAttr);
IntPtr oldBmp = nativeObject;
nativeObject = bmp.nativeObject;
bmp.nativeObject = oldBmp;
gr.Dispose();
bmp.Dispose();
imageAttr.Dispose();
}
public void SetResolution(float xDpi, float yDpi)
{
int status = SafeNativeMethods.Gdip.GdipBitmapSetResolution(nativeObject, xDpi, yDpi);
SafeNativeMethods.Gdip.CheckStatus(status);
}
public void UnlockBits(BitmapData bitmapdata)
{
int status = SafeNativeMethods.Gdip.GdipBitmapUnlockBits(nativeObject, bitmapdata);
SafeNativeMethods.Gdip.CheckStatus(status);
}
}
}
| |
namespace Nancy
{
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text.RegularExpressions;
using Nancy.Extensions;
using Nancy.Helpers;
using Nancy.IO;
using Session;
/// <summary>
/// Encapsulates HTTP-request information to an Nancy application.
/// </summary>
[DebuggerDisplay("{DebuggerDisplay, nq}")]
public class Request : IDisposable
{
private readonly List<HttpFile> files = new List<HttpFile>();
private dynamic form = new DynamicDictionary();
private IDictionary<string, string> cookies;
/// <summary>
/// Initializes a new instance of the <see cref="Request"/> class.
/// </summary>
/// <param name="method">The HTTP data transfer method used by the client.</param>
/// <param name="path">The path of the requested resource, relative to the "Nancy root". This should not include the scheme, host name, or query portion of the URI.</param>
/// <param name="scheme">The HTTP protocol that was used by the client.</param>
public Request(string method, string path, string scheme)
: this(method, new Url { Path = path, Scheme = scheme })
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Request"/> class.
/// </summary>
/// <param name="method">The HTTP data transfer method used by the client.</param>
/// <param name="url">The <see cref="Url"/> of the requested resource</param>
/// <param name="headers">The headers that was passed in by the client.</param>
/// <param name="body">The <see cref="Stream"/> that represents the incoming HTTP body.</param>
/// <param name="ip">The client's IP address</param>
/// <param name="certificate">The client's certificate when present.</param>
/// <param name="protocolVersion">The HTTP protocol version.</param>
public Request(string method,
Url url,
RequestStream body = null,
IDictionary<string, IEnumerable<string>> headers = null,
string ip = null,
byte[] certificate = null,
string protocolVersion = null)
{
if (String.IsNullOrEmpty(method))
{
throw new ArgumentOutOfRangeException("method");
}
if (url == null)
{
throw new ArgumentNullException("url");
}
if (url.Path == null)
{
throw new ArgumentNullException("url.Path");
}
if (String.IsNullOrEmpty(url.Scheme))
{
throw new ArgumentOutOfRangeException("url.Scheme");
}
this.UserHostAddress = ip;
this.Url = url;
this.Method = method;
this.Query = url.Query.AsQueryDictionary();
this.Body = body ?? RequestStream.FromStream(new MemoryStream());
this.Headers = new RequestHeaders(headers ?? new Dictionary<string, IEnumerable<string>>());
this.Session = new NullSessionProvider();
if (certificate != null && certificate.Length != 0)
{
this.ClientCertificate = new X509Certificate2(certificate);
}
this.ProtocolVersion = protocolVersion ?? string.Empty;
if (String.IsNullOrEmpty(this.Url.Path))
{
this.Url.Path = "/";
}
this.ParseFormData();
this.RewriteMethod();
}
/// <summary>
/// Gets the certificate sent by the client.
/// </summary>
public X509Certificate ClientCertificate { get; private set; }
/// <summary>
/// Gets the HTTP protocol version.
/// </summary>
public string ProtocolVersion { get; private set; }
/// <summary>
/// Gets the IP address of the client
/// </summary>
public string UserHostAddress { get; private set; }
/// <summary>
/// Gets or sets the HTTP data transfer method used by the client.
/// </summary>
/// <value>The method.</value>
public string Method { get; private set; }
/// <summary>
/// Gets the url
/// </summary>
public Url Url { get; private set; }
/// <summary>
/// Gets the request path, relative to the base path.
/// Used for route matching etc.
/// </summary>
public string Path
{
get
{
return this.Url.Path;
}
}
/// <summary>
/// Gets the query string data of the requested resource.
/// </summary>
/// <value>A <see cref="DynamicDictionary"/>instance, containing the key/value pairs of query string data.</value>
public dynamic Query { get; set; }
/// <summary>
/// Gets a <see cref="RequestStream"/> that can be used to read the incoming HTTP body
/// </summary>
/// <value>A <see cref="RequestStream"/> object representing the incoming HTTP body.</value>
public RequestStream Body { get; private set; }
/// <summary>
/// Gets the request cookies.
/// </summary>
public IDictionary<string, string> Cookies
{
get { return this.cookies ?? (this.cookies = this.GetCookieData()); }
}
/// <summary>
/// Gets the current session.
/// </summary>
public ISession Session { get; set; }
/// <summary>
/// Gets the cookie data from the request header if it exists
/// </summary>
/// <returns>Cookies dictionary</returns>
private IDictionary<string, string> GetCookieData()
{
var cookieDictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
if (!this.Headers.Cookie.Any())
{
return cookieDictionary;
}
var values = this.Headers["cookie"].First().TrimEnd(';').Split(';');
foreach (var parts in values.Select(c => c.Split(new[] { '=' }, 2)))
{
var cookieName = parts[0].Trim();
string cookieValue;
if (parts.Length == 1)
{
//Cookie attribute
cookieValue = string.Empty;
}
else
{
cookieValue = HttpUtility.UrlDecode(parts[1]);
}
cookieDictionary[cookieName] = cookieValue;
}
return cookieDictionary;
}
/// <summary>
/// Gets a collection of files sent by the client-
/// </summary>
/// <value>An <see cref="IEnumerable{T}"/> instance, containing an <see cref="HttpFile"/> instance for each uploaded file.</value>
public IEnumerable<HttpFile> Files
{
get { return this.files; }
}
/// <summary>
/// Gets the form data of the request.
/// </summary>
/// <value>A <see cref="DynamicDictionary"/>instance, containing the key/value pairs of form data.</value>
/// <remarks>Currently Nancy will only parse form data sent using the application/x-www-url-encoded mime-type.</remarks>
public dynamic Form
{
get { return this.form; }
}
/// <summary>
/// Gets the HTTP headers sent by the client.
/// </summary>
/// <value>An <see cref="IDictionary{TKey,TValue}"/> containing the name and values of the headers.</value>
/// <remarks>The values are stored in an <see cref="IEnumerable{T}"/> of string to be compliant with multi-value headers.</remarks>
public RequestHeaders Headers { get; private set; }
public void Dispose()
{
((IDisposable)this.Body).Dispose();
}
private void ParseFormData()
{
if (string.IsNullOrEmpty(this.Headers.ContentType))
{
return;
}
var contentType = this.Headers["content-type"].First();
var mimeType = contentType.Split(';').First();
if (mimeType.Equals("application/x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase))
{
var reader = new StreamReader(this.Body);
this.form = reader.ReadToEnd().AsQueryDictionary();
this.Body.Position = 0;
}
if (!mimeType.Equals("multipart/form-data", StringComparison.OrdinalIgnoreCase))
{
return;
}
var boundary = Regex.Match(contentType, @"boundary=""?(?<token>[^\n\;\"" ]*)").Groups["token"].Value;
var multipart = new HttpMultipart(this.Body, boundary);
var formValues =
new NameValueCollection(StaticConfiguration.CaseSensitive ? StringComparer.Ordinal : StringComparer.OrdinalIgnoreCase);
foreach (var httpMultipartBoundary in multipart.GetBoundaries())
{
if (string.IsNullOrEmpty(httpMultipartBoundary.Filename))
{
var reader =
new StreamReader(httpMultipartBoundary.Value);
formValues.Add(httpMultipartBoundary.Name, reader.ReadToEnd());
}
else
{
this.files.Add(new HttpFile(httpMultipartBoundary));
}
}
foreach (var key in formValues.AllKeys.Where(key => key != null))
{
this.form[key] = formValues[key];
}
this.Body.Position = 0;
}
private void RewriteMethod()
{
if (!this.Method.Equals("POST", StringComparison.OrdinalIgnoreCase))
{
return;
}
var overrides =
new List<Tuple<string, string>>
{
Tuple.Create("_method form input element", (string)this.Form["_method"]),
Tuple.Create("X-HTTP-Method-Override form input element", (string)this.Form["X-HTTP-Method-Override"]),
Tuple.Create("X-HTTP-Method-Override header", this.Headers["X-HTTP-Method-Override"].FirstOrDefault())
};
var providedOverride =
overrides.Where(x => !string.IsNullOrEmpty(x.Item2));
if (!providedOverride.Any())
{
return;
}
if (providedOverride.Count() > 1)
{
var overrideSources =
string.Join(", ", providedOverride);
var errorMessage =
string.Format("More than one HTTP method override was provided. The provided values where: {0}", overrideSources);
throw new InvalidOperationException(errorMessage);
}
this.Method = providedOverride.Single().Item2;
}
private string DebuggerDisplay
{
get { return string.Format("{0} {1} {2}", this.Method, this.Url, this.ProtocolVersion).Trim(); }
}
}
}
| |
//
// ListBox.cs
//
// Author:
// Lluis Sanchez <lluis@xamarin.com>
//
// Copyright (c) 2012 Xamarin Inc
//
// 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 Xwt.Backends;
using System.ComponentModel;
namespace Xwt
{
/// <summary>
/// A list of selectable items
/// </summary>
[BackendType (typeof(IListBoxBackend))]
public class ListBox: Widget
{
CellViewCollection views;
IListDataSource source;
ItemCollection itemCollection;
SelectionMode mode;
protected new class WidgetBackendHost: Widget.WidgetBackendHost, IListBoxEventSink, ICellContainer
{
public void NotifyCellChanged ()
{
((ListBox)Parent).OnCellChanged ();
}
public void OnSelectionChanged ()
{
((ListBox)Parent).OnSelectionChanged (EventArgs.Empty);
}
public void OnRowActivated (int rowIndex)
{
((ListBox)Parent).OnRowActivated (new ListViewRowEventArgs (rowIndex));
}
public override Size GetDefaultNaturalSize ()
{
return Xwt.Backends.DefaultNaturalSizes.ComboBox;
}
}
static ListBox ()
{
MapEvent (TableViewEvent.SelectionChanged, typeof(ListView), "OnSelectionChanged");
MapEvent (ListViewEvent.RowActivated, typeof(ListView), "OnRowActivated");
}
IListBoxBackend Backend {
get { return (IListBoxBackend) BackendHost.Backend; }
}
public ListBox ()
{
views = new CellViewCollection ((ICellContainer)BackendHost);
}
protected override BackendHost CreateBackendHost ()
{
return new WidgetBackendHost ();
}
/// <summary>
/// Views to be used to display the data of the items
/// </summary>
public CellViewCollection Views {
get { return views; }
}
/// <summary>
/// Items shown in the list
/// </summary>
/// <remarks>
/// The Items collection can only be used when no custom DataSource is set.
/// </remarks>
public ItemCollection Items {
get {
if (itemCollection == null) {
itemCollection = new ItemCollection ();
DataSource = itemCollection.DataSource;
views.Clear ();
views.Add (new TextCellView (itemCollection.LabelField));
} else {
if (DataSource != itemCollection.DataSource)
throw new InvalidOperationException ("The Items collection can't be used when a custom DataSource is set");
}
return itemCollection;
}
}
/// <summary>
/// Gets or sets the data source from which to get the data of the items
/// </summary>
/// <value>
/// The data source.
/// </value>
/// <remarks>
/// Then a DataSource is set, the Items collection can't be used.
/// </remarks>
public IListDataSource DataSource {
get { return source; }
set {
BackendHost.ToolkitEngine.ValidateObject (value);
if (source != null) {
source.RowChanged -= HandleModelChanged;
source.RowDeleted -= HandleModelChanged;
source.RowInserted -= HandleModelChanged;
source.RowsReordered -= HandleModelChanged;
}
source = value;
Backend.SetSource (source, source is IFrontend ? (IBackend) Toolkit.GetBackend (source) : null);
if (source != null) {
source.RowChanged += HandleModelChanged;
source.RowDeleted += HandleModelChanged;
source.RowInserted += HandleModelChanged;
source.RowsReordered += HandleModelChanged;
}
}
}
/// <summary>
/// Gets or sets the vertical scroll policy.
/// </summary>
/// <value>
/// The vertical scroll policy.
/// </value>
public ScrollPolicy VerticalScrollPolicy {
get { return Backend.VerticalScrollPolicy; }
set { Backend.VerticalScrollPolicy = value; }
}
/// <summary>
/// Gets or sets the horizontal scroll policy.
/// </summary>
/// <value>
/// The horizontal scroll policy.
/// </value>
public ScrollPolicy HorizontalScrollPolicy {
get { return Backend.HorizontalScrollPolicy; }
set { Backend.HorizontalScrollPolicy = value; }
}
/// <summary>
/// Gets or sets the selection mode.
/// </summary>
/// <value>
/// The selection mode.
/// </value>
public SelectionMode SelectionMode {
get {
return mode;
}
set {
mode = value;
Backend.SetSelectionMode (mode);
}
}
/// <summary>
/// Gets the selected row.
/// </summary>
/// <value>
/// The selected row.
/// </value>
public int SelectedRow {
get {
var items = SelectedRows;
if (items.Length == 0)
return -1;
else
return items [0];
}
}
public object SelectedItem {
get {
if (SelectedRow == -1)
return null;
return Items [SelectedRow];
}
set {
if (SelectionMode == Xwt.SelectionMode.Multiple)
UnselectAll ();
var i = Items.IndexOf (value);
if (i != -1)
SelectRow (i);
else
UnselectAll ();
}
}
/// <summary>
/// Gets the selected rows.
/// </summary>
/// <value>
/// The selected rows.
/// </value>
[DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
public int[] SelectedRows {
get {
return Backend.SelectedRows;
}
}
/// <summary>
/// Selects a row.
/// </summary>
/// <param name='row'>
/// a row.
/// </param>
/// <remarks>
/// In single selection mode, the row will be selected and the previously selected row will be deselected.
/// In multiple selection mode, the row will be added to the set of selected rows.
/// </remarks>
public void SelectRow (int row)
{
Backend.SelectRow (row);
}
/// <summary>
/// Unselects a row.
/// </summary>
/// <param name='row'>
/// A row
/// </param>
public void UnselectRow (int row)
{
Backend.UnselectRow (row);
}
/// <summary>
/// Selects all rows
/// </summary>
public void SelectAll ()
{
Backend.SelectAll ();
}
/// <summary>
/// Clears the selection
/// </summary>
public void UnselectAll ()
{
Backend.UnselectAll ();
}
void HandleModelChanged (object sender, ListRowEventArgs e)
{
OnPreferredSizeChanged ();
}
void OnCellChanged ()
{
Backend.SetViews (views);
}
EventHandler selectionChanged;
/// <summary>
/// Occurs when selection changes
/// </summary>
public event EventHandler SelectionChanged {
add {
BackendHost.OnBeforeEventAdd (TableViewEvent.SelectionChanged, selectionChanged);
selectionChanged += value;
}
remove {
selectionChanged -= value;
BackendHost.OnAfterEventRemove (TableViewEvent.SelectionChanged, selectionChanged);
}
}
/// <summary>
/// Raises the selection changed event.
/// </summary>
/// <param name='args'>
/// Arguments.
/// </param>
protected virtual void OnSelectionChanged (EventArgs args)
{
if (selectionChanged != null)
selectionChanged (this, args);
}
/// <summary>
/// Raises the row activated event.
/// </summary>
/// <param name="a">The alpha component.</param>
protected virtual void OnRowActivated (ListViewRowEventArgs a)
{
if (rowActivated != null)
rowActivated (this, a);
}
EventHandler<ListViewRowEventArgs> rowActivated;
/// <summary>
/// Occurs when the user double-clicks on a row
/// </summary>
public event EventHandler<ListViewRowEventArgs> RowActivated {
add {
BackendHost.OnBeforeEventAdd (ListViewEvent.RowActivated, rowActivated);
rowActivated += value;
}
remove {
rowActivated -= value;
BackendHost.OnAfterEventRemove (ListViewEvent.RowActivated, rowActivated);
}
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: test/proto/benchmarks/payloads.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Grpc.Testing {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class Payloads {
#region Descriptor
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static Payloads() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CiR0ZXN0L3Byb3RvL2JlbmNobWFya3MvcGF5bG9hZHMucHJvdG8SDGdycGMu",
"dGVzdGluZyI3ChBCeXRlQnVmZmVyUGFyYW1zEhAKCHJlcV9zaXplGAEgASgF",
"EhEKCXJlc3Bfc2l6ZRgCIAEoBSI4ChFTaW1wbGVQcm90b1BhcmFtcxIQCghy",
"ZXFfc2l6ZRgBIAEoBRIRCglyZXNwX3NpemUYAiABKAUiFAoSQ29tcGxleFBy",
"b3RvUGFyYW1zIsoBCg1QYXlsb2FkQ29uZmlnEjgKDmJ5dGVidWZfcGFyYW1z",
"GAEgASgLMh4uZ3JwYy50ZXN0aW5nLkJ5dGVCdWZmZXJQYXJhbXNIABI4Cg1z",
"aW1wbGVfcGFyYW1zGAIgASgLMh8uZ3JwYy50ZXN0aW5nLlNpbXBsZVByb3Rv",
"UGFyYW1zSAASOgoOY29tcGxleF9wYXJhbXMYAyABKAsyIC5ncnBjLnRlc3Rp",
"bmcuQ29tcGxleFByb3RvUGFyYW1zSABCCQoHcGF5bG9hZGIGcHJvdG8z"));
descriptor = pbr::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedCodeInfo(null, new pbr::GeneratedCodeInfo[] {
new pbr::GeneratedCodeInfo(typeof(global::Grpc.Testing.ByteBufferParams), new[]{ "ReqSize", "RespSize" }, null, null, null),
new pbr::GeneratedCodeInfo(typeof(global::Grpc.Testing.SimpleProtoParams), new[]{ "ReqSize", "RespSize" }, null, null, null),
new pbr::GeneratedCodeInfo(typeof(global::Grpc.Testing.ComplexProtoParams), null, null, null, null),
new pbr::GeneratedCodeInfo(typeof(global::Grpc.Testing.PayloadConfig), new[]{ "BytebufParams", "SimpleParams", "ComplexParams" }, new[]{ "Payload" }, null, null)
}));
}
#endregion
}
#region Messages
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class ByteBufferParams : pb::IMessage<ByteBufferParams> {
private static readonly pb::MessageParser<ByteBufferParams> _parser = new pb::MessageParser<ByteBufferParams>(() => new ByteBufferParams());
public static pb::MessageParser<ByteBufferParams> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::Grpc.Testing.Payloads.Descriptor.MessageTypes[0]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public ByteBufferParams() {
OnConstruction();
}
partial void OnConstruction();
public ByteBufferParams(ByteBufferParams other) : this() {
reqSize_ = other.reqSize_;
respSize_ = other.respSize_;
}
public ByteBufferParams Clone() {
return new ByteBufferParams(this);
}
public const int ReqSizeFieldNumber = 1;
private int reqSize_;
public int ReqSize {
get { return reqSize_; }
set {
reqSize_ = value;
}
}
public const int RespSizeFieldNumber = 2;
private int respSize_;
public int RespSize {
get { return respSize_; }
set {
respSize_ = value;
}
}
public override bool Equals(object other) {
return Equals(other as ByteBufferParams);
}
public bool Equals(ByteBufferParams other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (ReqSize != other.ReqSize) return false;
if (RespSize != other.RespSize) return false;
return true;
}
public override int GetHashCode() {
int hash = 1;
if (ReqSize != 0) hash ^= ReqSize.GetHashCode();
if (RespSize != 0) hash ^= RespSize.GetHashCode();
return hash;
}
public override string ToString() {
return pb::JsonFormatter.Default.Format(this);
}
public void WriteTo(pb::CodedOutputStream output) {
if (ReqSize != 0) {
output.WriteRawTag(8);
output.WriteInt32(ReqSize);
}
if (RespSize != 0) {
output.WriteRawTag(16);
output.WriteInt32(RespSize);
}
}
public int CalculateSize() {
int size = 0;
if (ReqSize != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(ReqSize);
}
if (RespSize != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(RespSize);
}
return size;
}
public void MergeFrom(ByteBufferParams other) {
if (other == null) {
return;
}
if (other.ReqSize != 0) {
ReqSize = other.ReqSize;
}
if (other.RespSize != 0) {
RespSize = other.RespSize;
}
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
ReqSize = input.ReadInt32();
break;
}
case 16: {
RespSize = input.ReadInt32();
break;
}
}
}
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class SimpleProtoParams : pb::IMessage<SimpleProtoParams> {
private static readonly pb::MessageParser<SimpleProtoParams> _parser = new pb::MessageParser<SimpleProtoParams>(() => new SimpleProtoParams());
public static pb::MessageParser<SimpleProtoParams> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::Grpc.Testing.Payloads.Descriptor.MessageTypes[1]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public SimpleProtoParams() {
OnConstruction();
}
partial void OnConstruction();
public SimpleProtoParams(SimpleProtoParams other) : this() {
reqSize_ = other.reqSize_;
respSize_ = other.respSize_;
}
public SimpleProtoParams Clone() {
return new SimpleProtoParams(this);
}
public const int ReqSizeFieldNumber = 1;
private int reqSize_;
public int ReqSize {
get { return reqSize_; }
set {
reqSize_ = value;
}
}
public const int RespSizeFieldNumber = 2;
private int respSize_;
public int RespSize {
get { return respSize_; }
set {
respSize_ = value;
}
}
public override bool Equals(object other) {
return Equals(other as SimpleProtoParams);
}
public bool Equals(SimpleProtoParams other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (ReqSize != other.ReqSize) return false;
if (RespSize != other.RespSize) return false;
return true;
}
public override int GetHashCode() {
int hash = 1;
if (ReqSize != 0) hash ^= ReqSize.GetHashCode();
if (RespSize != 0) hash ^= RespSize.GetHashCode();
return hash;
}
public override string ToString() {
return pb::JsonFormatter.Default.Format(this);
}
public void WriteTo(pb::CodedOutputStream output) {
if (ReqSize != 0) {
output.WriteRawTag(8);
output.WriteInt32(ReqSize);
}
if (RespSize != 0) {
output.WriteRawTag(16);
output.WriteInt32(RespSize);
}
}
public int CalculateSize() {
int size = 0;
if (ReqSize != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(ReqSize);
}
if (RespSize != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(RespSize);
}
return size;
}
public void MergeFrom(SimpleProtoParams other) {
if (other == null) {
return;
}
if (other.ReqSize != 0) {
ReqSize = other.ReqSize;
}
if (other.RespSize != 0) {
RespSize = other.RespSize;
}
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
ReqSize = input.ReadInt32();
break;
}
case 16: {
RespSize = input.ReadInt32();
break;
}
}
}
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class ComplexProtoParams : pb::IMessage<ComplexProtoParams> {
private static readonly pb::MessageParser<ComplexProtoParams> _parser = new pb::MessageParser<ComplexProtoParams>(() => new ComplexProtoParams());
public static pb::MessageParser<ComplexProtoParams> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::Grpc.Testing.Payloads.Descriptor.MessageTypes[2]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public ComplexProtoParams() {
OnConstruction();
}
partial void OnConstruction();
public ComplexProtoParams(ComplexProtoParams other) : this() {
}
public ComplexProtoParams Clone() {
return new ComplexProtoParams(this);
}
public override bool Equals(object other) {
return Equals(other as ComplexProtoParams);
}
public bool Equals(ComplexProtoParams other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
return true;
}
public override int GetHashCode() {
int hash = 1;
return hash;
}
public override string ToString() {
return pb::JsonFormatter.Default.Format(this);
}
public void WriteTo(pb::CodedOutputStream output) {
}
public int CalculateSize() {
int size = 0;
return size;
}
public void MergeFrom(ComplexProtoParams other) {
if (other == null) {
return;
}
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
}
}
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class PayloadConfig : pb::IMessage<PayloadConfig> {
private static readonly pb::MessageParser<PayloadConfig> _parser = new pb::MessageParser<PayloadConfig>(() => new PayloadConfig());
public static pb::MessageParser<PayloadConfig> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::Grpc.Testing.Payloads.Descriptor.MessageTypes[3]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public PayloadConfig() {
OnConstruction();
}
partial void OnConstruction();
public PayloadConfig(PayloadConfig other) : this() {
switch (other.PayloadCase) {
case PayloadOneofCase.BytebufParams:
BytebufParams = other.BytebufParams.Clone();
break;
case PayloadOneofCase.SimpleParams:
SimpleParams = other.SimpleParams.Clone();
break;
case PayloadOneofCase.ComplexParams:
ComplexParams = other.ComplexParams.Clone();
break;
}
}
public PayloadConfig Clone() {
return new PayloadConfig(this);
}
public const int BytebufParamsFieldNumber = 1;
public global::Grpc.Testing.ByteBufferParams BytebufParams {
get { return payloadCase_ == PayloadOneofCase.BytebufParams ? (global::Grpc.Testing.ByteBufferParams) payload_ : null; }
set {
payload_ = value;
payloadCase_ = value == null ? PayloadOneofCase.None : PayloadOneofCase.BytebufParams;
}
}
public const int SimpleParamsFieldNumber = 2;
public global::Grpc.Testing.SimpleProtoParams SimpleParams {
get { return payloadCase_ == PayloadOneofCase.SimpleParams ? (global::Grpc.Testing.SimpleProtoParams) payload_ : null; }
set {
payload_ = value;
payloadCase_ = value == null ? PayloadOneofCase.None : PayloadOneofCase.SimpleParams;
}
}
public const int ComplexParamsFieldNumber = 3;
public global::Grpc.Testing.ComplexProtoParams ComplexParams {
get { return payloadCase_ == PayloadOneofCase.ComplexParams ? (global::Grpc.Testing.ComplexProtoParams) payload_ : null; }
set {
payload_ = value;
payloadCase_ = value == null ? PayloadOneofCase.None : PayloadOneofCase.ComplexParams;
}
}
private object payload_;
public enum PayloadOneofCase {
None = 0,
BytebufParams = 1,
SimpleParams = 2,
ComplexParams = 3,
}
private PayloadOneofCase payloadCase_ = PayloadOneofCase.None;
public PayloadOneofCase PayloadCase {
get { return payloadCase_; }
}
public void ClearPayload() {
payloadCase_ = PayloadOneofCase.None;
payload_ = null;
}
public override bool Equals(object other) {
return Equals(other as PayloadConfig);
}
public bool Equals(PayloadConfig other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(BytebufParams, other.BytebufParams)) return false;
if (!object.Equals(SimpleParams, other.SimpleParams)) return false;
if (!object.Equals(ComplexParams, other.ComplexParams)) return false;
return true;
}
public override int GetHashCode() {
int hash = 1;
if (payloadCase_ == PayloadOneofCase.BytebufParams) hash ^= BytebufParams.GetHashCode();
if (payloadCase_ == PayloadOneofCase.SimpleParams) hash ^= SimpleParams.GetHashCode();
if (payloadCase_ == PayloadOneofCase.ComplexParams) hash ^= ComplexParams.GetHashCode();
return hash;
}
public override string ToString() {
return pb::JsonFormatter.Default.Format(this);
}
public void WriteTo(pb::CodedOutputStream output) {
if (payloadCase_ == PayloadOneofCase.BytebufParams) {
output.WriteRawTag(10);
output.WriteMessage(BytebufParams);
}
if (payloadCase_ == PayloadOneofCase.SimpleParams) {
output.WriteRawTag(18);
output.WriteMessage(SimpleParams);
}
if (payloadCase_ == PayloadOneofCase.ComplexParams) {
output.WriteRawTag(26);
output.WriteMessage(ComplexParams);
}
}
public int CalculateSize() {
int size = 0;
if (payloadCase_ == PayloadOneofCase.BytebufParams) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(BytebufParams);
}
if (payloadCase_ == PayloadOneofCase.SimpleParams) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(SimpleParams);
}
if (payloadCase_ == PayloadOneofCase.ComplexParams) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(ComplexParams);
}
return size;
}
public void MergeFrom(PayloadConfig other) {
if (other == null) {
return;
}
switch (other.PayloadCase) {
case PayloadOneofCase.BytebufParams:
BytebufParams = other.BytebufParams;
break;
case PayloadOneofCase.SimpleParams:
SimpleParams = other.SimpleParams;
break;
case PayloadOneofCase.ComplexParams:
ComplexParams = other.ComplexParams;
break;
}
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
global::Grpc.Testing.ByteBufferParams subBuilder = new global::Grpc.Testing.ByteBufferParams();
if (payloadCase_ == PayloadOneofCase.BytebufParams) {
subBuilder.MergeFrom(BytebufParams);
}
input.ReadMessage(subBuilder);
BytebufParams = subBuilder;
break;
}
case 18: {
global::Grpc.Testing.SimpleProtoParams subBuilder = new global::Grpc.Testing.SimpleProtoParams();
if (payloadCase_ == PayloadOneofCase.SimpleParams) {
subBuilder.MergeFrom(SimpleParams);
}
input.ReadMessage(subBuilder);
SimpleParams = subBuilder;
break;
}
case 26: {
global::Grpc.Testing.ComplexProtoParams subBuilder = new global::Grpc.Testing.ComplexProtoParams();
if (payloadCase_ == PayloadOneofCase.ComplexParams) {
subBuilder.MergeFrom(ComplexParams);
}
input.ReadMessage(subBuilder);
ComplexParams = subBuilder;
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Orleans.Configuration;
using Orleans.Providers;
using Orleans.Runtime.Versions;
using Orleans.Runtime.Versions.Compatibility;
using Orleans.Runtime.Versions.Selector;
using Orleans.Statistics;
using Orleans.Versions.Compatibility;
using Orleans.Versions.Selector;
namespace Orleans.Runtime
{
internal class SiloControl : SystemTarget, ISiloControl
{
private readonly ILogger logger;
private readonly ILocalSiloDetails localSiloDetails;
private readonly DeploymentLoadPublisher deploymentLoadPublisher;
private readonly Catalog catalog;
private readonly GrainTypeManager grainTypeManager;
private readonly CachedVersionSelectorManager cachedVersionSelectorManager;
private readonly CompatibilityDirectorManager compatibilityDirectorManager;
private readonly VersionSelectorManager selectorManager;
private readonly IMessageCenter messageCenter;
private readonly ActivationDirectory activationDirectory;
private readonly ActivationCollector activationCollector;
private readonly IAppEnvironmentStatistics appEnvironmentStatistics;
private readonly IHostEnvironmentStatistics hostEnvironmentStatistics;
private readonly IOptions<LoadSheddingOptions> loadSheddingOptions;
private readonly Dictionary<Tuple<string,string>, IControllable> controllables;
public SiloControl(
ILocalSiloDetails localSiloDetails,
DeploymentLoadPublisher deploymentLoadPublisher,
Catalog catalog,
GrainTypeManager grainTypeManager,
CachedVersionSelectorManager cachedVersionSelectorManager,
CompatibilityDirectorManager compatibilityDirectorManager,
VersionSelectorManager selectorManager,
IServiceProvider services,
ILoggerFactory loggerFactory,
IMessageCenter messageCenter,
ActivationDirectory activationDirectory,
ActivationCollector activationCollector,
IAppEnvironmentStatistics appEnvironmentStatistics,
IHostEnvironmentStatistics hostEnvironmentStatistics,
IOptions<LoadSheddingOptions> loadSheddingOptions)
: base(Constants.SiloControlId, localSiloDetails.SiloAddress, loggerFactory)
{
this.localSiloDetails = localSiloDetails;
this.logger = loggerFactory.CreateLogger<SiloControl>();
this.deploymentLoadPublisher = deploymentLoadPublisher;
this.catalog = catalog;
this.grainTypeManager = grainTypeManager;
this.cachedVersionSelectorManager = cachedVersionSelectorManager;
this.compatibilityDirectorManager = compatibilityDirectorManager;
this.selectorManager = selectorManager;
this.messageCenter = messageCenter;
this.activationDirectory = activationDirectory;
this.activationCollector = activationCollector;
this.appEnvironmentStatistics = appEnvironmentStatistics;
this.hostEnvironmentStatistics = hostEnvironmentStatistics;
this.loadSheddingOptions = loadSheddingOptions;
this.controllables = new Dictionary<Tuple<string, string>, IControllable>();
IEnumerable<IKeyedServiceCollection<string, IControllable>> namedIControllableCollections = services.GetServices<IKeyedServiceCollection<string, IControllable>>();
foreach (IKeyedService<string, IControllable> keyedService in namedIControllableCollections.SelectMany(c => c.GetServices(services)))
{
IControllable controllable = keyedService.GetService(services);
if(controllable != null)
{
this.controllables.Add(Tuple.Create(controllable.GetType().FullName, keyedService.Key), controllable);
}
}
}
#region Implementation of ISiloControl
public Task Ping(string message)
{
logger.Info("Ping");
return Task.CompletedTask;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods", MessageId = "System.GC.Collect")]
public Task ForceGarbageCollection()
{
logger.Info("ForceGarbageCollection");
GC.Collect();
return Task.CompletedTask;
}
public Task ForceActivationCollection(TimeSpan ageLimit)
{
logger.Info("ForceActivationCollection");
return this.catalog.CollectActivations(ageLimit);
}
public Task ForceRuntimeStatisticsCollection()
{
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("ForceRuntimeStatisticsCollection");
return this.deploymentLoadPublisher.RefreshStatistics();
}
public Task<SiloRuntimeStatistics> GetRuntimeStatistics()
{
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("GetRuntimeStatistics");
var activationCount = this.activationDirectory.Count;
var recentlyUsedActivationCount = this.activationCollector.GetNumRecentlyUsed(TimeSpan.FromMinutes(10));
var stats = new SiloRuntimeStatistics(
this.messageCenter,
activationCount,
recentlyUsedActivationCount,
this.appEnvironmentStatistics,
this.hostEnvironmentStatistics,
this.loadSheddingOptions,
DateTime.UtcNow);
return Task.FromResult(stats);
}
public Task<List<Tuple<GrainId, string, int>>> GetGrainStatistics()
{
logger.Info("GetGrainStatistics");
return Task.FromResult(this.catalog.GetGrainStatistics());
}
public Task<List<DetailedGrainStatistic>> GetDetailedGrainStatistics(string[] types=null)
{
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("GetDetailedGrainStatistics");
return Task.FromResult(this.catalog.GetDetailedGrainStatistics(types));
}
public Task<SimpleGrainStatistic[]> GetSimpleGrainStatistics()
{
logger.Info("GetSimpleGrainStatistics");
return Task.FromResult( this.catalog.GetSimpleGrainStatistics().Select(p =>
new SimpleGrainStatistic { SiloAddress = this.localSiloDetails.SiloAddress, GrainType = p.Key, ActivationCount = (int)p.Value }).ToArray());
}
public Task<DetailedGrainReport> GetDetailedGrainReport(GrainId grainId)
{
logger.Info("DetailedGrainReport for grain id {0}", grainId);
return Task.FromResult( this.catalog.GetDetailedGrainReport(grainId));
}
public Task<int> GetActivationCount()
{
return Task.FromResult(this.catalog.ActivationCount);
}
public Task<object> SendControlCommandToProvider(string providerTypeFullName, string providerName, int command, object arg)
{
IControllable controllable;
if(!this.controllables.TryGetValue(Tuple.Create(providerTypeFullName, providerName), out controllable))
{
string error = $"Could not find a controllable service for type {providerTypeFullName} and name {providerName}.";
logger.Error(ErrorCode.Provider_ProviderNotFound, error);
throw new ArgumentException(error);
}
return controllable.ExecuteCommand(command, arg);
}
public Task<string[]> GetGrainTypeList()
{
return Task.FromResult(this.grainTypeManager.GetGrainTypeList());
}
public Task SetCompatibilityStrategy(CompatibilityStrategy strategy)
{
this.compatibilityDirectorManager.SetStrategy(strategy);
this.cachedVersionSelectorManager.ResetCache();
return Task.CompletedTask;
}
public Task SetSelectorStrategy(VersionSelectorStrategy strategy)
{
this.selectorManager.SetSelector(strategy);
this.cachedVersionSelectorManager.ResetCache();
return Task.CompletedTask;
}
public Task SetCompatibilityStrategy(int interfaceId, CompatibilityStrategy strategy)
{
this.compatibilityDirectorManager.SetStrategy(interfaceId, strategy);
this.cachedVersionSelectorManager.ResetCache();
return Task.CompletedTask;
}
public Task SetSelectorStrategy(int interfaceId, VersionSelectorStrategy strategy)
{
this.selectorManager.SetSelector(interfaceId, strategy);
this.cachedVersionSelectorManager.ResetCache();
return Task.CompletedTask;
}
#endregion
}
}
| |
namespace PeregrineDb.Tests.Schema
{
using System;
using System.Collections.Immutable;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using FluentAssertions;
using Moq;
using PeregrineDb.Schema;
using PeregrineDb.Tests.ExampleEntities;
using PeregrineDb.Tests.Utils;
using Xunit;
[SuppressMessage("ReSharper", "UnusedAutoPropertyAccessor.Local")]
[SuppressMessage("ReSharper", "MemberCanBePrivate.Local")]
[SuppressMessage("ReSharper", "UnusedMember.Local")]
[SuppressMessage("ReSharper", "UnassignedGetOnlyAutoProperty")]
public class TableSchemaFactoryTests
{
private PeregrineConfig sut;
public TableSchemaFactoryTests()
{
var sqlNameEscaper = new TestSqlNameEscaper();
this.sut = new PeregrineConfig(TestDialect.Instance, sqlNameEscaper, new AtttributeTableNameConvention(sqlNameEscaper),
new AttributeColumnNameConvention(sqlNameEscaper), true, PeregrineConfig.DefaultSqlTypeMapping);
}
public class MakeTableSchema
: TableSchemaFactoryTests
{
private TableSchema PerformAct(Type entityType)
{
var sqlNameEscaper = new TestSqlNameEscaper();
var schemaFactory = new TableSchemaFactory(sqlNameEscaper, this.sut.TableNameConvention, this.sut.ColumnNameConvention, PeregrineConfig.DefaultSqlTypeMapping);
return schemaFactory.GetTableSchema(entityType);
}
public class Naming
: MakeTableSchema
{
[Fact]
public void Uses_table_name_resolver_to_get_table_name()
{
// Arrange
var tableNameFactory = new Mock<ITableNameConvention>();
tableNameFactory.Setup(f => f.GetTableName(typeof(SingleColumn)))
.Returns("'SingleColumn'");
this.sut = this.sut.WithTableNameConvention(tableNameFactory.Object);
// Act
var result = this.PerformAct(typeof(SingleColumn));
// Assert
result.Name.Should().Be("'SingleColumn'");
}
[Fact]
public void Uses_column_name_resolver_to_get_column_name()
{
// Arrange
var columnNameFactory = new Mock<IColumnNameConvention>();
columnNameFactory.Setup(
f => f.GetColumnName(
It.Is<PropertySchema>(p => p.Name == "Id")))
.Returns("'Id'");
this.sut = this.sut.WithColumnNameConvention(columnNameFactory.Object);
// Act
var result = this.PerformAct(typeof(SingleColumn));
// Assert
var column = result.Columns.Single();
column.ColumnName.Should().Be("'Id'");
}
[Fact]
public void Uses_property_name_to_populate_select_name()
{
// Act
var result = this.PerformAct(typeof(SingleColumn));
// Assert
var column = result.Columns.Single();
column.SelectName.Should().Be("'Id'");
}
[Fact]
public void Uses_property_name_to_populate_parameter_name()
{
// Act
var result = this.PerformAct(typeof(SingleColumn));
// Assert
var column = result.Columns.Single();
column.Index.Should().Be(0);
}
private class SingleColumn
{
public int Id { get; set; }
}
}
public class Columns
: MakeTableSchema
{
[Fact]
public void Treats_readonly_properties_as_computed()
{
// Act
var result = this.PerformAct(typeof(ReadOnlyProperty));
// Assert
var column = result.Columns.Single();
column.Usage.IsPrimaryKey.Should().BeFalse();
column.Usage.IncludeInInsertStatements.Should().BeFalse();
column.Usage.IncludeInUpdateStatements.Should().BeFalse();
}
[Fact]
public void Sets_none_generated_property_to_included_in_insert_statements()
{
// Act
var result = this.PerformAct(typeof(PropertyNotGenerated));
// Assert
var column = result.Columns.Single();
column.Usage.IncludeInInsertStatements.Should().BeTrue();
}
[Fact]
public void Sets_generated_property_to_not_be_in_insert_statements()
{
// Act
var result = this.PerformAct(typeof(PropertyIdentity));
// Assert
var column = result.Columns.Single();
column.Usage.IncludeInInsertStatements.Should().BeFalse();
column.Usage.IncludeInUpdateStatements.Should().BeTrue();
}
[Fact]
public void Sets_computed_property_to_not_be_in_insert_or_update_statements()
{
// Act
var result = this.PerformAct(typeof(PropertyComputed));
// Assert
var column = result.Columns.Single();
column.Usage.IncludeInInsertStatements.Should().BeFalse();
column.Usage.IncludeInUpdateStatements.Should().BeFalse();
}
[Fact]
public void Ignores_methods()
{
// Act
var result = this.PerformAct(typeof(Method));
// Assert
result.Columns.Should().BeEmpty();
}
[Fact]
public void Ignores_unmapped_properties()
{
// Act
var result = this.PerformAct(typeof(NotMapped));
// Assert
result.Columns.Should().BeEmpty();
}
private class ReadOnlyProperty
{
public DateTime LastUpdated { get; }
}
private class PropertyNotGenerated
{
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int Name { get; set; }
}
private class PropertyComputed
{
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public int Name { get; set; }
}
private class PropertyIdentity
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Name { get; set; }
}
private class Method
{
[SuppressMessage("ReSharper", "UnusedParameter.Local")]
public string Value(string value)
{
throw new NotSupportedException();
}
}
private class NotMapped
{
[NotMapped]
public string Value { get; set; }
}
}
public class PrimaryKeys
: MakeTableSchema
{
[Fact]
public void Marks_property_called_id_as_primary_key()
{
// Act
var result = this.PerformAct(typeof(KeyDefault));
// Assert
result.PrimaryKeyColumns.Single().PropertyName.Should().Be("Id");
}
[Fact]
public void Marks_property_with_key_attribute_as_primary_key()
{
// Act
var result = this.PerformAct(typeof(KeyAlias));
// Assert
result.PrimaryKeyColumns.Single().PropertyName.Should().Be("Key");
}
[Fact]
public void Marks_properties_with_key_attribute_as_primary_keys()
{
// Act
var result = this.PerformAct(typeof(KeyComposite));
// Assert
result.PrimaryKeyColumns.Length.Should().Be(2);
}
[Fact]
public void Takes_key_attribute_over_property_called_id()
{
// Act
var result = this.PerformAct(typeof(KeyNotId));
// Assert
result.PrimaryKeyColumns.Single().PropertyName.Should().Be("Key");
}
[Fact]
public void Treats_readonly_keys_as_computed()
{
// Act
var result = this.PerformAct(typeof(ReadOnlyKey));
// Assert
var column = result.Columns.Single();
column.Usage.IsPrimaryKey.Should().BeTrue();
column.Usage.IncludeInInsertStatements.Should().BeFalse();
column.Usage.IncludeInUpdateStatements.Should().BeFalse();
}
[Fact]
public void Sets_none_generated_key_to_included_in_insert_statements()
{
// Act
var result = this.PerformAct(typeof(KeyNotGenerated));
// Assert
var column = result.Columns.Single(c => c.PropertyName == "Id");
column.Usage.IncludeInInsertStatements.Should().BeTrue();
}
[Fact]
public void Sets_computed_key_to_not_be_in_insert_or_update_statements()
{
// Act
var result = this.PerformAct(typeof(KeyComputed));
// Assert
var column = result.Columns.Single(c => c.PropertyName == "Id");
column.Usage.IncludeInInsertStatements.Should().BeFalse();
column.Usage.IncludeInUpdateStatements.Should().BeFalse();
}
[Fact]
public void Sets_generated_key_to_not_be_in_insert_or_update_statements()
{
// Act
var result = this.PerformAct(typeof(KeyIdentity));
// Assert
var column = result.Columns.Single(c => c.PropertyName == "Id");
column.Usage.IncludeInInsertStatements.Should().BeFalse();
column.Usage.IncludeInUpdateStatements.Should().BeFalse();
}
[Fact]
public void Ignores_methods()
{
// Act
var result = this.PerformAct(typeof(MethodKey));
// Assert
result.Columns.Should().BeEmpty();
}
[Fact]
public void Ignores_unmapped_properties()
{
// Act
var result = this.PerformAct(typeof(NotMappedKey));
// Assert
result.Columns.Should().BeEmpty();
}
[Fact]
public void Ignores_static_properties()
{
// Act
var result = this.PerformAct(typeof(StaticProperty));
// Assert
result.Columns.Should().BeEmpty();
}
[Fact]
public void Ignores_indexers()
{
// Act
var result = this.PerformAct(typeof(Indexer));
// Assert
result.Columns.Should().BeEmpty();
}
private class ReadOnlyKey
{
public int Id { get; }
}
private class KeyDefault
{
public int Id { get; set; }
}
private class KeyAlias
{
[Key]
public int Key { get; set; }
}
private class KeyComposite
{
[Key]
public int Key1 { get; set; }
[Key]
public int Key2 { get; set; }
}
private class KeyNotId
{
public int Id { get; set; }
[Key]
public int Key { get; set; }
}
private class KeyNotGenerated
{
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int Id { get; set; }
}
private class KeyComputed
{
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public int Id { get; set; }
}
private class KeyIdentity
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
}
private class MethodKey
{
public int Id()
{
throw new NotSupportedException();
}
}
private class NotMappedKey
{
[NotMapped]
public int Id { get; set; }
}
private class StaticProperty
{
public static string Name { get; set; }
}
private class Indexer
{
[SuppressMessage("ReSharper", "UnusedParameter.Local")]
public string this[int i]
{
get => throw new NotSupportedException();
set => throw new NotSupportedException();
}
}
}
}
public class MakeConditionsSchema
: TableSchemaFactoryTests
{
[SuppressMessage("ReSharper", "UnusedParameter.Local")]
private ImmutableArray<ConditionColumnSchema> PerformAct<T>(T conditions, TableSchema schema)
{
var sqlNameEscaper = new TestSqlNameEscaper();
var schemaFactory = new TableSchemaFactory(sqlNameEscaper, new AtttributeTableNameConvention(sqlNameEscaper),
new AttributeColumnNameConvention(sqlNameEscaper), PeregrineConfig.DefaultSqlTypeMapping);
return schemaFactory.GetConditionsSchema(typeof(T), schema, typeof(T));
}
private TableSchema GetTableSchema<T>()
{
var sqlNameEscaper = new TestSqlNameEscaper();
var schemaFactory = new TableSchemaFactory(sqlNameEscaper, new AtttributeTableNameConvention(sqlNameEscaper),
new AttributeColumnNameConvention(sqlNameEscaper), PeregrineConfig.DefaultSqlTypeMapping);
return schemaFactory.GetTableSchema(typeof(T));
}
public class Naming
: MakeConditionsSchema
{
[Fact]
public void Gets_column_by_property_name()
{
// Arrange
var tableSchema = this.GetTableSchema<PropertyAlias>();
// Act
var result = this.PerformAct(new { Age = 12 }, tableSchema);
// Assert
var column = result.Single().Column;
column.ColumnName.Should().Be("'YearsOld'");
column.Index.Should().Be(1);
}
}
public class Columns
: MakeConditionsSchema
{
[Fact]
public void Ignores_methods()
{
// Arrange
var tableSchema = this.GetTableSchema<Method>();
// Act
var result = this.PerformAct(new Method(), tableSchema);
// Assert
result.Should().BeEmpty();
}
[Fact]
public void Ignores_unmapped_properties()
{
// Arrange
var tableSchema = this.GetTableSchema<NotMapped>();
// Act
var result = this.PerformAct(new NotMapped(), tableSchema);
// Assert
result.Should().BeEmpty();
}
[Fact]
public void Ignores_unreadable_properties()
{
// Arrange
var tableSchema = this.GetTableSchema<NotMapped>();
// Act
var result = this.PerformAct(new NotMapped(), tableSchema);
// Assert
result.Should().BeEmpty();
}
private class Method
{
[SuppressMessage("ReSharper", "UnusedParameter.Local")]
public string Value(string value)
{
throw new NotSupportedException();
}
}
private class NotMapped
{
[NotMapped]
public string Value { get; set; }
}
private class PropertyNotReadable
{
[SuppressMessage("ReSharper", "NotAccessedField.Local")]
private string name;
public string Name
{
set { this.name = value; }
}
}
}
}
}
}
| |
//
// System.Web.Services.Protocols.WebClientProtocol.cs
//
// Author:
// Tim Coleman (tim@timcoleman.com)
//
// Copyright (C) Tim Coleman, 2002
//
//
// 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.Collections.Specialized;
using System.ComponentModel;
using System.Net;
using System.Text;
using System.Threading;
using System.Web.Services;
namespace System.Web.Services.Protocols {
public abstract class WebClientProtocol : Component {
#region Fields
string connectionGroupName;
ICredentials credentials;
bool preAuthenticate;
Encoding requestEncoding;
int timeout;
string url;
bool abort;
//
// Used by SoapHttpClientProtocol, use this to avoid creating a new Uri on each invocation.
//
internal Uri uri;
//
// Points to the current request, so we can call Abort() on it
//
WebRequest current_request;
#if !TARGET_JVM
static HybridDictionary cache;
#else
static HybridDictionary cache {
get {
return (HybridDictionary)AppDomain.CurrentDomain.GetData("WebClientProtocol.cache");
}
set {
AppDomain.CurrentDomain.SetData("WebClientProtocol.cache", value);
}
}
#endif
#endregion
#region Constructors
static WebClientProtocol ()
{
cache = new HybridDictionary ();
}
protected WebClientProtocol ()
{
connectionGroupName = String.Empty;
credentials = null;
preAuthenticate = false;
requestEncoding = null;
timeout = 100000;
url = String.Empty;
abort = false;
}
#endregion // Constructors
#region Properties
[DefaultValue ("")]
public string ConnectionGroupName {
get { return connectionGroupName; }
set { connectionGroupName = value; }
}
public ICredentials Credentials {
get { return credentials; }
set { credentials = value; }
}
[DefaultValue (false)]
[WebServicesDescription ("Enables pre authentication of the request.")]
public bool PreAuthenticate {
get { return preAuthenticate; }
set { preAuthenticate = value; }
}
[DefaultValue ("")]
[RecommendedAsConfigurable (true)]
[WebServicesDescription ("The encoding to use for requests.")]
public Encoding RequestEncoding {
get { return requestEncoding; }
set { requestEncoding = value; }
}
[DefaultValue (100000)]
[RecommendedAsConfigurable (true)]
[WebServicesDescription ("Sets the timeout in milliseconds to be used for synchronous calls. The default of -1 means infinite.")]
public int Timeout {
get { return timeout; }
set { timeout = value; }
}
[DefaultValue ("")]
[RecommendedAsConfigurable (true)]
[WebServicesDescription ("The base URL to the server to use for requests.")]
public string Url {
get { return url; }
set {
url = value;
uri = new Uri (url);
}
}
#endregion // Properties
#region Methods
public virtual void Abort ()
{
if (current_request != null){
current_request.Abort ();
current_request = null;
}
abort = true;
}
protected static void AddToCache (Type type, object value)
{
cache [type] = value;
}
protected static object GetFromCache (Type type)
{
return cache [type];
}
protected virtual WebRequest GetWebRequest (Uri uri)
{
if (uri == null)
throw new InvalidOperationException ("uri is null");
current_request = WebRequest.Create (uri);
current_request.Timeout = timeout;
current_request.PreAuthenticate = preAuthenticate;
current_request.ConnectionGroupName = connectionGroupName;
if (credentials != null)
current_request.Credentials = credentials;
return current_request;
}
protected virtual WebResponse GetWebResponse (WebRequest request)
{
if (abort)
throw new WebException ("The operation has been aborted.", WebExceptionStatus.RequestCanceled);
WebResponse response = null;
try {
request.Timeout = timeout;
response = request.GetResponse ();
} catch (WebException e) {
response = e.Response;
if (response == null)
throw;
}
return response;
}
protected virtual WebResponse GetWebResponse (WebRequest request, IAsyncResult result)
{
if (abort)
throw new WebException ("The operation has been aborted.", WebExceptionStatus.RequestCanceled);
return request.EndGetResponse (result);
}
#endregion // Methods
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection.Metadata.Ecma335;
namespace System.Reflection.Metadata
{
/// <summary>
/// Represents generic type parameters of a method or type.
/// </summary>
public struct GenericParameterHandleCollection : IReadOnlyList<GenericParameterHandle>
{
private readonly int _firstRowId;
private readonly ushort _count;
internal GenericParameterHandleCollection(int firstRowId, ushort count)
{
_firstRowId = firstRowId;
_count = count;
}
public int Count
{
get
{
return _count;
}
}
public GenericParameterHandle this[int index]
{
get
{
if (index < 0 || index >= _count)
{
Throw.IndexOutOfRange();
}
return GenericParameterHandle.FromRowId(_firstRowId + index);
}
}
public Enumerator GetEnumerator()
{
return new Enumerator(_firstRowId, _firstRowId + _count - 1);
}
IEnumerator<GenericParameterHandle> IEnumerable<GenericParameterHandle>.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public struct Enumerator : IEnumerator<GenericParameterHandle>, IEnumerator
{
private readonly int _lastRowId; // inclusive
// first parameter rid - 1: initial state
// EnumEnded: enumeration ended
private int _currentRowId;
// greater than any RowId and with last 24 bits clear, so that Current returns nil token
private const int EnumEnded = (int)TokenTypeIds.RIDMask + 1;
internal Enumerator(int firstRowId, int lastRowId)
{
_currentRowId = firstRowId - 1;
_lastRowId = lastRowId;
}
public GenericParameterHandle Current
{
get
{
// PERF: keep this code small to enable inlining.
return GenericParameterHandle.FromRowId((int)(_currentRowId & TokenTypeIds.RIDMask));
}
}
public bool MoveNext()
{
// PERF: keep this code small to enable inlining.
if (_currentRowId >= _lastRowId)
{
_currentRowId = EnumEnded;
return false;
}
else
{
_currentRowId++;
return true;
}
}
object IEnumerator.Current
{
get { return Current; }
}
void IEnumerator.Reset()
{
throw new NotSupportedException();
}
void IDisposable.Dispose()
{
}
}
}
/// <summary>
/// Represents constraints of a generic type parameter.
/// </summary>
public struct GenericParameterConstraintHandleCollection : IReadOnlyList<GenericParameterConstraintHandle>
{
private readonly int _firstRowId;
private readonly ushort _count;
internal GenericParameterConstraintHandleCollection(int firstRowId, ushort count)
{
_firstRowId = firstRowId;
_count = count;
}
public int Count
{
get
{
return _count;
}
}
public GenericParameterConstraintHandle this[int index]
{
get
{
if (index < 0 || index >= _count)
{
Throw.IndexOutOfRange();
}
return GenericParameterConstraintHandle.FromRowId(_firstRowId + index);
}
}
public Enumerator GetEnumerator()
{
return new Enumerator(_firstRowId, _firstRowId + _count - 1);
}
IEnumerator<GenericParameterConstraintHandle> IEnumerable<GenericParameterConstraintHandle>.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public struct Enumerator : IEnumerator<GenericParameterConstraintHandle>, IEnumerator
{
private readonly int _lastRowId; // inclusive
// first parameter rid - 1: initial state
// EnumEnded: enumeration ended
private int _currentRowId;
// greater than any RowId and with last 24 bits clear, so that Current returns nil token
private const int EnumEnded = (int)TokenTypeIds.RIDMask + 1;
internal Enumerator(int firstRowId, int lastRowId)
{
_currentRowId = firstRowId - 1;
_lastRowId = lastRowId;
}
public GenericParameterConstraintHandle Current
{
get
{
// PERF: keep this code small to enable inlining.
return GenericParameterConstraintHandle.FromRowId((int)(_currentRowId & TokenTypeIds.RIDMask));
}
}
public bool MoveNext()
{
// PERF: keep this code small to enable inlining.
if (_currentRowId >= _lastRowId)
{
_currentRowId = EnumEnded;
return false;
}
else
{
_currentRowId++;
return true;
}
}
object IEnumerator.Current
{
get { return Current; }
}
void IEnumerator.Reset()
{
throw new NotSupportedException();
}
void IDisposable.Dispose()
{
}
}
}
public struct CustomAttributeHandleCollection : IReadOnlyCollection<CustomAttributeHandle>
{
private readonly MetadataReader _reader;
private readonly int _firstRowId;
private readonly int _lastRowId;
internal CustomAttributeHandleCollection(MetadataReader reader)
{
Debug.Assert(reader != null);
_reader = reader;
_firstRowId = 1;
_lastRowId = reader.CustomAttributeTable.NumberOfRows;
}
internal CustomAttributeHandleCollection(MetadataReader reader, EntityHandle handle)
{
Debug.Assert(reader != null);
_reader = reader;
reader.CustomAttributeTable.GetAttributeRange(handle, out _firstRowId, out _lastRowId);
}
public int Count
{
get
{
return _lastRowId - _firstRowId + 1;
}
}
public Enumerator GetEnumerator()
{
return new Enumerator(_reader, _firstRowId, _lastRowId);
}
IEnumerator<CustomAttributeHandle> IEnumerable<CustomAttributeHandle>.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public struct Enumerator : IEnumerator<CustomAttributeHandle>, IEnumerator
{
private readonly MetadataReader _reader;
private readonly int _lastRowId; // inclusive
// first custom attribute rid - 1: initial state
// EnumEnded: enumeration ended
private int _currentRowId;
// greater than any RowId and with last 24 bits clear, so that Current returns nil token
private const int EnumEnded = (int)TokenTypeIds.RIDMask + 1;
internal Enumerator(MetadataReader reader, int firstRowId, int lastRowId)
{
_reader = reader;
_currentRowId = firstRowId - 1;
_lastRowId = lastRowId;
}
public CustomAttributeHandle Current
{
get
{
// PERF: keep this code small to enable inlining.
if (_reader.CustomAttributeTable.PtrTable != null)
{
return GetCurrentCustomAttributeIndirect();
}
else
{
return CustomAttributeHandle.FromRowId((int)(_currentRowId & TokenTypeIds.RIDMask));
}
}
}
private CustomAttributeHandle GetCurrentCustomAttributeIndirect()
{
return CustomAttributeHandle.FromRowId(
_reader.CustomAttributeTable.PtrTable[(_currentRowId & (int)TokenTypeIds.RIDMask) - 1]);
}
public bool MoveNext()
{
// PERF: keep this code small to enable inlining.
if (_currentRowId >= _lastRowId)
{
_currentRowId = EnumEnded;
return false;
}
else
{
_currentRowId++;
return true;
}
}
object IEnumerator.Current
{
get { return Current; }
}
void IEnumerator.Reset()
{
throw new NotSupportedException();
}
void IDisposable.Dispose()
{
}
}
}
public struct DeclarativeSecurityAttributeHandleCollection : IReadOnlyCollection<DeclarativeSecurityAttributeHandle>
{
private readonly MetadataReader _reader;
private readonly int _firstRowId;
private readonly int _lastRowId;
internal DeclarativeSecurityAttributeHandleCollection(MetadataReader reader)
{
Debug.Assert(reader != null);
_reader = reader;
_firstRowId = 1;
_lastRowId = reader.DeclSecurityTable.NumberOfRows;
}
internal DeclarativeSecurityAttributeHandleCollection(MetadataReader reader, EntityHandle handle)
{
Debug.Assert(reader != null);
Debug.Assert(!handle.IsNil);
_reader = reader;
reader.DeclSecurityTable.GetAttributeRange(handle, out _firstRowId, out _lastRowId);
}
public int Count
{
get
{
return _lastRowId - _firstRowId + 1;
}
}
public Enumerator GetEnumerator()
{
return new Enumerator(_reader, _firstRowId, _lastRowId);
}
IEnumerator<DeclarativeSecurityAttributeHandle> IEnumerable<DeclarativeSecurityAttributeHandle>.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public struct Enumerator : IEnumerator<DeclarativeSecurityAttributeHandle>, IEnumerator
{
private readonly MetadataReader _reader;
private readonly int _lastRowId; // inclusive
// first custom attribute rid - 1: initial state
// EnumEnded: enumeration ended
private int _currentRowId;
// greater than any RowId and with last 24 bits clear, so that Current returns nil token
private const int EnumEnded = (int)TokenTypeIds.RIDMask + 1;
internal Enumerator(MetadataReader reader, int firstRowId, int lastRowId)
{
_reader = reader;
_currentRowId = firstRowId - 1;
_lastRowId = lastRowId;
}
public DeclarativeSecurityAttributeHandle Current
{
get
{
// PERF: keep this code small to enable inlining.
return DeclarativeSecurityAttributeHandle.FromRowId((int)(_currentRowId & TokenTypeIds.RIDMask));
}
}
public bool MoveNext()
{
// PERF: keep this code small to enable inlining.
if (_currentRowId >= _lastRowId)
{
_currentRowId = EnumEnded;
return false;
}
else
{
_currentRowId++;
return true;
}
}
object IEnumerator.Current
{
get { return Current; }
}
void IEnumerator.Reset()
{
throw new NotSupportedException();
}
void IDisposable.Dispose()
{
}
}
}
public struct MethodDefinitionHandleCollection : IReadOnlyCollection<MethodDefinitionHandle>
{
private readonly MetadataReader _reader;
private readonly int _firstRowId;
private readonly int _lastRowId;
internal MethodDefinitionHandleCollection(MetadataReader reader)
{
Debug.Assert(reader != null);
_reader = reader;
_firstRowId = 1;
_lastRowId = reader.MethodDefTable.NumberOfRows;
}
internal MethodDefinitionHandleCollection(MetadataReader reader, TypeDefinitionHandle containingType)
{
Debug.Assert(reader != null);
Debug.Assert(!containingType.IsNil);
_reader = reader;
reader.GetMethodRange(containingType, out _firstRowId, out _lastRowId);
}
public int Count
{
get
{
return _lastRowId - _firstRowId + 1;
}
}
public Enumerator GetEnumerator()
{
return new Enumerator(_reader, _firstRowId, _lastRowId);
}
IEnumerator<MethodDefinitionHandle> IEnumerable<MethodDefinitionHandle>.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public struct Enumerator : IEnumerator<MethodDefinitionHandle>, IEnumerator
{
private readonly MetadataReader _reader;
private readonly int _lastRowId; // inclusive
// first method rid - 1: initial state
// EnumEnded: enumeration ended
private int _currentRowId;
// greater than any RowId and with last 24 bits clear, so that Current returns nil token
private const int EnumEnded = (int)TokenTypeIds.RIDMask + 1;
internal Enumerator(MetadataReader reader, int firstRowId, int lastRowId)
{
_reader = reader;
_currentRowId = firstRowId - 1;
_lastRowId = lastRowId;
}
public MethodDefinitionHandle Current
{
get
{
// PERF: keep this code small to enable inlining.
if (_reader.UseMethodPtrTable)
{
return GetCurrentMethodIndirect();
}
else
{
return MethodDefinitionHandle.FromRowId((int)(_currentRowId & TokenTypeIds.RIDMask));
}
}
}
private MethodDefinitionHandle GetCurrentMethodIndirect()
{
return _reader.MethodPtrTable.GetMethodFor(_currentRowId & (int)TokenTypeIds.RIDMask);
}
public bool MoveNext()
{
// PERF: keep this code small to enable inlining.
if (_currentRowId >= _lastRowId)
{
_currentRowId = EnumEnded;
return false;
}
else
{
_currentRowId++;
return true;
}
}
object IEnumerator.Current
{
get { return Current; }
}
void IEnumerator.Reset()
{
throw new NotSupportedException();
}
void IDisposable.Dispose()
{
}
}
}
public struct FieldDefinitionHandleCollection : IReadOnlyCollection<FieldDefinitionHandle>
{
private readonly MetadataReader _reader;
private readonly int _firstRowId;
private readonly int _lastRowId;
internal FieldDefinitionHandleCollection(MetadataReader reader)
{
Debug.Assert(reader != null);
_reader = reader;
_firstRowId = 1;
_lastRowId = reader.FieldTable.NumberOfRows;
}
internal FieldDefinitionHandleCollection(MetadataReader reader, TypeDefinitionHandle containingType)
{
Debug.Assert(reader != null);
Debug.Assert(!containingType.IsNil);
_reader = reader;
reader.GetFieldRange(containingType, out _firstRowId, out _lastRowId);
}
public int Count
{
get
{
return _lastRowId - _firstRowId + 1;
}
}
public Enumerator GetEnumerator()
{
return new Enumerator(_reader, _firstRowId, _lastRowId);
}
IEnumerator<FieldDefinitionHandle> IEnumerable<FieldDefinitionHandle>.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public struct Enumerator : IEnumerator<FieldDefinitionHandle>, IEnumerator
{
private readonly MetadataReader _reader;
private readonly int _lastRowId; // inclusive
// first field rid - 1: initial state
// EnumEnded: enumeration ended
private int _currentRowId;
// greater than any RowId and with last 24 bits clear, so that Current returns nil token
private const int EnumEnded = (int)TokenTypeIds.RIDMask + 1;
internal Enumerator(MetadataReader reader, int firstRowId, int lastRowId)
{
_reader = reader;
_currentRowId = firstRowId - 1;
_lastRowId = lastRowId;
}
public FieldDefinitionHandle Current
{
get
{
// PERF: keep this code small to enable inlining.
if (_reader.UseFieldPtrTable)
{
return GetCurrentFieldIndirect();
}
else
{
return FieldDefinitionHandle.FromRowId((int)(_currentRowId & TokenTypeIds.RIDMask));
}
}
}
private FieldDefinitionHandle GetCurrentFieldIndirect()
{
return _reader.FieldPtrTable.GetFieldFor(_currentRowId & (int)TokenTypeIds.RIDMask);
}
public bool MoveNext()
{
// PERF: keep this code small to enable inlining.
if (_currentRowId >= _lastRowId)
{
_currentRowId = EnumEnded;
return false;
}
else
{
_currentRowId++;
return true;
}
}
object IEnumerator.Current
{
get { return Current; }
}
void IEnumerator.Reset()
{
throw new NotSupportedException();
}
void IDisposable.Dispose()
{
}
}
}
public struct PropertyDefinitionHandleCollection : IReadOnlyCollection<PropertyDefinitionHandle>
{
private readonly MetadataReader _reader;
private readonly int _firstRowId;
private readonly int _lastRowId;
internal PropertyDefinitionHandleCollection(MetadataReader reader)
{
Debug.Assert(reader != null);
_reader = reader;
_firstRowId = 1;
_lastRowId = reader.PropertyTable.NumberOfRows;
}
internal PropertyDefinitionHandleCollection(MetadataReader reader, TypeDefinitionHandle containingType)
{
Debug.Assert(reader != null);
Debug.Assert(!containingType.IsNil);
_reader = reader;
reader.GetPropertyRange(containingType, out _firstRowId, out _lastRowId);
}
public int Count
{
get
{
return _lastRowId - _firstRowId + 1;
}
}
public Enumerator GetEnumerator()
{
return new Enumerator(_reader, _firstRowId, _lastRowId);
}
IEnumerator<PropertyDefinitionHandle> IEnumerable<PropertyDefinitionHandle>.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public struct Enumerator : IEnumerator<PropertyDefinitionHandle>, IEnumerator
{
private readonly MetadataReader _reader;
private readonly int _lastRowId; // inclusive
// first Property rid - 1: initial state
// EnumEnded: enumeration ended
private int _currentRowId;
// greater than any RowId and with last 24 bits clear, so that Current returns nil token
private const int EnumEnded = (int)TokenTypeIds.RIDMask + 1;
internal Enumerator(MetadataReader reader, int firstRowId, int lastRowId)
{
_reader = reader;
_currentRowId = firstRowId - 1;
_lastRowId = lastRowId;
}
public PropertyDefinitionHandle Current
{
get
{
// PERF: keep this code small to enable inlining.
if (_reader.UsePropertyPtrTable)
{
return GetCurrentPropertyIndirect();
}
else
{
return PropertyDefinitionHandle.FromRowId((int)(_currentRowId & TokenTypeIds.RIDMask));
}
}
}
private PropertyDefinitionHandle GetCurrentPropertyIndirect()
{
return _reader.PropertyPtrTable.GetPropertyFor(_currentRowId & (int)TokenTypeIds.RIDMask);
}
public bool MoveNext()
{
// PERF: keep this code small to enable inlining.
if (_currentRowId >= _lastRowId)
{
_currentRowId = EnumEnded;
return false;
}
else
{
_currentRowId++;
return true;
}
}
object IEnumerator.Current
{
get { return Current; }
}
void IEnumerator.Reset()
{
throw new NotSupportedException();
}
void IDisposable.Dispose()
{
}
}
}
public struct EventDefinitionHandleCollection : IReadOnlyCollection<EventDefinitionHandle>
{
private readonly MetadataReader _reader;
private readonly int _firstRowId;
private readonly int _lastRowId;
internal EventDefinitionHandleCollection(MetadataReader reader)
{
Debug.Assert(reader != null);
_reader = reader;
_firstRowId = 1;
_lastRowId = reader.EventTable.NumberOfRows;
}
internal EventDefinitionHandleCollection(MetadataReader reader, TypeDefinitionHandle containingType)
{
Debug.Assert(reader != null);
Debug.Assert(!containingType.IsNil);
_reader = reader;
reader.GetEventRange(containingType, out _firstRowId, out _lastRowId);
}
public int Count
{
get
{
return _lastRowId - _firstRowId + 1;
}
}
public Enumerator GetEnumerator()
{
return new Enumerator(_reader, _firstRowId, _lastRowId);
}
IEnumerator<EventDefinitionHandle> IEnumerable<EventDefinitionHandle>.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public struct Enumerator : IEnumerator<EventDefinitionHandle>, IEnumerator
{
private readonly MetadataReader _reader;
private readonly int _lastRowId;
// first rid - 1: initial state
// EnumEnded: enumeration ended
private int _currentRowId;
// greater than any RowId and with last 24 bits clear, so that Current returns nil token
private const int EnumEnded = (int)TokenTypeIds.RIDMask + 1;
internal Enumerator(MetadataReader reader, int firstRowId, int lastRowId)
{
_reader = reader;
_currentRowId = firstRowId - 1;
_lastRowId = lastRowId;
}
public EventDefinitionHandle Current
{
get
{
// PERF: keep this code small to enable inlining.
if (_reader.UseEventPtrTable)
{
return GetCurrentEventIndirect();
}
else
{
return EventDefinitionHandle.FromRowId((int)(_currentRowId & TokenTypeIds.RIDMask));
}
}
}
private EventDefinitionHandle GetCurrentEventIndirect()
{
return _reader.EventPtrTable.GetEventFor(_currentRowId & (int)TokenTypeIds.RIDMask);
}
public bool MoveNext()
{
// PERF: keep this code small to enable inlining.
if (_currentRowId >= _lastRowId)
{
_currentRowId = EnumEnded;
return false;
}
else
{
_currentRowId++;
return true;
}
}
object IEnumerator.Current
{
get { return Current; }
}
void IEnumerator.Reset()
{
throw new NotSupportedException();
}
void IDisposable.Dispose()
{
}
}
}
public struct MethodImplementationHandleCollection : IReadOnlyCollection<MethodImplementationHandle>
{
private readonly int _firstRowId;
private readonly int _lastRowId;
internal MethodImplementationHandleCollection(MetadataReader reader, TypeDefinitionHandle containingType)
{
Debug.Assert(reader != null);
if (containingType.IsNil)
{
_firstRowId = 1;
_lastRowId = reader.MethodImplTable.NumberOfRows;
}
else
{
reader.MethodImplTable.GetMethodImplRange(containingType, out _firstRowId, out _lastRowId);
}
}
public int Count
{
get
{
return _lastRowId - _firstRowId + 1;
}
}
public Enumerator GetEnumerator()
{
return new Enumerator(_firstRowId, _lastRowId);
}
IEnumerator<MethodImplementationHandle> IEnumerable<MethodImplementationHandle>.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public struct Enumerator : IEnumerator<MethodImplementationHandle>, IEnumerator
{
private readonly int _lastRowId; // inclusive
// first impl rid - 1: initial state
// EnumEnded: enumeration ended
private int _currentRowId;
// greater than any RowId and with last 24 bits clear, so that Current returns nil token
private const int EnumEnded = (int)TokenTypeIds.RIDMask + 1;
internal Enumerator(int firstRowId, int lastRowId)
{
_currentRowId = firstRowId - 1;
_lastRowId = lastRowId;
}
public MethodImplementationHandle Current
{
get
{
return MethodImplementationHandle.FromRowId((int)(_currentRowId & TokenTypeIds.RIDMask));
}
}
public bool MoveNext()
{
// PERF: keep this code small to enable inlining.
if (_currentRowId >= _lastRowId)
{
_currentRowId = EnumEnded;
return false;
}
else
{
_currentRowId++;
return true;
}
}
object IEnumerator.Current
{
get { return Current; }
}
void IEnumerator.Reset()
{
throw new NotSupportedException();
}
void IDisposable.Dispose()
{
}
}
}
/// <summary>
/// Collection of parameters of a specified method.
/// </summary>
public struct ParameterHandleCollection : IReadOnlyCollection<ParameterHandle>
{
private readonly MetadataReader _reader;
private readonly int _firstRowId;
private readonly int _lastRowId;
internal ParameterHandleCollection(MetadataReader reader, MethodDefinitionHandle containingMethod)
{
Debug.Assert(reader != null);
Debug.Assert(!containingMethod.IsNil);
_reader = reader;
reader.GetParameterRange(containingMethod, out _firstRowId, out _lastRowId);
}
public int Count
{
get
{
return _lastRowId - _firstRowId + 1;
}
}
public Enumerator GetEnumerator()
{
return new Enumerator(_reader, _firstRowId, _lastRowId);
}
IEnumerator<ParameterHandle> IEnumerable<ParameterHandle>.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public struct Enumerator : IEnumerator<ParameterHandle>, IEnumerator
{
private readonly MetadataReader _reader;
private readonly int _lastRowId; // inclusive
// first Parameter rid - 1: initial state
// EnumEnded: enumeration ended
private int _currentRowId;
// greater than any RowId and with last 24 bits clear, so that Current returns nil token
private const int EnumEnded = (int)TokenTypeIds.RIDMask + 1;
internal Enumerator(MetadataReader reader, int firstRowId, int lastRowId)
{
_reader = reader;
_lastRowId = lastRowId;
_currentRowId = firstRowId - 1;
}
public ParameterHandle Current
{
get
{
// PERF: keep this code small to enable inlining.
if (_reader.UseParamPtrTable)
{
return GetCurrentParameterIndirect();
}
else
{
return ParameterHandle.FromRowId((int)(_currentRowId & TokenTypeIds.RIDMask));
}
}
}
private ParameterHandle GetCurrentParameterIndirect()
{
return _reader.ParamPtrTable.GetParamFor(_currentRowId & (int)TokenTypeIds.RIDMask);
}
public bool MoveNext()
{
// PERF: keep this code small to enable inlining.
if (_currentRowId >= _lastRowId)
{
_currentRowId = EnumEnded;
return false;
}
else
{
_currentRowId++;
return true;
}
}
object IEnumerator.Current
{
get { return Current; }
}
void IEnumerator.Reset()
{
throw new NotSupportedException();
}
void IDisposable.Dispose()
{
}
}
}
public struct InterfaceImplementationHandleCollection : IReadOnlyCollection<InterfaceImplementationHandle>
{
private readonly MetadataReader _reader;
private readonly int _firstRowId;
private readonly int _lastRowId;
internal InterfaceImplementationHandleCollection(MetadataReader reader, TypeDefinitionHandle implementingType)
{
Debug.Assert(reader != null);
Debug.Assert(!implementingType.IsNil);
_reader = reader;
reader.InterfaceImplTable.GetInterfaceImplRange(implementingType, out _firstRowId, out _lastRowId);
}
public int Count
{
get
{
return _lastRowId - _firstRowId + 1;
}
}
public Enumerator GetEnumerator()
{
return new Enumerator(_reader, _firstRowId, _lastRowId);
}
IEnumerator<InterfaceImplementationHandle> IEnumerable<InterfaceImplementationHandle>.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public struct Enumerator : IEnumerator<InterfaceImplementationHandle>, IEnumerator
{
private readonly MetadataReader _reader;
private readonly int _lastRowId; // inclusive
// first rid - 1: initial state
// EnumEnded: enumeration ended
private int _currentRowId;
// greater than any RowId and with last 24 bits clear, so that Current returns nil token
private const int EnumEnded = (int)TokenTypeIds.RIDMask + 1;
internal Enumerator(MetadataReader reader, int firstRowId, int lastRowId)
{
_reader = reader;
_currentRowId = firstRowId - 1;
_lastRowId = lastRowId;
}
public InterfaceImplementationHandle Current
{
get
{
return InterfaceImplementationHandle.FromRowId((int)(_currentRowId & TokenTypeIds.RIDMask));
}
}
public bool MoveNext()
{
// PERF: keep this code small to enable inlining.
if (_currentRowId >= _lastRowId)
{
_currentRowId = EnumEnded;
return false;
}
else
{
_currentRowId++;
return true;
}
}
object IEnumerator.Current
{
get { return Current; }
}
void IEnumerator.Reset()
{
throw new NotSupportedException();
}
void IDisposable.Dispose()
{
}
}
}
/// <summary>
/// Represents a collection of <see cref="TypeDefinitionHandle"/>.
/// </summary>
public struct TypeDefinitionHandleCollection : IReadOnlyCollection<TypeDefinitionHandle>
{
private readonly int _lastRowId;
// Creates collection that represents the entire TypeDef table.
internal TypeDefinitionHandleCollection(int lastRowId)
{
_lastRowId = lastRowId;
}
public int Count
{
get { return _lastRowId; }
}
public Enumerator GetEnumerator()
{
return new Enumerator(_lastRowId);
}
IEnumerator<TypeDefinitionHandle> IEnumerable<TypeDefinitionHandle>.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public struct Enumerator : IEnumerator<TypeDefinitionHandle>, IEnumerator
{
private readonly int _lastRowId;
// 0: initial state
// EnumEnded: enumeration ended
private int _currentRowId;
// greater than any RowId and with last 24 bits clear, so that Current returns nil token
private const int EnumEnded = (int)TokenTypeIds.RIDMask + 1;
internal Enumerator(int lastRowId)
{
_lastRowId = lastRowId;
_currentRowId = 0;
}
public TypeDefinitionHandle Current
{
get
{
return TypeDefinitionHandle.FromRowId((int)(_currentRowId & TokenTypeIds.RIDMask));
}
}
public bool MoveNext()
{
// PERF: keep this method small to enable inlining.
if (_currentRowId >= _lastRowId)
{
_currentRowId = EnumEnded;
return false;
}
else
{
_currentRowId++;
return true;
}
}
object IEnumerator.Current
{
get { return Current; }
}
void IEnumerator.Reset()
{
throw new NotSupportedException();
}
void IDisposable.Dispose()
{
}
}
}
/// <summary>
/// Represents a collection of <see cref="TypeReferenceHandle"/>.
/// </summary>
public struct TypeReferenceHandleCollection : IReadOnlyCollection<TypeReferenceHandle>
{
private readonly int _lastRowId;
// Creates collection that represents the entire TypeRef table.
internal TypeReferenceHandleCollection(int lastRowId)
{
_lastRowId = lastRowId;
}
public int Count
{
get { return _lastRowId; }
}
public Enumerator GetEnumerator()
{
return new Enumerator(_lastRowId);
}
IEnumerator<TypeReferenceHandle> IEnumerable<TypeReferenceHandle>.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public struct Enumerator : IEnumerator<TypeReferenceHandle>, IEnumerator
{
private readonly int _lastRowId;
// 0: initial state
// EnumEnded: enumeration ended
private int _currentRowId;
// greater than any RowId and with last 24 bits clear, so that Current returns nil token
private const int EnumEnded = (int)TokenTypeIds.RIDMask + 1;
internal Enumerator(int lastRowId)
{
_lastRowId = lastRowId;
_currentRowId = 0;
}
public TypeReferenceHandle Current
{
get
{
return TypeReferenceHandle.FromRowId((int)(_currentRowId & TokenTypeIds.RIDMask));
}
}
public bool MoveNext()
{
// PERF: keep this method small to enable inlining.
if (_currentRowId >= _lastRowId)
{
_currentRowId = EnumEnded;
return false;
}
else
{
_currentRowId++;
return true;
}
}
object IEnumerator.Current
{
get { return Current; }
}
void IEnumerator.Reset()
{
throw new NotSupportedException();
}
void IDisposable.Dispose()
{
}
}
}
/// <summary>
/// Represents a collection of <see cref="TypeReferenceHandle"/>.
/// </summary>
public struct ExportedTypeHandleCollection : IReadOnlyCollection<ExportedTypeHandle>
{
private readonly int _lastRowId;
// Creates collection that represents the entire TypeRef table.
internal ExportedTypeHandleCollection(int lastRowId)
{
_lastRowId = lastRowId;
}
public int Count
{
get { return _lastRowId; }
}
public Enumerator GetEnumerator()
{
return new Enumerator(_lastRowId);
}
IEnumerator<ExportedTypeHandle> IEnumerable<ExportedTypeHandle>.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public struct Enumerator : IEnumerator<ExportedTypeHandle>, IEnumerator
{
private readonly int _lastRowId;
// 0: initial state
// EnumEnded: enumeration ended
private int _currentRowId;
// greater than any RowId and with last 24 bits clear, so that Current returns nil token
private const int EnumEnded = (int)TokenTypeIds.RIDMask + 1;
internal Enumerator(int lastRowId)
{
_lastRowId = lastRowId;
_currentRowId = 0;
}
public ExportedTypeHandle Current
{
get
{
return ExportedTypeHandle.FromRowId((int)(_currentRowId & TokenTypeIds.RIDMask));
}
}
public bool MoveNext()
{
// PERF: keep this method small to enable inlining.
if (_currentRowId >= _lastRowId)
{
_currentRowId = EnumEnded;
return false;
}
else
{
_currentRowId++;
return true;
}
}
object IEnumerator.Current
{
get { return Current; }
}
void IEnumerator.Reset()
{
throw new NotSupportedException();
}
void IDisposable.Dispose()
{
}
}
}
/// <summary>
/// Represents a collection of <see cref="MemberReferenceHandle"/>.
/// </summary>
public struct MemberReferenceHandleCollection : IReadOnlyCollection<MemberReferenceHandle>
{
private readonly int _lastRowId;
// Creates collection that represents the entire TypeRef table.
internal MemberReferenceHandleCollection(int lastRowId)
{
_lastRowId = lastRowId;
}
public int Count
{
get { return _lastRowId; }
}
public Enumerator GetEnumerator()
{
return new Enumerator(_lastRowId);
}
IEnumerator<MemberReferenceHandle> IEnumerable<MemberReferenceHandle>.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public struct Enumerator : IEnumerator<MemberReferenceHandle>, IEnumerator
{
private readonly int _lastRowId;
// 0: initial state
// EnumEnded: enumeration ended
private int _currentRowId;
// greater than any RowId and with last 24 bits clear, so that Current returns nil token
private const int EnumEnded = (int)TokenTypeIds.RIDMask + 1;
internal Enumerator(int lastRowId)
{
_lastRowId = lastRowId;
_currentRowId = 0;
}
public MemberReferenceHandle Current
{
get
{
return MemberReferenceHandle.FromRowId((int)(_currentRowId & TokenTypeIds.RIDMask));
}
}
public bool MoveNext()
{
// PERF: keep this method small to enable inlining.
if (_currentRowId >= _lastRowId)
{
_currentRowId = EnumEnded;
return false;
}
else
{
_currentRowId++;
return true;
}
}
object IEnumerator.Current
{
get { return Current; }
}
void IEnumerator.Reset()
{
throw new NotSupportedException();
}
void IDisposable.Dispose()
{
}
}
}
public struct PropertyAccessors
{
// Workaround: JIT doesn't generate good code for nested structures, so use uints.
private readonly int _getterRowId;
private readonly int _setterRowId;
public MethodDefinitionHandle Getter { get { return MethodDefinitionHandle.FromRowId(_getterRowId); } }
public MethodDefinitionHandle Setter { get { return MethodDefinitionHandle.FromRowId(_setterRowId); } }
internal PropertyAccessors(int getterRowId, int setterRowId)
{
_getterRowId = getterRowId;
_setterRowId = setterRowId;
}
}
public struct EventAccessors
{
// Workaround: JIT doesn't generate good code for nested structures, so use uints.
private readonly int _adderRowId;
private readonly int _removerRowId;
private readonly int _raiserRowId;
public MethodDefinitionHandle Adder { get { return MethodDefinitionHandle.FromRowId(_adderRowId); } }
public MethodDefinitionHandle Remover { get { return MethodDefinitionHandle.FromRowId(_removerRowId); } }
public MethodDefinitionHandle Raiser { get { return MethodDefinitionHandle.FromRowId(_raiserRowId); } }
internal EventAccessors(int adderRowId, int removerRowId, int raiserRowId)
{
_adderRowId = adderRowId;
_removerRowId = removerRowId;
_raiserRowId = raiserRowId;
}
}
/// <summary>
/// Collection of assembly references.
/// </summary>
public struct AssemblyReferenceHandleCollection : IReadOnlyCollection<AssemblyReferenceHandle>
{
private readonly MetadataReader _reader;
internal AssemblyReferenceHandleCollection(MetadataReader reader)
{
Debug.Assert(reader != null);
_reader = reader;
}
public int Count
{
get
{
return _reader.AssemblyRefTable.NumberOfNonVirtualRows + _reader.AssemblyRefTable.NumberOfVirtualRows;
}
}
public Enumerator GetEnumerator()
{
return new Enumerator(_reader);
}
IEnumerator<AssemblyReferenceHandle> IEnumerable<AssemblyReferenceHandle>.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public struct Enumerator : IEnumerator<AssemblyReferenceHandle>, IEnumerator
{
private readonly MetadataReader _reader;
// 0: initial state
// EnumEnded: enumeration ended
private int _currentRowId;
// greater than any RowId and with last 24 bits clear, so that Current returns nil token
private const int EnumEnded = (int)TokenTypeIds.RIDMask + 1;
private int _virtualRowId;
internal Enumerator(MetadataReader reader)
{
_reader = reader;
_currentRowId = 0;
_virtualRowId = -1;
}
public AssemblyReferenceHandle Current
{
get
{
if (_virtualRowId >= 0)
{
if (_virtualRowId == EnumEnded)
{
return default(AssemblyReferenceHandle);
}
return AssemblyReferenceHandle.FromVirtualIndex((AssemblyReferenceHandle.VirtualIndex)((uint)_virtualRowId));
}
else
{
return AssemblyReferenceHandle.FromRowId((int)(_currentRowId & TokenTypeIds.RIDMask));
}
}
}
public bool MoveNext()
{
if (_currentRowId < _reader.AssemblyRefTable.NumberOfNonVirtualRows)
{
_currentRowId++;
return true;
}
if (_virtualRowId < _reader.AssemblyRefTable.NumberOfVirtualRows - 1)
{
_virtualRowId++;
return true;
}
_currentRowId = EnumEnded;
_virtualRowId = EnumEnded;
return false;
}
object IEnumerator.Current
{
get { return Current; }
}
void IEnumerator.Reset()
{
throw new NotSupportedException();
}
void IDisposable.Dispose()
{
}
}
}
/// <summary>
/// Represents a collection of <see cref="ManifestResourceHandle"/>.
/// </summary>
public struct ManifestResourceHandleCollection : IReadOnlyCollection<ManifestResourceHandle>
{
private readonly int _lastRowId;
// Creates collection that represents the entire ManifestResource table.
internal ManifestResourceHandleCollection(int lastRowId)
{
_lastRowId = lastRowId;
}
public int Count
{
get { return _lastRowId; }
}
public Enumerator GetEnumerator()
{
return new Enumerator(_lastRowId);
}
IEnumerator<ManifestResourceHandle> IEnumerable<ManifestResourceHandle>.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public struct Enumerator : IEnumerator<ManifestResourceHandle>, IEnumerator
{
private readonly int _lastRowId;
// 0: initial state
// EnumEnded: enumeration ended
private int _currentRowId;
// greater than any RowId and with last 24 bits clear, so that Current returns nil token
private const int EnumEnded = (int)TokenTypeIds.RIDMask + 1;
internal Enumerator(int lastRowId)
{
_lastRowId = lastRowId;
_currentRowId = 0;
}
public ManifestResourceHandle Current
{
get
{
return ManifestResourceHandle.FromRowId((int)(_currentRowId & TokenTypeIds.RIDMask));
}
}
public bool MoveNext()
{
// PERF: keep this method small to enable inlining.
if (_currentRowId >= _lastRowId)
{
_currentRowId = EnumEnded;
return false;
}
else
{
_currentRowId++;
return true;
}
}
object IEnumerator.Current
{
get { return Current; }
}
void IEnumerator.Reset()
{
throw new NotSupportedException();
}
void IDisposable.Dispose()
{
}
}
}
/// <summary>
/// Represents a collection of <see cref="AssemblyFileHandle"/>.
/// </summary>
public struct AssemblyFileHandleCollection : IReadOnlyCollection<AssemblyFileHandle>
{
private readonly int _lastRowId;
// Creates collection that represents the entire AssemblyFile table.
internal AssemblyFileHandleCollection(int lastRowId)
{
_lastRowId = lastRowId;
}
public int Count
{
get { return _lastRowId; }
}
public Enumerator GetEnumerator()
{
return new Enumerator(_lastRowId);
}
IEnumerator<AssemblyFileHandle> IEnumerable<AssemblyFileHandle>.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public struct Enumerator : IEnumerator<AssemblyFileHandle>, IEnumerator
{
private readonly int _lastRowId;
// 0: initial state
// EnumEnded: enumeration ended
private int _currentRowId;
// greater than any RowId and with last 24 bits clear, so that Current returns nil token
private const int EnumEnded = (int)TokenTypeIds.RIDMask + 1;
internal Enumerator(int lastRowId)
{
_lastRowId = lastRowId;
_currentRowId = 0;
}
public AssemblyFileHandle Current
{
get
{
return AssemblyFileHandle.FromRowId((int)(_currentRowId & TokenTypeIds.RIDMask));
}
}
public bool MoveNext()
{
// PERF: keep this method small to enable inlining.
if (_currentRowId >= _lastRowId)
{
_currentRowId = EnumEnded;
return false;
}
else
{
_currentRowId++;
return true;
}
}
object IEnumerator.Current
{
get { return Current; }
}
void IEnumerator.Reset()
{
throw new NotSupportedException();
}
void IDisposable.Dispose()
{
}
}
}
}
| |
////////////////////////////////////////////////////////////////////////////
//
// Copyright 2017 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Nito.AsyncEx;
using NUnit.Framework;
using Realms;
using Realms.Exceptions;
namespace Tests.Database
{
[TestFixture, Preserve(AllMembers = true)]
public class ThreadHandoverTests : RealmInstanceTest
{
[Test]
public void ObjectReference_ShouldWork()
{
AsyncContext.Run(async () =>
{
var objReference = SetupObjectReference();
await Task.Run(() =>
{
using (var otherRealm = Realm.GetInstance(_realm.Config))
{
var otherObj = otherRealm.ResolveReference(objReference);
Assert.That(otherObj.IsManaged);
Assert.That(otherObj.IsValid);
Assert.That(otherObj.Int, Is.EqualTo(12));
}
});
});
}
[Test]
public void ListReference_ShouldWork()
{
AsyncContext.Run(async () =>
{
var obj = new Owner();
obj.Dogs.Add(new Dog { Name = "1" });
obj.Dogs.Add(new Dog { Name = "2" });
_realm.Write(() => _realm.Add(obj));
var listReference = ThreadSafeReference.Create(obj.Dogs);
await Task.Run(() =>
{
using (var otherRealm = Realm.GetInstance(_realm.Config))
{
var otherList = otherRealm.ResolveReference(listReference);
Assert.That(otherList, Is.InstanceOf(typeof(RealmList<Dog>)));
var dogNames = otherList.Select(d => d.Name);
Assert.That(dogNames, Is.EqualTo(new[] { "1", "2" }));
}
});
});
}
[Test]
public void QueryReference_WhenNoQueryApplied_ShouldWork()
{
AsyncContext.Run(async () =>
{
var queryReference = SetupQueryReference(q => q);
await AssertQueryReference(queryReference, new[] { 1, 2, 3, 4 });
});
}
[Test]
public void ThreadSafeReference_CanOnlyBeConsumedOnce()
{
AsyncContext.Run(async () =>
{
var objReference = SetupObjectReference();
await Task.Run(() =>
{
using (var otherRealm = Realm.GetInstance(_realm.Config))
{
otherRealm.ResolveReference(objReference);
Assert.That(() => otherRealm.ResolveReference(objReference), Throws.InstanceOf<RealmException>().And.Message.Contains("Can only resolve a thread safe reference once."));
}
});
});
}
[Test]
public void ThreadSafeReference_WhenAnObjectIsUnmanaged_ShouldFail()
{
var obj = new IntPropertyObject();
Assert.That(() => ThreadSafeReference.Create(obj), Throws.InstanceOf<RealmException>().And.Message.Contains("unmanaged object"));
}
[Test]
public void ThreadSafeReference_WhenObjectIsDeleted_ShouldFail()
{
var obj = new IntPropertyObject();
_realm.Write(() => _realm.Add(obj));
_realm.Write(() => _realm.Remove(obj));
Assert.That(() => ThreadSafeReference.Create(obj), Throws.InstanceOf<RealmException>().And.Message.Contains("invalidated object"));
}
[Test]
public void ThreadSafeReference_CanBeResolvedOnTheSameThread()
{
var objReference = SetupObjectReference();
using (var otherRealm = Realm.GetInstance(_realm.Config))
{
var otherObj = otherRealm.ResolveReference(objReference);
Assert.That(otherObj.IsManaged);
Assert.That(otherObj.IsValid);
Assert.That(otherObj.Int, Is.EqualTo(12));
}
}
[Test]
public void ThreadSafeReference_CanBeResolvedByTheSameRealm()
{
var objReference = SetupObjectReference();
var otherObj = _realm.ResolveReference(objReference);
Assert.That(otherObj.IsManaged);
Assert.That(otherObj.IsValid);
Assert.That(otherObj.Int, Is.EqualTo(12));
}
[Test]
public void ListReference_WhenListIsNotRealmList_ShouldFail()
{
IList<Dog> unmanagedDogs = new List<Dog>();
unmanagedDogs.Add(new Dog());
Assert.That(() => ThreadSafeReference.Create(unmanagedDogs), Throws.InstanceOf<InvalidCastException>());
_realm.Write(() => _realm.Add(new Dog()));
IList<Dog> managedDogs = _realm.All<Dog>().ToList();
Assert.That(() => ThreadSafeReference.Create(managedDogs), Throws.InstanceOf<InvalidCastException>());
}
[Test]
public void QueryReference_WhenQueryIsNotRealmResults_ShouldFail()
{
var unmanagedDogs = new[] { new Dog() };
Assert.That(() => ThreadSafeReference.Create(unmanagedDogs.AsQueryable()), Throws.InstanceOf<InvalidCastException>());
_realm.Write(() => _realm.Add(new Dog()));
var managedDogs = _realm.All<Dog>().ToArray().AsQueryable();
Assert.That(() => ThreadSafeReference.Create(managedDogs), Throws.InstanceOf<InvalidCastException>());
}
[Test]
public void ThreadReference_WhenResolvedWithDifferentConfiguration_ShouldFail()
{
AsyncContext.Run(async () =>
{
var objReference = SetupObjectReference();
await Task.Run(() =>
{
var otherRealm = Realm.GetInstance("other.realm");
Assert.That(() => otherRealm.ResolveReference(objReference),
Throws.InstanceOf<RealmException>().And.Message.Contains("different configuration"));
otherRealm.Dispose();
Realm.DeleteRealm(otherRealm.Config);
});
});
}
[Test]
public void ThreadSafeReference_WhenTargetRealmInTransaction_ShouldFail()
{
AsyncContext.Run(async () =>
{
var objReference = SetupObjectReference();
await Task.Run(() =>
{
using (var otherRealm = Realm.GetInstance(_realm.Config))
{
otherRealm.Write(() =>
{
Assert.That(() => otherRealm.ResolveReference(objReference),
Throws.InstanceOf<RealmException>().And.Message.Contains("write transaction"));
});
}
});
});
}
[Test]
public void ObjectReference_WhenSourceRealmInTransaction_ShouldFail()
{
_realm.Write(() =>
{
var obj = _realm.Add(new IntPropertyObject());
Assert.That(() => ThreadSafeReference.Create(obj), Throws.InstanceOf<RealmInvalidTransactionException>());
});
}
[Test]
public void ObjectReference_ResolveDeletedObject_ShouldReturnNull()
{
AsyncContext.Run(async () =>
{
var obj = new IntPropertyObject { Int = 12 };
_realm.Write(() => _realm.Add(obj));
var objReference = ThreadSafeReference.Create(obj);
_realm.Write(() => _realm.Remove(obj));
await Task.Run(() =>
{
using (var otherRealm = Realm.GetInstance(_realm.Config))
{
var otherObj = otherRealm.ResolveReference(objReference);
Assert.That(otherObj, Is.Null);
}
});
});
}
[Test]
public void ListReference_ResolveDeletedParentObject_ShouldReturnNull()
{
AsyncContext.Run(async () =>
{
var obj = new Owner();
obj.Dogs.Add(new Dog { Name = "1" });
obj.Dogs.Add(new Dog { Name = "2" });
_realm.Write(() => _realm.Add(obj));
var listReference = ThreadSafeReference.Create(obj.Dogs);
_realm.Write(() => _realm.Remove(obj));
await Task.Run(() =>
{
using (var otherRealm = Realm.GetInstance(_realm.Config))
{
var otherList = otherRealm.ResolveReference(listReference);
Assert.That(otherList, Is.Null);
}
});
});
}
[Test]
public void QueryReference_WhenFilterApplied_ShouldWork()
{
AsyncContext.Run(async () =>
{
_realm.Write(() =>
{
_realm.Add(new IntPropertyObject { Int = 1 });
_realm.Add(new IntPropertyObject { Int = 2 });
_realm.Add(new IntPropertyObject { Int = 3 });
_realm.Add(new IntPropertyObject { Int = 4 });
});
var query = _realm.All<IntPropertyObject>().Where(o => o.Int != 2);
var queryReference = ThreadSafeReference.Create(query);
await AssertQueryReference(queryReference, new[] { 1, 3, 4 });
});
}
[Test]
public void QueryReference_WhenSortApplied_ShouldWork()
{
AsyncContext.Run(async () =>
{
var queryReference = SetupQueryReference(q => q.OrderByDescending(o => o.Int));
await AssertQueryReference(queryReference, new[] { 4, 3, 2, 1 });
});
}
[Test]
public void QueryReference_WhenSortAndFilterApplied_ShouldWork()
{
AsyncContext.Run(async () =>
{
var queryReference = SetupQueryReference(q => q.Where(o => o.Int != 2).OrderByDescending(o => o.Int));
await AssertQueryReference(queryReference, new[] { 4, 3, 1 });
});
}
private ThreadSafeReference.Query<IntPropertyObject> SetupQueryReference(Func<IQueryable<IntPropertyObject>, IQueryable<IntPropertyObject>> queryFunc)
{
_realm.Write(() =>
{
_realm.Add(new IntPropertyObject { Int = 1 });
_realm.Add(new IntPropertyObject { Int = 2 });
_realm.Add(new IntPropertyObject { Int = 3 });
_realm.Add(new IntPropertyObject { Int = 4 });
});
var query = queryFunc(_realm.All<IntPropertyObject>());
return ThreadSafeReference.Create(query);
}
private ThreadSafeReference.Object<IntPropertyObject> SetupObjectReference()
{
var obj = new IntPropertyObject { Int = 12 };
_realm.Write(() => _realm.Add(obj));
return ThreadSafeReference.Create(obj);
}
private Task AssertQueryReference(ThreadSafeReference.Query<IntPropertyObject> reference, int[] expected)
{
return Task.Run(() =>
{
using (var otherRealm = Realm.GetInstance(_realm.Config))
{
var otherQuery = otherRealm.ResolveReference(reference);
Assert.That(otherQuery, Is.InstanceOf(typeof(RealmResults<IntPropertyObject>)));
var values = otherQuery.ToArray().Select(q => q.Int);
Assert.That(values, Is.EqualTo(expected));
}
});
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// This file is best viewed using outline mode (Ctrl-M Ctrl-O)
//
// This program uses code hyperlinks available as part of the HyperAddin Visual Studio plug-in.
// It is available from http://www.codeplex.com/hyperAddin
//
using Microsoft.Diagnostics.Tracing.Compatibility;
using Microsoft.Diagnostics.Tracing.Parsers;
using Microsoft.Diagnostics.Tracing.Parsers.Clr;
using Microsoft.Diagnostics.Tracing.Parsers.Kernel;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
using Utilities;
using Address = System.UInt64;
// code:System.Diagnostics.ETWTraceEventSource definition.
namespace Microsoft.Diagnostics.Tracing
{
/// <summary>
/// A ETWTraceEventSource represents the stream of events that was collected from a
/// TraceEventSession (eg the ETL moduleFile, or the live session event stream). Like all
/// TraceEventSource, it logically represents a stream of TraceEvent s. Like all
/// TraceEventDispathers it supports a callback model where Parsers attach themselves to this
/// sources, and user callbacks defined on the parsers are called when the 'Process' method is called.
///
/// * See also TraceEventDispatcher
/// * See also TraceEvent
/// * See also #ETWTraceEventSourceInternals
/// * See also #ETWTraceEventSourceFields
/// </summary>
public sealed unsafe class ETWTraceEventSource : TraceEventDispatcher, IDisposable
{
/// <summary>
/// Open a ETW event trace moduleFile (ETL moduleFile) for processing.
/// </summary>
/// <param name="fileName">The ETL data moduleFile to open</param>`
public ETWTraceEventSource(string fileName)
: this(fileName, TraceEventSourceType.MergeAll)
{
}
/// <summary>
/// Open a ETW event source for processing. This can either be a moduleFile or a real time ETW session
/// </summary>
/// <param name="fileOrSessionName">
/// If type == ModuleFile this is the name of the moduleFile to open.
/// If type == Session this is the name of real time session to open.</param>
/// <param name="type"></param>
// [SecuritySafeCritical]
public ETWTraceEventSource(string fileOrSessionName, TraceEventSourceType type)
{
Initialize(fileOrSessionName, type);
}
/// <summary>
/// Process all the files in 'fileNames' in order (that is all the events in the first
/// file are processed, then the second ...). Intended for parsing the 'Multi-File' collection mode.
/// </summary>
/// <param name="fileNames">The list of files path names to process (in that order)</param>
public ETWTraceEventSource(IEnumerable<string> fileNames)
{
this.fileNames = fileNames;
}
// Process is called after all desired subscriptions have been registered.
/// <summary>
/// Processes all the events in the data source, issuing callbacks that were subscribed to. See
/// #Introduction for more
/// </summary>
/// <returns>false If StopProcesing was called</returns>
// [SecuritySafeCritical]
public override bool Process()
{
stopProcessing = false;
if (processTraceCalled)
{
Reset();
}
processTraceCalled = true;
if (fileNames != null)
{
foreach (var fileName in fileNames)
{
if (handles != null)
{
Debug.Assert(handles.Length == 1);
if (handles[0] != TraceEventNativeMethods.INVALID_HANDLE_VALUE)
{
TraceEventNativeMethods.CloseTrace(handles[0]);
}
}
Initialize(fileName, TraceEventSourceType.FileOnly);
if (!ProcessOneFile())
{
OnCompleted();
Debug.Assert(sessionEndTimeQPC != long.MaxValue); // Not a real time session
return false;
}
}
OnCompleted();
Debug.Assert(sessionEndTimeQPC != long.MaxValue); // Not a real time session
return true;
}
else
{
var ret = ProcessOneFile();
// If the session is real time, set he sessionEndTime (since the session is stopping).
if (sessionEndTimeQPC == long.MaxValue)
{
sessionEndTimeQPC = QPCTime.GetUTCTimeAsQPC(DateTime.UtcNow);
}
OnCompleted();
return ret;
}
}
/// <summary>
/// Reprocess a pre-constructed event which this processor has presumably created. Helpful to re-examine
/// "unknown" events, perhaps after a manifest has been received from the ETW stream.
/// Note when queuing events to reprocess you must <see cref="TraceEvent.Clone">Clone</see> them first
/// or certain internal data may no longer be available and you may receive memory access violations.
/// </summary>
/// <param name="ev">Event to re-process.</param>
[Obsolete("Not obsolete but experimental. We may change this in the future.")]
public void ReprocessEvent(TraceEvent ev)
{
RawDispatch(ev.eventRecord);
}
/// <summary>
/// The log moduleFile that is being processed (if present)
/// TODO: what does this do for Real time sessions?
/// </summary>
public string LogFileName { get { return logFiles[0].LogFileName; } }
/// <summary>
/// The name of the session that generated the data.
/// </summary>
public string SessionName { get { return logFiles[0].LoggerName; } }
/// <summary>
/// The size of the log, will return 0 if it does not know.
/// </summary>
public override long Size
{
get
{
long ret = 0;
for (int i = 0; i < logFiles.Length; i++)
{
var fileName = logFiles[i].LogFileName;
if (File.Exists(fileName))
{
ret += new FileInfo(fileName).Length;
}
}
return ret;
}
}
/// <summary>
/// returns the number of events that have been lost in this session. Note that this value is NOT updated
/// for real time sessions (it is a snapshot). Instead you need to use the TraceEventSession.EventsLost property.
/// </summary>
public override int EventsLost
{
get
{
int ret = 0;
for (int i = 0; i < logFiles.Length; i++)
{
ret += (int)logFiles[i].LogfileHeader.EventsLost;
}
return ret;
}
}
/// <summary>
/// Returns true if the Process can be called multiple times (if the Data source is from a
/// moduleFile, not a real time stream.
/// </summary>
public bool CanReset { get { return (logFiles[0].LogFileMode & TraceEventNativeMethods.EVENT_TRACE_REAL_TIME_MODE) == 0; } }
/// <summary>
/// This routine is only useful/valid for real-time sessions.
///
/// TraceEvent.TimeStamp internally is stored using a high resolution clock called the Query Performance Counter (QPC).
/// This clock is INDEPENDENT of the system clock used by DateTime. These two clocks are synchronized to within 2 msec at
/// session startup but they can drift from there (typically 2msec / min == 3 seconds / day). Thus if you have long
/// running real time session it becomes problematic to compare the timestamps with those in another session or something
/// timestamped with the system clock. SynchronizeClock will synchronize the TraceEvent.Timestamp clock with the system
/// clock again. If you do this right before you start another session, then the two sessions will be within 2 msec of
/// each other, and their timestamps will correlate. Doing it periodically (e.g. hourly), will keep things reasonably close.
///
/// TODO: we can achieve perfect synchronization by exposing the QPC tick sync point so we could read the sync point
/// from one session and set that exact sync point for another session.
/// </summary>
public void SynchronizeClock()
{
if (!IsRealTime)
{
throw new InvalidOperationException("SynchronizeClock is only for Real-Time Sessions");
}
DateTime utcNow = DateTime.UtcNow;
_syncTimeQPC = QPCTime.GetUTCTimeAsQPC(utcNow);
_syncTimeUTC = utcNow;
}
/// <summary>
/// Options that can be passed to GetModulesNeedingSymbols
/// </summary>
[Flags]
public enum ModuleSymbolOptions
{
/// <summary>
/// This is the default, where only NGEN images are included (since these are the only images whose PDBS typically
/// need to be resolved agressively AT COLLECTION TIME)
/// </summary>
OnlyNGENImages = 0,
/// <summary>
/// If set, this option indicates that non-NGEN images should also be included in the list of returned modules
/// </summary>
IncludeUnmanagedModules = 1,
/// <summary>
/// Normally only modules what have a CPU or stack sample are included in the list of assemblies (thus you don't
/// unnecessarily have to generate NGEN PDBS for modules that will never be looked up). However if there are
/// events that have addresses that need resolving that this routine does not recognise, this option can be
/// set to insure that any module that was event LOADED is included. This is inefficient, but guarenteed to
/// be complete
/// </summary>
IncludeModulesWithOutSamples = 2
}
/// <summary>
/// Given an ETL file, returns a list of the full paths to DLLs that were loaded in the trace that need symbolic
/// information (PDBs) so that the stack traces and CPU samples can be properly resolved. By default this only
/// returns NGEN images since these are the ones that need to be resolved and generated at collection time.
/// </summary>
public static IEnumerable<string> GetModulesNeedingSymbols(string etlFile, ModuleSymbolOptions options = ModuleSymbolOptions.OnlyNGENImages)
{
var images = new List<ImageData>(300);
var addressCounts = new Dictionary<Address, int>();
// Get the name of all DLLS (in the file, and the set of all address-process pairs in the file.
using (var source = new ETWTraceEventSource(etlFile))
{
source.Kernel.ImageGroup += delegate (ImageLoadTraceData data)
{
var fileName = data.FileName;
if (fileName.IndexOf(".ni.", StringComparison.OrdinalIgnoreCase) < 0)
{
// READY_TO_RUN support generate PDBs for ready-to-run images.
// TODO can rip this out when we don't package ready-to-run images
var windowsIdx = fileName.IndexOf(@"\windows\", StringComparison.OrdinalIgnoreCase);
if (0 <= windowsIdx && windowsIdx <= 2)
{
return;
}
if (!File.Exists(fileName))
{
return;
}
try
{
using (var peFile = new PEFile.PEFile(fileName))
{
if (!peFile.IsManagedReadyToRun)
{
return;
}
}
}
catch { return; }
}
var processId = data.ProcessID;
images.Add(new ImageData(processId, fileName, data.ImageBase, data.ImageSize));
};
source.Kernel.StackWalkStack += delegate (StackWalkStackTraceData data)
{
if (data.ProcessID == 0)
{
return;
}
var processId = data.ProcessID;
for (int i = 0; i < data.FrameCount; i++)
{
var address = (data.InstructionPointer(i) & 0xFFFFFFFFFFFF0000L) + ((Address)(processId & 0xFFFF));
addressCounts[address] = 1;
}
};
source.Clr.ClrStackWalk += delegate (ClrStackWalkTraceData data)
{
var processId = data.ProcessID;
for (int i = 0; i < data.FrameCount; i++)
{
var address = (data.InstructionPointer(i) & 0xFFFFFFFFFFFF0000L) + ((Address)(processId & 0xFFFF));
addressCounts[address] = 1;
}
};
source.Kernel.PerfInfoSample += delegate (SampledProfileTraceData data)
{
if (data.ProcessID == 0)
{
return;
}
var processId = data.ProcessID;
var address = (data.InstructionPointer & 0xFFFFFFFFFFFF0000L) + ((Address)(processId & 0xFFFF));
addressCounts[address] = 1;
};
source.Process();
}
// imageNames is a set of names that we want symbols for.
var imageNames = new Dictionary<string, string>(100);
foreach (var image in images)
{
if (!imageNames.ContainsKey(image.DllName))
{
for (uint offset = 0; offset < (uint)image.Size; offset += 0x10000)
{
var key = image.BaseAddress + offset + (uint)(image.ProcessID & 0xFFFF);
if (addressCounts.ContainsKey(key))
{
imageNames[image.DllName] = image.DllName;
break;
}
}
}
}
// Find the PDBS for the given images.
return new List<string>(imageNames.Keys);
}
#region Private
/// <summary>
/// Image data is a trivial record for image data, where it is keyed by the base address, processID and name.
/// </summary>
private class ImageData : IComparable<ImageData>
{
public int CompareTo(ImageData other)
{
var ret = BaseAddress.CompareTo(other.BaseAddress);
if (ret != 0)
{
return ret;
}
ret = ProcessID - other.ProcessID;
if (ret != 0)
{
return ret;
}
return DllName.CompareTo(other.DllName);
}
public ImageData(int ProcessID, string DllName, Address BaseAddress, int Size)
{
this.ProcessID = ProcessID;
this.DllName = DllName;
this.BaseAddress = BaseAddress;
this.Size = Size;
}
public int ProcessID;
public string DllName;
public Address BaseAddress;
public int Size;
}
private void Initialize(string fileOrSessionName, TraceEventSourceType type)
{
// Allocate the LOGFILE and structures and arrays that hold them
// Figure out how many log files we have
if (type == TraceEventSourceType.MergeAll)
{
List<string> allLogFiles = GetMergeAllLogFiles(fileOrSessionName);
logFiles = new TraceEventNativeMethods.EVENT_TRACE_LOGFILEW[allLogFiles.Count];
for (int i = 0; i < allLogFiles.Count; i++)
{
logFiles[i].LogFileName = allLogFiles[i];
}
}
else
{
logFiles = new TraceEventNativeMethods.EVENT_TRACE_LOGFILEW[1];
if (type == TraceEventSourceType.FileOnly)
{
logFiles[0].LogFileName = fileOrSessionName;
}
else
{
Debug.Assert(type == TraceEventSourceType.Session);
logFiles[0].LoggerName = fileOrSessionName;
logFiles[0].LogFileMode |= TraceEventNativeMethods.EVENT_TRACE_REAL_TIME_MODE;
IsRealTime = true;
}
}
handles = new ulong[logFiles.Length];
// Fill out the first log file information (we will clone it later if we have multiple files).
logFiles[0].BufferCallback = TraceEventBufferCallback;
handles[0] = TraceEventNativeMethods.INVALID_HANDLE_VALUE;
useClassicETW = !OperatingSystemVersion.AtLeast(OperatingSystemVersion.Vista);
if (useClassicETW)
{
var mem = (TraceEventNativeMethods.EVENT_RECORD*)Marshal.AllocHGlobal(sizeof(TraceEventNativeMethods.EVENT_RECORD));
*mem = default(TraceEventNativeMethods.EVENT_RECORD);
convertedHeader = mem;
logFiles[0].EventCallback = RawDispatchClassic;
}
else
{
logFiles[0].LogFileMode |= TraceEventNativeMethods.PROCESS_TRACE_MODE_EVENT_RECORD;
logFiles[0].EventCallback = RawDispatch;
}
// We want the raw timestamp because it is needed to match up stacks with the event they go with.
logFiles[0].LogFileMode |= TraceEventNativeMethods.PROCESS_TRACE_MODE_RAW_TIMESTAMP;
// Copy the information to any additional log files
for (int i = 1; i < logFiles.Length; i++)
{
logFiles[i].BufferCallback = logFiles[0].BufferCallback;
logFiles[i].EventCallback = logFiles[0].EventCallback;
logFiles[i].LogFileMode = logFiles[0].LogFileMode;
handles[i] = handles[0];
}
DateTime minSessionStartTimeUTC = DateTime.MaxValue;
DateTime maxSessionEndTimeUTC = DateTime.MinValue + new TimeSpan(1 * 365, 0, 0, 0); // TO avoid roundoff error when converting to QPC add a year.
// Open all the traces
for (int i = 0; i < handles.Length; i++)
{
handles[i] = TraceEventNativeMethods.OpenTrace(ref logFiles[i]);
if (handles[i] == TraceEventNativeMethods.INVALID_HANDLE_VALUE)
{
Marshal.ThrowExceptionForHR(TraceEventNativeMethods.GetHRForLastWin32Error());
}
// Start time is minimum of all start times
DateTime logFileStartTimeUTC = SafeFromFileTimeUtc(logFiles[i].LogfileHeader.StartTime);
DateTime logFileEndTimeUTC = SafeFromFileTimeUtc(logFiles[i].LogfileHeader.EndTime);
if (logFileStartTimeUTC < minSessionStartTimeUTC)
{
minSessionStartTimeUTC = logFileStartTimeUTC;
}
// End time is maximum of all start times
if (logFileEndTimeUTC > maxSessionEndTimeUTC)
{
maxSessionEndTimeUTC = logFileEndTimeUTC;
}
// TODO do we even need log pointer size anymore?
// We take the max pointer size.
if ((int)logFiles[i].LogfileHeader.PointerSize > pointerSize)
{
pointerSize = (int)logFiles[i].LogfileHeader.PointerSize;
}
}
_QPCFreq = logFiles[0].LogfileHeader.PerfFreq;
if (_QPCFreq == 0)
{
_QPCFreq = Stopwatch.Frequency;
}
// Real time providers don't set this to something useful
if ((logFiles[0].LogFileMode & TraceEventNativeMethods.EVENT_TRACE_REAL_TIME_MODE) != 0)
{
DateTime nowUTC = DateTime.UtcNow;
long nowQPC = QPCTime.GetUTCTimeAsQPC(nowUTC);
_syncTimeQPC = nowQPC;
_syncTimeUTC = nowUTC;
sessionStartTimeQPC = nowQPC - _QPCFreq / 10; // Subtract 1/10 sec to keep now and nowQPC in sync.
sessionEndTimeQPC = long.MaxValue; // Represents infinity.
Debug.Assert(SessionStartTime < SessionEndTime);
}
else
{
_syncTimeUTC = minSessionStartTimeUTC;
// UTCDateTimeToQPC is actually going to give the wrong value for these because we have
// not set _syncTimeQPC, but will be adjusted when we see the event Header and know _syncTypeQPC.
sessionStartTimeQPC = UTCDateTimeToQPC(minSessionStartTimeUTC);
sessionEndTimeQPC = UTCDateTimeToQPC(maxSessionEndTimeUTC);
}
Debug.Assert(_QPCFreq != 0);
if (pointerSize == 0 || IsRealTime) // We get on x64 OS 4 as pointer size which is wrong for realtime sessions. Fix it up.
{
pointerSize = GetOSPointerSize();
Debug.Assert((logFiles[0].LogFileMode & TraceEventNativeMethods.EVENT_TRACE_REAL_TIME_MODE) != 0);
}
Debug.Assert(pointerSize == 4 || pointerSize == 8);
cpuSpeedMHz = (int)logFiles[0].LogfileHeader.CpuSpeedInMHz;
numberOfProcessors = (int)logFiles[0].LogfileHeader.NumberOfProcessors;
// We ask for raw timestamps, but the log file may have used system time as its raw timestamp.
// SystemTime is like a QPC time that happens 10M times a second (100ns).
// ReservedFlags is actually the ClockType 0 = Raw, 1 = QPC, 2 = SystemTimne 3 = CpuTick (we don't support)
if (logFiles[0].LogfileHeader.ReservedFlags == 2) // If ClockType == EVENT_TRACE_CLOCK_SYSTEMTIME
{
_QPCFreq = 10000000;
}
Debug.Assert(_QPCFreq != 0);
int ver = (int)logFiles[0].LogfileHeader.Version;
osVersion = new Version((byte)ver, (byte)(ver >> 8));
// Logic for looking up process names
processNameForID = new Dictionary<int, string>();
var kernelParser = new KernelTraceEventParser(this, KernelTraceEventParser.ParserTrackingOptions.None);
kernelParser.ProcessStartGroup += delegate (ProcessTraceData data)
{
// Get just the file name without the extension. Can't use the 'Path' class because
// it tests to make certain it does not have illegal chars etc. Since KernelImageFileName
// is not a true user mode path, we can get failures.
string path = data.KernelImageFileName;
int startIdx = path.LastIndexOf('\\');
if (0 <= startIdx)
{
startIdx++;
}
else
{
startIdx = 0;
}
int endIdx = path.LastIndexOf('.');
if (endIdx <= startIdx)
{
endIdx = path.Length;
}
processNameForID[data.ProcessID] = path.Substring(startIdx, endIdx - startIdx);
};
kernelParser.ProcessEndGroup += delegate (ProcessTraceData data)
{
processNameForID.Remove(data.ProcessID);
};
kernelParser.EventTraceHeader += delegate (EventTraceHeaderTraceData data)
{
if (_syncTimeQPC == 0)
{ // In merged files there can be more of these, we only set the QPC time on the first one
// We were using a 'start location' of 0, but we want it to be the timestamp of this events, so we add this to our
// existing QPC values.
_syncTimeQPC = data.TimeStampQPC;
sessionStartTimeQPC += data.TimeStampQPC;
sessionEndTimeQPC += data.TimeStampQPC;
}
};
}
/// <summary>
/// Returns the size of pointer (8 or 4) for the operating system (not necessarily the process)
/// </summary>
internal static int GetOSPointerSize()
{
if (IntPtr.Size == 8)
{
return 8;
}
#if !NETSTANDARD1_6
bool is64bitOS = Environment.Is64BitOperatingSystem;
#else
// Sadly this API does not work properly on V4.7.1 of the Desktop framework. See https://github.com/Microsoft/perfview/issues/478 for more.
// However with this partial fix, (works on everything not NetSTandard, and only in 32 bit processes), that we can wait for the fix.
bool is64bitOS = (RuntimeInformation.OSArchitecture == Architecture.X64 || RuntimeInformation.OSArchitecture == Architecture.Arm64);
#endif
return is64bitOS ? 8 : 4;
}
internal static DateTime SafeFromFileTimeUtc(long fileTime)
{
ulong maxTime = (ulong)DateTime.MaxValue.ToFileTimeUtc();
if (maxTime < (ulong)fileTime)
{
return DateTime.MaxValue;
}
return DateTime.FromFileTimeUtc(fileTime);
}
/// <summary>
/// This is a little helper class that maps QueryPerformanceCounter (QPC) ticks to DateTime. There is an error of
/// a few msec, but as long as every one uses the same one, we probably don't care.
/// </summary>
private class QPCTime
{
public static long GetUTCTimeAsQPC(DateTime utcTime)
{
QPCTime qpcTime = new QPCTime();
return qpcTime._GetUTCTimeAsQPC(utcTime);
}
#region private
private long _GetUTCTimeAsQPC(DateTime utcTime)
{
// Convert to seconds from the baseline
double deltaSec = (utcTime.Ticks - m_timeAsDateTimeUTC.Ticks) / 10000000.0;
// scale to QPC units and then add back in the base.
return (long)(deltaSec * Stopwatch.Frequency) + m_timeAsQPC;
}
private QPCTime()
{
// We call Now and GetTimeStame at one point (it will be off by the latency of
// one call to these functions). However since UtcNow only changes once every 16
// msec, we loop until we see it change which lets us get with 1-2 msec of the
// correct synchronization.
DateTime start = DateTime.UtcNow;
long lastQPC = Stopwatch.GetTimestamp();
for (; ; )
{
var next = DateTime.UtcNow;
m_timeAsQPC = Stopwatch.GetTimestamp();
if (next != start)
{
m_timeAsDateTimeUTC = next;
m_timeAsQPC = lastQPC; // We would rather be before than after.
break;
}
lastQPC = m_timeAsQPC;
}
}
// A QPC object just needs to hold a point in time in both units (DateTime and QPC).
private DateTime m_timeAsDateTimeUTC;
private long m_timeAsQPC;
#endregion
}
internal static List<string> GetMergeAllLogFiles(string fileName)
{
string fileBaseName = Path.GetFileNameWithoutExtension(fileName);
string dir = Path.GetDirectoryName(fileName);
if (dir.Length == 0)
{
dir = ".";
}
List<string> allLogFiles = new List<string>();
allLogFiles.AddRange(Directory.GetFiles(dir, fileBaseName + ".etl"));
allLogFiles.AddRange(Directory.GetFiles(dir, fileBaseName + ".kernel*.etl"));
allLogFiles.AddRange(Directory.GetFiles(dir, fileBaseName + ".clr*.etl"));
allLogFiles.AddRange(Directory.GetFiles(dir, fileBaseName + ".user*.etl"));
if (allLogFiles.Count == 0)
{
throw new FileNotFoundException("Could not find file " + fileName);
}
return allLogFiles;
}
private bool ProcessOneFile()
{
int dwErr = TraceEventNativeMethods.ProcessTrace(handles, (uint)handles.Length, (IntPtr)0, (IntPtr)0);
if (dwErr == 6)
{
throw new ApplicationException("Error opening ETL file. Most likely caused by opening a Win8 Trace on a Pre Win8 OS.");
}
// ETW returns 1223 when you stop processing explicitly
if (!(dwErr == 1223 && stopProcessing))
{
Marshal.ThrowExceptionForHR(TraceEventNativeMethods.GetHRFromWin32(dwErr));
}
return !stopProcessing;
}
#if DEBUG
internal bool DisallowEventIndexAccess { get; set; }
#endif
// #ETWTraceEventSourceInternals
//
// ETWTraceEventSource is a wrapper around the Windows API TraceEventNativeMethods.OpenTrace
// method (see http://msdn2.microsoft.com/en-us/library/aa364089.aspx) We set it up so that we call
// back to ETWTraceEventSource.Dispatch which is the heart of the event callback logic.
// [SecuritySafeCritical]
private void RawDispatchClassic(TraceEventNativeMethods.EVENT_RECORD* eventData)
{
// TODO not really a EVENT_RECORD on input, but it is a pain to be type-correct.
TraceEventNativeMethods.EVENT_TRACE* oldStyleHeader = (TraceEventNativeMethods.EVENT_TRACE*)eventData;
eventData = convertedHeader;
eventData->EventHeader.Size = (ushort)sizeof(TraceEventNativeMethods.EVENT_TRACE_HEADER);
// HeaderType
eventData->EventHeader.Flags = TraceEventNativeMethods.EVENT_HEADER_FLAG_CLASSIC_HEADER;
// TODO Figure out if there is a marker that is used in the WOW for the classic providers
// right now I assume they are all the same as the machine.
if (pointerSize == 8)
{
eventData->EventHeader.Flags |= TraceEventNativeMethods.EVENT_HEADER_FLAG_64_BIT_HEADER;
}
else
{
eventData->EventHeader.Flags |= TraceEventNativeMethods.EVENT_HEADER_FLAG_32_BIT_HEADER;
}
// EventProperty
eventData->EventHeader.ThreadId = oldStyleHeader->Header.ThreadId;
eventData->EventHeader.ProcessId = oldStyleHeader->Header.ProcessId;
eventData->EventHeader.TimeStamp = oldStyleHeader->Header.TimeStamp;
eventData->EventHeader.ProviderId = oldStyleHeader->Header.Guid; // ProviderId = TaskId
// ID left 0
eventData->EventHeader.Version = (byte)oldStyleHeader->Header.Version;
// Channel
eventData->EventHeader.Level = oldStyleHeader->Header.Level;
eventData->EventHeader.Opcode = oldStyleHeader->Header.Type;
// Task
// Keyword
eventData->EventHeader.KernelTime = oldStyleHeader->Header.KernelTime;
eventData->EventHeader.UserTime = oldStyleHeader->Header.UserTime;
// ActivityID
eventData->BufferContext = oldStyleHeader->BufferContext;
// ExtendedDataCount
eventData->UserDataLength = (ushort)oldStyleHeader->MofLength;
// ExtendedData
eventData->UserData = oldStyleHeader->MofData;
// UserContext
RawDispatch(eventData);
}
// [SecuritySafeCritical]
private void RawDispatch(TraceEventNativeMethods.EVENT_RECORD* rawData)
{
if (stopProcessing)
{
return;
}
if (lockObj != null)
{
Monitor.Enter(lockObj);
}
Debug.Assert(rawData->EventHeader.HeaderType == 0); // if non-zero probably old-style ETW header
// Give it an event ID if it does not have one.
traceLoggingEventId.TestForTraceLoggingEventAndFixupIfNeeded(rawData);
TraceEvent anEvent = Lookup(rawData);
#if DEBUG
anEvent.DisallowEventIndexAccess = DisallowEventIndexAccess;
#endif
// Keep in mind that for UnhandledTraceEvent 'PrepForCallback' has NOT been called, which means the
// opcode, guid and eventIds are not correct at this point. The ToString() routine WILL call
// this so if that is in your debug window, it will have this side effect (which is good and bad)
// Looking at rawData will give you the truth however.
anEvent.DebugValidate();
if (anEvent.NeedsFixup)
{
anEvent.FixupData();
}
Dispatch(anEvent);
if (lockObj != null)
{
Monitor.Exit(lockObj);
}
}
/// <summary>
/// see Dispose pattern
/// </summary>
protected override void Dispose(bool disposing)
{
// We only want one thread doing this at a time.
lock (this)
{
stopProcessing = true;
if (handles != null)
{
foreach (ulong handle in handles)
{
if (handle != TraceEventNativeMethods.INVALID_HANDLE_VALUE)
{
TraceEventNativeMethods.CloseTrace(handle);
}
}
handles = null;
}
if (convertedHeader != null)
{
Marshal.FreeHGlobal((IntPtr)convertedHeader);
convertedHeader = null;
}
traceLoggingEventId.Dispose();
// logFiles = null; Keep the callback delegate alive as long as possible.
base.Dispose(disposing);
}
}
/// <summary>
/// see Dispose pattern
/// </summary>
~ETWTraceEventSource()
{
Dispose(false);
}
private void Reset()
{
if (!CanReset)
{
throw new InvalidOperationException("Event stream is not resetable (e.g. real time).");
}
if (handles != null)
{
for (int i = 0; i < handles.Length; i++)
{
if (handles[i] != TraceEventNativeMethods.INVALID_HANDLE_VALUE)
{
TraceEventNativeMethods.CloseTrace(handles[i]);
handles[i] = TraceEventNativeMethods.INVALID_HANDLE_VALUE;
}
// Annoying. The OS resets the LogFileMode field, so I have to set it up again.
if (!useClassicETW)
{
logFiles[i].LogFileMode = TraceEventNativeMethods.PROCESS_TRACE_MODE_EVENT_RECORD;
logFiles[i].LogFileMode |= TraceEventNativeMethods.PROCESS_TRACE_MODE_RAW_TIMESTAMP;
}
handles[i] = TraceEventNativeMethods.OpenTrace(ref logFiles[i]);
if (handles[i] == TraceEventNativeMethods.INVALID_HANDLE_VALUE)
{
Marshal.ThrowExceptionForHR(TraceEventNativeMethods.GetHRForLastWin32Error());
}
}
}
}
// Private data / methods
// [SecuritySafeCritical]
private bool TraceEventBufferCallback(IntPtr rawLogFile)
{
return !stopProcessing;
}
// #ETWTraceEventSourceFields
private bool processTraceCalled;
private TraceEventNativeMethods.EVENT_RECORD* convertedHeader;
// Returned from OpenTrace
private TraceEventNativeMethods.EVENT_TRACE_LOGFILEW[] logFiles;
private UInt64[] handles;
private IEnumerable<string> fileNames; // Used if more than one file being processed. (Null otherwise)
// TODO this can be removed, and use AddDispatchHook instead.
/// <summary>
/// Used by real time TraceLog on Windows7.
/// If we have several real time sources we have them coming in on several threads, but we want the illusion that they
/// are one source (thus being processed one at a time). Thus we want a lock that is taken on every dispatch.
/// </summary>
internal object lockObj;
// We do minimal processing to keep track of process names (since they are REALLY handy).
private Dictionary<int, string> processNameForID;
// Used to give TraceLogging events Event IDs.
private TraceLoggingEventId traceLoggingEventId;
internal override string ProcessName(int processID, long time100ns)
{
string ret;
if (!processNameForID.TryGetValue(processID, out ret))
{
ret = "";
}
return ret;
}
#endregion
}
/// <summary>
/// The kinds of data sources that can be opened (see ETWTraceEventSource)
/// </summary>
public enum TraceEventSourceType
{
/// <summary>
/// Look for any files like *.etl or *.*.etl (the later holds things like *.kernel.etl or *.clrRundown.etl ...)
/// </summary>
MergeAll,
/// <summary>
/// Look for a ETL moduleFile *.etl as the event data source
/// </summary>
FileOnly,
/// <summary>
/// Use a real time session as the event data source.
/// </summary>
Session,
};
}
| |
// 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.Net.Security;
using System.Runtime;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.Xml;
namespace System.ServiceModel.Security
{
public class ChannelProtectionRequirements
{
private ScopedMessagePartSpecification _incomingSignatureParts;
private ScopedMessagePartSpecification _incomingEncryptionParts;
private ScopedMessagePartSpecification _outgoingSignatureParts;
private ScopedMessagePartSpecification _outgoingEncryptionParts;
private bool _isReadOnly;
public ChannelProtectionRequirements()
{
_incomingSignatureParts = new ScopedMessagePartSpecification();
_incomingEncryptionParts = new ScopedMessagePartSpecification();
_outgoingSignatureParts = new ScopedMessagePartSpecification();
_outgoingEncryptionParts = new ScopedMessagePartSpecification();
}
public bool IsReadOnly
{
get
{
return _isReadOnly;
}
}
public ChannelProtectionRequirements(ChannelProtectionRequirements other)
{
if (other == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("other"));
_incomingSignatureParts = new ScopedMessagePartSpecification(other._incomingSignatureParts);
_incomingEncryptionParts = new ScopedMessagePartSpecification(other._incomingEncryptionParts);
_outgoingSignatureParts = new ScopedMessagePartSpecification(other._outgoingSignatureParts);
_outgoingEncryptionParts = new ScopedMessagePartSpecification(other._outgoingEncryptionParts);
}
internal ChannelProtectionRequirements(ChannelProtectionRequirements other, ProtectionLevel newBodyProtectionLevel)
{
if (other == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("other"));
_incomingSignatureParts = new ScopedMessagePartSpecification(other._incomingSignatureParts, newBodyProtectionLevel != ProtectionLevel.None);
_incomingEncryptionParts = new ScopedMessagePartSpecification(other._incomingEncryptionParts, newBodyProtectionLevel == ProtectionLevel.EncryptAndSign);
_outgoingSignatureParts = new ScopedMessagePartSpecification(other._outgoingSignatureParts, newBodyProtectionLevel != ProtectionLevel.None);
_outgoingEncryptionParts = new ScopedMessagePartSpecification(other._outgoingEncryptionParts, newBodyProtectionLevel == ProtectionLevel.EncryptAndSign);
}
public ScopedMessagePartSpecification IncomingSignatureParts
{
get
{
return _incomingSignatureParts;
}
}
public ScopedMessagePartSpecification IncomingEncryptionParts
{
get
{
return _incomingEncryptionParts;
}
}
public ScopedMessagePartSpecification OutgoingSignatureParts
{
get
{
return _outgoingSignatureParts;
}
}
public ScopedMessagePartSpecification OutgoingEncryptionParts
{
get
{
return _outgoingEncryptionParts;
}
}
public void Add(ChannelProtectionRequirements protectionRequirements)
{
this.Add(protectionRequirements, false);
}
public void Add(ChannelProtectionRequirements protectionRequirements, bool channelScopeOnly)
{
if (protectionRequirements == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("protectionRequirements"));
if (protectionRequirements._incomingSignatureParts != null)
_incomingSignatureParts.AddParts(protectionRequirements._incomingSignatureParts.ChannelParts);
if (protectionRequirements._incomingEncryptionParts != null)
_incomingEncryptionParts.AddParts(protectionRequirements._incomingEncryptionParts.ChannelParts);
if (protectionRequirements._outgoingSignatureParts != null)
_outgoingSignatureParts.AddParts(protectionRequirements._outgoingSignatureParts.ChannelParts);
if (protectionRequirements._outgoingEncryptionParts != null)
_outgoingEncryptionParts.AddParts(protectionRequirements._outgoingEncryptionParts.ChannelParts);
if (!channelScopeOnly)
{
AddActionParts(_incomingSignatureParts, protectionRequirements._incomingSignatureParts);
AddActionParts(_incomingEncryptionParts, protectionRequirements._incomingEncryptionParts);
AddActionParts(_outgoingSignatureParts, protectionRequirements._outgoingSignatureParts);
AddActionParts(_outgoingEncryptionParts, protectionRequirements._outgoingEncryptionParts);
}
}
private static void AddActionParts(ScopedMessagePartSpecification to, ScopedMessagePartSpecification from)
{
foreach (string action in from.Actions)
{
MessagePartSpecification p;
if (from.TryGetParts(action, true, out p))
to.AddParts(p, action);
}
}
public void MakeReadOnly()
{
if (!_isReadOnly)
{
_incomingSignatureParts.MakeReadOnly();
_incomingEncryptionParts.MakeReadOnly();
_outgoingSignatureParts.MakeReadOnly();
_outgoingEncryptionParts.MakeReadOnly();
_isReadOnly = true;
}
}
public ChannelProtectionRequirements CreateInverse()
{
ChannelProtectionRequirements result = new ChannelProtectionRequirements();
result.Add(this, true);
result._incomingSignatureParts = new ScopedMessagePartSpecification(this.OutgoingSignatureParts);
result._outgoingSignatureParts = new ScopedMessagePartSpecification(this.IncomingSignatureParts);
result._incomingEncryptionParts = new ScopedMessagePartSpecification(this.OutgoingEncryptionParts);
result._outgoingEncryptionParts = new ScopedMessagePartSpecification(this.IncomingEncryptionParts);
return result;
}
internal static ChannelProtectionRequirements CreateFromContract(ContractDescription contract, ISecurityCapabilities bindingElement, bool isForClient)
{
return CreateFromContract(contract, bindingElement.SupportedRequestProtectionLevel, bindingElement.SupportedResponseProtectionLevel, isForClient);
}
private static MessagePartSpecification UnionMessagePartSpecifications(ScopedMessagePartSpecification actionParts)
{
MessagePartSpecification result = new MessagePartSpecification(false);
foreach (string action in actionParts.Actions)
{
MessagePartSpecification parts;
if (actionParts.TryGetParts(action, out parts))
{
if (parts.IsBodyIncluded)
{
result.IsBodyIncluded = true;
}
foreach (XmlQualifiedName headerType in parts.HeaderTypes)
{
if (!result.IsHeaderIncluded(headerType.Name, headerType.Namespace))
{
result.HeaderTypes.Add(headerType);
}
}
}
}
return result;
}
internal static ChannelProtectionRequirements CreateFromContractAndUnionResponseProtectionRequirements(ContractDescription contract, ISecurityCapabilities bindingElement, bool isForClient)
{
ChannelProtectionRequirements contractRequirements = CreateFromContract(contract, bindingElement.SupportedRequestProtectionLevel, bindingElement.SupportedResponseProtectionLevel, isForClient);
// union all the protection requirements for the response actions
ChannelProtectionRequirements result = new ChannelProtectionRequirements();
if (isForClient)
{
result.IncomingEncryptionParts.AddParts(UnionMessagePartSpecifications(contractRequirements.IncomingEncryptionParts), MessageHeaders.WildcardAction);
result.IncomingSignatureParts.AddParts(UnionMessagePartSpecifications(contractRequirements.IncomingSignatureParts), MessageHeaders.WildcardAction);
contractRequirements.OutgoingEncryptionParts.CopyTo(result.OutgoingEncryptionParts);
contractRequirements.OutgoingSignatureParts.CopyTo(result.OutgoingSignatureParts);
}
else
{
result.OutgoingEncryptionParts.AddParts(UnionMessagePartSpecifications(contractRequirements.OutgoingEncryptionParts), MessageHeaders.WildcardAction);
result.OutgoingSignatureParts.AddParts(UnionMessagePartSpecifications(contractRequirements.OutgoingSignatureParts), MessageHeaders.WildcardAction);
contractRequirements.IncomingEncryptionParts.CopyTo(result.IncomingEncryptionParts);
contractRequirements.IncomingSignatureParts.CopyTo(result.IncomingSignatureParts);
}
return result;
}
internal static ChannelProtectionRequirements CreateFromContract(ContractDescription contract, ProtectionLevel defaultRequestProtectionLevel, ProtectionLevel defaultResponseProtectionLevel, bool isForClient)
{
if (contract == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("contract"));
ChannelProtectionRequirements requirements = new ChannelProtectionRequirements();
ProtectionLevel contractScopeDefaultRequestProtectionLevel;
ProtectionLevel contractScopeDefaultResponseProtectionLevel;
if (contract.HasProtectionLevel)
{
contractScopeDefaultRequestProtectionLevel = contract.ProtectionLevel;
contractScopeDefaultResponseProtectionLevel = contract.ProtectionLevel;
}
else
{
contractScopeDefaultRequestProtectionLevel = defaultRequestProtectionLevel;
contractScopeDefaultResponseProtectionLevel = defaultResponseProtectionLevel;
}
foreach (OperationDescription operation in contract.Operations)
{
ProtectionLevel operationScopeDefaultRequestProtectionLevel;
ProtectionLevel operationScopeDefaultResponseProtectionLevel;
operationScopeDefaultRequestProtectionLevel = contractScopeDefaultRequestProtectionLevel;
operationScopeDefaultResponseProtectionLevel = contractScopeDefaultResponseProtectionLevel;
foreach (MessageDescription message in operation.Messages)
{
ProtectionLevel messageScopeDefaultProtectionLevel;
if (message.HasProtectionLevel)
{
messageScopeDefaultProtectionLevel = message.ProtectionLevel;
}
else if (message.Direction == MessageDirection.Input)
{
messageScopeDefaultProtectionLevel = operationScopeDefaultRequestProtectionLevel;
}
else
{
messageScopeDefaultProtectionLevel = operationScopeDefaultResponseProtectionLevel;
}
MessagePartSpecification signedParts = new MessagePartSpecification();
MessagePartSpecification encryptedParts = new MessagePartSpecification();
// determine header protection requirements for message
foreach (MessageHeaderDescription header in message.Headers)
{
AddHeaderProtectionRequirements(header, signedParts, encryptedParts, messageScopeDefaultProtectionLevel);
}
// determine body protection requirements for message
ProtectionLevel bodyProtectionLevel;
if (message.Body.Parts.Count > 0)
{
// initialize the body protection level to none. all the body parts will be
// unioned to get the effective body protection level
bodyProtectionLevel = ProtectionLevel.None;
}
else if (message.Body.ReturnValue != null)
{
if (!(message.Body.ReturnValue.GetType().Equals(typeof(MessagePartDescription))))
{
Fx.Assert("Only body return values are supported currently");
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.OnlyBodyReturnValuesSupported));
}
MessagePartDescription desc = message.Body.ReturnValue;
bodyProtectionLevel = desc.HasProtectionLevel ? desc.ProtectionLevel : messageScopeDefaultProtectionLevel;
}
else
{
bodyProtectionLevel = messageScopeDefaultProtectionLevel;
}
// determine body protection requirements for message
if (message.Body.Parts.Count > 0)
{
foreach (MessagePartDescription body in message.Body.Parts)
{
ProtectionLevel partProtectionLevel = body.HasProtectionLevel ? body.ProtectionLevel : messageScopeDefaultProtectionLevel;
bodyProtectionLevel = ProtectionLevelHelper.Max(bodyProtectionLevel, partProtectionLevel);
if (bodyProtectionLevel == ProtectionLevel.EncryptAndSign)
break;
}
}
if (bodyProtectionLevel != ProtectionLevel.None)
{
signedParts.IsBodyIncluded = true;
if (bodyProtectionLevel == ProtectionLevel.EncryptAndSign)
encryptedParts.IsBodyIncluded = true;
}
// add requirements for message
if (message.Direction == MessageDirection.Input)
{
requirements.IncomingSignatureParts.AddParts(signedParts, message.Action);
requirements.IncomingEncryptionParts.AddParts(encryptedParts, message.Action);
}
else
{
requirements.OutgoingSignatureParts.AddParts(signedParts, message.Action);
requirements.OutgoingEncryptionParts.AddParts(encryptedParts, message.Action);
}
}
if (operation.Faults != null)
{
if (operation.IsServerInitiated())
{
AddFaultProtectionRequirements(operation.Faults, requirements, operationScopeDefaultRequestProtectionLevel, true);
}
else
{
AddFaultProtectionRequirements(operation.Faults, requirements, operationScopeDefaultResponseProtectionLevel, false);
}
}
}
return requirements;
}
private static void AddHeaderProtectionRequirements(MessageHeaderDescription header, MessagePartSpecification signedParts,
MessagePartSpecification encryptedParts, ProtectionLevel defaultProtectionLevel)
{
ProtectionLevel p = header.HasProtectionLevel ? header.ProtectionLevel : defaultProtectionLevel;
if (p != ProtectionLevel.None)
{
XmlQualifiedName headerName = new XmlQualifiedName(header.Name, header.Namespace);
signedParts.HeaderTypes.Add(headerName);
if (p == ProtectionLevel.EncryptAndSign)
encryptedParts.HeaderTypes.Add(headerName);
}
}
private static void AddFaultProtectionRequirements(FaultDescriptionCollection faults, ChannelProtectionRequirements requirements, ProtectionLevel defaultProtectionLevel, bool addToIncoming)
{
if (faults == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("faults"));
if (requirements == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("requirements"));
foreach (FaultDescription fault in faults)
{
MessagePartSpecification signedParts = new MessagePartSpecification();
MessagePartSpecification encryptedParts = new MessagePartSpecification();
ProtectionLevel p = fault.HasProtectionLevel ? fault.ProtectionLevel : defaultProtectionLevel;
if (p != ProtectionLevel.None)
{
signedParts.IsBodyIncluded = true;
if (p == ProtectionLevel.EncryptAndSign)
{
encryptedParts.IsBodyIncluded = true;
}
}
if (addToIncoming)
{
requirements.IncomingSignatureParts.AddParts(signedParts, fault.Action);
requirements.IncomingEncryptionParts.AddParts(encryptedParts, fault.Action);
}
else
{
requirements.OutgoingSignatureParts.AddParts(signedParts, fault.Action);
requirements.OutgoingEncryptionParts.AddParts(encryptedParts, fault.Action);
}
}
}
}
}
| |
/*
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. See License.txt in the project root for license information.
*/
using System;
using System.Web;
using System.Web.Routing;
using Adxstudio.Xrm.Web.Routing;
using Microsoft.Xrm.Client.Security;
using Microsoft.Xrm.Portal;
using Microsoft.Xrm.Portal.Web;
using Microsoft.Xrm.Portal.Web.Providers;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
namespace Adxstudio.Xrm.Blogs
{
public class DataAdapterDependencies : IDataAdapterDependencies
{
private readonly EntityReference _portalUser;
private RequestContext _requestContext;
private readonly ICrmEntitySecurityProvider _securityProvider;
private readonly OrganizationServiceContext _serviceContext;
private readonly IEntityUrlProvider _urlProvider;
private readonly EntityReference _website;
public DataAdapterDependencies(OrganizationServiceContext serviceContext, ICrmEntitySecurityProvider securityProvider,
IEntityUrlProvider urlProvider, EntityReference website, EntityReference portalUser = null, RequestContext requestContext = null)
{
if (serviceContext == null)
{
throw new ArgumentNullException("serviceContext");
}
if (securityProvider == null)
{
throw new ArgumentNullException("securityProvider");
}
if (urlProvider == null)
{
throw new ArgumentNullException("urlProvider");
}
if (website == null)
{
throw new ArgumentNullException("website");
}
_serviceContext = serviceContext;
_securityProvider = securityProvider;
_urlProvider = urlProvider;
_website = website;
_portalUser = portalUser;
_requestContext = requestContext;
}
public DataAdapterDependencies(OrganizationServiceContext serviceContext, ICrmEntitySecurityProvider securityProvider,
IEntityUrlProvider urlProvider, IPortalContext portalContext, RequestContext requestContext = null) : this(
serviceContext,
securityProvider,
urlProvider,
portalContext.Website == null ? null : portalContext.Website.ToEntityReference(),
portalContext.User == null ? null : portalContext.User.ToEntityReference(),
requestContext)
{
if (portalContext == null)
{
throw new ArgumentNullException("portalContext");
}
}
public ApplicationPath GetBlogAggregationFeedPath()
{
var requestContext = GetRequestContext();
if (requestContext == null)
{
return null;
}
var virtualPath = RouteTable.Routes.GetVirtualPath(requestContext, typeof(WebsiteBlogAggregationFeedRouteHandler).FullName, new RouteValueDictionary
{
{ "__portalScopeId__", _website.Id }
});
return virtualPath == null ? null : ApplicationPath.FromAbsolutePath(VirtualPathUtility.ToAbsolute(virtualPath.VirtualPath));
}
public ApplicationPath GetBlogFeedPath(Guid blogId)
{
var requestContext = GetRequestContext();
if (requestContext == null)
{
return null;
}
var virtualPath = RouteTable.Routes.GetVirtualPath(requestContext, typeof(BlogFeedRouteHandler).FullName, new RouteValueDictionary
{
{ "__portalScopeId__", _website.Id },
{ "id", blogId }
});
return virtualPath == null ? null : ApplicationPath.FromAbsolutePath(VirtualPathUtility.ToAbsolute(virtualPath.VirtualPath));
}
public ApplicationPath GetDeletePath(EntityReference entity)
{
if (entity == null || _requestContext == null) return null;
var website = GetWebsite();
if (website == null) return null;
try
{
var pathData = RouteTable.Routes.GetVirtualPath(_requestContext, typeof(CmsEntityDeleteRouteHandler).FullName, new RouteValueDictionary
{
{ "__portalScopeId__", website.Id.ToString() },
{ "entityLogicalName", entity.LogicalName },
{ "id", entity.Id.ToString() },
});
return pathData == null ? null : ApplicationPath.FromAbsolutePath(VirtualPathUtility.ToAbsolute(pathData.VirtualPath));
}
catch (ArgumentException)
{
return null;
}
}
public ApplicationPath GetEditPath(EntityReference entity)
{
if (entity == null || _requestContext == null) return null;
var website = GetWebsite();
if (website == null) return null;
try
{
var pathData = RouteTable.Routes.GetVirtualPath(_requestContext, typeof(CmsEntityRouteHandler).FullName, new RouteValueDictionary
{
{ "__portalScopeId__", website.Id.ToString() },
{ "entityLogicalName", entity.LogicalName },
{ "id", entity.Id.ToString() },
});
return pathData == null ? null : ApplicationPath.FromAbsolutePath(VirtualPathUtility.ToAbsolute(pathData.VirtualPath));
}
catch (ArgumentException)
{
return null;
}
}
public EntityReference GetPortalUser()
{
return _portalUser;
}
public ICrmEntitySecurityProvider GetSecurityProvider()
{
return _securityProvider;
}
public OrganizationServiceContext GetServiceContext()
{
return _serviceContext;
}
public OrganizationServiceContext GetServiceContextForWrite()
{
return _serviceContext;
}
public IEntityUrlProvider GetUrlProvider()
{
return _urlProvider;
}
public EntityReference GetWebsite()
{
return _website;
}
public RequestContext GetRequestContext()
{
if (_requestContext != null)
{
return _requestContext;
}
_requestContext = GetCurrentRequestContext();
return _requestContext;
}
private static RequestContext GetCurrentRequestContext()
{
var current = HttpContext.Current;
if (current == null)
{
return null;
}
var http = new HttpContextWrapper(current);
var routeData = RouteTable.Routes.GetRouteData(http) ?? new RouteData();
return new RequestContext(http, routeData);
}
}
}
| |
// 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.Management.DataLake.Analytics
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Azure.Management.DataLake;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Microsoft.Rest.Azure.OData;
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for JobOperations.
/// </summary>
public static partial class JobOperationsExtensions
{
/// <summary>
/// Gets statistics of the specified job.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='accountName'>
/// The Azure Data Lake Analytics account to execute job operations on.
/// </param>
/// <param name='jobIdentity'>
/// Job Information ID.
/// </param>
public static JobStatistics GetStatistics(this IJobOperations operations, string accountName, System.Guid jobIdentity)
{
return operations.GetStatisticsAsync(accountName, jobIdentity).GetAwaiter().GetResult();
}
/// <summary>
/// Gets statistics of the specified job.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='accountName'>
/// The Azure Data Lake Analytics account to execute job operations on.
/// </param>
/// <param name='jobIdentity'>
/// Job Information ID.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<JobStatistics> GetStatisticsAsync(this IJobOperations operations, string accountName, System.Guid jobIdentity, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetStatisticsWithHttpMessagesAsync(accountName, jobIdentity, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets the job debug data information specified by the job ID.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='accountName'>
/// The Azure Data Lake Analytics account to execute job operations on.
/// </param>
/// <param name='jobIdentity'>
/// JobInfo ID.
/// </param>
public static JobDataPath GetDebugDataPath(this IJobOperations operations, string accountName, System.Guid jobIdentity)
{
return operations.GetDebugDataPathAsync(accountName, jobIdentity).GetAwaiter().GetResult();
}
/// <summary>
/// Gets the job debug data information specified by the job ID.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='accountName'>
/// The Azure Data Lake Analytics account to execute job operations on.
/// </param>
/// <param name='jobIdentity'>
/// JobInfo ID.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<JobDataPath> GetDebugDataPathAsync(this IJobOperations operations, string accountName, System.Guid jobIdentity, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetDebugDataPathWithHttpMessagesAsync(accountName, jobIdentity, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Builds (compiles) the specified job in the specified Data Lake Analytics
/// account for job correctness and validation.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='accountName'>
/// The Azure Data Lake Analytics account to execute job operations on.
/// </param>
/// <param name='parameters'>
/// The parameters to build a job.
/// </param>
public static JobInformation Build(this IJobOperations operations, string accountName, BuildJobParameters parameters)
{
return operations.BuildAsync(accountName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Builds (compiles) the specified job in the specified Data Lake Analytics
/// account for job correctness and validation.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='accountName'>
/// The Azure Data Lake Analytics account to execute job operations on.
/// </param>
/// <param name='parameters'>
/// The parameters to build a job.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<JobInformation> BuildAsync(this IJobOperations operations, string accountName, BuildJobParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BuildWithHttpMessagesAsync(accountName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Cancels the running job specified by the job ID.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='accountName'>
/// The Azure Data Lake Analytics account to execute job operations on.
/// </param>
/// <param name='jobIdentity'>
/// JobInfo ID to cancel.
/// </param>
public static void Cancel(this IJobOperations operations, string accountName, System.Guid jobIdentity)
{
operations.CancelAsync(accountName, jobIdentity).GetAwaiter().GetResult();
}
/// <summary>
/// Cancels the running job specified by the job ID.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='accountName'>
/// The Azure Data Lake Analytics account to execute job operations on.
/// </param>
/// <param name='jobIdentity'>
/// JobInfo ID to cancel.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task CancelAsync(this IJobOperations operations, string accountName, System.Guid jobIdentity, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.CancelWithHttpMessagesAsync(accountName, jobIdentity, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Submits a job to the specified Data Lake Analytics account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='accountName'>
/// The Azure Data Lake Analytics account to execute job operations on.
/// </param>
/// <param name='jobIdentity'>
/// The job ID (a GUID) for the job being submitted.
/// </param>
/// <param name='parameters'>
/// The parameters to submit a job.
/// </param>
public static JobInformation Create(this IJobOperations operations, string accountName, System.Guid jobIdentity, CreateJobParameters parameters)
{
return operations.CreateAsync(accountName, jobIdentity, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Submits a job to the specified Data Lake Analytics account.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='accountName'>
/// The Azure Data Lake Analytics account to execute job operations on.
/// </param>
/// <param name='jobIdentity'>
/// The job ID (a GUID) for the job being submitted.
/// </param>
/// <param name='parameters'>
/// The parameters to submit a job.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<JobInformation> CreateAsync(this IJobOperations operations, string accountName, System.Guid jobIdentity, CreateJobParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateWithHttpMessagesAsync(accountName, jobIdentity, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets the job information for the specified job ID.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='accountName'>
/// The Azure Data Lake Analytics account to execute job operations on.
/// </param>
/// <param name='jobIdentity'>
/// JobInfo ID.
/// </param>
public static JobInformation Get(this IJobOperations operations, string accountName, System.Guid jobIdentity)
{
return operations.GetAsync(accountName, jobIdentity).GetAwaiter().GetResult();
}
/// <summary>
/// Gets the job information for the specified job ID.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='accountName'>
/// The Azure Data Lake Analytics account to execute job operations on.
/// </param>
/// <param name='jobIdentity'>
/// JobInfo ID.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<JobInformation> GetAsync(this IJobOperations operations, string accountName, System.Guid jobIdentity, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(accountName, jobIdentity, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists the jobs, if any, associated with the specified Data Lake Analytics
/// account. The response includes a link to the next page of results, if any.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='accountName'>
/// The Azure Data Lake Analytics account to execute job operations on.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='select'>
/// OData Select statement. Limits the properties on each entry to just those
/// requested, e.g. Categories?$select=CategoryName,Description. Optional.
/// </param>
/// <param name='count'>
/// The Boolean value of true or false to request a count of the matching
/// resources included with the resources in the response, e.g.
/// Categories?$count=true. Optional.
/// </param>
public static IPage<JobInformationBasic> List(this IJobOperations operations, string accountName, ODataQuery<JobInformation> odataQuery = default(ODataQuery<JobInformation>), string select = default(string), bool? count = default(bool?))
{
return ((IJobOperations)operations).ListAsync(accountName, odataQuery, select, count).GetAwaiter().GetResult();
}
/// <summary>
/// Lists the jobs, if any, associated with the specified Data Lake Analytics
/// account. The response includes a link to the next page of results, if any.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='accountName'>
/// The Azure Data Lake Analytics account to execute job operations on.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='select'>
/// OData Select statement. Limits the properties on each entry to just those
/// requested, e.g. Categories?$select=CategoryName,Description. Optional.
/// </param>
/// <param name='count'>
/// The Boolean value of true or false to request a count of the matching
/// resources included with the resources in the response, e.g.
/// Categories?$count=true. Optional.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<JobInformationBasic>> ListAsync(this IJobOperations operations, string accountName, ODataQuery<JobInformation> odataQuery = default(ODataQuery<JobInformation>), string select = default(string), bool? count = default(bool?), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(accountName, odataQuery, select, count, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists the jobs, if any, associated with the specified Data Lake Analytics
/// account. The response includes a link to the next page of results, if any.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<JobInformationBasic> ListNext(this IJobOperations operations, string nextPageLink)
{
return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Lists the jobs, if any, associated with the specified Data Lake Analytics
/// account. The response includes a link to the next page of results, if any.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<JobInformationBasic>> ListNextAsync(this IJobOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="QueueSinkSpec.cs" company="Akka.NET Project">
// Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Akka.Actor;
using Akka.Pattern;
using Akka.Streams.Dsl;
using Akka.Streams.TestKit;
using Akka.Streams.TestKit.Tests;
using Akka.Streams.Util;
using FluentAssertions;
using Xunit;
using Xunit.Abstractions;
namespace Akka.Streams.Tests.Dsl
{
public class QueueSinkSpec : AkkaSpec
{
private readonly ActorMaterializer _materializer;
private readonly TimeSpan _pause = TimeSpan.FromMilliseconds(300);
private static TestException TestException()
{
return new TestException("boom");
}
public QueueSinkSpec(ITestOutputHelper output) : base(output)
{
_materializer = Sys.Materializer();
}
[Fact]
public void QueueSink_should_send_the_elements_as_result_of_future()
{
this.AssertAllStagesStopped(() =>
{
var expected = new List<Option<int>>
{
new Option<int>(1),
new Option<int>(2),
new Option<int>(3),
new Option<int>()
};
var queue = Source.From(expected.Where(o => o.HasValue).Select(o => o.Value))
.RunWith(Sink.Queue<int>(), _materializer);
expected.ForEach(v =>
{
queue.PullAsync().PipeTo(TestActor);
ExpectMsg(v);
});
}, _materializer);
}
[Fact]
public void QueueSink_should_allow_to_have_only_one_future_waiting_for_result_in_each_point_in_time()
{
this.AssertAllStagesStopped(() =>
{
var probe = TestPublisher.CreateManualProbe<int>(this);
var queue = Source.FromPublisher(probe).RunWith(Sink.Queue<int>(), _materializer);
var sub = probe.ExpectSubscription();
var future = queue.PullAsync();
var future2 = queue.PullAsync();
future2.Invoking(t => t.Wait(TimeSpan.FromMilliseconds(300))).ShouldThrow<IllegalStateException>();
sub.SendNext(1);
future.PipeTo(TestActor);
ExpectMsg(new Option<int>(1));
sub.SendComplete();
queue.PullAsync();
}, _materializer);
}
[Fact]
public void QueueSink_should_wait_for_next_element_from_upstream()
{
this.AssertAllStagesStopped(() =>
{
var probe = TestPublisher.CreateManualProbe<int>(this);
var queue = Source.FromPublisher(probe).RunWith(Sink.Queue<int>(), _materializer);
var sub = probe.ExpectSubscription();
queue.PullAsync().PipeTo(TestActor);
ExpectNoMsg(_pause);
sub.SendNext(1);
ExpectMsg(new Option<int>(1));
sub.SendComplete();
queue.PullAsync();
}, _materializer);
}
[Fact]
public void QueueSink_should_fail_future_on_stream_failure()
{
this.AssertAllStagesStopped(() =>
{
var probe = TestPublisher.CreateManualProbe<int>(this);
var queue = Source.FromPublisher(probe).RunWith(Sink.Queue<int>(), _materializer);
var sub = probe.ExpectSubscription();
queue.PullAsync().PipeTo(TestActor);
ExpectNoMsg(_pause);
sub.SendError(TestException());
ExpectMsg<Status.Failure>(
f => f.Cause is AggregateException && f.Cause.InnerException.Equals(TestException()));
}, _materializer);
}
[Fact]
public void QueueSink_should_fail_future_when_stream_failed()
{
this.AssertAllStagesStopped(() =>
{
var probe = TestPublisher.CreateManualProbe<int>(this);
var queue = Source.FromPublisher(probe).RunWith(Sink.Queue<int>(), _materializer);
var sub = probe.ExpectSubscription();
sub.SendError(TestException());
queue.Invoking(q => q.PullAsync().Wait(TimeSpan.FromMilliseconds(300)))
.ShouldThrow<TestException>();
}, _materializer);
}
[Fact]
public void QueueSink_should_timeout_future_when_stream_cannot_provide_data()
{
this.AssertAllStagesStopped(() =>
{
var probe = TestPublisher.CreateManualProbe<int>(this);
var queue = Source.FromPublisher(probe).RunWith(Sink.Queue<int>(), _materializer);
var sub = probe.ExpectSubscription();
queue.PullAsync().PipeTo(TestActor);
ExpectNoMsg(_pause);
sub.SendNext(1);
ExpectMsg(new Option<int>(1));
sub.SendComplete();
queue.PullAsync();
}, _materializer);
}
[Fact]
public void QueueSink_should_fail_pull_future_when_stream_is_completed()
{
this.AssertAllStagesStopped(() =>
{
var probe = TestPublisher.CreateManualProbe<int>(this);
var queue = Source.FromPublisher(probe).RunWith(Sink.Queue<int>(), _materializer);
var sub = probe.ExpectSubscription();
queue.PullAsync().PipeTo(TestActor);
sub.SendNext(1);
ExpectMsg(new Option<int>(1));
sub.SendComplete();
var future = queue.PullAsync();
future.Wait(_pause).Should().BeTrue();
future.Result.Should().Be(Option<int>.None);
((Task)queue.PullAsync()).ContinueWith(t =>
{
t.Exception.InnerException.Should().BeOfType<IllegalStateException>();
}, TaskContinuationOptions.OnlyOnFaulted).Wait(TimeSpan.FromMilliseconds(300));
}, _materializer);
}
[Fact]
public void QueueSink_should_keep_on_sending_even_after_the_buffer_has_been_full()
{
this.AssertAllStagesStopped(() =>
{
const int bufferSize = 16;
const int streamElementCount = bufferSize + 4;
var sink = Sink.Queue<int>().WithAttributes(Attributes.CreateInputBuffer(bufferSize, bufferSize));
var tuple = Source.From(Enumerable.Range(1, streamElementCount))
.AlsoToMaterialized(
Flow.Create<int>().Take(bufferSize).WatchTermination(Keep.Right).To(Sink.Ignore<int>()),
Keep.Right)
.ToMaterialized(sink, Keep.Both)
.Run(_materializer);
var probe = tuple.Item1;
var queue = tuple.Item2;
probe.Wait(TimeSpan.FromMilliseconds(300)).Should().BeTrue();
for (var i = 1; i <= streamElementCount; i++)
{
queue.PullAsync().PipeTo(TestActor);
ExpectMsg(new Option<int>(i));
}
queue.PullAsync().PipeTo(TestActor);
ExpectMsg(Option<int>.None);
}, _materializer);
}
[Fact]
public void QueueSink_should_work_with_one_element_buffer()
{
this.AssertAllStagesStopped(() =>
{
var sink = Sink.Queue<int>().WithAttributes(Attributes.CreateInputBuffer(1, 1));
var probe = TestPublisher.CreateManualProbe<int>(this);
var queue = Source.FromPublisher(probe).RunWith(sink, _materializer);
var sub = probe.ExpectSubscription();
queue.PullAsync().PipeTo(TestActor);
sub.SendNext(1); // should pull next element
ExpectMsg(new Option<int>(1));
queue.PullAsync().PipeTo(TestActor);
ExpectNoMsg(); // element requested but buffer empty
sub.SendNext(2);
ExpectMsg(new Option<int>(2));
sub.SendComplete();
var future = queue.PullAsync();
future.Wait(_pause).Should().BeTrue();
future.Result.Should().Be(Option<int>.None);
}, _materializer);
}
[Fact]
public void QueueSink_should_fail_to_materialize_with_zero_sized_input_buffer()
{
Source.Single(1)
.Invoking(
s => s.RunWith(Sink.Queue<int>().WithAttributes(Attributes.CreateInputBuffer(0, 0)), _materializer))
.ShouldThrow<ArgumentException>();
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Net;
using System.Net.Security;
using System.Reflection;
using System.Text;
using System.Web;
using System.Xml;
using System.Xml.Serialization;
using log4net;
using OpenMetaverse.StructuredData;
namespace OpenSim.Framework
{
/// <summary>
/// Miscellaneous static methods and extension methods related to the web
/// </summary>
public static class WebUtil
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// Control the printing of certain debug messages.
/// </summary>
/// <remarks>
/// If DebugLevel >= 3 then short notices about outgoing HTTP requests are logged.
/// </remarks>
public static int DebugLevel { get; set; }
/// <summary>
/// Request number for diagnostic purposes.
/// </summary>
public static int RequestNumber { get; internal set; }
/// <summary>
/// Control where OSD requests should be serialized per endpoint.
/// </summary>
public static bool SerializeOSDRequestsPerEndpoint { get; set; }
/// <summary>
/// this is the header field used to communicate the local request id
/// used for performance and debugging
/// </summary>
public const string OSHeaderRequestID = "opensim-request-id";
/// <summary>
/// Number of milliseconds a call can take before it is considered
/// a "long" call for warning & debugging purposes
/// </summary>
public const int LongCallTime = 3000;
/// <summary>
/// The maximum length of any data logged because of a long request time.
/// </summary>
/// <remarks>
/// This is to truncate any really large post data, such as an asset. In theory, the first section should
/// give us useful information about the call (which agent it relates to if applicable, etc.).
/// </remarks>
public const int MaxRequestDiagLength = 100;
/// <summary>
/// Dictionary of end points
/// </summary>
private static Dictionary<string,object> m_endpointSerializer = new Dictionary<string,object>();
private static object EndPointLock(string url)
{
System.Uri uri = new System.Uri(url);
string endpoint = string.Format("{0}:{1}",uri.Host,uri.Port);
lock (m_endpointSerializer)
{
object eplock = null;
if (! m_endpointSerializer.TryGetValue(endpoint,out eplock))
{
eplock = new object();
m_endpointSerializer.Add(endpoint,eplock);
// m_log.WarnFormat("[WEB UTIL] add a new host to end point serializer {0}",endpoint);
}
return eplock;
}
}
#region JSONRequest
/// <summary>
/// PUT JSON-encoded data to a web service that returns LLSD or
/// JSON data
/// </summary>
public static OSDMap PutToServiceCompressed(string url, OSDMap data, int timeout)
{
return ServiceOSDRequest(url,data, "PUT", timeout, true);
}
public static OSDMap PutToService(string url, OSDMap data, int timeout)
{
return ServiceOSDRequest(url,data, "PUT", timeout, false);
}
public static OSDMap PostToService(string url, OSDMap data, int timeout)
{
return ServiceOSDRequest(url, data, "POST", timeout, false);
}
public static OSDMap PostToServiceCompressed(string url, OSDMap data, int timeout)
{
return ServiceOSDRequest(url, data, "POST", timeout, true);
}
public static OSDMap GetFromService(string url, int timeout)
{
return ServiceOSDRequest(url, null, "GET", timeout, false);
}
public static OSDMap ServiceOSDRequest(string url, OSDMap data, string method, int timeout, bool compressed)
{
if (SerializeOSDRequestsPerEndpoint)
{
lock (EndPointLock(url))
{
return ServiceOSDRequestWorker(url, data, method, timeout, compressed);
}
}
else
{
return ServiceOSDRequestWorker(url, data, method, timeout, compressed);
}
}
public static void LogOutgoingDetail(Stream outputStream)
{
using (StreamReader reader = new StreamReader(Util.Copy(outputStream), Encoding.UTF8))
{
string output;
if (DebugLevel == 5)
{
const int sampleLength = 80;
char[] sampleChars = new char[sampleLength];
reader.Read(sampleChars, 0, sampleLength);
output = new string(sampleChars);
}
else
{
output = reader.ReadToEnd();
}
LogOutgoingDetail(output);
}
}
public static void LogOutgoingDetail(string output)
{
if (DebugLevel == 5)
{
output = output.Substring(0, 80);
output = output + "...";
}
m_log.DebugFormat("[WEB UTIL]: {0}", output.Replace("\n", @"\n"));
}
private static OSDMap ServiceOSDRequestWorker(string url, OSDMap data, string method, int timeout, bool compressed)
{
int reqnum = RequestNumber++;
if (DebugLevel >= 3)
m_log.DebugFormat(
"[WEB UTIL]: HTTP OUT {0} ServiceOSD {1} {2} (timeout {3}, compressed {4})",
reqnum, method, url, timeout, compressed);
string errorMessage = "unknown error";
int tickstart = Util.EnvironmentTickCount();
int tickdata = 0;
string strBuffer = null;
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = method;
request.Timeout = timeout;
request.KeepAlive = false;
request.MaximumAutomaticRedirections = 10;
request.ReadWriteTimeout = timeout / 4;
request.Headers[OSHeaderRequestID] = reqnum.ToString();
// If there is some input, write it into the request
if (data != null)
{
strBuffer = OSDParser.SerializeJsonString(data);
if (DebugLevel >= 5)
LogOutgoingDetail(strBuffer);
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(strBuffer);
if (compressed)
{
request.ContentType = "application/x-gzip";
using (MemoryStream ms = new MemoryStream())
{
using (GZipStream comp = new GZipStream(ms, CompressionMode.Compress))
{
comp.Write(buffer, 0, buffer.Length);
// We need to close the gzip stream before we write it anywhere
// because apparently something important related to gzip compression
// gets written on the strteam upon Dispose()
}
byte[] buf = ms.ToArray();
request.ContentLength = buf.Length; //Count bytes to send
using (Stream requestStream = request.GetRequestStream())
requestStream.Write(buf, 0, (int)buf.Length);
}
}
else
{
request.ContentType = "application/json";
request.ContentLength = buffer.Length; //Count bytes to send
using (Stream requestStream = request.GetRequestStream())
requestStream.Write(buffer, 0, buffer.Length); //Send it
}
}
// capture how much time was spent writing, this may seem silly
// but with the number concurrent requests, this often blocks
tickdata = Util.EnvironmentTickCountSubtract(tickstart);
using (WebResponse response = request.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
string responseStr = null;
responseStr = responseStream.GetStreamString();
// m_log.DebugFormat("[WEB UTIL]: <{0}> response is <{1}>",reqnum,responseStr);
return CanonicalizeResults(responseStr);
}
}
}
catch (WebException we)
{
errorMessage = we.Message;
if (we.Status == WebExceptionStatus.ProtocolError)
{
using (HttpWebResponse webResponse = (HttpWebResponse)we.Response)
errorMessage = String.Format("[{0}] {1}", webResponse.StatusCode, webResponse.StatusDescription);
}
}
catch (Exception ex)
{
errorMessage = ex.Message;
}
finally
{
int tickdiff = Util.EnvironmentTickCountSubtract(tickstart);
if (tickdiff > LongCallTime)
m_log.InfoFormat(
"[WEB UTIL]: Slow ServiceOSD request {0} {1} {2} took {3}ms, {4}ms writing, {5}",
reqnum,
method,
url,
tickdiff,
tickdata,
strBuffer != null
? (strBuffer.Length > MaxRequestDiagLength ? strBuffer.Remove(MaxRequestDiagLength) : strBuffer)
: "");
else if (DebugLevel >= 4)
m_log.DebugFormat(
"[WEB UTIL]: HTTP OUT {0} took {1}ms, {2}ms writing",
reqnum, tickdiff, tickdata);
}
m_log.DebugFormat(
"[WEB UTIL]: ServiceOSD request {0} {1} {2} FAILED: {3}", reqnum, url, method, errorMessage);
return ErrorResponseMap(errorMessage);
}
/// <summary>
/// Since there are no consistencies in the way web requests are
/// formed, we need to do a little guessing about the result format.
/// Keys:
/// Success|success == the success fail of the request
/// _RawResult == the raw string that came back
/// _Result == the OSD unpacked string
/// </summary>
private static OSDMap CanonicalizeResults(string response)
{
OSDMap result = new OSDMap();
// Default values
result["Success"] = OSD.FromBoolean(true);
result["success"] = OSD.FromBoolean(true);
result["_RawResult"] = OSD.FromString(response);
result["_Result"] = new OSDMap();
if (response.Equals("true",System.StringComparison.OrdinalIgnoreCase))
return result;
if (response.Equals("false",System.StringComparison.OrdinalIgnoreCase))
{
result["Success"] = OSD.FromBoolean(false);
result["success"] = OSD.FromBoolean(false);
return result;
}
try
{
OSD responseOSD = OSDParser.Deserialize(response);
if (responseOSD.Type == OSDType.Map)
{
result["_Result"] = (OSDMap)responseOSD;
return result;
}
}
catch
{
// don't need to treat this as an error... we're just guessing anyway
// m_log.DebugFormat("[WEB UTIL] couldn't decode <{0}>: {1}",response,e.Message);
}
return result;
}
#endregion JSONRequest
#region FormRequest
/// <summary>
/// POST URL-encoded form data to a web service that returns LLSD or
/// JSON data
/// </summary>
public static OSDMap PostToService(string url, NameValueCollection data)
{
return ServiceFormRequest(url,data,10000);
}
public static OSDMap ServiceFormRequest(string url, NameValueCollection data, int timeout)
{
lock (EndPointLock(url))
{
return ServiceFormRequestWorker(url,data,timeout);
}
}
private static OSDMap ServiceFormRequestWorker(string url, NameValueCollection data, int timeout)
{
int reqnum = RequestNumber++;
string method = (data != null && data["RequestMethod"] != null) ? data["RequestMethod"] : "unknown";
if (DebugLevel >= 3)
m_log.DebugFormat(
"[WEB UTIL]: HTTP OUT {0} ServiceForm {1} {2} (timeout {3})",
reqnum, method, url, timeout);
string errorMessage = "unknown error";
int tickstart = Util.EnvironmentTickCount();
int tickdata = 0;
string queryString = null;
try
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.Method = "POST";
request.Timeout = timeout;
request.KeepAlive = false;
request.MaximumAutomaticRedirections = 10;
request.ReadWriteTimeout = timeout / 4;
request.Headers[OSHeaderRequestID] = reqnum.ToString();
if (data != null)
{
queryString = BuildQueryString(data);
if (DebugLevel >= 5)
LogOutgoingDetail(queryString);
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(queryString);
request.ContentLength = buffer.Length;
request.ContentType = "application/x-www-form-urlencoded";
using (Stream requestStream = request.GetRequestStream())
requestStream.Write(buffer, 0, buffer.Length);
}
// capture how much time was spent writing, this may seem silly
// but with the number concurrent requests, this often blocks
tickdata = Util.EnvironmentTickCountSubtract(tickstart);
using (WebResponse response = request.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
string responseStr = null;
responseStr = responseStream.GetStreamString();
OSD responseOSD = OSDParser.Deserialize(responseStr);
if (responseOSD.Type == OSDType.Map)
return (OSDMap)responseOSD;
}
}
}
catch (WebException we)
{
errorMessage = we.Message;
if (we.Status == WebExceptionStatus.ProtocolError)
{
using (HttpWebResponse webResponse = (HttpWebResponse)we.Response)
errorMessage = String.Format("[{0}] {1}",webResponse.StatusCode,webResponse.StatusDescription);
}
}
catch (Exception ex)
{
errorMessage = ex.Message;
}
finally
{
int tickdiff = Util.EnvironmentTickCountSubtract(tickstart);
if (tickdiff > LongCallTime)
m_log.InfoFormat(
"[WEB UTIL]: Slow ServiceForm request {0} {1} {2} took {3}ms, {4}ms writing, {5}",
reqnum,
method,
url,
tickdiff,
tickdata,
queryString != null
? (queryString.Length > MaxRequestDiagLength) ? queryString.Remove(MaxRequestDiagLength) : queryString
: "");
else if (DebugLevel >= 4)
m_log.DebugFormat(
"[WEB UTIL]: HTTP OUT {0} took {1}ms, {2}ms writing",
reqnum, tickdiff, tickdata);
}
m_log.WarnFormat("[WEB UTIL]: ServiceForm request {0} {1} {2} failed: {2}", reqnum, method, url, errorMessage);
return ErrorResponseMap(errorMessage);
}
/// <summary>
/// Create a response map for an error, trying to keep
/// the result formats consistent
/// </summary>
private static OSDMap ErrorResponseMap(string msg)
{
OSDMap result = new OSDMap();
result["Success"] = "False";
result["Message"] = OSD.FromString("Service request failed: " + msg);
return result;
}
#endregion FormRequest
#region Uri
/// <summary>
/// Combines a Uri that can contain both a base Uri and relative path
/// with a second relative path fragment
/// </summary>
/// <param name="uri">Starting (base) Uri</param>
/// <param name="fragment">Relative path fragment to append to the end
/// of the Uri</param>
/// <returns>The combined Uri</returns>
/// <remarks>This is similar to the Uri constructor that takes a base
/// Uri and the relative path, except this method can append a relative
/// path fragment on to an existing relative path</remarks>
public static Uri Combine(this Uri uri, string fragment)
{
string fragment1 = uri.Fragment;
string fragment2 = fragment;
if (!fragment1.EndsWith("/"))
fragment1 = fragment1 + '/';
if (fragment2.StartsWith("/"))
fragment2 = fragment2.Substring(1);
return new Uri(uri, fragment1 + fragment2);
}
/// <summary>
/// Combines a Uri that can contain both a base Uri and relative path
/// with a second relative path fragment. If the fragment is absolute,
/// it will be returned without modification
/// </summary>
/// <param name="uri">Starting (base) Uri</param>
/// <param name="fragment">Relative path fragment to append to the end
/// of the Uri, or an absolute Uri to return unmodified</param>
/// <returns>The combined Uri</returns>
public static Uri Combine(this Uri uri, Uri fragment)
{
if (fragment.IsAbsoluteUri)
return fragment;
string fragment1 = uri.Fragment;
string fragment2 = fragment.ToString();
if (!fragment1.EndsWith("/"))
fragment1 = fragment1 + '/';
if (fragment2.StartsWith("/"))
fragment2 = fragment2.Substring(1);
return new Uri(uri, fragment1 + fragment2);
}
/// <summary>
/// Appends a query string to a Uri that may or may not have existing
/// query parameters
/// </summary>
/// <param name="uri">Uri to append the query to</param>
/// <param name="query">Query string to append. Can either start with ?
/// or just containg key/value pairs</param>
/// <returns>String representation of the Uri with the query string
/// appended</returns>
public static string AppendQuery(this Uri uri, string query)
{
if (String.IsNullOrEmpty(query))
return uri.ToString();
if (query[0] == '?' || query[0] == '&')
query = query.Substring(1);
string uriStr = uri.ToString();
if (uriStr.Contains("?"))
return uriStr + '&' + query;
else
return uriStr + '?' + query;
}
#endregion Uri
#region NameValueCollection
/// <summary>
/// Convert a NameValueCollection into a query string. This is the
/// inverse of HttpUtility.ParseQueryString()
/// </summary>
/// <param name="parameters">Collection of key/value pairs to convert</param>
/// <returns>A query string with URL-escaped values</returns>
public static string BuildQueryString(NameValueCollection parameters)
{
List<string> items = new List<string>(parameters.Count);
foreach (string key in parameters.Keys)
{
string[] values = parameters.GetValues(key);
if (values != null)
{
foreach (string value in values)
items.Add(String.Concat(key, "=", HttpUtility.UrlEncode(value ?? String.Empty)));
}
}
return String.Join("&", items.ToArray());
}
/// <summary>
///
/// </summary>
/// <param name="collection"></param>
/// <param name="key"></param>
/// <returns></returns>
public static string GetOne(this NameValueCollection collection, string key)
{
string[] values = collection.GetValues(key);
if (values != null && values.Length > 0)
return values[0];
return null;
}
#endregion NameValueCollection
#region Stream
/// <summary>
/// Copies the contents of one stream to another, starting at the
/// current position of each stream
/// </summary>
/// <param name="copyFrom">The stream to copy from, at the position
/// where copying should begin</param>
/// <param name="copyTo">The stream to copy to, at the position where
/// bytes should be written</param>
/// <param name="maximumBytesToCopy">The maximum bytes to copy</param>
/// <returns>The total number of bytes copied</returns>
/// <remarks>
/// Copying begins at the streams' current positions. The positions are
/// NOT reset after copying is complete.
/// NOTE!! .NET 4.0 adds the method 'Stream.CopyTo(stream, bufferSize)'.
/// This function could be replaced with that method once we move
/// totally to .NET 4.0. For versions before, this routine exists.
/// This routine used to be named 'CopyTo' but the int parameter has
/// a different meaning so this method was renamed to avoid any confusion.
/// </remarks>
public static int CopyStream(this Stream copyFrom, Stream copyTo, int maximumBytesToCopy)
{
byte[] buffer = new byte[4096];
int readBytes;
int totalCopiedBytes = 0;
while ((readBytes = copyFrom.Read(buffer, 0, Math.Min(4096, maximumBytesToCopy))) > 0)
{
int writeBytes = Math.Min(maximumBytesToCopy, readBytes);
copyTo.Write(buffer, 0, writeBytes);
totalCopiedBytes += writeBytes;
maximumBytesToCopy -= writeBytes;
}
return totalCopiedBytes;
}
/// <summary>
/// Converts an entire stream to a string, regardless of current stream
/// position
/// </summary>
/// <param name="stream">The stream to convert to a string</param>
/// <returns></returns>
/// <remarks>When this method is done, the stream position will be
/// reset to its previous position before this method was called</remarks>
public static string GetStreamString(this Stream stream)
{
string value = null;
if (stream != null && stream.CanRead)
{
long rewindPos = -1;
if (stream.CanSeek)
{
rewindPos = stream.Position;
stream.Seek(0, SeekOrigin.Begin);
}
StreamReader reader = new StreamReader(stream);
value = reader.ReadToEnd();
if (rewindPos >= 0)
stream.Seek(rewindPos, SeekOrigin.Begin);
}
return value;
}
#endregion Stream
public class QBasedComparer : IComparer
{
public int Compare(Object x, Object y)
{
float qx = GetQ(x);
float qy = GetQ(y);
return qy.CompareTo(qx); // descending order
}
private float GetQ(Object o)
{
// Example: image/png;q=0.9
float qvalue = 1F;
if (o is String)
{
string mime = (string)o;
string[] parts = mime.Split(';');
if (parts.Length > 1)
{
string[] kvp = parts[1].Split('=');
if (kvp.Length == 2 && kvp[0] == "q")
float.TryParse(kvp[1], NumberStyles.Number, CultureInfo.InvariantCulture, out qvalue);
}
}
return qvalue;
}
}
/// <summary>
/// Takes the value of an Accept header and returns the preferred types
/// ordered by q value (if it exists).
/// Example input: image/jpg;q=0.7, image/png;q=0.8, image/jp2
/// Exmaple output: ["jp2", "png", "jpg"]
/// NOTE: This doesn't handle the semantics of *'s...
/// </summary>
/// <param name="accept"></param>
/// <returns></returns>
public static string[] GetPreferredImageTypes(string accept)
{
if (string.IsNullOrEmpty(accept))
return new string[0];
string[] types = accept.Split(new char[] { ',' });
if (types.Length > 0)
{
List<string> list = new List<string>(types);
list.RemoveAll(delegate(string s) { return !s.ToLower().StartsWith("image"); });
ArrayList tlist = new ArrayList(list);
tlist.Sort(new QBasedComparer());
string[] result = new string[tlist.Count];
for (int i = 0; i < tlist.Count; i++)
{
string mime = (string)tlist[i];
string[] parts = mime.Split(new char[] { ';' });
string[] pair = parts[0].Split(new char[] { '/' });
if (pair.Length == 2)
result[i] = pair[1].ToLower();
else // oops, we don't know what this is...
result[i] = pair[0];
}
return result;
}
return new string[0];
}
}
public static class AsynchronousRestObjectRequester
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// Perform an asynchronous REST request.
/// </summary>
/// <param name="verb">GET or POST</param>
/// <param name="requestUrl"></param>
/// <param name="obj"></param>
/// <param name="action"></param>
/// <returns></returns>
///
/// <exception cref="System.Net.WebException">Thrown if we encounter a
/// network issue while posting the request. You'll want to make
/// sure you deal with this as they're not uncommon</exception>
//
public static void MakeRequest<TRequest, TResponse>(string verb,
string requestUrl, TRequest obj, Action<TResponse> action)
{
MakeRequest<TRequest, TResponse>(verb, requestUrl, obj, action, 0);
}
public static void MakeRequest<TRequest, TResponse>(string verb,
string requestUrl, TRequest obj, Action<TResponse> action,
int maxConnections)
{
int reqnum = WebUtil.RequestNumber++;
if (WebUtil.DebugLevel >= 3)
m_log.DebugFormat(
"[WEB UTIL]: HTTP OUT {0} AsynchronousRequestObject {1} {2}",
reqnum, verb, requestUrl);
int tickstart = Util.EnvironmentTickCount();
int tickdata = 0;
Type type = typeof(TRequest);
WebRequest request = WebRequest.Create(requestUrl);
HttpWebRequest ht = (HttpWebRequest)request;
if (maxConnections > 0 && ht.ServicePoint.ConnectionLimit < maxConnections)
ht.ServicePoint.ConnectionLimit = maxConnections;
WebResponse response = null;
TResponse deserial = default(TResponse);
XmlSerializer deserializer = new XmlSerializer(typeof(TResponse));
request.Method = verb;
MemoryStream buffer = null;
if (verb == "POST")
{
request.ContentType = "text/xml";
buffer = new MemoryStream();
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = Encoding.UTF8;
using (XmlWriter writer = XmlWriter.Create(buffer, settings))
{
XmlSerializer serializer = new XmlSerializer(type);
serializer.Serialize(writer, obj);
writer.Flush();
}
int length = (int)buffer.Length;
request.ContentLength = length;
if (WebUtil.DebugLevel >= 5)
WebUtil.LogOutgoingDetail(buffer);
request.BeginGetRequestStream(delegate(IAsyncResult res)
{
Stream requestStream = request.EndGetRequestStream(res);
requestStream.Write(buffer.ToArray(), 0, length);
requestStream.Close();
// capture how much time was spent writing
tickdata = Util.EnvironmentTickCountSubtract(tickstart);
request.BeginGetResponse(delegate(IAsyncResult ar)
{
response = request.EndGetResponse(ar);
Stream respStream = null;
try
{
respStream = response.GetResponseStream();
deserial = (TResponse)deserializer.Deserialize(
respStream);
}
catch (System.InvalidOperationException)
{
}
finally
{
// Let's not close this
//buffer.Close();
respStream.Close();
response.Close();
}
action(deserial);
}, null);
}, null);
}
else
{
request.BeginGetResponse(delegate(IAsyncResult res2)
{
try
{
// If the server returns a 404, this appears to trigger a System.Net.WebException even though that isn't
// documented in MSDN
response = request.EndGetResponse(res2);
Stream respStream = null;
try
{
respStream = response.GetResponseStream();
deserial = (TResponse)deserializer.Deserialize(respStream);
}
catch (System.InvalidOperationException)
{
}
finally
{
respStream.Close();
response.Close();
}
}
catch (WebException e)
{
if (e.Status == WebExceptionStatus.ProtocolError)
{
if (e.Response is HttpWebResponse)
{
using (HttpWebResponse httpResponse = (HttpWebResponse)e.Response)
{
if (httpResponse.StatusCode != HttpStatusCode.NotFound)
{
// We don't appear to be handling any other status codes, so log these feailures to that
// people don't spend unnecessary hours hunting phantom bugs.
m_log.DebugFormat(
"[ASYNC REQUEST]: Request {0} {1} failed with unexpected status code {2}",
verb, requestUrl, httpResponse.StatusCode);
}
}
}
}
else
{
m_log.ErrorFormat(
"[ASYNC REQUEST]: Request {0} {1} failed with status {2} and message {3}",
verb, requestUrl, e.Status, e.Message);
}
}
catch (Exception e)
{
m_log.ErrorFormat(
"[ASYNC REQUEST]: Request {0} {1} failed with exception {2}{3}",
verb, requestUrl, e.Message, e.StackTrace);
}
// m_log.DebugFormat("[ASYNC REQUEST]: Received {0}", deserial.ToString());
try
{
action(deserial);
}
catch (Exception e)
{
m_log.ErrorFormat(
"[ASYNC REQUEST]: Request {0} {1} callback failed with exception {2}{3}",
verb, requestUrl, e.Message, e.StackTrace);
}
}, null);
}
int tickdiff = Util.EnvironmentTickCountSubtract(tickstart);
if (tickdiff > WebUtil.LongCallTime)
{
string originalRequest = null;
if (buffer != null)
{
originalRequest = Encoding.UTF8.GetString(buffer.ToArray());
if (originalRequest.Length > WebUtil.MaxRequestDiagLength)
originalRequest = originalRequest.Remove(WebUtil.MaxRequestDiagLength);
}
m_log.InfoFormat(
"[ASYNC REQUEST]: Slow request {0} {1} {2} took {3}ms, {4}ms writing, {5}",
reqnum,
verb,
requestUrl,
tickdiff,
tickdata,
originalRequest);
}
else if (WebUtil.DebugLevel >= 4)
{
m_log.DebugFormat(
"[WEB UTIL]: HTTP OUT {0} took {1}ms, {2}ms writing",
reqnum, tickdiff, tickdata);
}
}
}
public static class SynchronousRestFormsRequester
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// Perform a synchronous REST request.
/// </summary>
/// <param name="verb"></param>
/// <param name="requestUrl"></param>
/// <param name="obj"> </param>
/// <param name="timeoutsecs"> </param>
/// <returns></returns>
///
/// <exception cref="System.Net.WebException">Thrown if we encounter a network issue while posting
/// the request. You'll want to make sure you deal with this as they're not uncommon</exception>
public static string MakeRequest(string verb, string requestUrl, string obj, int timeoutsecs)
{
int reqnum = WebUtil.RequestNumber++;
if (WebUtil.DebugLevel >= 3)
m_log.DebugFormat(
"[WEB UTIL]: HTTP OUT {0} SynchronousRestForms {1} {2}",
reqnum, verb, requestUrl);
int tickstart = Util.EnvironmentTickCount();
int tickdata = 0;
WebRequest request = WebRequest.Create(requestUrl);
request.Method = verb;
if (timeoutsecs > 0)
request.Timeout = timeoutsecs * 1000;
string respstring = String.Empty;
using (MemoryStream buffer = new MemoryStream())
{
if ((verb == "POST") || (verb == "PUT"))
{
request.ContentType = "application/x-www-form-urlencoded";
int length = 0;
using (StreamWriter writer = new StreamWriter(buffer))
{
writer.Write(obj);
writer.Flush();
}
length = (int)obj.Length;
request.ContentLength = length;
if (WebUtil.DebugLevel >= 5)
WebUtil.LogOutgoingDetail(buffer);
Stream requestStream = null;
try
{
requestStream = request.GetRequestStream();
requestStream.Write(buffer.ToArray(), 0, length);
}
catch (Exception e)
{
m_log.DebugFormat(
"[FORMS]: exception occured {0} {1}: {2}{3}", verb, requestUrl, e.Message, e.StackTrace);
}
finally
{
if (requestStream != null)
requestStream.Close();
// capture how much time was spent writing
tickdata = Util.EnvironmentTickCountSubtract(tickstart);
}
}
try
{
using (WebResponse resp = request.GetResponse())
{
if (resp.ContentLength != 0)
{
Stream respStream = null;
try
{
using (respStream = resp.GetResponseStream())
using (StreamReader reader = new StreamReader(respStream))
respstring = reader.ReadToEnd();
}
catch (Exception e)
{
m_log.DebugFormat(
"[FORMS]: Exception occured on receiving {0} {1}: {2}{3}",
verb, requestUrl, e.Message, e.StackTrace);
}
finally
{
if (respStream != null)
respStream.Close();
}
}
}
}
catch (System.InvalidOperationException)
{
// This is what happens when there is invalid XML
m_log.DebugFormat("[FORMS]: InvalidOperationException on receiving {0} {1}", verb, requestUrl);
}
}
int tickdiff = Util.EnvironmentTickCountSubtract(tickstart);
if (tickdiff > WebUtil.LongCallTime)
m_log.InfoFormat(
"[FORMS]: Slow request {0} {1} {2} took {3}ms, {4}ms writing, {5}",
reqnum,
verb,
requestUrl,
tickdiff,
tickdata,
obj.Length > WebUtil.MaxRequestDiagLength ? obj.Remove(WebUtil.MaxRequestDiagLength) : obj);
else if (WebUtil.DebugLevel >= 4)
m_log.DebugFormat(
"[WEB UTIL]: HTTP OUT {0} took {1}ms, {2}ms writing",
reqnum, tickdiff, tickdata);
return respstring;
}
public static string MakeRequest(string verb, string requestUrl, string obj)
{
return MakeRequest(verb, requestUrl, obj, -1);
}
}
public class SynchronousRestObjectRequester
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// Perform a synchronous REST request.
/// </summary>
/// <param name="verb"></param>
/// <param name="requestUrl"></param>
/// <param name="obj"> </param>
/// <returns></returns>
///
/// <exception cref="System.Net.WebException">Thrown if we encounter a network issue while posting
/// the request. You'll want to make sure you deal with this as they're not uncommon</exception>
public static TResponse MakeRequest<TRequest, TResponse>(string verb, string requestUrl, TRequest obj)
{
return MakeRequest<TRequest, TResponse>(verb, requestUrl, obj, 0);
}
public static TResponse MakeRequest<TRequest, TResponse>(string verb, string requestUrl, TRequest obj, int pTimeout)
{
return MakeRequest<TRequest, TResponse>(verb, requestUrl, obj, pTimeout, 0);
}
public static TResponse MakeRequest<TRequest, TResponse>(string verb, string requestUrl, TRequest obj, int pTimeout, int maxConnections)
{
int reqnum = WebUtil.RequestNumber++;
if (WebUtil.DebugLevel >= 3)
m_log.DebugFormat(
"[WEB UTIL]: HTTP OUT {0} SynchronousRestObject {1} {2}",
reqnum, verb, requestUrl);
int tickstart = Util.EnvironmentTickCount();
int tickdata = 0;
Type type = typeof(TRequest);
TResponse deserial = default(TResponse);
WebRequest request = WebRequest.Create(requestUrl);
HttpWebRequest ht = (HttpWebRequest)request;
if (maxConnections > 0 && ht.ServicePoint.ConnectionLimit < maxConnections)
ht.ServicePoint.ConnectionLimit = maxConnections;
request.Method = verb;
MemoryStream buffer = null;
if ((verb == "POST") || (verb == "PUT"))
{
request.ContentType = "text/xml";
buffer = new MemoryStream();
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = Encoding.UTF8;
using (XmlWriter writer = XmlWriter.Create(buffer, settings))
{
XmlSerializer serializer = new XmlSerializer(type);
serializer.Serialize(writer, obj);
writer.Flush();
}
int length = (int)buffer.Length;
request.ContentLength = length;
if (WebUtil.DebugLevel >= 5)
WebUtil.LogOutgoingDetail(buffer);
Stream requestStream = null;
try
{
requestStream = request.GetRequestStream();
requestStream.Write(buffer.ToArray(), 0, length);
}
catch (Exception e)
{
m_log.DebugFormat(
"[SynchronousRestObjectRequester]: Exception in making request {0} {1}: {2}{3}",
verb, requestUrl, e.Message, e.StackTrace);
return deserial;
}
finally
{
if (requestStream != null)
requestStream.Close();
// capture how much time was spent writing
tickdata = Util.EnvironmentTickCountSubtract(tickstart);
}
}
try
{
using (HttpWebResponse resp = (HttpWebResponse)request.GetResponse())
{
if (resp.ContentLength != 0)
{
using (Stream respStream = resp.GetResponseStream())
{
XmlSerializer deserializer = new XmlSerializer(typeof(TResponse));
deserial = (TResponse)deserializer.Deserialize(respStream);
}
}
else
{
m_log.DebugFormat(
"[SynchronousRestObjectRequester]: Oops! no content found in response stream from {0} {1}",
verb, requestUrl);
}
}
}
catch (WebException e)
{
using (HttpWebResponse hwr = (HttpWebResponse)e.Response)
{
if (hwr != null && hwr.StatusCode == HttpStatusCode.NotFound)
return deserial;
else
m_log.ErrorFormat(
"[SynchronousRestObjectRequester]: WebException for {0} {1} {2}: {3} {4}",
verb, requestUrl, typeof(TResponse).ToString(), e.Message, e.StackTrace);
}
}
catch (System.InvalidOperationException)
{
// This is what happens when there is invalid XML
m_log.DebugFormat(
"[SynchronousRestObjectRequester]: Invalid XML from {0} {1} {2}",
verb, requestUrl, typeof(TResponse).ToString());
}
catch (Exception e)
{
m_log.DebugFormat(
"[SynchronousRestObjectRequester]: Exception on response from {0} {1}: {2}{3}",
verb, requestUrl, e.Message, e.StackTrace);
}
int tickdiff = Util.EnvironmentTickCountSubtract(tickstart);
if (tickdiff > WebUtil.LongCallTime)
{
string originalRequest = null;
if (buffer != null)
{
originalRequest = Encoding.UTF8.GetString(buffer.ToArray());
if (originalRequest.Length > WebUtil.MaxRequestDiagLength)
originalRequest = originalRequest.Remove(WebUtil.MaxRequestDiagLength);
}
m_log.InfoFormat(
"[SynchronousRestObjectRequester]: Slow request {0} {1} {2} took {3}ms, {4}ms writing, {5}",
reqnum,
verb,
requestUrl,
tickdiff,
tickdata,
originalRequest);
}
else if (WebUtil.DebugLevel >= 4)
{
m_log.DebugFormat(
"[WEB UTIL]: HTTP OUT {0} took {1}ms, {2}ms writing",
reqnum, tickdiff, tickdata);
}
return deserial;
}
}
}
| |
// Copyright (c) <2015> <Playdead>
// This file is subject to the MIT License as seen in the root of this folder structure (LICENSE.TXT)
// AUTHOR: Lasse Jon Fuglsang Pedersen <lasse@playdead.com>
#if UNITY_5_5_OR_NEWER
#define SUPPORT_STEREO
#endif
using UnityEngine;
[ExecuteInEditMode]
[RequireComponent(typeof(Camera))]
[AddComponentMenu("Playdead/FrustumJitter")]
public class FrustumJitter : MonoBehaviour
{
#region Static point data
private static float[] points_Still = new float[] {
0.5f, 0.5f,
};
private static float[] points_Uniform2 = new float[] {
-0.25f, -0.25f,//ll
0.25f, 0.25f,//ur
};
private static float[] points_Uniform4 = new float[] {
-0.25f, -0.25f,//ll
0.25f, -0.25f,//lr
0.25f, 0.25f,//ur
-0.25f, 0.25f,//ul
};
private static float[] points_Uniform4_Helix = new float[] {
-0.25f, -0.25f,//ll 3 1
0.25f, 0.25f,//ur \/|
0.25f, -0.25f,//lr /\|
-0.25f, 0.25f,//ul 0 2
};
private static float[] points_Uniform4_DoubleHelix = new float[] {
-0.25f, -0.25f,//ll 3 1
0.25f, 0.25f,//ur \/|
0.25f, -0.25f,//lr /\|
-0.25f, 0.25f,//ul 0 2
-0.25f, -0.25f,//ll 6--7
0.25f, -0.25f,//lr \
-0.25f, 0.25f,//ul \
0.25f, 0.25f,//ur 4--5
};
private static float[] points_SkewButterfly = new float[] {
-0.250f, -0.250f,
0.250f, 0.250f,
0.125f, -0.125f,
-0.125f, 0.125f,
};
private static float[] points_Rotated4 = new float[] {
-0.125f, -0.375f,//ll
0.375f, -0.125f,//lr
0.125f, 0.375f,//ur
-0.375f, 0.125f,//ul
};
private static float[] points_Rotated4_Helix = new float[] {
-0.125f, -0.375f,//ll 3 1
0.125f, 0.375f,//ur \/|
0.375f, -0.125f,//lr /\|
-0.375f, 0.125f,//ul 0 2
};
private static float[] points_Rotated4_Helix2 = new float[] {
-0.125f, -0.375f,//ll 2--1
0.125f, 0.375f,//ur \/
-0.375f, 0.125f,//ul /\
0.375f, -0.125f,//lr 0 3
};
private static float[] points_Poisson10 = new float[] {
-0.16795960f*0.25f, 0.65544910f*0.25f,
-0.69096030f*0.25f, 0.59015970f*0.25f,
0.49843820f*0.25f, 0.83099720f*0.25f,
0.17230150f*0.25f, -0.03882703f*0.25f,
-0.60772670f*0.25f, -0.06013587f*0.25f,
0.65606390f*0.25f, 0.24007600f*0.25f,
0.80348370f*0.25f, -0.48096900f*0.25f,
0.33436540f*0.25f, -0.73007030f*0.25f,
-0.47839520f*0.25f, -0.56005300f*0.25f,
-0.12388120f*0.25f, -0.96633990f*0.25f,
};
private static float[] points_Pentagram = new float[] {
0.000000f*0.5f, 0.525731f*0.5f,// head
-0.309017f*0.5f, -0.425325f*0.5f,// lleg
0.500000f*0.5f, 0.162460f*0.5f,// rarm
-0.500000f*0.5f, 0.162460f*0.5f,// larm
0.309017f*0.5f, -0.425325f*0.5f,// rleg
};
private static float[] points_Halton_2_3_x8 = new float[8 * 2];
private static float[] points_Halton_2_3_x16 = new float[16 * 2];
private static float[] points_Halton_2_3_x32 = new float[32 * 2];
private static float[] points_Halton_2_3_x256 = new float[256 * 2];
private static float[] points_MotionPerp2 = new float[] {
0.00f, -0.25f,
0.00f, 0.25f,
};
#endregion
#region Static point data, static initialization
private static void TransformPattern(float[] seq, float theta, float scale)
{
float cs = Mathf.Cos(theta);
float sn = Mathf.Sin(theta);
for (int i = 0, j = 1, n = seq.Length; i != n; i += 2, j += 2)
{
float x = scale * seq[i];
float y = scale * seq[j];
seq[i] = x * cs - y * sn;
seq[j] = x * sn + y * cs;
}
}
// http://en.wikipedia.org/wiki/Halton_sequence
private static float HaltonSeq(int prime, int index = 1/* NOT! zero-based */)
{
float r = 0.0f;
float f = 1.0f;
int i = index;
while (i > 0)
{
f /= prime;
r += f * (i % prime);
i = (int)Mathf.Floor(i / (float)prime);
}
return r;
}
private static void InitializeHalton_2_3(float[] seq)
{
for (int i = 0, n = seq.Length / 2; i != n; i++)
{
float u = HaltonSeq(2, i + 1) - 0.5f;
float v = HaltonSeq(3, i + 1) - 0.5f;
seq[2 * i + 0] = u;
seq[2 * i + 1] = v;
}
}
static FrustumJitter()
{
// points_Pentagram
Vector2 vh = new Vector2(points_Pentagram[0] - points_Pentagram[2], points_Pentagram[1] - points_Pentagram[3]);
Vector2 vu = new Vector2(0.0f, 1.0f);
TransformPattern(points_Pentagram, Mathf.Deg2Rad * (0.5f * Vector2.Angle(vu, vh)), 1.0f);
// points_Halton_2_3_xN
InitializeHalton_2_3(points_Halton_2_3_x8);
InitializeHalton_2_3(points_Halton_2_3_x16);
InitializeHalton_2_3(points_Halton_2_3_x32);
InitializeHalton_2_3(points_Halton_2_3_x256);
}
#endregion
#region Static point data accessors
public enum Pattern
{
Still,
Uniform2,
Uniform4,
Uniform4_Helix,
Uniform4_DoubleHelix,
SkewButterfly,
Rotated4,
Rotated4_Helix,
Rotated4_Helix2,
Poisson10,
Pentagram,
Halton_2_3_X8,
Halton_2_3_X16,
Halton_2_3_X32,
Halton_2_3_X256,
MotionPerp2,
};
private static float[] AccessPointData(Pattern pattern)
{
switch (pattern)
{
case Pattern.Still:
return points_Still;
case Pattern.Uniform2:
return points_Uniform2;
case Pattern.Uniform4:
return points_Uniform4;
case Pattern.Uniform4_Helix:
return points_Uniform4_Helix;
case Pattern.Uniform4_DoubleHelix:
return points_Uniform4_DoubleHelix;
case Pattern.SkewButterfly:
return points_SkewButterfly;
case Pattern.Rotated4:
return points_Rotated4;
case Pattern.Rotated4_Helix:
return points_Rotated4_Helix;
case Pattern.Rotated4_Helix2:
return points_Rotated4_Helix2;
case Pattern.Poisson10:
return points_Poisson10;
case Pattern.Pentagram:
return points_Pentagram;
case Pattern.Halton_2_3_X8:
return points_Halton_2_3_x8;
case Pattern.Halton_2_3_X16:
return points_Halton_2_3_x16;
case Pattern.Halton_2_3_X32:
return points_Halton_2_3_x32;
case Pattern.Halton_2_3_X256:
return points_Halton_2_3_x256;
case Pattern.MotionPerp2:
return points_MotionPerp2;
default:
Debug.LogError("missing point distribution");
return points_Halton_2_3_x16;
}
}
public static int AccessLength(Pattern pattern)
{
return AccessPointData(pattern).Length / 2;
}
public Vector2 Sample(Pattern pattern, int index)
{
float[] points = AccessPointData(pattern);
int n = points.Length / 2;
int i = index % n;
float x = patternScale * points[2 * i + 0];
float y = patternScale * points[2 * i + 1];
if (pattern != Pattern.MotionPerp2)
return new Vector2(x, y);
else
return new Vector2(x, y).Rotate(Vector2.right.SignedAngle(focalMotionDir));
}
#endregion
private Camera _camera;
private Vector3 focalMotionPos = Vector3.zero;
private Vector3 focalMotionDir = Vector3.right;
public Pattern pattern = Pattern.Halton_2_3_X16;
public float patternScale = 1.0f;
public Vector4 activeSample = Vector4.zero;// xy = current sample, zw = previous sample
public int activeIndex = -2;
void Reset()
{
_camera = GetComponent<Camera>();
}
void Clear()
{
_camera.ResetProjectionMatrix();
activeSample = Vector4.zero;
activeIndex = -2;
}
void Awake()
{
Reset();
Clear();
}
void OnPreCull()
{
// update motion dir
{
Vector3 oldWorld = focalMotionPos;
Vector3 newWorld = _camera.transform.TransformVector(_camera.nearClipPlane * Vector3.forward);
Vector3 oldPoint = (_camera.worldToCameraMatrix * oldWorld);
Vector3 newPoint = (_camera.worldToCameraMatrix * newWorld);
Vector3 newDelta = (newPoint - oldPoint).WithZ(0.0f);
var mag = newDelta.magnitude;
if (mag != 0.0f)
{
var dir = newDelta / mag;// yes, apparently this is necessary instead of newDelta.normalized... because facepalm
if (dir.sqrMagnitude != 0.0f)
{
focalMotionPos = newWorld;
focalMotionDir = Vector3.Slerp(focalMotionDir, dir, 0.2f);
//Debug.Log("CHANGE focalMotionDir " + focalMotionDir.ToString("G4") + " delta was " + newDelta.ToString("G4") + " delta.mag " + newDelta.magnitude);
}
}
}
// update jitter
#if SUPPORT_STEREO
if (_camera.stereoEnabled)
{
Clear();
}
else
#endif
{
if (activeIndex == -2)
{
activeSample = Vector4.zero;
activeIndex += 1;
_camera.projectionMatrix = _camera.GetProjectionMatrix();
}
else
{
activeIndex += 1;
activeIndex %= AccessLength(pattern);
Vector2 sample = Sample(pattern, activeIndex);
activeSample.z = activeSample.x;
activeSample.w = activeSample.y;
activeSample.x = sample.x;
activeSample.y = sample.y;
_camera.projectionMatrix = _camera.GetProjectionMatrix(sample.x, sample.y);
}
}
}
void OnDisable()
{
Clear();
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Azure.Cosmos.Table;
using Microsoft.Extensions.Logging;
using Orleans.Clustering.AzureStorage;
using Orleans.Clustering.AzureStorage.Utilities;
using Orleans.Internal;
using Orleans.Runtime;
namespace Orleans.AzureUtils
{
internal class OrleansSiloInstanceManager
{
public string TableName { get; }
private readonly string INSTANCE_STATUS_CREATED = SiloStatus.Created.ToString(); //"Created";
private readonly string INSTANCE_STATUS_ACTIVE = SiloStatus.Active.ToString(); //"Active";
private readonly string INSTANCE_STATUS_DEAD = SiloStatus.Dead.ToString(); //"Dead";
private readonly AzureTableDataManager<SiloInstanceTableEntry> storage;
private readonly ILogger logger;
internal static TimeSpan initTimeout = AzureTableDefaultPolicies.TableCreationTimeout;
public string DeploymentId { get; private set; }
private OrleansSiloInstanceManager(string clusterId, string storageConnectionString, string tableName, ILoggerFactory loggerFactory)
{
DeploymentId = clusterId;
TableName = tableName;
logger = loggerFactory.CreateLogger<OrleansSiloInstanceManager>();
storage = new AzureTableDataManager<SiloInstanceTableEntry>(
tableName, storageConnectionString, loggerFactory);
}
public static async Task<OrleansSiloInstanceManager> GetManager(string clusterId, string storageConnectionString, string tableName, ILoggerFactory loggerFactory)
{
var instance = new OrleansSiloInstanceManager(clusterId, storageConnectionString, tableName, loggerFactory);
try
{
await instance.storage.InitTableAsync()
.WithTimeout(initTimeout);
}
catch (TimeoutException te)
{
string errorMsg = String.Format("Unable to create or connect to the Azure table in {0}", initTimeout);
instance.logger.Error((int)TableStorageErrorCode.AzureTable_32, errorMsg, te);
throw new OrleansException(errorMsg, te);
}
catch (Exception ex)
{
string errorMsg = String.Format("Exception trying to create or connect to the Azure table: {0}", ex.Message);
instance.logger.Error((int)TableStorageErrorCode.AzureTable_33, errorMsg, ex);
throw new OrleansException(errorMsg, ex);
}
return instance;
}
public SiloInstanceTableEntry CreateTableVersionEntry(int tableVersion)
{
return new SiloInstanceTableEntry
{
DeploymentId = DeploymentId,
PartitionKey = DeploymentId,
RowKey = SiloInstanceTableEntry.TABLE_VERSION_ROW,
MembershipVersion = tableVersion.ToString(CultureInfo.InvariantCulture)
};
}
public void RegisterSiloInstance(SiloInstanceTableEntry entry)
{
entry.Status = INSTANCE_STATUS_CREATED;
logger.Info(ErrorCode.Runtime_Error_100270, "Registering silo instance: {0}", entry.ToString());
storage.UpsertTableEntryAsync(entry)
.WaitWithThrow(AzureTableDefaultPolicies.TableOperationTimeout);
}
public void UnregisterSiloInstance(SiloInstanceTableEntry entry)
{
entry.Status = INSTANCE_STATUS_DEAD;
logger.Info(ErrorCode.Runtime_Error_100271, "Unregistering silo instance: {0}", entry.ToString());
storage.UpsertTableEntryAsync(entry)
.WaitWithThrow(AzureTableDefaultPolicies.TableOperationTimeout);
}
public void ActivateSiloInstance(SiloInstanceTableEntry entry)
{
logger.Info(ErrorCode.Runtime_Error_100272, "Activating silo instance: {0}", entry.ToString());
entry.Status = INSTANCE_STATUS_ACTIVE;
storage.UpsertTableEntryAsync(entry)
.WaitWithThrow(AzureTableDefaultPolicies.TableOperationTimeout);
}
public async Task<IList<Uri>> FindAllGatewayProxyEndpoints()
{
IEnumerable<SiloInstanceTableEntry> gatewaySiloInstances = await FindAllGatewaySilos();
return gatewaySiloInstances.Select(ConvertToGatewayUri).ToList();
}
/// <summary>
/// Represent a silo instance entry in the gateway URI format.
/// </summary>
/// <param name="gateway">The input silo instance</param>
/// <returns></returns>
private static Uri ConvertToGatewayUri(SiloInstanceTableEntry gateway)
{
int proxyPort = 0;
if (!string.IsNullOrEmpty(gateway.ProxyPort))
int.TryParse(gateway.ProxyPort, out proxyPort);
int gen = 0;
if (!string.IsNullOrEmpty(gateway.Generation))
int.TryParse(gateway.Generation, out gen);
SiloAddress address = SiloAddress.New(new IPEndPoint(IPAddress.Parse(gateway.Address), proxyPort), gen);
return address.ToGatewayUri();
}
private async Task<IEnumerable<SiloInstanceTableEntry>> FindAllGatewaySilos()
{
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug(ErrorCode.Runtime_Error_100277, "Searching for active gateway silos for deployment {0}.", this.DeploymentId);
const string zeroPort = "0";
try
{
string filterOnPartitionKey = TableQuery.GenerateFilterCondition(nameof(SiloInstanceTableEntry.PartitionKey), QueryComparisons.Equal,
this.DeploymentId);
string filterOnStatus = TableQuery.GenerateFilterCondition(nameof(SiloInstanceTableEntry.Status), QueryComparisons.Equal,
INSTANCE_STATUS_ACTIVE);
string filterOnProxyPort = TableQuery.GenerateFilterCondition(nameof(SiloInstanceTableEntry.ProxyPort), QueryComparisons.NotEqual, zeroPort);
string query = TableQuery.CombineFilters(filterOnPartitionKey, TableOperators.And, TableQuery.CombineFilters(filterOnStatus, TableOperators.And, filterOnProxyPort));
var queryResults = await storage.ReadTableEntriesAndEtagsAsync(query)
.WithTimeout(AzureTableDefaultPolicies.TableOperationTimeout);
List<SiloInstanceTableEntry> gatewaySiloInstances = queryResults.Select(entity => entity.Item1).ToList();
logger.Info(ErrorCode.Runtime_Error_100278, "Found {0} active Gateway Silos for deployment {1}.", gatewaySiloInstances.Count, this.DeploymentId);
return gatewaySiloInstances;
}catch(Exception exc)
{
logger.Error(ErrorCode.Runtime_Error_100331, string.Format("Error searching for active gateway silos for deployment {0} ", this.DeploymentId), exc);
throw;
}
}
public async Task<string> DumpSiloInstanceTable()
{
var queryResults = await storage.ReadAllTableEntriesForPartitionAsync(this.DeploymentId);
SiloInstanceTableEntry[] entries = queryResults.Select(entry => entry.Item1).ToArray();
var sb = new StringBuilder();
sb.Append(String.Format("Deployment {0}. Silos: ", DeploymentId));
// Loop through the results, displaying information about the entity
Array.Sort(entries,
(e1, e2) =>
{
if (e1 == null) return (e2 == null) ? 0 : -1;
if (e2 == null) return (e1 == null) ? 0 : 1;
if (e1.SiloName == null) return (e2.SiloName == null) ? 0 : -1;
if (e2.SiloName == null) return (e1.SiloName == null) ? 0 : 1;
return String.CompareOrdinal(e1.SiloName, e2.SiloName);
});
foreach (SiloInstanceTableEntry entry in entries)
{
sb.AppendLine(String.Format("[IP {0}:{1}:{2}, {3}, Instance={4}, Status={5}]", entry.Address, entry.Port, entry.Generation,
entry.HostName, entry.SiloName, entry.Status));
}
return sb.ToString();
}
internal Task<string> MergeTableEntryAsync(SiloInstanceTableEntry data)
{
return storage.MergeTableEntryAsync(data, AzureTableUtils.ANY_ETAG); // we merge this without checking eTags.
}
internal Task<Tuple<SiloInstanceTableEntry, string>> ReadSingleTableEntryAsync(string partitionKey, string rowKey)
{
return storage.ReadSingleTableEntryAsync(partitionKey, rowKey);
}
internal async Task<int> DeleteTableEntries(string clusterId)
{
if (clusterId == null) throw new ArgumentNullException(nameof(clusterId));
var entries = await storage.ReadAllTableEntriesForPartitionAsync(clusterId);
var entriesList = new List<Tuple<SiloInstanceTableEntry, string>>(entries);
await DeleteEntriesBatch(entriesList);
return entriesList.Count();
}
public async Task CleanupDefunctSiloEntries(DateTimeOffset beforeDate)
{
var entriesList = (await FindAllSiloEntries())
.Where(entry => entry.Item1.Status == INSTANCE_STATUS_DEAD && entry.Item1.Timestamp < beforeDate)
.ToList();
await DeleteEntriesBatch(entriesList);
}
private async Task DeleteEntriesBatch(List<Tuple<SiloInstanceTableEntry, string>> entriesList)
{
if (entriesList.Count <= AzureTableDefaultPolicies.MAX_BULK_UPDATE_ROWS)
{
await storage.DeleteTableEntriesAsync(entriesList);
}
else
{
var tasks = new List<Task>();
foreach (var batch in entriesList.BatchIEnumerable(AzureTableDefaultPolicies.MAX_BULK_UPDATE_ROWS))
{
tasks.Add(storage.DeleteTableEntriesAsync(batch));
}
await Task.WhenAll(tasks);
}
}
internal async Task<List<Tuple<SiloInstanceTableEntry, string>>> FindSiloEntryAndTableVersionRow(SiloAddress siloAddress)
{
string rowKey = SiloInstanceTableEntry.ConstructRowKey(siloAddress);
string filterOnPartitionKey = TableQuery.GenerateFilterCondition(nameof(SiloInstanceTableEntry.PartitionKey), QueryComparisons.Equal,
this.DeploymentId);
string filterOnRowKey1 = TableQuery.GenerateFilterCondition(nameof(SiloInstanceTableEntry.RowKey), QueryComparisons.Equal,
rowKey);
string filterOnRowKey2 = TableQuery.GenerateFilterCondition(nameof(SiloInstanceTableEntry.RowKey), QueryComparisons.Equal, SiloInstanceTableEntry.TABLE_VERSION_ROW);
string query = TableQuery.CombineFilters(filterOnPartitionKey, TableOperators.And, TableQuery.CombineFilters(filterOnRowKey1, TableOperators.Or, filterOnRowKey2));
var queryResults = await storage.ReadTableEntriesAndEtagsAsync(query);
var asList = queryResults.ToList();
if (asList.Count < 1 || asList.Count > 2)
throw new KeyNotFoundException(string.Format("Could not find table version row or found too many entries. Was looking for key {0}, found = {1}", siloAddress.ToLongString(), Utils.EnumerableToString(asList)));
int numTableVersionRows = asList.Count(tuple => tuple.Item1.RowKey == SiloInstanceTableEntry.TABLE_VERSION_ROW);
if (numTableVersionRows < 1)
throw new KeyNotFoundException(string.Format("Did not read table version row. Read = {0}", Utils.EnumerableToString(asList)));
if (numTableVersionRows > 1)
throw new KeyNotFoundException(string.Format("Read {0} table version rows, while was expecting only 1. Read = {1}", numTableVersionRows, Utils.EnumerableToString(asList)));
return asList;
}
internal async Task<List<Tuple<SiloInstanceTableEntry, string>>> FindAllSiloEntries()
{
var queryResults = await storage.ReadAllTableEntriesForPartitionAsync(this.DeploymentId);
var asList = queryResults.ToList();
if (asList.Count < 1)
throw new KeyNotFoundException(string.Format("Could not find enough rows in the FindAllSiloEntries call. Found = {0}", Utils.EnumerableToString(asList)));
int numTableVersionRows = asList.Count(tuple => tuple.Item1.RowKey == SiloInstanceTableEntry.TABLE_VERSION_ROW);
if (numTableVersionRows < 1)
throw new KeyNotFoundException(string.Format("Did not find table version row. Read = {0}", Utils.EnumerableToString(asList)));
if (numTableVersionRows > 1)
throw new KeyNotFoundException(string.Format("Read {0} table version rows, while was expecting only 1. Read = {1}", numTableVersionRows, Utils.EnumerableToString(asList)));
return asList;
}
/// <summary>
/// Insert (create new) row entry
/// </summary>
internal async Task<bool> TryCreateTableVersionEntryAsync()
{
try
{
var versionRow = await storage.ReadSingleTableEntryAsync(DeploymentId, SiloInstanceTableEntry.TABLE_VERSION_ROW);
if (versionRow != null && versionRow.Item1 != null)
{
return false;
}
SiloInstanceTableEntry entry = CreateTableVersionEntry(0);
await storage.CreateTableEntryAsync(entry);
return true;
}
catch (Exception exc)
{
HttpStatusCode httpStatusCode;
string restStatus;
if (!AzureTableUtils.EvaluateException(exc, out httpStatusCode, out restStatus)) throw;
if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("InsertSiloEntryConditionally failed with httpStatusCode={0}, restStatus={1}", httpStatusCode, restStatus);
if (AzureTableUtils.IsContentionError(httpStatusCode)) return false;
throw;
}
}
/// <summary>
/// Insert (create new) row entry
/// </summary>
/// <param name="siloEntry">Silo Entry to be written</param>
/// <param name="tableVersionEntry">Version row to update</param>
/// <param name="tableVersionEtag">Version row eTag</param>
internal async Task<bool> InsertSiloEntryConditionally(SiloInstanceTableEntry siloEntry, SiloInstanceTableEntry tableVersionEntry, string tableVersionEtag)
{
try
{
await storage.InsertTwoTableEntriesConditionallyAsync(siloEntry, tableVersionEntry, tableVersionEtag);
return true;
}
catch (Exception exc)
{
HttpStatusCode httpStatusCode;
string restStatus;
if (!AzureTableUtils.EvaluateException(exc, out httpStatusCode, out restStatus)) throw;
if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("InsertSiloEntryConditionally failed with httpStatusCode={0}, restStatus={1}", httpStatusCode, restStatus);
if (AzureTableUtils.IsContentionError(httpStatusCode)) return false;
throw;
}
}
/// <summary>
/// Conditionally update the row for this entry, but only if the eTag matches with the current record in data store
/// </summary>
/// <param name="siloEntry">Silo Entry to be written</param>
/// <param name="entryEtag">ETag value for the entry being updated</param>
/// <param name="tableVersionEntry">Version row to update</param>
/// <param name="versionEtag">ETag value for the version row</param>
/// <returns></returns>
internal async Task<bool> UpdateSiloEntryConditionally(SiloInstanceTableEntry siloEntry, string entryEtag, SiloInstanceTableEntry tableVersionEntry, string versionEtag)
{
try
{
await storage.UpdateTwoTableEntriesConditionallyAsync(siloEntry, entryEtag, tableVersionEntry, versionEtag);
return true;
}
catch (Exception exc)
{
HttpStatusCode httpStatusCode;
string restStatus;
if (!AzureTableUtils.EvaluateException(exc, out httpStatusCode, out restStatus)) throw;
if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("UpdateSiloEntryConditionally failed with httpStatusCode={0}, restStatus={1}", httpStatusCode, restStatus);
if (AzureTableUtils.IsContentionError(httpStatusCode)) return false;
throw;
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.SignatureHelp;
using Microsoft.CodeAnalysis.Editor.UnitTests.SignatureHelp;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.SignatureHelp;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SignatureHelp
{
public class ConstructorInitializerSignatureHelpProviderTests : AbstractCSharpSignatureHelpProviderTests
{
public ConstructorInitializerSignatureHelpProviderTests(CSharpTestWorkspaceFixture workspaceFixture) : base(workspaceFixture)
{
}
internal override ISignatureHelpProvider CreateSignatureHelpProvider()
{
return new ConstructorInitializerSignatureHelpProvider();
}
#region "Regular tests"
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithoutParameters()
{
var markup = @"
class BaseClass
{
public BaseClass() { }
}
class Derived : BaseClass
{
public Derived() [|: base($$|])
{ }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("BaseClass()", string.Empty, null, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithoutParametersMethodXmlComments()
{
var markup = @"
class BaseClass
{
/// <summary>Summary for BaseClass</summary>
public BaseClass() { }
}
class Derived : BaseClass
{
public Derived() [|: base($$|])
{ }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("BaseClass()", "Summary for BaseClass", null, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithParametersOn1()
{
var markup = @"
class BaseClass
{
public BaseClass(int a, int b) { }
}
class Derived : BaseClass
{
public Derived() [|: base($$2, 3|])
{ }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("BaseClass(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithParametersXmlCommentsOn1()
{
var markup = @"
class BaseClass
{
/// <summary>Summary for BaseClass</summary>
/// <param name=""a"">Param a</param>
/// <param name=""b"">Param b</param>
public BaseClass(int a, int b) { }
}
class Derived : BaseClass
{
public Derived() [|: base($$2, 3|])
{ }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("BaseClass(int a, int b)", "Summary for BaseClass", "Param a", currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithParametersOn2()
{
var markup = @"
class BaseClass
{
/// <summary>Summary for BaseClass</summary>
/// <param name=""a"">Param a</param>
/// <param name=""b"">Param b</param>
public BaseClass(int a, int b) { }
}
class Derived : BaseClass
{
public Derived() [|: base(2, $$3|])
{ }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("BaseClass(int a, int b)", "Summary for BaseClass", "Param b", currentParameterIndex: 1));
await TestAsync(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithParametersXmlComentsOn2()
{
var markup = @"
class BaseClass
{
/// <summary>Summary for BaseClass</summary>
/// <param name=""a"">Param a</param>
/// <param name=""b"">Param b</param>
public BaseClass(int a, int b) { }
}
class Derived : BaseClass
{
public Derived() [|: base(2, $$3|])
{ }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("BaseClass(int a, int b)", "Summary for BaseClass", "Param b", currentParameterIndex: 1));
await TestAsync(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestThisInvocation()
{
var markup = @"
class Foo
{
public Foo(int a, int b) { }
public Foo() [|: this(2, $$3|]) { }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem("Foo()", string.Empty, null, currentParameterIndex: 1),
new SignatureHelpTestItem("Foo(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 1),
};
await TestAsync(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithoutClosingParen()
{
var markup = @"
class Foo
{
public Foo(int a, int b) { }
public Foo() [|: this(2, $$
|]}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem("Foo()", string.Empty, null, currentParameterIndex: 1),
new SignatureHelpTestItem("Foo(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 1),
};
await TestAsync(markup, expectedOrderedItems);
}
#endregion
#region "Current Parameter Name"
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestCurrentParameterName()
{
var markup = @"
class Foo
{
public Foo(int a, int b) { }
public Foo() : this(b: 2, a: $$
}";
await VerifyCurrentParameterNameAsync(markup, "a");
}
#endregion
#region "Trigger tests"
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationOnTriggerParens()
{
var markup = @"
class Foo
{
public Foo(int a) { }
public Foo() : this($$
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem("Foo()", string.Empty, null, currentParameterIndex: 0),
new SignatureHelpTestItem("Foo(int a)", string.Empty, string.Empty, currentParameterIndex: 0),
};
await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationOnTriggerComma()
{
var markup = @"
class Foo
{
public Foo(int a, int b) { }
public Foo() : this(2,$$
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem("Foo()", string.Empty, null, currentParameterIndex: 1),
new SignatureHelpTestItem("Foo(int a, int b)", string.Empty, string.Empty, currentParameterIndex: 1),
};
await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestNoInvocationOnSpace()
{
var markup = @"
class Foo
{
public Foo(int a, int b) { }
public Foo() : this(2, $$
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public void TestTriggerCharacters()
{
char[] expectedCharacters = { ',', '(' };
char[] unexpectedCharacters = { ' ', '[', '<' };
VerifyTriggerCharacters(expectedCharacters, unexpectedCharacters);
}
#endregion
#region "EditorBrowsable tests"
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task EditorBrowsable_ConstructorInitializer_BrowsableStateAlways()
{
var markup = @"
class DerivedClass : BaseClass
{
public DerivedClass() : base($$
}";
var referencedCode = @"
public class BaseClass
{
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)]
public BaseClass(int x)
{ }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("BaseClass(int x)", string.Empty, string.Empty, currentParameterIndex: 0));
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItems,
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task EditorBrowsable_ConstructorInitializer_BrowsableStateNever()
{
var markup = @"
class DerivedClass : BaseClass
{
public DerivedClass() : base($$
}";
var referencedCode = @"
public class BaseClass
{
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public BaseClass(int x)
{ }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("BaseClass(int x)", string.Empty, string.Empty, currentParameterIndex: 0));
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(),
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task EditorBrowsable_ConstructorInitializer_BrowsableStateAdvanced()
{
var markup = @"
class DerivedClass : BaseClass
{
public DerivedClass() : base($$
}";
var referencedCode = @"
public class BaseClass
{
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)]
public BaseClass(int x)
{ }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("BaseClass(int x)", string.Empty, string.Empty, currentParameterIndex: 0));
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(),
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItems,
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task EditorBrowsable_ConstructorInitializer_BrowsableStateMixed()
{
var markup = @"
class DerivedClass : BaseClass
{
public DerivedClass() : base($$
}";
var referencedCode = @"
public class BaseClass
{
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)]
public BaseClass(int x)
{ }
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public BaseClass(int x, int y)
{ }
}";
var expectedOrderedItemsMetadataReference = new List<SignatureHelpTestItem>();
expectedOrderedItemsMetadataReference.Add(new SignatureHelpTestItem("BaseClass(int x)", string.Empty, string.Empty, currentParameterIndex: 0));
var expectedOrderedItemsSameSolution = new List<SignatureHelpTestItem>();
expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("BaseClass(int x)", string.Empty, string.Empty, currentParameterIndex: 0));
expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("BaseClass(int x, int y)", string.Empty, string.Empty, currentParameterIndex: 0));
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItemsMetadataReference,
expectedOrderedItemsSameSolution: expectedOrderedItemsSameSolution,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
#endregion
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task FieldUnavailableInOneLinkedFile()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""FOO"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
#if FOO
class Secret
{
public Secret(int secret)
{
}
}
#endif
class SuperSecret : Secret
{
public SuperSecret(int secret) : base($$
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
var expectedDescription = new SignatureHelpTestItem($"Secret(int secret)\r\n\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_context}", currentParameterIndex: 0);
await VerifyItemWithReferenceWorkerAsync(markup, new[] { expectedDescription }, false);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task ExcludeFilesWithInactiveRegions()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""FOO,BAR"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
#if FOO
class Secret
{
public Secret(int secret)
{
}
}
#endif
#if BAR
class SuperSecret : Secret
{
public SuperSecret(int secret) : base($$
}
#endif
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument"" />
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3"" PreprocessorSymbols=""BAR"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
var expectedDescription = new SignatureHelpTestItem($"Secret(int secret)\r\n\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj3", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_context}", currentParameterIndex: 0);
await VerifyItemWithReferenceWorkerAsync(markup, new[] { expectedDescription }, false);
}
[WorkItem(1067933, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1067933")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task InvokedWithNoToken()
{
var markup = @"
// foo($$";
await TestAsync(markup);
}
[WorkItem(1082601, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1082601")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationWithBadParameterList()
{
var markup = @"
class BaseClass
{
public BaseClass() { }
}
class Derived : BaseClass
{
public Derived() [|: base{$$|])
{ }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
await TestAsync(markup, expectedOrderedItems);
}
}
}
| |
using System;
using System.Collections;
using System.Net;
using System.IO;
using System.Security.Cryptography.X509Certificates;
namespace TKCode123.Net.Http
{
public class TinyWeb : IDisposable
{
public interface IVariable
{
bool IsReadOnly { get; }
string Name { get; }
string ValueString { get; set; }
}
protected readonly HttpListener _listener;
private readonly string _startTime;
private readonly string _me;
private readonly Hashtable _variablesByName;
private int _calls;
private bool _ok;
public TinyWeb(int port, X509Certificate certificate)
{
_ok = true;
string prefix = certificate != null ? "https" : "http";
_me = prefix + "://" + IPAddress.GetDefaultLocalAddress() + ":" + port;
// Create a listener.
_listener = new HttpListener(prefix, port);
if (certificate != null)
{
_listener.HttpsCert = certificate;
}
_startTime = DateTime.Now.ToString("g");
_variablesByName = new Hashtable();
}
protected virtual void Shutdown(string reason)
{
Debugger.Write(reason);
_ok = false;
}
public virtual void Dispose()
{
if (_listener != null)
{
_listener.Close();
}
}
public virtual void Handle()
{
try
{
_listener.Start();
Debugger.Write("Listening ", _me);
while (_ok && _listener.IsListening)
{
// Note: The GetContext method blocks while waiting for a request.
var req = _listener.GetContext();
if (req != null && _ok)
{
_calls++;
PreHandle();
try
{
DebugOut(req.Request, false);
var ctx = CreateContext(req);
_ok = Handle(ctx);
DebugOut(req.Response, false);
}
catch (Exception e)
{
Debugger.Write(e.ToString());
try
{
req.Close();
}
catch
{
}
}
PostHandle();
}
}
Debugger.Write("Stopped.");
}
catch (Exception e)
{
Debugger.Write(e.ToString());
}
}
protected virtual TinyContext CreateContext(HttpListenerContext c)
{
return new TinyContext(c, this);
}
protected virtual void PreHandle() { }
protected virtual void PostHandle() { }
protected virtual bool Handle(TinyContext context)
{
using (HttpListenerResponse response = context.ClientContext.Response)
{
HttpListenerRequest request = context.ClientContext.Request;
if (string.Equals(request.HttpMethod, "GET"))
{
return HandlePageNotFound(context);
}
else
{
response.StatusCode = (int)HttpStatusCode.NotImplemented;
}
return true;
}
}
protected virtual bool HandlePageNotFound(TinyContext context)
{
return Respond(context, HttpStatusCode.NotFound, true, "text/html", false, PageNotFound);
}
protected virtual bool Respond(TinyContext context, HttpStatusCode code, bool replaceSyms, string contentType, bool dontCache, object content)
{
try
{
using (HttpListenerResponse response = context.ClientContext.Response)
{
response.StatusCode = (int)code;
if (dontCache) response.Headers.Add("cache-control", "dont-cache");
if (contentType != null) response.ContentType = contentType;
//if (context.ClientContext.Request.KeepAlive) response.KeepAlive = true;
if (content.GetType() == typeof(string))
{
response.ContentEncoding = System.Text.Encoding.UTF8;
new ReplacingUTF8Encoder(context, replaceSyms, response.OutputStream).Encode(content.ToString());
}
else if (content is byte[])
{
byte [] arr = content as byte[];
response.ContentLength64 = arr.Length;
response.OutputStream.Write(arr, 0, arr.Length);
}
response.OutputStream.Close();
return true;
}
}
catch
{
return true;
}
}
public virtual IVariable AddVariable(IVariable v)
{
IVariable old = (IVariable)_variablesByName[v.Name];
_variablesByName[v.Name] = v;
return old;
}
public virtual IVariable GetVariable(string n)
{
return (IVariable)_variablesByName[n];
}
public virtual bool RemoveVariable(IVariable v)
{
IVariable old = (IVariable)_variablesByName[v.Name];
_variablesByName.Remove(v.Name);
return old != null;
}
protected virtual bool TryParseDouble(string s, out double val)
{
if (s != null && s.Length > 0)
{
return double.TryParse(s, out val);
}
val = 0.0;
return false;
}
protected virtual bool TryParseBoolean(string s, out bool val)
{
if (s != null && s.Length > 0)
{
if (s.Equals(bool.TrueString) || s.Equals("1") || s.Equals("ON"))
{
val = true;
return true;
}
if (s.Equals(bool.FalseString) || s.Equals("0") || s.Equals("OFF"))
{
val = false;
return true;
}
}
val = false;
return false;
}
public virtual string ReplaceSymbol(string source, TinyContext context)
{
IVariable v = GetVariable(source);
if (v != null)
return v.ValueString;
switch (source)
{
case "CURRENTDATETIME": return this.CurrentDateTime;
case "CALLS": return this.Calls;
case "SERVERLINK": return this.ServerLink;
case "REMOTEENDPOINT": return context.ClientContext.Request.RemoteEndPoint.ToString();
case "HTTPMETHOD": return context.ClientContext.Request.HttpMethod;
case "RAWURL": return context.ClientContext.Request.RawUrl;
case "LOCALENDPOINT": return context.ClientContext.Request.LocalEndPoint.ToString();
case "TITLE": return this.Title;
case "GENERATOR": return this.ToString();
case "SERVERSTART": return this._startTime;
default: return context.ClientContext.Request.Headers[source];
}
}
public string ServerStartTime
{
get { return _startTime; }
}
public virtual string PageNotFound
{
get { return "<html><head><meta http-equiv='Content-Type' content='text/html; charset=utf-8' /><title>{Title}</title></head><body>PAGE '{RawUrl}' NOT FOUND<br/>This page was referenced from {Referer}.<br/>Here it is {CurrentDateTime}.<br/>Connected from {RemoteEndPoint}.<br/><a href='{ServerLink}'>Root Page Link</a> for this server.<br/>This is {ServerVersion}.</body></html>"; }
}
public virtual string Title
{
get { return this.GetType().Name; }
}
public virtual string CurrentDateTime
{
get { return DateTime.Now.ToRFCString(); }
}
public virtual string Calls
{
get { return _calls.ToString(); }
}
public virtual string ServerLink
{
get { return _me; }
}
public override string ToString()
{
return "TinyWeb/1.0";
}
protected virtual void DebugOut(HttpListenerRequest req, bool hdr)
{
Debugger.Write(req.HttpMethod, " ", req.RawUrl);
if (hdr)
{
foreach (var k in req.Headers.AllKeys)
Debugger.Write(k, ":", req.Headers.GetValues(k)[0]);
}
if (req.ContentType != null) Debugger.Write("TYPE=", req.ContentType);
if (req.ContentLength64 > 0) Debugger.Write("LENGTH=", req.ContentLength64);
}
protected virtual void DebugOut(HttpListenerResponse resp, bool hdr)
{
Debugger.Write(" ==> ", resp.StatusCode);
if (hdr)
{
foreach (var k in resp.Headers.AllKeys)
Debugger.Write(k, ":", resp.Headers.GetValues(k)[0]);
}
}
public class TinyContext
{
private readonly HttpListenerContext _listenerContext;
private readonly TinyWeb _server;
private readonly long _start;
public TinyContext(HttpListenerContext ctx, TinyWeb server)
{
_listenerContext = ctx; _server = server; _start = DateTime.Now.Ticks;
}
public TinyWeb Server { get { return _server; } }
public HttpListenerContext ClientContext { get { return _listenerContext; } }
public TimeSpan Duration { get { return new TimeSpan(DateTime.Now.Ticks - _start); } }
public virtual string ReplaceSymbol(string source)
{
if ("DURATION".Equals(source))
return Duration.ToString();
return Server.ReplaceSymbol(source, this);
}
}
class ReplacingUTF8Encoder
{
private readonly TinyContext _ctx;
private readonly byte[] _tmp;
private readonly Stream _stream;
private readonly bool _replace;
internal ReplacingUTF8Encoder(TinyContext context, bool repl, Stream stream)
{
_tmp = new byte[1000];
_ctx = context;
_stream = stream;
_replace = repl;
}
internal void Encode(string source)
{
int len = source.Length;
if (_replace)
{
int pos = 0;
while (pos < len)
{
int a = source.IndexOf("{@", pos);
int b = source.IndexOf("@}", pos);
if (a >= 0 && b > (a+2))
{
if (pos < a)
SimpleUTF8(source, pos, a - pos);
string symbol = source.Substring(a + 2, b - a - 2);
string repl = _ctx.ReplaceSymbol(symbol);
if (repl != null)
{
Encode(repl);
}
else
SimpleUTF8(source, a, b - a + 2);
pos = b + 2;
}
else
pos += SimpleUTF8(source, pos, len - pos);
}
}
else
{
SimpleUTF8(source, 0, len);
}
}
private int SimpleUTF8Rec(string source, int pos, int len)
{
int todo = System.Math.Min(_tmp.Length, len);
for (int i = 0; i < todo; i++)
_tmp[i] = (byte)source[pos + i];
_stream.Write(_tmp, 0, todo);
return todo;
}
private int SimpleUTF8(string source, int pos, int len)
{
int done = 0;
while (done < len)
{
done += SimpleUTF8Rec(source, pos + done, len - done);
}
return done;
}
private int SimpleUTF8(string source)
{
int pos = 0;
int len = source.Length;
while (pos < len)
{
pos += SimpleUTF8(source, pos, len - pos);
}
return len;
}
}
}
}
| |
using UnityEngine;
using System.IO;
[AddComponentMenu("Modifiers/Path Deform")]
public class MegaPathDeform : MegaModifier
{
public float percent = 0.0f;
public float stretch = 1.0f;
public float twist = 0.0f;
public float rotate = 0.0f;
public MegaAxis axis = MegaAxis.X;
public bool flip = false;
public MegaShape path = null;
public bool animate = false;
public float speed = 1.0f;
public bool drawpath = false;
public float tangent = 1.0f;
[HideInInspector]
public Matrix4x4 mat = new Matrix4x4();
public bool UseTwistCurve = false;
public AnimationCurve twistCurve = new AnimationCurve(new Keyframe(0, 0), new Keyframe(1, 1));
public bool UseStretchCurve = false;
public AnimationCurve stretchCurve = new AnimationCurve(new Keyframe(0, 1), new Keyframe(1, 1));
public override string ModName() { return "PathDeform"; }
public override string GetHelpURL() { return "?page_id=273"; }
public Vector3 Up = Vector3.up;
public int curve = 0;
public bool usedist = false;
public float distance = 0.0f;
public MegaLoopMode loopmode = MegaLoopMode.None;
Vector3 start;
Quaternion tw = Quaternion.identity;
float usepercent;
float usetan;
float ovlen;
public override Vector3 Map(int i, Vector3 p)
{
p = tm.MultiplyPoint3x4(p); // Dont need either, so saving 3 vector mat mults but gaining a mat mult
float alpha;
float tws = 0.0f;
if ( UseStretchCurve )
{
float str = stretchCurve.Evaluate(Mathf.Repeat(p.z * ovlen + usepercent, 1.0f)) * stretch;
alpha = (p.z * ovlen * str) + usepercent; //(percent / 100.0f); // can precalc this
}
else
alpha = (p.z * ovlen * stretch) + usepercent; //(percent / 100.0f); // can precalc this
Vector3 ps = path.InterpCurve3D(curve, alpha, path.normalizedInterp, ref tws) - start;
Vector3 ps1 = path.InterpCurve3D(curve, alpha + usetan, path.normalizedInterp) - start;
if ( path.splines[curve].closed )
alpha = Mathf.Repeat(alpha, 1.0f);
else
alpha = Mathf.Clamp01(alpha);
if ( UseTwistCurve )
{
float twst = twistCurve.Evaluate(alpha) * twist;
tw = Quaternion.AngleAxis(twst + tws, Vector3.forward);
}
else
tw = Quaternion.AngleAxis(tws + (twist * alpha), Vector3.forward);
Vector3 relativePos = ps1 - ps;
Quaternion rotation = Quaternion.LookRotation(relativePos, Up) * tw;
//wtm.SetTRS(ps, rotation, Vector3.one);
Matrix4x4 wtm = Matrix4x4.identity;
MegaMatrix.SetTR(ref wtm, ps, rotation);
wtm = mat * wtm;
p.z = 0.0f;
return wtm.MultiplyPoint3x4(p);
}
public override void ModStart(MegaModifiers mc)
{
}
public override bool ModLateUpdate(MegaModContext mc)
{
if ( animate )
{
if ( Application.isPlaying )
percent += speed * Time.deltaTime;
if ( usedist )
distance = percent * 0.01f * path.splines[curve].length;
}
return Prepare(mc);
}
public override bool Prepare(MegaModContext mc)
{
if ( path != null )
{
if ( curve >= path.splines.Count )
curve = 0;
if ( usedist )
percent = distance / path.splines[curve].length * 100.0f;
usepercent = percent / 100.0f;
switch ( loopmode )
{
case MegaLoopMode.Clamp: usepercent = Mathf.Clamp01(usepercent); break;
case MegaLoopMode.Loop: usepercent = Mathf.Repeat(usepercent, 1.0f); break;
case MegaLoopMode.PingPong: usepercent = Mathf.PingPong(usepercent, 1.0f); break;
}
ovlen = (1.0f / path.splines[curve].length); // * stretch;
usetan = (tangent * 0.01f);
mat = Matrix4x4.identity;
switch ( axis )
{
case MegaAxis.Z: MegaMatrix.RotateX(ref mat, -Mathf.PI * 0.5f); break;
}
MegaMatrix.RotateZ(ref mat, Mathf.Deg2Rad * rotate);
SetAxis(mat);
start = path.splines[curve].knots[0].p;
Vector3 p1 = path.InterpCurve3D(0, 0.01f, path.normalizedInterp);
Vector3 up = Vector3.zero;
switch ( axis )
{
case MegaAxis.X: up = Vector3.left; break;
case MegaAxis.Y: up = Vector3.back; break;
case MegaAxis.Z: up = Vector3.up; break;
}
Quaternion lrot = Quaternion.identity;
if ( flip )
up = -up;
lrot = Quaternion.FromToRotation(p1 - start, up);
mat.SetTRS(Vector3.zero, lrot, Vector3.one);
return true;
}
return false;
}
public void OnDrawGizmos()
{
if ( drawpath )
Display(this);
}
// Mmm should be in gizmo code
void Display(MegaPathDeform pd)
{
if ( pd.path != null )
{
// Need to do a lookat on first point to get the direction
pd.mat = Matrix4x4.identity;
Vector3 p = pd.path.splines[curve].knots[0].p;
Vector3 p1 = pd.path.InterpCurve3D(curve, 0.01f, pd.path.normalizedInterp);
Vector3 up = Vector3.zero;
switch ( axis )
{
case MegaAxis.X: up = Vector3.left; break;
case MegaAxis.Y: up = Vector3.back; break;
case MegaAxis.Z: up = Vector3.up; break;
}
Quaternion lrot = Quaternion.identity;
if ( flip )
up = -up;
lrot = Quaternion.FromToRotation(p1 - p, up);
pd.mat.SetTRS(Vector3.zero, lrot, Vector3.one);
Matrix4x4 mat = pd.transform.localToWorldMatrix * pd.mat;
for ( int s = 0; s < pd.path.splines.Count; s++ )
{
float ldist = pd.path.stepdist * 0.1f;
if ( ldist < 0.01f )
ldist = 0.01f;
float ds = pd.path.splines[s].length / (pd.path.splines[s].length / ldist);
int c = 0;
int k = -1;
int lk = -1;
Vector3 first = pd.path.splines[s].Interpolate(0.0f, pd.path.normalizedInterp, ref lk) - p;
for ( float dist = ds; dist < pd.path.splines[s].length; dist += ds )
{
float alpha = dist / pd.path.splines[s].length;
Vector3 pos = pd.path.splines[s].Interpolate(alpha, pd.path.normalizedInterp, ref k) - p;
if ( (c & 1) == 1 )
Gizmos.color = pd.path.col1;
else
Gizmos.color = pd.path.col2;
if ( k != lk )
{
for ( lk = lk + 1; lk <= k; lk++ )
{
Gizmos.DrawLine(mat.MultiplyPoint(first), mat.MultiplyPoint(pd.path.splines[s].knots[lk].p - p));
first = pd.path.splines[s].knots[lk].p - p;
}
}
lk = k;
Gizmos.DrawLine(mat.MultiplyPoint(first), mat.MultiplyPoint(pos));
c++;
first = pos;
}
if ( (c & 1) == 1 )
Gizmos.color = pd.path.col1;
else
Gizmos.color = pd.path.col2;
if ( pd.path.splines[s].closed )
{
Vector3 pos = pd.path.splines[s].Interpolate(0.0f, pd.path.normalizedInterp, ref k) - p;
Gizmos.DrawLine(mat.MultiplyPoint(first), mat.MultiplyPoint(pos));
}
}
Vector3 p0 = pd.path.InterpCurve3D(curve, (percent / 100.0f), pd.path.normalizedInterp) - p;
p1 = pd.path.InterpCurve3D(curve, (percent / 100.0f) + (tangent * 0.01f), pd.path.normalizedInterp) - p;
Gizmos.color = Color.blue;
Vector3 sz = new Vector3(pd.path.KnotSize * 0.01f, pd.path.KnotSize * 0.01f, pd.path.KnotSize * 0.01f);
Gizmos.DrawCube(mat.MultiplyPoint(p0), sz);
Gizmos.DrawCube(mat.MultiplyPoint(p1), sz);
}
}
public override void DrawGizmo(MegaModContext context)
{
if ( !Prepare(context) )
return;
Vector3 min = context.bbox.min;
Vector3 max = context.bbox.max;
if ( context.mod.sourceObj != null )
Gizmos.matrix = context.mod.sourceObj.transform.localToWorldMatrix; // * gtm;
else
Gizmos.matrix = transform.localToWorldMatrix; // * gtm;
corners[0] = new Vector3(min.x, min.y, min.z);
corners[1] = new Vector3(min.x, max.y, min.z);
corners[2] = new Vector3(max.x, max.y, min.z);
corners[3] = new Vector3(max.x, min.y, min.z);
corners[4] = new Vector3(min.x, min.y, max.z);
corners[5] = new Vector3(min.x, max.y, max.z);
corners[6] = new Vector3(max.x, max.y, max.z);
corners[7] = new Vector3(max.x, min.y, max.z);
DrawEdge(corners[0], corners[1]);
DrawEdge(corners[1], corners[2]);
DrawEdge(corners[2], corners[3]);
DrawEdge(corners[3], corners[0]);
DrawEdge(corners[4], corners[5]);
DrawEdge(corners[5], corners[6]);
DrawEdge(corners[6], corners[7]);
DrawEdge(corners[7], corners[4]);
DrawEdge(corners[0], corners[4]);
DrawEdge(corners[1], corners[5]);
DrawEdge(corners[2], corners[6]);
DrawEdge(corners[3], corners[7]);
ExtraGizmo(context);
}
}
| |
// <copyright file="ChromeDriverService.cs" company="WebDriver Committers">
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC 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.
// </copyright>
using System;
using System.Globalization;
using System.Text;
using OpenQA.Selenium.Internal;
namespace OpenQA.Selenium.Chrome
{
/// <summary>
/// Exposes the service provided by the native ChromeDriver executable.
/// </summary>
public sealed class ChromeDriverService : DriverService
{
private const string DefaultChromeDriverServiceExecutableName = "chromedriver";
private static readonly Uri ChromeDriverDownloadUrl = new Uri("http://chromedriver.storage.googleapis.com/index.html");
private string logPath = string.Empty;
private string urlPathPrefix = string.Empty;
private string portServerAddress = string.Empty;
private string whitelistedIpAddresses = string.Empty;
private int adbPort = -1;
private bool enableVerboseLogging;
/// <summary>
/// Initializes a new instance of the <see cref="ChromeDriverService"/> class.
/// </summary>
/// <param name="executablePath">The full path to the ChromeDriver executable.</param>
/// <param name="executableFileName">The file name of the ChromeDriver executable.</param>
/// <param name="port">The port on which the ChromeDriver executable should listen.</param>
private ChromeDriverService(string executablePath, string executableFileName, int port)
: base(executablePath, port, executableFileName, ChromeDriverDownloadUrl)
{
}
/// <summary>
/// Gets or sets the location of the log file written to by the ChromeDriver executable.
/// </summary>
public string LogPath
{
get { return this.logPath; }
set { this.logPath = value; }
}
/// <summary>
/// Gets or sets the base URL path prefix for commands (e.g., "wd/url").
/// </summary>
public string UrlPathPrefix
{
get { return this.urlPathPrefix; }
set { this.urlPathPrefix = value; }
}
/// <summary>
/// Gets or sets the address of a server to contact for reserving a port.
/// </summary>
public string PortServerAddress
{
get { return this.portServerAddress; }
set { this.portServerAddress = value; }
}
/// <summary>
/// Gets or sets the port on which the Android Debug Bridge is listening for commands.
/// </summary>
public int AndroidDebugBridgePort
{
get { return this.adbPort; }
set { this.adbPort = value; }
}
/// <summary>
/// Gets or sets a value indicating whether to enable verbose logging for the ChromeDriver executable.
/// Defaults to <see langword="false"/>.
/// </summary>
public bool EnableVerboseLogging
{
get { return this.enableVerboseLogging; }
set { this.enableVerboseLogging = value; }
}
/// <summary>
/// Gets or sets the comma-delimited list of IP addresses that are approved to
/// connect to this instance of the Chrome driver. Defaults to an empty string,
/// which means only the local loopback address can connect.
/// </summary>
public string WhitelistedIPAddresses
{
get { return this.whitelistedIpAddresses; }
set { this.whitelistedIpAddresses = value; }
}
/// <summary>
/// Gets the command-line arguments for the driver service.
/// </summary>
protected override string CommandLineArguments
{
get
{
StringBuilder argsBuilder = new StringBuilder(base.CommandLineArguments);
if (this.adbPort > 0)
{
argsBuilder.AppendFormat(CultureInfo.InvariantCulture, " --adb-port={0}", this.adbPort);
}
if (this.SuppressInitialDiagnosticInformation)
{
argsBuilder.Append(" --silent");
}
if (this.enableVerboseLogging)
{
argsBuilder.Append(" --verbose");
}
if (!string.IsNullOrEmpty(this.logPath))
{
argsBuilder.AppendFormat(CultureInfo.InvariantCulture, " --log-path=\"{0}\"", this.logPath);
}
if (!string.IsNullOrEmpty(this.urlPathPrefix))
{
argsBuilder.AppendFormat(CultureInfo.InvariantCulture, " --url-base={0}", this.urlPathPrefix);
}
if (!string.IsNullOrEmpty(this.portServerAddress))
{
argsBuilder.AppendFormat(CultureInfo.InvariantCulture, " --port-server={0}", this.portServerAddress);
}
if (!string.IsNullOrEmpty(this.whitelistedIpAddresses))
{
argsBuilder.Append(string.Format(CultureInfo.InvariantCulture, " -whitelisted-ips={0}", this.whitelistedIpAddresses));
}
return argsBuilder.ToString();
}
}
/// <summary>
/// Creates a default instance of the ChromeDriverService.
/// </summary>
/// <returns>A ChromeDriverService that implements default settings.</returns>
public static ChromeDriverService CreateDefaultService()
{
string serviceDirectory = DriverService.FindDriverServiceExecutable(ChromeDriverServiceFileName(), ChromeDriverDownloadUrl);
return CreateDefaultService(serviceDirectory);
}
/// <summary>
/// Creates a default instance of the ChromeDriverService using a specified path to the ChromeDriver executable.
/// </summary>
/// <param name="driverPath">The directory containing the ChromeDriver executable.</param>
/// <returns>A ChromeDriverService using a random port.</returns>
public static ChromeDriverService CreateDefaultService(string driverPath)
{
return CreateDefaultService(driverPath, ChromeDriverServiceFileName());
}
/// <summary>
/// Creates a default instance of the ChromeDriverService using a specified path to the ChromeDriver executable with the given name.
/// </summary>
/// <param name="driverPath">The directory containing the ChromeDriver executable.</param>
/// <param name="driverExecutableFileName">The name of the ChromeDriver executable file.</param>
/// <returns>A ChromeDriverService using a random port.</returns>
public static ChromeDriverService CreateDefaultService(string driverPath, string driverExecutableFileName)
{
return new ChromeDriverService(driverPath, driverExecutableFileName, PortUtilities.FindFreePort());
}
/// <summary>
/// Returns the Chrome driver filename for the currently running platform
/// </summary>
/// <returns>The file name of the Chrome driver service executable.</returns>
private static string ChromeDriverServiceFileName()
{
string fileName = DefaultChromeDriverServiceExecutableName;
// Unfortunately, detecting the currently running platform isn't as
// straightforward as you might hope.
// See: http://mono.wikia.com/wiki/Detecting_the_execution_platform
// and https://msdn.microsoft.com/en-us/library/3a8hyw88(v=vs.110).aspx
const int PlatformMonoUnixValue = 128;
switch (Environment.OSVersion.Platform)
{
case PlatformID.Win32NT:
case PlatformID.Win32S:
case PlatformID.Win32Windows:
case PlatformID.WinCE:
fileName += ".exe";
break;
case PlatformID.MacOSX:
case PlatformID.Unix:
break;
// Don't handle the Xbox case. Let default handle it.
// case PlatformID.Xbox:
// break;
default:
if ((int)Environment.OSVersion.Platform == PlatformMonoUnixValue)
{
break;
}
throw new WebDriverException("Unsupported platform: " + Environment.OSVersion.Platform);
}
return fileName;
}
}
}
| |
using System;
using System.Data;
using System.Data.OleDb;
using PCSComUtils.Common;
using PCSComUtils.DataAccess;
using PCSComUtils.PCSExc;
namespace PCSComSale.Order.DS
{
public class SO_ConfirmShipDetailDS
{
private const string THIS = "PCSComSale.Order.DS.SO_ConfirmShipDetailDS";
public void Add(object pobjObjectVO)
{
const string METHOD_NAME = THIS + ".Add()";
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
SO_ConfirmShipDetailVO objObject = (SO_ConfirmShipDetailVO) pobjObjectVO;
string strSql = String.Empty;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand("", oconPCS);
strSql = "INSERT INTO SO_ConfirmShipDetail("
+ SO_ConfirmShipDetailTable.CONFIRMSHIPMASTERID_FLD + ","
+ SO_ConfirmShipDetailTable.SALEORDERDETAILID_FLD + ","
+ SO_ConfirmShipDetailTable.DELIVERYSCHEDULEID_FLD + ","
+ SO_ConfirmShipDetailTable.PRODUCTID_FLD + ")"
+ "VALUES(?,?,?,?)";
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ConfirmShipDetailTable.CONFIRMSHIPMASTERID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[SO_ConfirmShipDetailTable.CONFIRMSHIPMASTERID_FLD].Value = objObject.ConfirmShipMasterID;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ConfirmShipDetailTable.SALEORDERDETAILID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[SO_ConfirmShipDetailTable.SALEORDERDETAILID_FLD].Value = objObject.SaleOrderDetailID;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ConfirmShipDetailTable.DELIVERYSCHEDULEID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[SO_ConfirmShipDetailTable.DELIVERYSCHEDULEID_FLD].Value = objObject.DeliveryScheduleID;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ConfirmShipDetailTable.PRODUCTID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[SO_ConfirmShipDetailTable.PRODUCTID_FLD].Value = objObject.ProductID;
ocmdPCS.CommandText = strSql;
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
}
catch (OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
}
catch (InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS != null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
public void Delete(int pintID)
{
const string METHOD_NAME = THIS + ".Delete()";
string strSql = String.Empty;
strSql = "DELETE " + SO_ConfirmShipDetailTable.TABLE_NAME + " WHERE " + "ConfirmShipDetailID" + "=" + pintID.ToString();
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
ocmdPCS = null;
}
catch (OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE)
{
throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS != null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
public object GetObjectVO(int pintID)
{
const string METHOD_NAME = THIS + ".GetObjectVO()";
DataSet dstPCS = new DataSet();
OleDbDataReader odrPCS = null;
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql = "SELECT "
+ SO_ConfirmShipDetailTable.CONFIRMSHIPDETAILID_FLD + ","
+ SO_ConfirmShipDetailTable.CONFIRMSHIPMASTERID_FLD + ","
+ SO_ConfirmShipDetailTable.SALEORDERDETAILID_FLD + ","
+ SO_ConfirmShipDetailTable.DELIVERYSCHEDULEID_FLD + ","
+ SO_ConfirmShipDetailTable.PRODUCTID_FLD
+ " FROM " + SO_ConfirmShipDetailTable.TABLE_NAME
+ " WHERE " + SO_ConfirmShipDetailTable.CONFIRMSHIPDETAILID_FLD + "=" + pintID;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
odrPCS = ocmdPCS.ExecuteReader();
SO_ConfirmShipDetailVO objObject = new SO_ConfirmShipDetailVO();
while (odrPCS.Read())
{
objObject.ConfirmShipDetailID = int.Parse(odrPCS[SO_ConfirmShipDetailTable.CONFIRMSHIPDETAILID_FLD].ToString().Trim());
objObject.ConfirmShipMasterID = int.Parse(odrPCS[SO_ConfirmShipDetailTable.CONFIRMSHIPMASTERID_FLD].ToString().Trim());
objObject.SaleOrderDetailID = int.Parse(odrPCS[SO_ConfirmShipDetailTable.SALEORDERDETAILID_FLD].ToString().Trim());
objObject.DeliveryScheduleID = int.Parse(odrPCS[SO_ConfirmShipDetailTable.DELIVERYSCHEDULEID_FLD].ToString().Trim());
objObject.ProductID = int.Parse(odrPCS[SO_ConfirmShipDetailTable.PRODUCTID_FLD].ToString().Trim());
}
return objObject;
}
catch (OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS != null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
public void Update(object pobjObjecVO)
{
const string METHOD_NAME = THIS + ".Update()";
SO_ConfirmShipDetailVO objObject = (SO_ConfirmShipDetailVO) pobjObjecVO;
//prepare value for parameters
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
strSql = "UPDATE SO_ConfirmShipDetail SET "
+ SO_ConfirmShipDetailTable.CONFIRMSHIPMASTERID_FLD + "= ?" + ","
+ SO_ConfirmShipDetailTable.SALEORDERDETAILID_FLD + "= ?" + ","
+ SO_ConfirmShipDetailTable.DELIVERYSCHEDULEID_FLD + "= ?" + ","
+ SO_ConfirmShipDetailTable.PRODUCTID_FLD + "= ?"
+ " WHERE " + SO_ConfirmShipDetailTable.CONFIRMSHIPDETAILID_FLD + "= ?";
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ConfirmShipDetailTable.CONFIRMSHIPMASTERID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[SO_ConfirmShipDetailTable.CONFIRMSHIPMASTERID_FLD].Value = objObject.ConfirmShipMasterID;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ConfirmShipDetailTable.SALEORDERDETAILID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[SO_ConfirmShipDetailTable.SALEORDERDETAILID_FLD].Value = objObject.SaleOrderDetailID;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ConfirmShipDetailTable.DELIVERYSCHEDULEID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[SO_ConfirmShipDetailTable.DELIVERYSCHEDULEID_FLD].Value = objObject.DeliveryScheduleID;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ConfirmShipDetailTable.PRODUCTID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[SO_ConfirmShipDetailTable.PRODUCTID_FLD].Value = objObject.ProductID;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_ConfirmShipDetailTable.CONFIRMSHIPDETAILID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[SO_ConfirmShipDetailTable.CONFIRMSHIPDETAILID_FLD].Value = objObject.ConfirmShipDetailID;
ocmdPCS.CommandText = strSql;
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
}
catch (OleDbException ex)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
}
catch (InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS != null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
public DataSet List()
{
const string METHOD_NAME = THIS + ".List()";
DataSet dstPCS = new DataSet();
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql = "SELECT "
+ SO_ConfirmShipDetailTable.CONFIRMSHIPDETAILID_FLD + ","
+ SO_ConfirmShipDetailTable.CONFIRMSHIPMASTERID_FLD + ","
+ SO_ConfirmShipDetailTable.SALEORDERDETAILID_FLD + ","
+ SO_ConfirmShipDetailTable.DELIVERYSCHEDULEID_FLD + ","
+ SO_ConfirmShipDetailTable.PRODUCTID_FLD
+ " FROM " + SO_ConfirmShipDetailTable.TABLE_NAME;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dstPCS, SO_ConfirmShipDetailTable.TABLE_NAME);
return dstPCS;
}
catch (OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS != null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
public void UpdateDataSet(DataSet pData)
{
const string METHOD_NAME = THIS + ".UpdateDataSet()";
string strSql;
OleDbConnection oconPCS = null;
OleDbCommandBuilder odcbPCS;
OleDbDataAdapter odadPCS = new OleDbDataAdapter();
try
{
strSql = "SELECT "
+ SO_ConfirmShipDetailTable.CONFIRMSHIPDETAILID_FLD + ","
+ SO_ConfirmShipDetailTable.CONFIRMSHIPMASTERID_FLD + ","
+ SO_ConfirmShipDetailTable.SALEORDERDETAILID_FLD + ","
+ SO_ConfirmShipDetailTable.DELIVERYSCHEDULEID_FLD + ","
+ SO_ConfirmShipDetailTable.PRICE_FLD + ","
+ SO_ConfirmShipDetailTable.INVOICEQTY_FLD + ","
+ SO_ConfirmShipDetailTable.NETAMOUNT_FLD + ","
+ SO_ConfirmShipDetailTable.VATAMOUNT_FLD + ","
+ SO_ConfirmShipDetailTable.VATPERCENT_FLD + ","
+ SO_ConfirmShipDetailTable.PRODUCTID_FLD
+ " FROM " + SO_ConfirmShipDetailTable.TABLE_NAME;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
OleDbCommand cmdSelect = new OleDbCommand(strSql, oconPCS);
cmdSelect.CommandTimeout = 10000;
odadPCS.SelectCommand = cmdSelect;
odcbPCS = new OleDbCommandBuilder(odadPCS);
pData.EnforceConstraints = false;
odadPCS.Update(pData, SO_ConfirmShipDetailTable.TABLE_NAME);
}
catch (OleDbException ex)
{
if (ex.Errors.Count > 1)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
{
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
else if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE)
{
throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex);
}
else
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
}
}
catch (InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS != null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
public DataSet ListByMaster(int pintMasterID)
{
const string METHOD_NAME = THIS + ".List()";
DataSet dstPCS = new DataSet();
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql = "SELECT "
+ SO_ConfirmShipDetailTable.CONFIRMSHIPDETAILID_FLD + ","
+ SO_ConfirmShipDetailTable.CONFIRMSHIPMASTERID_FLD + ","
+ SO_ConfirmShipDetailTable.SALEORDERDETAILID_FLD + ","
+ SO_ConfirmShipDetailTable.DELIVERYSCHEDULEID_FLD + ","
+ SO_ConfirmShipDetailTable.PRICE_FLD + ","
+ SO_ConfirmShipDetailTable.INVOICEQTY_FLD + ","
+ SO_ConfirmShipDetailTable.NETAMOUNT_FLD + ","
+ SO_ConfirmShipDetailTable.VATPERCENT_FLD + ","
+ SO_ConfirmShipDetailTable.VATAMOUNT_FLD + ","
+ SO_ConfirmShipDetailTable.PRODUCTID_FLD
+ " FROM " + SO_ConfirmShipDetailTable.TABLE_NAME
+ " WHERE " + SO_ConfirmShipDetailTable.CONFIRMSHIPMASTERID_FLD + "=?";
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
ocmdPCS.Parameters.AddWithValue(SO_ConfirmShipDetailTable.CONFIRMSHIPMASTERID_FLD, pintMasterID);
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dstPCS, SO_ConfirmShipDetailTable.TABLE_NAME);
return dstPCS;
}
catch (OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS != null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
public DataSet ListForReview(int pintMasterID)
{
const string METHOD_NAME = THIS + ".ListForReview()";
DataSet dstPCS = new DataSet();
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
var strSql = " SELECT DISTINCT Bin.Code AS BCode, L.Code As LCode," +
" CA.Code ITM_CategoryCode, G.Code PartNo, G.Description, G.Revision,H.Code UMCode, " +
" C.SaleOrderDetailID, E.DeliveryScheduleID, G.ProductID, ISNULL(G.AllowNegativeQty,0) AllowNegativeQty," +
" E.ScheduleDate, GA.Code SO_GateCode, E.DeliveryQuantity AS CommittedQuantity," +
" A.InvoiceQty, A.InvoiceQty OldInvoiceQty, ISNULL(BC.OHQuantity,0) - ISNULL(BC.CommitQuantity,0) AvailableQty, " +
" A.Price, A.NetAmount,A.VATPercent, A.VATAmount, A.ConfirmShipMasterID ," +
" A.ConfirmShipDetailID, B.LocationID,B.BinID," +
" C.SellingUMID, C.SaleOrderMasterID,D.Code, C.SaleOrderLine, E.Line" +
" FROM SO_ConfirmShipDetail A INNER JOIN SO_ConfirmShipMaster B ON A.ConfirmShipMasterID = B.ConfirmShipMasterID" +
" INNER JOIN SO_SaleOrderDetail C ON C.SaleOrderDetailID = A.SaleOrderDetailID" +
" INNER JOIN SO_SaleOrderMaster D ON C.SaleOrderMasterID = D.SaleOrderMasterID" +
" INNER JOIN SO_DeliverySchedule E ON E.DeliveryScheduleID = A.DeliveryScheduleID" +
" LEFT JOIN SO_Gate GA ON E.GateID = GA.GateID" +
" INNER JOIN ITM_Product G ON C.ProductID = G.ProductID" +
" LEFT JOIN ITM_Category CA ON CA.CategoryID = G.CategoryID" +
" LEFT JOIN MST_Location L ON L.LocationID= B.LocationID " +
" LEFT JOIN MST_BIN Bin ON Bin.BinID = B.BinID " +
" LEFT JOIN IV_BinCache BC ON B.BinID = BC.BinID" +
" AND BC.ProductID = G.ProductID" +
" INNER JOIN MST_UnitOfMeasure H ON C.SellingUMID = H.UnitOfMeasureID " +
" WHERE B.ConfirmShipMasterID = ?";
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
ocmdPCS.Parameters.AddWithValue(SO_ConfirmShipDetailTable.CONFIRMSHIPMASTERID_FLD, pintMasterID);
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dstPCS, SO_ConfirmShipDetailTable.TABLE_NAME);
return dstPCS;
}
catch (OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS != null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
}
}
| |
//
// SQLinfo - (C) 2015 Patrick Lambert - http://dendory.net
//
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Management;
using System.Data.SqlClient;
using System.Data;
[assembly: AssemblyTitle("SQLinfo")]
[assembly: AssemblyCopyright("(C) 2015 Patrick Lambert")]
[assembly: AssemblyFileVersion("0.1.0.0")]
namespace SQLinfo
{
public class Program
{
static void Main(string[] args)
{
string server = "127.0.0.1";
string dbname = "master";
string userid = "sa";
string passwd = "";
string tmp = "";
Int32 timeout = 10;
SqlDataReader res;
SqlCommand sql;
SqlConnection con;
// Parse parameters
for(int i=0; i < args.Length; i++)
{
switch(args[i].ToLower())
{
case "-s":
server = args[++i];
break;
case "-d":
dbname = args[++i];
break;
case "-u":
userid = args[++i];
break;
case "-p":
passwd = args[++i];
break;
case "-t":
timeout = Int32.Parse(args[++i]);
break;
case "-h":
Console.WriteLine("* Usage:\n\t sqlinfo -s <server> -d <database> -u <username> -p <password> -t <timeout>\n");
Environment.Exit(0);
break;
default:
Console.WriteLine("* Unknown option: " + args[i] + ". Try sqlinfo -h for help.");
break;
}
}
// Connect to database server
Console.WriteLine("* Connecting to [" + server.ToUpper() + ":" + dbname + "]");
con = new SqlConnection("Server=" + server + "; Database=" + dbname + "; User Id=" + userid + "; Password=" + passwd + "; connection timeout=" + timeout);
try
{
con.Open();
}
catch(Exception e)
{
Console.WriteLine("Error connecting to server: " + e.Message);
Environment.Exit(1);
}
// server version
Console.Write("\n* Server version:\n");
try
{
sql = new SqlCommand();
sql.Connection = con;
sql.CommandType = CommandType.Text;
sql.CommandText = "SELECT @@version";
res = sql.ExecuteReader();
while(res.Read())
{
Console.WriteLine(res[0]);
}
res.Close();
}
catch(Exception e)
{
Console.WriteLine("Error querying server: " + e.Message);
}
// List databases
Console.WriteLine("\n* Server database names:");
try
{
sql = new SqlCommand();
sql.Connection = con;
sql.CommandType = CommandType.StoredProcedure;
sql.CommandText = "sp_databases";
res = sql.ExecuteReader();
while(res.Read())
{
Console.Write(res.GetString(0) + " ");
}
Console.Write("\n");
res.Close();
}
catch(Exception e)
{
Console.WriteLine("Error querying server: " + e.Message);
}
// List logins
Console.Write("\n* Server logins:\n");
try
{
sql = new SqlCommand();
sql.Connection = con;
sql.CommandType = CommandType.Text;
sql.CommandText = "SELECT name,type,default_database_name FROM sys.server_principals";
res = sql.ExecuteReader();
Console.WriteLine(String.Format("{0,-44} {1,-8} {2,-20}", "Login name", "Type", "Default database"));
Console.WriteLine(String.Format("{0,-44} {1,-8} {2,-20}", "----------", "----", "----------------"));
while(res.Read())
{
switch(res[1].ToString())
{
case "S":
tmp = "SQL";
break;
case "U":
tmp = "Windows";
break;
case "G":
tmp = "Group";
break;
case "R":
tmp = "Role";
break;
default:
tmp = "Mapped";
break;
}
Console.WriteLine(String.Format("{0,-44} {1,-8} {2,-20}", res[0], tmp, res[2]));
}
res.Close();
}
catch(Exception e)
{
Console.WriteLine("Error querying server: " + e.Message);
}
// Log info
Console.Write("\n* Transaction logs size:\n");
try
{
sql = new SqlCommand();
sql.Connection = con;
sql.CommandType = CommandType.Text;
sql.CommandText = "DBCC SQLPERF(logspace)";
res = sql.ExecuteReader();
Console.WriteLine(String.Format("{0,-20} {1,-15} {2,-16}", "Database name", "Log size (MB)", "Space used (%)"));
Console.WriteLine(String.Format("{0,-20} {1,-15} {2,-16}", "-------------", "-------------", "--------------"));
while(res.Read())
{
Console.WriteLine(String.Format("{0,-20} {1,-15} {2,-16}", res[0], res[1], res[2]));
}
res.Close();
}
catch(Exception e)
{
Console.WriteLine("Error querying server: " + e.Message);
}
// db files
Console.Write("\n* Database files:\n");
try
{
sql = new SqlCommand();
sql.Connection = con;
sql.CommandType = CommandType.Text;
sql.CommandText = "SELECT name,type_desc,physical_name FROM sys.database_files";
res = sql.ExecuteReader();
Console.WriteLine(String.Format("{0,-20} {1,-6} {2,-30}", "Name", "Type", "Physical path"));
Console.WriteLine(String.Format("{0,-20} {1,-6} {2,-30}", "----", "----", "-------------"));
while(res.Read())
{
Console.WriteLine(String.Format("{0,-20} {1,-6} {2,-30}", res[0], res[1], res[2]));
}
res.Close();
}
catch(Exception e)
{
Console.WriteLine("Error querying server: " + e.Message);
}
// db tables
Console.Write("\n* Database tables:\n");
try
{
sql = new SqlCommand();
sql.Connection = con;
sql.CommandType = CommandType.Text;
sql.CommandText = "SELECT sobjects.name FROM sysobjects sobjects WHERE sobjects.xtype = 'U' ORDER BY name";
res = sql.ExecuteReader();
while(res.Read())
{
Console.Write(res[0] + " ");
}
Console.Write("\n");
res.Close();
}
catch(Exception e)
{
Console.WriteLine("Error querying server: " + e.Message);
}
// Close connection
con.Close();
}
}
}
| |
/*
* 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.
*/
// ReSharper disable UnassignedField.Global
// ReSharper disable CollectionNeverUpdated.Global
// ReSharper disable UnusedAutoPropertyAccessor.Global
namespace Apache.Ignite.Core.Tests.Binary
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Impl;
using Apache.Ignite.Core.Impl.Binary;
using NUnit.Framework;
/// <summary>
/// Binary builder self test.
/// </summary>
public class BinaryBuilderSelfTest
{
/** Undefined type: Empty. */
private const string TypeEmpty = "EmptyUndefined";
/** Grid. */
private Ignite _grid;
/** Marshaller. */
private Marshaller _marsh;
/// <summary>
/// Set up routine.
/// </summary>
[TestFixtureSetUp]
public void SetUp()
{
TestUtils.KillProcesses();
var cfg = new IgniteConfiguration(TestUtils.GetTestConfiguration())
{
BinaryConfiguration = new BinaryConfiguration
{
TypeConfigurations = new List<BinaryTypeConfiguration>
{
new BinaryTypeConfiguration(typeof(Empty)) {EqualityComparer = GetIdentityResolver()},
new BinaryTypeConfiguration(typeof(Primitives)) {EqualityComparer = GetIdentityResolver()},
new BinaryTypeConfiguration(typeof(PrimitiveArrays)) {EqualityComparer = GetIdentityResolver()},
new BinaryTypeConfiguration(typeof(StringDateGuidEnum))
{
EqualityComparer = GetIdentityResolver()
},
new BinaryTypeConfiguration(typeof(WithRaw)) {EqualityComparer = GetIdentityResolver()},
new BinaryTypeConfiguration(typeof(MetaOverwrite)) {EqualityComparer = GetIdentityResolver()},
new BinaryTypeConfiguration(typeof(NestedOuter)) {EqualityComparer = GetIdentityResolver()},
new BinaryTypeConfiguration(typeof(NestedInner)) {EqualityComparer = GetIdentityResolver()},
new BinaryTypeConfiguration(typeof(MigrationOuter)) {EqualityComparer = GetIdentityResolver()},
new BinaryTypeConfiguration(typeof(MigrationInner)) {EqualityComparer = GetIdentityResolver()},
new BinaryTypeConfiguration(typeof(InversionOuter)) {EqualityComparer = GetIdentityResolver()},
new BinaryTypeConfiguration(typeof(InversionInner)) {EqualityComparer = GetIdentityResolver()},
new BinaryTypeConfiguration(typeof(CompositeOuter)) {EqualityComparer = GetIdentityResolver()},
new BinaryTypeConfiguration(typeof(CompositeInner)) {EqualityComparer = GetIdentityResolver()},
new BinaryTypeConfiguration(typeof(CompositeArray)) {EqualityComparer = GetIdentityResolver()},
new BinaryTypeConfiguration(typeof(CompositeContainer))
{
EqualityComparer = GetIdentityResolver()
},
new BinaryTypeConfiguration(typeof(ToBinary)) {EqualityComparer = GetIdentityResolver()},
new BinaryTypeConfiguration(typeof(Remove)) {EqualityComparer = GetIdentityResolver()},
new BinaryTypeConfiguration(typeof(RemoveInner)) {EqualityComparer = GetIdentityResolver()},
new BinaryTypeConfiguration(typeof(BuilderInBuilderOuter))
{
EqualityComparer = GetIdentityResolver()
},
new BinaryTypeConfiguration(typeof(BuilderInBuilderInner))
{
EqualityComparer = GetIdentityResolver()
},
new BinaryTypeConfiguration(typeof(BuilderCollection))
{
EqualityComparer = GetIdentityResolver()
},
new BinaryTypeConfiguration(typeof(BuilderCollectionItem))
{
EqualityComparer = GetIdentityResolver()
},
new BinaryTypeConfiguration(typeof(DecimalHolder)) {EqualityComparer = GetIdentityResolver()},
new BinaryTypeConfiguration(TypeEmpty) {EqualityComparer = GetIdentityResolver()},
new BinaryTypeConfiguration(typeof(TestEnumRegistered))
{
EqualityComparer = GetIdentityResolver()
},
new BinaryTypeConfiguration(typeof(NameMapperTestType))
{
EqualityComparer = GetIdentityResolver()
}
},
DefaultIdMapper = new IdMapper(),
DefaultNameMapper = new NameMapper(),
CompactFooter = GetCompactFooter()
}
};
_grid = (Ignite) Ignition.Start(cfg);
_marsh = _grid.Marshaller;
}
/// <summary>
/// Gets the compact footer setting.
/// </summary>
protected virtual bool GetCompactFooter()
{
return true;
}
/// <summary>
/// Gets the identity resolver.
/// </summary>
protected virtual IEqualityComparer<IBinaryObject> GetIdentityResolver()
{
return null;
}
/// <summary>
/// Tear down routine.
/// </summary>
[TestFixtureTearDown]
public void TearDown()
{
if (_grid != null)
Ignition.Stop(_grid.Name, true);
_grid = null;
}
/// <summary>
/// Ensure that binary engine is able to work with type names, which are not configured.
/// </summary>
[Test]
public void TestNonConfigured()
{
string typeName1 = "Type1";
string typeName2 = "Type2";
string field1 = "field1";
string field2 = "field2";
// 1. Ensure that builder works fine.
IBinaryObject binObj1 = _grid.GetBinary().GetBuilder(typeName1).SetField(field1, 1).Build();
Assert.AreEqual(typeName1, binObj1.GetBinaryType().TypeName);
Assert.AreEqual(1, binObj1.GetBinaryType().Fields.Count);
Assert.AreEqual(field1, binObj1.GetBinaryType().Fields.First());
Assert.AreEqual(BinaryTypeNames.TypeNameInt, binObj1.GetBinaryType().GetFieldTypeName(field1));
Assert.AreEqual(1, binObj1.GetField<int>(field1));
// 2. Ensure that object can be unmarshalled without deserialization.
byte[] data = ((BinaryObject) binObj1).Data;
binObj1 = _grid.Marshaller.Unmarshal<IBinaryObject>(data, BinaryMode.ForceBinary);
Assert.AreEqual(typeName1, binObj1.GetBinaryType().TypeName);
Assert.AreEqual(1, binObj1.GetBinaryType().Fields.Count);
Assert.AreEqual(field1, binObj1.GetBinaryType().Fields.First());
Assert.AreEqual(BinaryTypeNames.TypeNameInt, binObj1.GetBinaryType().GetFieldTypeName(field1));
Assert.AreEqual(1, binObj1.GetField<int>(field1));
// 3. Ensure that we can nest one anonymous object inside another
IBinaryObject binObj2 =
_grid.GetBinary().GetBuilder(typeName2).SetField(field2, binObj1).Build();
Assert.AreEqual(typeName2, binObj2.GetBinaryType().TypeName);
Assert.AreEqual(1, binObj2.GetBinaryType().Fields.Count);
Assert.AreEqual(field2, binObj2.GetBinaryType().Fields.First());
Assert.AreEqual(BinaryTypeNames.TypeNameObject, binObj2.GetBinaryType().GetFieldTypeName(field2));
binObj1 = binObj2.GetField<IBinaryObject>(field2);
Assert.AreEqual(typeName1, binObj1.GetBinaryType().TypeName);
Assert.AreEqual(1, binObj1.GetBinaryType().Fields.Count);
Assert.AreEqual(field1, binObj1.GetBinaryType().Fields.First());
Assert.AreEqual(BinaryTypeNames.TypeNameInt, binObj1.GetBinaryType().GetFieldTypeName(field1));
Assert.AreEqual(1, binObj1.GetField<int>(field1));
// 4. Ensure that we can unmarshal object with other nested object.
data = ((BinaryObject) binObj2).Data;
binObj2 = _grid.Marshaller.Unmarshal<IBinaryObject>(data, BinaryMode.ForceBinary);
Assert.AreEqual(typeName2, binObj2.GetBinaryType().TypeName);
Assert.AreEqual(1, binObj2.GetBinaryType().Fields.Count);
Assert.AreEqual(field2, binObj2.GetBinaryType().Fields.First());
Assert.AreEqual(BinaryTypeNames.TypeNameObject, binObj2.GetBinaryType().GetFieldTypeName(field2));
binObj1 = binObj2.GetField<IBinaryObject>(field2);
Assert.AreEqual(typeName1, binObj1.GetBinaryType().TypeName);
Assert.AreEqual(1, binObj1.GetBinaryType().Fields.Count);
Assert.AreEqual(field1, binObj1.GetBinaryType().Fields.First());
Assert.AreEqual(BinaryTypeNames.TypeNameInt, binObj1.GetBinaryType().GetFieldTypeName(field1));
Assert.AreEqual(1, binObj1.GetField<int>(field1));
}
/// <summary>
/// Test "ToBinary()" method.
/// </summary>
[Test]
public void TestToBinary()
{
DateTime date = DateTime.Now.ToUniversalTime();
Guid guid = Guid.NewGuid();
IBinary api = _grid.GetBinary();
// 1. Primitives.
Assert.AreEqual(1, api.ToBinary<byte>((byte)1));
Assert.AreEqual(1, api.ToBinary<short>((short)1));
Assert.AreEqual(1, api.ToBinary<int>(1));
Assert.AreEqual(1, api.ToBinary<long>((long)1));
Assert.AreEqual((float)1, api.ToBinary<float>((float)1));
Assert.AreEqual((double)1, api.ToBinary<double>((double)1));
Assert.AreEqual(true, api.ToBinary<bool>(true));
Assert.AreEqual('a', api.ToBinary<char>('a'));
// 2. Special types.
Assert.AreEqual("a", api.ToBinary<string>("a"));
Assert.AreEqual(date, api.ToBinary<DateTime>(date));
Assert.AreEqual(guid, api.ToBinary<Guid>(guid));
Assert.AreEqual(TestEnumRegistered.One, api.ToBinary<IBinaryObject>(TestEnumRegistered.One)
.Deserialize<TestEnumRegistered>());
// 3. Arrays.
Assert.AreEqual(new byte[] { 1 }, api.ToBinary<byte[]>(new byte[] { 1 }));
Assert.AreEqual(new short[] { 1 }, api.ToBinary<short[]>(new short[] { 1 }));
Assert.AreEqual(new[] { 1 }, api.ToBinary<int[]>(new[] { 1 }));
Assert.AreEqual(new long[] { 1 }, api.ToBinary<long[]>(new long[] { 1 }));
Assert.AreEqual(new float[] { 1 }, api.ToBinary<float[]>(new float[] { 1 }));
Assert.AreEqual(new double[] { 1 }, api.ToBinary<double[]>(new double[] { 1 }));
Assert.AreEqual(new[] { true }, api.ToBinary<bool[]>(new[] { true }));
Assert.AreEqual(new[] { 'a' }, api.ToBinary<char[]>(new[] { 'a' }));
Assert.AreEqual(new[] { "a" }, api.ToBinary<string[]>(new[] { "a" }));
Assert.AreEqual(new[] { date }, api.ToBinary<DateTime[]>(new[] { date }));
Assert.AreEqual(new[] { guid }, api.ToBinary<Guid[]>(new[] { guid }));
Assert.AreEqual(new[] { TestEnumRegistered.One},
api.ToBinary<IBinaryObject[]>(new[] { TestEnumRegistered.One})
.Select(x => x.Deserialize<TestEnumRegistered>()).ToArray());
// 4. Objects.
IBinaryObject binObj = api.ToBinary<IBinaryObject>(new ToBinary(1));
Assert.AreEqual(typeof(ToBinary).Name, binObj.GetBinaryType().TypeName);
Assert.AreEqual(1, binObj.GetBinaryType().Fields.Count);
Assert.AreEqual("Val", binObj.GetBinaryType().Fields.First());
Assert.AreEqual(BinaryTypeNames.TypeNameInt, binObj.GetBinaryType().GetFieldTypeName("Val"));
Assert.AreEqual(1, binObj.GetField<int>("val"));
Assert.AreEqual(1, binObj.Deserialize<ToBinary>().Val);
// 5. Object array.
var binObjArr = api.ToBinary<object[]>(new object[] {new ToBinary(1)})
.OfType<IBinaryObject>().ToArray();
Assert.AreEqual(1, binObjArr.Length);
Assert.AreEqual(1, binObjArr[0].GetField<int>("Val"));
Assert.AreEqual(1, binObjArr[0].Deserialize<ToBinary>().Val);
}
/// <summary>
/// Test builder field remove logic.
/// </summary>
[Test]
public void TestRemove()
{
// Create empty object.
IBinaryObject binObj = _grid.GetBinary().GetBuilder(typeof(Remove)).Build();
Assert.IsNull(binObj.GetField<object>("val"));
Assert.IsNull(binObj.Deserialize<Remove>().Val);
IBinaryType meta = binObj.GetBinaryType();
Assert.AreEqual(typeof(Remove).Name, meta.TypeName);
Assert.AreEqual(0, meta.Fields.Count);
// Populate it with field.
IBinaryObjectBuilder builder = binObj.ToBuilder();
Assert.IsNull(builder.GetField<object>("val"));
object val = 1;
builder.SetField("val", val);
Assert.AreEqual(val, builder.GetField<object>("val"));
binObj = builder.Build();
Assert.AreEqual(val, binObj.GetField<object>("val"));
Assert.AreEqual(val, binObj.Deserialize<Remove>().Val);
meta = binObj.GetBinaryType();
Assert.AreEqual(typeof(Remove).Name, meta.TypeName);
Assert.AreEqual(1, meta.Fields.Count);
Assert.AreEqual("val", meta.Fields.First());
Assert.AreEqual(BinaryTypeNames.TypeNameObject, meta.GetFieldTypeName("val"));
// Perform field remove.
builder = binObj.ToBuilder();
Assert.AreEqual(val, builder.GetField<object>("val"));
builder.RemoveField("val");
Assert.IsNull(builder.GetField<object>("val"));
builder.SetField("val", val);
Assert.AreEqual(val, builder.GetField<object>("val"));
builder.RemoveField("val");
Assert.IsNull(builder.GetField<object>("val"));
binObj = builder.Build();
Assert.IsNull(binObj.GetField<object>("val"));
Assert.IsNull(binObj.Deserialize<Remove>().Val);
// Test correct removal of field being referenced by handle somewhere else.
RemoveInner inner = new RemoveInner(2);
binObj = _grid.GetBinary().GetBuilder(typeof(Remove))
.SetField("val", inner)
.SetField("val2", inner)
.Build();
binObj = binObj.ToBuilder().RemoveField("val").Build();
Remove obj = binObj.Deserialize<Remove>();
Assert.IsNull(obj.Val);
Assert.AreEqual(2, obj.Val2.Val);
}
/// <summary>
/// Test builder-in-builder scenario.
/// </summary>
[Test]
public void TestBuilderInBuilder()
{
// Test different builders assembly.
IBinaryObjectBuilder builderOuter = _grid.GetBinary().GetBuilder(typeof(BuilderInBuilderOuter));
IBinaryObjectBuilder builderInner = _grid.GetBinary().GetBuilder(typeof(BuilderInBuilderInner));
builderOuter.SetField<object>("inner", builderInner);
builderInner.SetField<object>("outer", builderOuter);
IBinaryObject outerbinObj = builderOuter.Build();
IBinaryType meta = outerbinObj.GetBinaryType();
Assert.AreEqual(typeof(BuilderInBuilderOuter).Name, meta.TypeName);
Assert.AreEqual(1, meta.Fields.Count);
Assert.AreEqual("inner", meta.Fields.First());
Assert.AreEqual(BinaryTypeNames.TypeNameObject, meta.GetFieldTypeName("inner"));
IBinaryObject innerbinObj = outerbinObj.GetField<IBinaryObject>("inner");
meta = innerbinObj.GetBinaryType();
Assert.AreEqual(typeof(BuilderInBuilderInner).Name, meta.TypeName);
Assert.AreEqual(1, meta.Fields.Count);
Assert.AreEqual("outer", meta.Fields.First());
Assert.AreEqual(BinaryTypeNames.TypeNameObject, meta.GetFieldTypeName("outer"));
BuilderInBuilderOuter outer = outerbinObj.Deserialize<BuilderInBuilderOuter>();
Assert.AreSame(outer, outer.Inner.Outer);
// Test same builders assembly.
innerbinObj = _grid.GetBinary().GetBuilder(typeof(BuilderInBuilderInner)).Build();
outerbinObj = _grid.GetBinary().GetBuilder(typeof(BuilderInBuilderOuter))
.SetField("inner", innerbinObj)
.SetField("inner2", innerbinObj)
.Build();
meta = outerbinObj.GetBinaryType();
Assert.AreEqual(typeof(BuilderInBuilderOuter).Name, meta.TypeName);
Assert.AreEqual(2, meta.Fields.Count);
Assert.IsTrue(meta.Fields.Contains("inner"));
Assert.IsTrue(meta.Fields.Contains("inner2"));
Assert.AreEqual(BinaryTypeNames.TypeNameObject, meta.GetFieldTypeName("inner"));
Assert.AreEqual(BinaryTypeNames.TypeNameObject, meta.GetFieldTypeName("inner2"));
outer = outerbinObj.Deserialize<BuilderInBuilderOuter>();
Assert.AreSame(outer.Inner, outer.Inner2);
builderOuter = _grid.GetBinary().GetBuilder(outerbinObj);
IBinaryObjectBuilder builderInner2 = builderOuter.GetField<IBinaryObjectBuilder>("inner2");
builderInner2.SetField("outer", builderOuter);
outerbinObj = builderOuter.Build();
outer = outerbinObj.Deserialize<BuilderInBuilderOuter>();
Assert.AreSame(outer, outer.Inner.Outer);
Assert.AreSame(outer.Inner, outer.Inner2);
}
/// <summary>
/// Test for decimals building.
/// </summary>
[Test]
public void TestDecimals()
{
IBinaryObject binObj = _grid.GetBinary().GetBuilder(typeof(DecimalHolder))
.SetField("val", decimal.One)
.SetField("valArr", new decimal?[] { decimal.MinusOne })
.Build();
IBinaryType meta = binObj.GetBinaryType();
Assert.AreEqual(typeof(DecimalHolder).Name, meta.TypeName);
Assert.AreEqual(2, meta.Fields.Count);
Assert.IsTrue(meta.Fields.Contains("val"));
Assert.IsTrue(meta.Fields.Contains("valArr"));
Assert.AreEqual(BinaryTypeNames.TypeNameDecimal, meta.GetFieldTypeName("val"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayDecimal, meta.GetFieldTypeName("valArr"));
Assert.AreEqual(decimal.One, binObj.GetField<decimal>("val"));
Assert.AreEqual(new decimal?[] { decimal.MinusOne }, binObj.GetField<decimal?[]>("valArr"));
DecimalHolder obj = binObj.Deserialize<DecimalHolder>();
Assert.AreEqual(decimal.One, obj.Val);
Assert.AreEqual(new decimal?[] { decimal.MinusOne }, obj.ValArr);
}
/// <summary>
/// Test for an object returning collection of builders.
/// </summary>
[Test]
public void TestBuilderCollection()
{
// Test collection with single element.
IBinaryObjectBuilder builderCol = _grid.GetBinary().GetBuilder(typeof(BuilderCollection));
IBinaryObjectBuilder builderItem =
_grid.GetBinary().GetBuilder(typeof(BuilderCollectionItem)).SetField("val", 1);
builderCol.SetCollectionField("col", new ArrayList { builderItem });
IBinaryObject binCol = builderCol.Build();
IBinaryType meta = binCol.GetBinaryType();
Assert.AreEqual(typeof(BuilderCollection).Name, meta.TypeName);
Assert.AreEqual(1, meta.Fields.Count);
Assert.AreEqual("col", meta.Fields.First());
Assert.AreEqual(BinaryTypeNames.TypeNameCollection, meta.GetFieldTypeName("col"));
var binColItems = binCol.GetField<ArrayList>("col");
Assert.AreEqual(1, binColItems.Count);
var binItem = (IBinaryObject) binColItems[0];
meta = binItem.GetBinaryType();
Assert.AreEqual(typeof(BuilderCollectionItem).Name, meta.TypeName);
Assert.AreEqual(1, meta.Fields.Count);
Assert.AreEqual("val", meta.Fields.First());
Assert.AreEqual(BinaryTypeNames.TypeNameInt, meta.GetFieldTypeName("val"));
BuilderCollection col = binCol.Deserialize<BuilderCollection>();
Assert.IsNotNull(col.Col);
Assert.AreEqual(1, col.Col.Count);
Assert.AreEqual(1, ((BuilderCollectionItem) col.Col[0]).Val);
// Add more binary objects to collection.
builderCol = _grid.GetBinary().GetBuilder(binCol);
IList builderColItems = builderCol.GetField<IList>("col");
Assert.AreEqual(1, builderColItems.Count);
BinaryObjectBuilder builderColItem = (BinaryObjectBuilder) builderColItems[0];
builderColItem.SetField("val", 2); // Change nested value.
builderColItems.Add(builderColItem); // Add the same object to check handles.
builderColItems.Add(builderItem); // Add item from another builder.
builderColItems.Add(binItem); // Add item in binary form.
binCol = builderCol.Build();
col = binCol.Deserialize<BuilderCollection>();
Assert.AreEqual(4, col.Col.Count);
var item0 = (BuilderCollectionItem) col.Col[0];
var item1 = (BuilderCollectionItem) col.Col[1];
var item2 = (BuilderCollectionItem) col.Col[2];
var item3 = (BuilderCollectionItem) col.Col[3];
Assert.AreEqual(2, item0.Val);
Assert.AreSame(item0, item1);
Assert.AreNotSame(item0, item2);
Assert.AreNotSame(item0, item3);
Assert.AreEqual(1, item2.Val);
Assert.AreEqual(1, item3.Val);
Assert.AreNotSame(item2, item3);
// Test handle update inside collection.
builderCol = _grid.GetBinary().GetBuilder(binCol);
builderColItems = builderCol.GetField<IList>("col");
((BinaryObjectBuilder) builderColItems[1]).SetField("val", 3);
binCol = builderCol.Build();
col = binCol.Deserialize<BuilderCollection>();
item0 = (BuilderCollectionItem) col.Col[0];
item1 = (BuilderCollectionItem) col.Col[1];
Assert.AreEqual(3, item0.Val);
Assert.AreSame(item0, item1);
}
/// <summary>
/// Test build of an empty object.
/// </summary>
[Test]
public void TestEmptyDefined()
{
IBinaryObject binObj = _grid.GetBinary().GetBuilder(typeof(Empty)).Build();
Assert.IsNotNull(binObj);
Assert.AreEqual(GetIdentityResolver() == null ? 0 : 1, binObj.GetHashCode());
IBinaryType meta = binObj.GetBinaryType();
Assert.IsNotNull(meta);
Assert.AreEqual(typeof(Empty).Name, meta.TypeName);
Assert.AreEqual(0, meta.Fields.Count);
Empty obj = binObj.Deserialize<Empty>();
Assert.IsNotNull(obj);
}
/// <summary>
/// Test build of an empty undefined object.
/// </summary>
[Test]
public void TestEmptyUndefined()
{
IBinaryObject binObj = _grid.GetBinary().GetBuilder(TypeEmpty).Build();
Assert.IsNotNull(binObj);
Assert.AreEqual(GetIdentityResolver() == null ? 0 : 1, binObj.GetHashCode());
IBinaryType meta = binObj.GetBinaryType();
Assert.IsNotNull(meta);
Assert.AreEqual(TypeEmpty, meta.TypeName);
Assert.AreEqual(0, meta.Fields.Count);
}
/// <summary>
/// Test object rebuild with no changes.
/// </summary>
[Test]
public void TestEmptyRebuild()
{
var binObj = (BinaryObject) _grid.GetBinary().GetBuilder(typeof(Empty)).Build();
BinaryObject newbinObj = (BinaryObject) _grid.GetBinary().GetBuilder(binObj).Build();
Assert.AreEqual(binObj.Data, newbinObj.Data);
}
/// <summary>
/// Test hash code alteration.
/// </summary>
[Test]
public void TestHashCodeChange()
{
IBinaryObject binObj = _grid.GetBinary().GetBuilder(typeof(Empty)).SetHashCode(100).Build();
Assert.AreEqual(100, binObj.GetHashCode());
}
/// <summary>
/// Tests equality and formatting members.
/// </summary>
[Test]
public void TestEquality()
{
var bin = _grid.GetBinary();
var obj1 = bin.GetBuilder("myType").SetStringField("str", "foo").SetIntField("int", 1).Build();
var obj2 = bin.GetBuilder("myType").SetStringField("str", "foo").SetIntField("int", 1).Build();
Assert.AreEqual(obj1, obj2);
Assert.AreEqual(0, obj1.GetHashCode());
Assert.AreEqual(0, obj2.GetHashCode());
Assert.IsTrue(Regex.IsMatch(obj1.ToString(), @"myType \[idHash=[0-9]+, str=foo, int=1\]"));
}
/// <summary>
/// Test primitive fields setting.
/// </summary>
[Test]
public void TestPrimitiveFields()
{
// Generic SetField method.
var binObj = _grid.GetBinary().GetBuilder(typeof(Primitives))
.SetField<byte>("fByte", 1)
.SetField("fBool", true)
.SetField<short>("fShort", 2)
.SetField("fChar", 'a')
.SetField("fInt", 3)
.SetField<long>("fLong", 4)
.SetField<float>("fFloat", 5)
.SetField<double>("fDouble", 6)
.SetField("fDecimal", 7.7m)
.SetHashCode(100)
.Build();
CheckPrimitiveFields1(binObj);
// Specific setter methods.
var binObj2 = _grid.GetBinary().GetBuilder(typeof(Primitives))
.SetByteField("fByte", 1)
.SetBooleanField("fBool", true)
.SetShortField("fShort", 2)
.SetCharField("fChar", 'a')
.SetIntField("fInt", 3)
.SetLongField("fLong", 4)
.SetFloatField("fFloat", 5)
.SetDoubleField("fDouble", 6)
.SetDecimalField("fDecimal", 7.7m)
.SetHashCode(100)
.Build();
CheckPrimitiveFields1(binObj2);
// Check equality.
Assert.AreEqual(binObj, binObj2);
Assert.AreEqual(binObj.GetHashCode(), binObj2.GetHashCode());
// Overwrite with generic methods.
binObj = binObj.ToBuilder()
.SetField<byte>("fByte", 7)
.SetField("fBool", false)
.SetField<short>("fShort", 8)
.SetField("fChar", 'b')
.SetField("fInt", 9)
.SetField<long>("fLong", 10)
.SetField<float>("fFloat", 11)
.SetField<double>("fDouble", 12)
.SetField("fDecimal", 13.13m)
.Build();
CheckPrimitiveFields2(binObj);
// Overwrite with specific methods.
binObj2 = binObj.ToBuilder()
.SetByteField("fByte", 7)
.SetBooleanField("fBool", false)
.SetShortField("fShort", 8)
.SetCharField("fChar", 'b')
.SetIntField("fInt", 9)
.SetLongField("fLong", 10)
.SetFloatField("fFloat", 11)
.SetDoubleField("fDouble", 12)
.SetDecimalField("fDecimal", 13.13m)
.Build();
CheckPrimitiveFields2(binObj);
// Check equality.
Assert.AreEqual(binObj, binObj2);
Assert.AreEqual(binObj.GetHashCode(), binObj2.GetHashCode());
}
/// <summary>
/// Checks the primitive fields values.
/// </summary>
private static void CheckPrimitiveFields1(IBinaryObject binObj)
{
Assert.AreEqual(100, binObj.GetHashCode());
IBinaryType meta = binObj.GetBinaryType();
Assert.AreEqual(typeof(Primitives).Name, meta.TypeName);
Assert.AreEqual(9, meta.Fields.Count);
Assert.AreEqual(BinaryTypeNames.TypeNameByte, meta.GetFieldTypeName("fByte"));
Assert.AreEqual(BinaryTypeNames.TypeNameBool, meta.GetFieldTypeName("fBool"));
Assert.AreEqual(BinaryTypeNames.TypeNameShort, meta.GetFieldTypeName("fShort"));
Assert.AreEqual(BinaryTypeNames.TypeNameChar, meta.GetFieldTypeName("fChar"));
Assert.AreEqual(BinaryTypeNames.TypeNameInt, meta.GetFieldTypeName("fInt"));
Assert.AreEqual(BinaryTypeNames.TypeNameLong, meta.GetFieldTypeName("fLong"));
Assert.AreEqual(BinaryTypeNames.TypeNameFloat, meta.GetFieldTypeName("fFloat"));
Assert.AreEqual(BinaryTypeNames.TypeNameDouble, meta.GetFieldTypeName("fDouble"));
Assert.AreEqual(BinaryTypeNames.TypeNameDecimal, meta.GetFieldTypeName("fDecimal"));
Assert.AreEqual(1, binObj.GetField<byte>("fByte"));
Assert.AreEqual(true, binObj.GetField<bool>("fBool"));
Assert.AreEqual(2, binObj.GetField<short>("fShort"));
Assert.AreEqual('a', binObj.GetField<char>("fChar"));
Assert.AreEqual(3, binObj.GetField<int>("fInt"));
Assert.AreEqual(4, binObj.GetField<long>("fLong"));
Assert.AreEqual(5, binObj.GetField<float>("fFloat"));
Assert.AreEqual(6, binObj.GetField<double>("fDouble"));
Assert.AreEqual(7.7m, binObj.GetField<decimal>("fDecimal"));
Primitives obj = binObj.Deserialize<Primitives>();
Assert.AreEqual(1, obj.FByte);
Assert.AreEqual(true, obj.FBool);
Assert.AreEqual(2, obj.FShort);
Assert.AreEqual('a', obj.FChar);
Assert.AreEqual(3, obj.FInt);
Assert.AreEqual(4, obj.FLong);
Assert.AreEqual(5, obj.FFloat);
Assert.AreEqual(6, obj.FDouble);
Assert.AreEqual(7.7m, obj.FDecimal);
}
/// <summary>
/// Checks the primitive fields values.
/// </summary>
private static void CheckPrimitiveFields2(IBinaryObject binObj)
{
Assert.AreEqual(7, binObj.GetField<byte>("fByte"));
Assert.AreEqual(false, binObj.GetField<bool>("fBool"));
Assert.AreEqual(8, binObj.GetField<short>("fShort"));
Assert.AreEqual('b', binObj.GetField<char>("fChar"));
Assert.AreEqual(9, binObj.GetField<int>("fInt"));
Assert.AreEqual(10, binObj.GetField<long>("fLong"));
Assert.AreEqual(11, binObj.GetField<float>("fFloat"));
Assert.AreEqual(12, binObj.GetField<double>("fDouble"));
Assert.AreEqual(13.13m, binObj.GetField<decimal>("fDecimal"));
var obj = binObj.Deserialize<Primitives>();
Assert.AreEqual(7, obj.FByte);
Assert.AreEqual(false, obj.FBool);
Assert.AreEqual(8, obj.FShort);
Assert.AreEqual('b', obj.FChar);
Assert.AreEqual(9, obj.FInt);
Assert.AreEqual(10, obj.FLong);
Assert.AreEqual(11, obj.FFloat);
Assert.AreEqual(12, obj.FDouble);
Assert.AreEqual(13.13m, obj.FDecimal);
}
/// <summary>
/// Test primitive array fields setting.
/// </summary>
[Test]
public void TestPrimitiveArrayFields()
{
// Generic SetField method.
var binObj = _grid.GetBinary().GetBuilder(typeof(PrimitiveArrays))
.SetField("fByte", new byte[] { 1 })
.SetField("fBool", new[] { true })
.SetField("fShort", new short[] { 2 })
.SetField("fChar", new[] { 'a' })
.SetField("fInt", new[] { 3 })
.SetField("fLong", new long[] { 4 })
.SetField("fFloat", new float[] { 5 })
.SetField("fDouble", new double[] { 6 })
.SetField("fDecimal", new decimal?[] { 7.7m })
.SetHashCode(100)
.Build();
CheckPrimitiveArrayFields1(binObj);
// Specific setters.
var binObj2 = _grid.GetBinary().GetBuilder(typeof(PrimitiveArrays))
.SetByteArrayField("fByte", new byte[] {1})
.SetBooleanArrayField("fBool", new[] {true})
.SetShortArrayField("fShort", new short[] {2})
.SetCharArrayField("fChar", new[] {'a'})
.SetIntArrayField("fInt", new[] {3})
.SetLongArrayField("fLong", new long[] {4})
.SetFloatArrayField("fFloat", new float[] {5})
.SetDoubleArrayField("fDouble", new double[] {6})
.SetDecimalArrayField("fDecimal", new decimal?[] {7.7m})
.SetHashCode(100)
.Build();
CheckPrimitiveArrayFields1(binObj2);
// Check equality.
Assert.AreEqual(binObj, binObj2);
Assert.AreEqual(binObj.GetHashCode(), binObj2.GetHashCode());
// Overwrite with generic setter.
binObj = _grid.GetBinary().GetBuilder(binObj)
.SetField("fByte", new byte[] { 7 })
.SetField("fBool", new[] { false })
.SetField("fShort", new short[] { 8 })
.SetField("fChar", new[] { 'b' })
.SetField("fInt", new[] { 9 })
.SetField("fLong", new long[] { 10 })
.SetField("fFloat", new float[] { 11 })
.SetField("fDouble", new double[] { 12 })
.SetField("fDecimal", new decimal?[] { 13.13m })
.Build();
CheckPrimitiveArrayFields2(binObj);
// Overwrite with specific setters.
binObj2 = _grid.GetBinary().GetBuilder(binObj)
.SetByteArrayField("fByte", new byte[] { 7 })
.SetBooleanArrayField("fBool", new[] { false })
.SetShortArrayField("fShort", new short[] { 8 })
.SetCharArrayField("fChar", new[] { 'b' })
.SetIntArrayField("fInt", new[] { 9 })
.SetLongArrayField("fLong", new long[] { 10 })
.SetFloatArrayField("fFloat", new float[] { 11 })
.SetDoubleArrayField("fDouble", new double[] { 12 })
.SetDecimalArrayField("fDecimal", new decimal?[] { 13.13m })
.Build();
CheckPrimitiveArrayFields2(binObj);
// Check equality.
Assert.AreEqual(binObj, binObj2);
Assert.AreEqual(binObj.GetHashCode(), binObj2.GetHashCode());
}
/// <summary>
/// Checks the primitive array fields.
/// </summary>
private static void CheckPrimitiveArrayFields1(IBinaryObject binObj)
{
Assert.AreEqual(100, binObj.GetHashCode());
IBinaryType meta = binObj.GetBinaryType();
Assert.AreEqual(typeof(PrimitiveArrays).Name, meta.TypeName);
Assert.AreEqual(9, meta.Fields.Count);
Assert.AreEqual(BinaryTypeNames.TypeNameArrayByte, meta.GetFieldTypeName("fByte"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayBool, meta.GetFieldTypeName("fBool"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayShort, meta.GetFieldTypeName("fShort"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayChar, meta.GetFieldTypeName("fChar"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayInt, meta.GetFieldTypeName("fInt"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayLong, meta.GetFieldTypeName("fLong"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayFloat, meta.GetFieldTypeName("fFloat"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayDouble, meta.GetFieldTypeName("fDouble"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayDecimal, meta.GetFieldTypeName("fDecimal"));
Assert.AreEqual(new byte[] { 1 }, binObj.GetField<byte[]>("fByte"));
Assert.AreEqual(new[] { true }, binObj.GetField<bool[]>("fBool"));
Assert.AreEqual(new short[] { 2 }, binObj.GetField<short[]>("fShort"));
Assert.AreEqual(new[] { 'a' }, binObj.GetField<char[]>("fChar"));
Assert.AreEqual(new[] { 3 }, binObj.GetField<int[]>("fInt"));
Assert.AreEqual(new long[] { 4 }, binObj.GetField<long[]>("fLong"));
Assert.AreEqual(new float[] { 5 }, binObj.GetField<float[]>("fFloat"));
Assert.AreEqual(new double[] { 6 }, binObj.GetField<double[]>("fDouble"));
Assert.AreEqual(new decimal?[] { 7.7m }, binObj.GetField<decimal?[]>("fDecimal"));
PrimitiveArrays obj = binObj.Deserialize<PrimitiveArrays>();
Assert.AreEqual(new byte[] { 1 }, obj.FByte);
Assert.AreEqual(new[] { true }, obj.FBool);
Assert.AreEqual(new short[] { 2 }, obj.FShort);
Assert.AreEqual(new[] { 'a' }, obj.FChar);
Assert.AreEqual(new[] { 3 }, obj.FInt);
Assert.AreEqual(new long[] { 4 }, obj.FLong);
Assert.AreEqual(new float[] { 5 }, obj.FFloat);
Assert.AreEqual(new double[] { 6 }, obj.FDouble);
Assert.AreEqual(new decimal?[] { 7.7m }, obj.FDecimal);
}
/// <summary>
/// Checks the primitive array fields.
/// </summary>
private static void CheckPrimitiveArrayFields2(IBinaryObject binObj)
{
Assert.AreEqual(new byte[] { 7 }, binObj.GetField<byte[]>("fByte"));
Assert.AreEqual(new[] { false }, binObj.GetField<bool[]>("fBool"));
Assert.AreEqual(new short[] { 8 }, binObj.GetField<short[]>("fShort"));
Assert.AreEqual(new[] { 'b' }, binObj.GetField<char[]>("fChar"));
Assert.AreEqual(new[] { 9 }, binObj.GetField<int[]>("fInt"));
Assert.AreEqual(new long[] { 10 }, binObj.GetField<long[]>("fLong"));
Assert.AreEqual(new float[] { 11 }, binObj.GetField<float[]>("fFloat"));
Assert.AreEqual(new double[] { 12 }, binObj.GetField<double[]>("fDouble"));
Assert.AreEqual(new decimal?[] { 13.13m }, binObj.GetField<decimal?[]>("fDecimal"));
var obj = binObj.Deserialize<PrimitiveArrays>();
Assert.AreEqual(new byte[] { 7 }, obj.FByte);
Assert.AreEqual(new[] { false }, obj.FBool);
Assert.AreEqual(new short[] { 8 }, obj.FShort);
Assert.AreEqual(new[] { 'b' }, obj.FChar);
Assert.AreEqual(new[] { 9 }, obj.FInt);
Assert.AreEqual(new long[] { 10 }, obj.FLong);
Assert.AreEqual(new float[] { 11 }, obj.FFloat);
Assert.AreEqual(new double[] { 12 }, obj.FDouble);
Assert.AreEqual(new decimal?[] { 13.13m }, obj.FDecimal);
}
/// <summary>
/// Test non-primitive fields and their array counterparts.
/// </summary>
[Test]
public void TestStringDateGuidEnum()
{
DateTime? nDate = DateTime.Now.ToUniversalTime();
Guid? nGuid = Guid.NewGuid();
// Generic setters.
var binObj = _grid.GetBinary().GetBuilder(typeof(StringDateGuidEnum))
.SetField("fStr", "str")
.SetField("fNDate", nDate)
.SetTimestampField("fNTimestamp", nDate)
.SetField("fNGuid", nGuid)
.SetField("fEnum", TestEnum.One)
.SetStringArrayField("fStrArr", new[] { "str" })
.SetArrayField("fDateArr", new[] { nDate })
.SetTimestampArrayField("fTimestampArr", new[] { nDate })
.SetGuidArrayField("fGuidArr", new[] { nGuid })
.SetEnumArrayField("fEnumArr", new[] { TestEnum.One })
.SetHashCode(100)
.Build();
CheckStringDateGuidEnum1(binObj, nDate, nGuid);
// Specific setters.
var binObj2 = _grid.GetBinary().GetBuilder(typeof(StringDateGuidEnum))
.SetStringField("fStr", "str")
.SetField("fNDate", nDate)
.SetTimestampField("fNTimestamp", nDate)
.SetGuidField("fNGuid", nGuid)
.SetEnumField("fEnum", TestEnum.One)
.SetStringArrayField("fStrArr", new[] { "str" })
.SetArrayField("fDateArr", new[] { nDate })
.SetTimestampArrayField("fTimestampArr", new[] { nDate })
.SetGuidArrayField("fGuidArr", new[] { nGuid })
.SetEnumArrayField("fEnumArr", new[] { TestEnum.One })
.SetHashCode(100)
.Build();
CheckStringDateGuidEnum1(binObj2, nDate, nGuid);
// Check equality.
Assert.AreEqual(binObj, binObj2);
Assert.AreEqual(binObj.GetHashCode(), binObj2.GetHashCode());
// Overwrite.
nDate = DateTime.Now.ToUniversalTime();
nGuid = Guid.NewGuid();
binObj = _grid.GetBinary().GetBuilder(typeof(StringDateGuidEnum))
.SetField("fStr", "str2")
.SetField("fNDate", nDate)
.SetTimestampField("fNTimestamp", nDate)
.SetField("fNGuid", nGuid)
.SetField("fEnum", TestEnum.Two)
.SetField("fStrArr", new[] { "str2" })
.SetArrayField("fDateArr", new[] { nDate })
.SetTimestampArrayField("fTimestampArr", new[] { nDate })
.SetField("fGuidArr", new[] { nGuid })
.SetField("fEnumArr", new[] { TestEnum.Two })
.Build();
CheckStringDateGuidEnum2(binObj, nDate, nGuid);
// Overwrite with specific setters
binObj2 = _grid.GetBinary().GetBuilder(typeof(StringDateGuidEnum))
.SetStringField("fStr", "str2")
.SetField("fNDate", nDate)
.SetTimestampField("fNTimestamp", nDate)
.SetGuidField("fNGuid", nGuid)
.SetEnumField("fEnum", TestEnum.Two)
.SetStringArrayField("fStrArr", new[] { "str2" })
.SetArrayField("fDateArr", new[] { nDate })
.SetTimestampArrayField("fTimestampArr", new[] { nDate })
.SetGuidArrayField("fGuidArr", new[] { nGuid })
.SetEnumArrayField("fEnumArr", new[] { TestEnum.Two })
.Build();
CheckStringDateGuidEnum2(binObj2, nDate, nGuid);
// Check equality.
Assert.AreEqual(binObj, binObj2);
Assert.AreEqual(binObj.GetHashCode(), binObj2.GetHashCode());
}
/// <summary>
/// Checks the string date guid enum values.
/// </summary>
private void CheckStringDateGuidEnum1(IBinaryObject binObj, DateTime? nDate, Guid? nGuid)
{
Assert.AreEqual(100, binObj.GetHashCode());
IBinaryType meta = binObj.GetBinaryType();
Assert.AreEqual(typeof(StringDateGuidEnum).Name, meta.TypeName);
Assert.AreEqual(10, meta.Fields.Count);
Assert.AreEqual(BinaryTypeNames.TypeNameString, meta.GetFieldTypeName("fStr"));
Assert.AreEqual(BinaryTypeNames.TypeNameObject, meta.GetFieldTypeName("fNDate"));
Assert.AreEqual(BinaryTypeNames.TypeNameTimestamp, meta.GetFieldTypeName("fNTimestamp"));
Assert.AreEqual(BinaryTypeNames.TypeNameGuid, meta.GetFieldTypeName("fNGuid"));
Assert.AreEqual(BinaryTypeNames.TypeNameEnum, meta.GetFieldTypeName("fEnum"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayString, meta.GetFieldTypeName("fStrArr"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayObject, meta.GetFieldTypeName("fDateArr"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayTimestamp, meta.GetFieldTypeName("fTimestampArr"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayGuid, meta.GetFieldTypeName("fGuidArr"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayEnum, meta.GetFieldTypeName("fEnumArr"));
Assert.AreEqual("str", binObj.GetField<string>("fStr"));
Assert.AreEqual(nDate, binObj.GetField<DateTime?>("fNDate"));
Assert.AreEqual(nDate, binObj.GetField<DateTime?>("fNTimestamp"));
Assert.AreEqual(nGuid, binObj.GetField<Guid?>("fNGuid"));
Assert.AreEqual(TestEnum.One, binObj.GetField<TestEnum>("fEnum"));
Assert.AreEqual(new[] {"str"}, binObj.GetField<string[]>("fStrArr"));
Assert.AreEqual(new[] {nDate}, binObj.GetField<DateTime?[]>("fDateArr"));
Assert.AreEqual(new[] {nDate}, binObj.GetField<DateTime?[]>("fTimestampArr"));
Assert.AreEqual(new[] {nGuid}, binObj.GetField<Guid?[]>("fGuidArr"));
Assert.AreEqual(new[] {TestEnum.One}, binObj.GetField<TestEnum[]>("fEnumArr"));
StringDateGuidEnum obj = binObj.Deserialize<StringDateGuidEnum>();
Assert.AreEqual("str", obj.FStr);
Assert.AreEqual(nDate, obj.FnDate);
Assert.AreEqual(nDate, obj.FnTimestamp);
Assert.AreEqual(nGuid, obj.FnGuid);
Assert.AreEqual(TestEnum.One, obj.FEnum);
Assert.AreEqual(new[] {"str"}, obj.FStrArr);
Assert.AreEqual(new[] {nDate}, obj.FDateArr);
Assert.AreEqual(new[] {nGuid}, obj.FGuidArr);
Assert.AreEqual(new[] {TestEnum.One}, obj.FEnumArr);
// Check builder field caching.
var builder = _grid.GetBinary().GetBuilder(binObj);
Assert.AreEqual("str", builder.GetField<string>("fStr"));
Assert.AreEqual(nDate, builder.GetField<DateTime?>("fNDate"));
Assert.AreEqual(nDate, builder.GetField<DateTime?>("fNTimestamp"));
Assert.AreEqual(nGuid, builder.GetField<Guid?>("fNGuid"));
Assert.AreEqual(TestEnum.One, builder.GetField<TestEnum>("fEnum"));
Assert.AreEqual(new[] {"str"}, builder.GetField<string[]>("fStrArr"));
Assert.AreEqual(new[] {nDate}, builder.GetField<DateTime?[]>("fDateArr"));
Assert.AreEqual(new[] {nDate}, builder.GetField<DateTime?[]>("fTimestampArr"));
Assert.AreEqual(new[] {nGuid}, builder.GetField<Guid?[]>("fGuidArr"));
Assert.AreEqual(new[] {TestEnum.One}, builder.GetField<TestEnum[]>("fEnumArr"));
// Check reassemble.
binObj = builder.Build();
Assert.AreEqual("str", binObj.GetField<string>("fStr"));
Assert.AreEqual(nDate, binObj.GetField<DateTime?>("fNDate"));
Assert.AreEqual(nDate, binObj.GetField<DateTime?>("fNTimestamp"));
Assert.AreEqual(nGuid, binObj.GetField<Guid?>("fNGuid"));
Assert.AreEqual(TestEnum.One, binObj.GetField<TestEnum>("fEnum"));
Assert.AreEqual(new[] {"str"}, binObj.GetField<string[]>("fStrArr"));
Assert.AreEqual(new[] {nDate}, binObj.GetField<DateTime?[]>("fDateArr"));
Assert.AreEqual(new[] {nDate}, binObj.GetField<DateTime?[]>("fTimestampArr"));
Assert.AreEqual(new[] {nGuid}, binObj.GetField<Guid?[]>("fGuidArr"));
Assert.AreEqual(new[] {TestEnum.One}, binObj.GetField<TestEnum[]>("fEnumArr"));
obj = binObj.Deserialize<StringDateGuidEnum>();
Assert.AreEqual("str", obj.FStr);
Assert.AreEqual(nDate, obj.FnDate);
Assert.AreEqual(nDate, obj.FnTimestamp);
Assert.AreEqual(nGuid, obj.FnGuid);
Assert.AreEqual(TestEnum.One, obj.FEnum);
Assert.AreEqual(new[] {"str"}, obj.FStrArr);
Assert.AreEqual(new[] {nDate}, obj.FDateArr);
Assert.AreEqual(new[] {nGuid}, obj.FGuidArr);
Assert.AreEqual(new[] {TestEnum.One}, obj.FEnumArr);
}
/// <summary>
/// Checks the string date guid enum values.
/// </summary>
private static void CheckStringDateGuidEnum2(IBinaryObject binObj, DateTime? nDate, Guid? nGuid)
{
Assert.AreEqual("str2", binObj.GetField<string>("fStr"));
Assert.AreEqual(nDate, binObj.GetField<DateTime?>("fNDate"));
Assert.AreEqual(nDate, binObj.GetField<DateTime?>("fNTimestamp"));
Assert.AreEqual(nGuid, binObj.GetField<Guid?>("fNGuid"));
Assert.AreEqual(TestEnum.Two, binObj.GetField<TestEnum>("fEnum"));
Assert.AreEqual(new[] { "str2" }, binObj.GetField<string[]>("fStrArr"));
Assert.AreEqual(new[] { nDate }, binObj.GetField<DateTime?[]>("fDateArr"));
Assert.AreEqual(new[] { nDate }, binObj.GetField<DateTime?[]>("fTimestampArr"));
Assert.AreEqual(new[] { nGuid }, binObj.GetField<Guid?[]>("fGuidArr"));
Assert.AreEqual(new[] { TestEnum.Two }, binObj.GetField<TestEnum[]>("fEnumArr"));
var obj = binObj.Deserialize<StringDateGuidEnum>();
Assert.AreEqual("str2", obj.FStr);
Assert.AreEqual(nDate, obj.FnDate);
Assert.AreEqual(nDate, obj.FnTimestamp);
Assert.AreEqual(nGuid, obj.FnGuid);
Assert.AreEqual(TestEnum.Two, obj.FEnum);
Assert.AreEqual(new[] { "str2" }, obj.FStrArr);
Assert.AreEqual(new[] { nDate }, obj.FDateArr);
Assert.AreEqual(new[] { nGuid }, obj.FGuidArr);
Assert.AreEqual(new[] { TestEnum.Two }, obj.FEnumArr);
}
[Test]
public void TestEnumMeta()
{
var bin = _grid.GetBinary();
// Put to cache to populate metas
var binEnum = bin.ToBinary<IBinaryObject>(TestEnumRegistered.One);
Assert.AreEqual(_marsh.GetDescriptor(typeof (TestEnumRegistered)).TypeId, binEnum.GetBinaryType().TypeId);
Assert.AreEqual(0, binEnum.EnumValue);
var meta = binEnum.GetBinaryType();
Assert.IsTrue(meta.IsEnum);
Assert.AreEqual(typeof (TestEnumRegistered).Name, meta.TypeName);
Assert.AreEqual(0, meta.Fields.Count);
}
/// <summary>
/// Test arrays.
/// </summary>
[Test]
public void TestCompositeArray()
{
// 1. Test simple array.
object[] inArr = { new CompositeInner(1) };
IBinaryObject binObj = _grid.GetBinary().GetBuilder(typeof(CompositeArray)).SetHashCode(100)
.SetField("inArr", inArr).Build();
IBinaryType meta = binObj.GetBinaryType();
Assert.AreEqual(typeof(CompositeArray).Name, meta.TypeName);
Assert.AreEqual(1, meta.Fields.Count);
Assert.AreEqual(BinaryTypeNames.TypeNameArrayObject, meta.GetFieldTypeName("inArr"));
Assert.AreEqual(100, binObj.GetHashCode());
var binInArr = binObj.GetField<IBinaryObject[]>("inArr").ToArray();
Assert.AreEqual(1, binInArr.Length);
Assert.AreEqual(1, binInArr[0].GetField<int>("val"));
CompositeArray arr = binObj.Deserialize<CompositeArray>();
Assert.IsNull(arr.OutArr);
Assert.AreEqual(1, arr.InArr.Length);
Assert.AreEqual(1, ((CompositeInner) arr.InArr[0]).Val);
// 2. Test addition to array.
binObj = _grid.GetBinary().GetBuilder(binObj).SetHashCode(200)
.SetField("inArr", new[] { binInArr[0], null }).Build();
Assert.AreEqual(200, binObj.GetHashCode());
binInArr = binObj.GetField<IBinaryObject[]>("inArr").ToArray();
Assert.AreEqual(2, binInArr.Length);
Assert.AreEqual(1, binInArr[0].GetField<int>("val"));
Assert.IsNull(binInArr[1]);
arr = binObj.Deserialize<CompositeArray>();
Assert.IsNull(arr.OutArr);
Assert.AreEqual(2, arr.InArr.Length);
Assert.AreEqual(1, ((CompositeInner) arr.InArr[0]).Val);
Assert.IsNull(arr.InArr[1]);
binInArr[1] = _grid.GetBinary().GetBuilder(typeof(CompositeInner)).SetField("val", 2).Build();
binObj = _grid.GetBinary().GetBuilder(binObj).SetHashCode(300)
.SetField("inArr", binInArr.OfType<object>().ToArray()).Build();
Assert.AreEqual(300, binObj.GetHashCode());
binInArr = binObj.GetField<IBinaryObject[]>("inArr").ToArray();
Assert.AreEqual(2, binInArr.Length);
Assert.AreEqual(1, binInArr[0].GetField<int>("val"));
Assert.AreEqual(2, binInArr[1].GetField<int>("val"));
arr = binObj.Deserialize<CompositeArray>();
Assert.IsNull(arr.OutArr);
Assert.AreEqual(2, arr.InArr.Length);
Assert.AreEqual(1, ((CompositeInner)arr.InArr[0]).Val);
Assert.AreEqual(2, ((CompositeInner)arr.InArr[1]).Val);
// 3. Test top-level handle inversion.
CompositeInner inner = new CompositeInner(1);
inArr = new object[] { inner, inner };
binObj = _grid.GetBinary().GetBuilder(typeof(CompositeArray)).SetHashCode(100)
.SetField("inArr", inArr).Build();
Assert.AreEqual(100, binObj.GetHashCode());
binInArr = binObj.GetField<IBinaryObject[]>("inArr").ToArray();
Assert.AreEqual(2, binInArr.Length);
Assert.AreEqual(1, binInArr[0].GetField<int>("val"));
Assert.AreEqual(1, binInArr[1].GetField<int>("val"));
arr = binObj.Deserialize<CompositeArray>();
Assert.IsNull(arr.OutArr);
Assert.AreEqual(2, arr.InArr.Length);
Assert.AreEqual(1, ((CompositeInner)arr.InArr[0]).Val);
Assert.AreEqual(1, ((CompositeInner)arr.InArr[1]).Val);
binInArr[0] = _grid.GetBinary().GetBuilder(typeof(CompositeInner)).SetField("val", 2).Build();
binObj = _grid.GetBinary().GetBuilder(binObj).SetHashCode(200)
.SetField("inArr", binInArr.ToArray<object>()).Build();
Assert.AreEqual(200, binObj.GetHashCode());
binInArr = binObj.GetField<IBinaryObject[]>("inArr").ToArray();
Assert.AreEqual(2, binInArr.Length);
Assert.AreEqual(2, binInArr[0].GetField<int>("val"));
Assert.AreEqual(1, binInArr[1].GetField<int>("val"));
arr = binObj.Deserialize<CompositeArray>();
Assert.IsNull(arr.OutArr);
Assert.AreEqual(2, arr.InArr.Length);
Assert.AreEqual(2, ((CompositeInner)arr.InArr[0]).Val);
Assert.AreEqual(1, ((CompositeInner)arr.InArr[1]).Val);
// 4. Test nested object handle inversion.
CompositeOuter[] outArr = { new CompositeOuter(inner), new CompositeOuter(inner) };
binObj = _grid.GetBinary().GetBuilder(typeof(CompositeArray)).SetHashCode(100)
.SetField("outArr", outArr.ToArray<object>()).Build();
meta = binObj.GetBinaryType();
Assert.AreEqual(typeof(CompositeArray).Name, meta.TypeName);
Assert.AreEqual(2, meta.Fields.Count);
Assert.AreEqual(BinaryTypeNames.TypeNameArrayObject, meta.GetFieldTypeName("inArr"));
Assert.AreEqual(BinaryTypeNames.TypeNameArrayObject, meta.GetFieldTypeName("outArr"));
Assert.AreEqual(100, binObj.GetHashCode());
var binOutArr = binObj.GetField<IBinaryObject[]>("outArr").ToArray();
Assert.AreEqual(2, binOutArr.Length);
Assert.AreEqual(1, binOutArr[0].GetField<IBinaryObject>("inner").GetField<int>("val"));
Assert.AreEqual(1, binOutArr[1].GetField<IBinaryObject>("inner").GetField<int>("val"));
arr = binObj.Deserialize<CompositeArray>();
Assert.IsNull(arr.InArr);
Assert.AreEqual(2, arr.OutArr.Length);
Assert.AreEqual(1, ((CompositeOuter) arr.OutArr[0]).Inner.Val);
Assert.AreEqual(1, ((CompositeOuter) arr.OutArr[0]).Inner.Val);
binOutArr[0] = _grid.GetBinary().GetBuilder(typeof(CompositeOuter))
.SetField("inner", new CompositeInner(2)).Build();
binObj = _grid.GetBinary().GetBuilder(binObj).SetHashCode(200)
.SetField("outArr", binOutArr.ToArray<object>()).Build();
Assert.AreEqual(200, binObj.GetHashCode());
binInArr = binObj.GetField<IBinaryObject[]>("outArr").ToArray();
Assert.AreEqual(2, binInArr.Length);
Assert.AreEqual(2, binOutArr[0].GetField<IBinaryObject>("inner").GetField<int>("val"));
Assert.AreEqual(1, binOutArr[1].GetField<IBinaryObject>("inner").GetField<int>("val"));
arr = binObj.Deserialize<CompositeArray>();
Assert.IsNull(arr.InArr);
Assert.AreEqual(2, arr.OutArr.Length);
Assert.AreEqual(2, ((CompositeOuter)arr.OutArr[0]).Inner.Val);
Assert.AreEqual(1, ((CompositeOuter)arr.OutArr[1]).Inner.Val);
}
/// <summary>
/// Test container types other than array.
/// </summary>
[Test]
public void TestCompositeContainer()
{
ArrayList col = new ArrayList();
IDictionary dict = new Hashtable();
col.Add(new CompositeInner(1));
dict[3] = new CompositeInner(3);
IBinaryObject binObj = _grid.GetBinary().GetBuilder(typeof(CompositeContainer)).SetHashCode(100)
.SetCollectionField("col", col)
.SetDictionaryField("dict", dict).Build();
// 1. Check meta.
IBinaryType meta = binObj.GetBinaryType();
Assert.AreEqual(typeof(CompositeContainer).Name, meta.TypeName);
Assert.AreEqual(2, meta.Fields.Count);
Assert.AreEqual(BinaryTypeNames.TypeNameCollection, meta.GetFieldTypeName("col"));
Assert.AreEqual(BinaryTypeNames.TypeNameMap, meta.GetFieldTypeName("dict"));
// 2. Check in binary form.
Assert.AreEqual(1, binObj.GetField<ICollection>("col").Count);
Assert.AreEqual(1, binObj.GetField<ICollection>("col").OfType<IBinaryObject>().First()
.GetField<int>("val"));
Assert.AreEqual(1, binObj.GetField<IDictionary>("dict").Count);
Assert.AreEqual(3, ((IBinaryObject) binObj.GetField<IDictionary>("dict")[3]).GetField<int>("val"));
// 3. Check in deserialized form.
CompositeContainer obj = binObj.Deserialize<CompositeContainer>();
Assert.AreEqual(1, obj.Col.Count);
Assert.AreEqual(1, obj.Col.OfType<CompositeInner>().First().Val);
Assert.AreEqual(1, obj.Dict.Count);
Assert.AreEqual(3, ((CompositeInner) obj.Dict[3]).Val);
}
/// <summary>
/// Ensure that raw data is not lost during build.
/// </summary>
[Test]
public void TestRawData()
{
var raw = new WithRaw
{
A = 1,
B = 2
};
var binObj = _marsh.Unmarshal<IBinaryObject>(_marsh.Marshal(raw), BinaryMode.ForceBinary);
raw = binObj.Deserialize<WithRaw>();
Assert.AreEqual(1, raw.A);
Assert.AreEqual(2, raw.B);
IBinaryObject newbinObj = _grid.GetBinary().GetBuilder(binObj).SetField("a", 3).Build();
raw = newbinObj.Deserialize<WithRaw>();
Assert.AreEqual(3, raw.A);
Assert.AreEqual(2, raw.B);
}
/// <summary>
/// Test nested objects.
/// </summary>
[Test]
public void TestNested()
{
// 1. Create from scratch.
IBinaryObjectBuilder builder = _grid.GetBinary().GetBuilder(typeof(NestedOuter));
NestedInner inner1 = new NestedInner {Val = 1};
builder.SetField("inner1", inner1);
IBinaryObject outerbinObj = builder.Build();
IBinaryType meta = outerbinObj.GetBinaryType();
Assert.AreEqual(typeof(NestedOuter).Name, meta.TypeName);
Assert.AreEqual(1, meta.Fields.Count);
Assert.AreEqual(BinaryTypeNames.TypeNameObject, meta.GetFieldTypeName("inner1"));
IBinaryObject innerbinObj1 = outerbinObj.GetField<IBinaryObject>("inner1");
IBinaryType innerMeta = innerbinObj1.GetBinaryType();
Assert.AreEqual(typeof(NestedInner).Name, innerMeta.TypeName);
Assert.AreEqual(1, innerMeta.Fields.Count);
Assert.AreEqual(BinaryTypeNames.TypeNameInt, innerMeta.GetFieldTypeName("Val"));
inner1 = innerbinObj1.Deserialize<NestedInner>();
Assert.AreEqual(1, inner1.Val);
NestedOuter outer = outerbinObj.Deserialize<NestedOuter>();
Assert.AreEqual(outer.Inner1.Val, 1);
Assert.IsNull(outer.Inner2);
// 2. Add another field over existing binary object.
builder = _grid.GetBinary().GetBuilder(outerbinObj);
NestedInner inner2 = new NestedInner {Val = 2};
builder.SetField("inner2", inner2);
outerbinObj = builder.Build();
outer = outerbinObj.Deserialize<NestedOuter>();
Assert.AreEqual(1, outer.Inner1.Val);
Assert.AreEqual(2, outer.Inner2.Val);
// 3. Try setting inner object in binary form.
innerbinObj1 = _grid.GetBinary().GetBuilder(innerbinObj1).SetField("val", 3).Build();
inner1 = innerbinObj1.Deserialize<NestedInner>();
Assert.AreEqual(3, inner1.Val);
outerbinObj = _grid.GetBinary().GetBuilder(outerbinObj).SetField<object>("inner1", innerbinObj1).Build();
outer = outerbinObj.Deserialize<NestedOuter>();
Assert.AreEqual(3, outer.Inner1.Val);
Assert.AreEqual(2, outer.Inner2.Val);
}
/// <summary>
/// Test handle migration.
/// </summary>
[Test]
public void TestHandleMigration()
{
// 1. Simple comparison of results.
MigrationInner inner = new MigrationInner {Val = 1};
MigrationOuter outer = new MigrationOuter
{
Inner1 = inner,
Inner2 = inner
};
byte[] outerBytes = _marsh.Marshal(outer);
IBinaryObjectBuilder builder = _grid.GetBinary().GetBuilder(typeof(MigrationOuter));
if (GetIdentityResolver() == null)
builder.SetHashCode(outer.GetHashCode());
builder.SetField<object>("inner1", inner);
builder.SetField<object>("inner2", inner);
BinaryObject portOuter = (BinaryObject) builder.Build();
byte[] portOuterBytes = new byte[outerBytes.Length];
Buffer.BlockCopy(portOuter.Data, 0, portOuterBytes, 0, portOuterBytes.Length);
Assert.AreEqual(outerBytes, portOuterBytes);
// 2. Change the first inner object so that the handle must migrate.
MigrationInner inner1 = new MigrationInner {Val = 2};
IBinaryObject portOuterMigrated =
_grid.GetBinary().GetBuilder(portOuter).SetField<object>("inner1", inner1).Build();
MigrationOuter outerMigrated = portOuterMigrated.Deserialize<MigrationOuter>();
Assert.AreEqual(2, outerMigrated.Inner1.Val);
Assert.AreEqual(1, outerMigrated.Inner2.Val);
// 3. Change the first value using serialized form.
IBinaryObject inner1Port =
_grid.GetBinary().GetBuilder(typeof(MigrationInner)).SetField("val", 2).Build();
portOuterMigrated =
_grid.GetBinary().GetBuilder(portOuter).SetField<object>("inner1", inner1Port).Build();
outerMigrated = portOuterMigrated.Deserialize<MigrationOuter>();
Assert.AreEqual(2, outerMigrated.Inner1.Val);
Assert.AreEqual(1, outerMigrated.Inner2.Val);
}
/// <summary>
/// Test handle inversion.
/// </summary>
[Test]
public void TestHandleInversion()
{
InversionInner inner = new InversionInner();
InversionOuter outer = new InversionOuter();
inner.Outer = outer;
outer.Inner = inner;
byte[] rawOuter = _marsh.Marshal(outer);
IBinaryObject portOuter = _marsh.Unmarshal<IBinaryObject>(rawOuter, BinaryMode.ForceBinary);
IBinaryObject portInner = portOuter.GetField<IBinaryObject>("inner");
// 1. Ensure that inner object can be deserialized after build.
IBinaryObject portInnerNew = _grid.GetBinary().GetBuilder(portInner).Build();
InversionInner innerNew = portInnerNew.Deserialize<InversionInner>();
Assert.AreSame(innerNew, innerNew.Outer.Inner);
// 2. Ensure that binary object with external dependencies could be added to builder.
IBinaryObject portOuterNew =
_grid.GetBinary().GetBuilder(typeof(InversionOuter)).SetField<object>("inner", portInner).Build();
InversionOuter outerNew = portOuterNew.Deserialize<InversionOuter>();
Assert.AreNotSame(outerNew, outerNew.Inner.Outer);
Assert.AreSame(outerNew.Inner, outerNew.Inner.Outer.Inner);
}
/// <summary>
/// Test build multiple objects.
/// </summary>
[Test]
public void TestBuildMultiple()
{
IBinaryObjectBuilder builder = _grid.GetBinary().GetBuilder(typeof(Primitives));
builder.SetField<byte>("fByte", 1).SetField("fBool", true);
IBinaryObject po1 = builder.Build();
IBinaryObject po2 = builder.Build();
Assert.AreEqual(1, po1.GetField<byte>("fByte"));
Assert.AreEqual(true, po1.GetField<bool>("fBool"));
Assert.AreEqual(1, po2.GetField<byte>("fByte"));
Assert.AreEqual(true, po2.GetField<bool>("fBool"));
builder.SetField<byte>("fByte", 2);
IBinaryObject po3 = builder.Build();
Assert.AreEqual(1, po1.GetField<byte>("fByte"));
Assert.AreEqual(true, po1.GetField<bool>("fBool"));
Assert.AreEqual(1, po2.GetField<byte>("fByte"));
Assert.AreEqual(true, po2.GetField<bool>("fBool"));
Assert.AreEqual(2, po3.GetField<byte>("fByte"));
Assert.AreEqual(true, po2.GetField<bool>("fBool"));
builder = _grid.GetBinary().GetBuilder(po1);
builder.SetField<byte>("fByte", 10);
po1 = builder.Build();
po2 = builder.Build();
builder.SetField<byte>("fByte", 20);
po3 = builder.Build();
Assert.AreEqual(10, po1.GetField<byte>("fByte"));
Assert.AreEqual(true, po1.GetField<bool>("fBool"));
Assert.AreEqual(10, po2.GetField<byte>("fByte"));
Assert.AreEqual(true, po2.GetField<bool>("fBool"));
Assert.AreEqual(20, po3.GetField<byte>("fByte"));
Assert.AreEqual(true, po3.GetField<bool>("fBool"));
}
/// <summary>
/// Tests type id method.
/// </summary>
[Test]
public void TestTypeId()
{
Assert.Throws<ArgumentException>(() => _grid.GetBinary().GetTypeId(null));
Assert.AreEqual(IdMapper.TestTypeId, _grid.GetBinary().GetTypeId(IdMapper.TestTypeName));
Assert.AreEqual(BinaryUtils.GetStringHashCode("someTypeName"), _grid.GetBinary().GetTypeId("someTypeName"));
}
/// <summary>
/// Tests type name mapper.
/// </summary>
[Test]
public void TestTypeName()
{
var bytes = _marsh.Marshal(new NameMapperTestType {NameMapperTestField = 17});
var bin = _marsh.Unmarshal<IBinaryObject>(bytes, BinaryMode.ForceBinary);
var binType = bin.GetBinaryType();
Assert.AreEqual(BinaryUtils.GetStringHashCode(NameMapper.TestTypeName + "_"), binType.TypeId);
Assert.AreEqual(17, bin.GetField<int>(NameMapper.TestFieldName));
}
/// <summary>
/// Tests metadata methods.
/// </summary>
[Test]
public void TestMetadata()
{
// Populate metadata
var binary = _grid.GetBinary();
binary.ToBinary<IBinaryObject>(new DecimalHolder());
// All meta
var allMetas = binary.GetBinaryTypes();
var decimalMeta = allMetas.Single(x => x.TypeName == "DecimalHolder");
Assert.AreEqual(new[] {"val", "valArr"}, decimalMeta.Fields);
// By type
decimalMeta = binary.GetBinaryType(typeof (DecimalHolder));
Assert.AreEqual(new[] {"val", "valArr"}, decimalMeta.Fields);
// By type id
decimalMeta = binary.GetBinaryType(binary.GetTypeId("DecimalHolder"));
Assert.AreEqual(new[] {"val", "valArr"}, decimalMeta.Fields);
// By type name
decimalMeta = binary.GetBinaryType("DecimalHolder");
Assert.AreEqual(new[] {"val", "valArr"}, decimalMeta.Fields);
}
[Test]
public void TestBuildEnum()
{
var binary = _grid.GetBinary();
int val = (int) TestEnumRegistered.Two;
var binEnums = new[]
{
binary.BuildEnum(typeof (TestEnumRegistered), val),
binary.BuildEnum(typeof (TestEnumRegistered).Name, val)
};
foreach (var binEnum in binEnums)
{
Assert.IsTrue(binEnum.GetBinaryType().IsEnum);
Assert.AreEqual(val, binEnum.EnumValue);
Assert.AreEqual((TestEnumRegistered) val, binEnum.Deserialize<TestEnumRegistered>());
}
Assert.AreEqual(binEnums[0], binEnums[1]);
Assert.AreEqual(binEnums[0].GetHashCode(), binEnums[1].GetHashCode());
}
/// <summary>
/// Tests the compact footer setting.
/// </summary>
[Test]
public void TestCompactFooterSetting()
{
Assert.AreEqual(GetCompactFooter(), _marsh.CompactFooter);
}
/// <summary>
/// Tests the binary mode on remote node.
/// </summary>
[Test]
public void TestRemoteBinaryMode()
{
if (GetIdentityResolver() != null)
return; // When identity resolver is set, it is required to have the same config on all nodes.
var cfg = new IgniteConfiguration(TestUtils.GetTestConfiguration())
{
GridName = "grid2",
BinaryConfiguration = new BinaryConfiguration
{
CompactFooter = GetCompactFooter()
}
};
using (var grid2 = Ignition.Start(cfg))
{
var cache1 = _grid.GetOrCreateCache<int, Primitives>("cache");
var cache2 = grid2.GetCache<int, object>("cache").WithKeepBinary<int, IBinaryObject>();
// Exchange data
cache1[1] = new Primitives {FByte = 3};
var obj = cache2[1];
// Rebuild with no changes
cache2[2] = obj.ToBuilder().Build();
Assert.AreEqual(3, cache1[2].FByte);
// Rebuild with read
Assert.AreEqual(3, obj.GetField<byte>("FByte"));
cache2[3] = obj.ToBuilder().Build();
Assert.AreEqual(3, cache1[3].FByte);
// Modify and rebuild
cache2[4] = obj.ToBuilder().SetField("FShort", (short) 15).Build();
Assert.AreEqual(15, cache1[4].FShort);
// New binary type without a class
cache2[5] = grid2.GetBinary().GetBuilder("myNewType").SetField("foo", "bar").Build();
var cache1Bin = cache1.WithKeepBinary<int, IBinaryObject>();
var newObj = cache1Bin[5];
Assert.AreEqual("bar", newObj.GetField<string>("foo"));
cache1Bin[6] = newObj.ToBuilder().SetField("foo2", 3).Build();
Assert.AreEqual(3, cache2[6].GetField<int>("foo2"));
}
}
}
/// <summary>
/// Empty binary class.
/// </summary>
public class Empty
{
// No-op.
}
/// <summary>
/// binary with primitive fields.
/// </summary>
public class Primitives
{
public byte FByte;
public bool FBool;
public short FShort;
public char FChar;
public int FInt;
public long FLong;
public float FFloat;
public double FDouble;
public decimal FDecimal;
}
/// <summary>
/// binary with primitive array fields.
/// </summary>
public class PrimitiveArrays
{
public byte[] FByte;
public bool[] FBool;
public short[] FShort;
public char[] FChar;
public int[] FInt;
public long[] FLong;
public float[] FFloat;
public double[] FDouble;
public decimal?[] FDecimal;
}
/// <summary>
/// binary having strings, dates, Guids and enums.
/// </summary>
public class StringDateGuidEnum
{
public string FStr;
public DateTime? FnDate;
public DateTime? FnTimestamp;
public Guid? FnGuid;
public TestEnum FEnum;
public string[] FStrArr;
public DateTime?[] FDateArr;
public Guid?[] FGuidArr;
public TestEnum[] FEnumArr;
}
/// <summary>
/// Enumeration.
/// </summary>
public enum TestEnum
{
One, Two
}
/// <summary>
/// Registered enumeration.
/// </summary>
public enum TestEnumRegistered
{
One, Two
}
/// <summary>
/// binary with raw data.
/// </summary>
public class WithRaw : IBinarizable
{
public int A;
public int B;
/** <inheritDoc /> */
public void WriteBinary(IBinaryWriter writer)
{
writer.WriteInt("a", A);
writer.GetRawWriter().WriteInt(B);
}
/** <inheritDoc /> */
public void ReadBinary(IBinaryReader reader)
{
A = reader.ReadInt("a");
B = reader.GetRawReader().ReadInt();
}
}
/// <summary>
/// Empty class for metadata overwrite test.
/// </summary>
public class MetaOverwrite
{
// No-op.
}
/// <summary>
/// Nested outer object.
/// </summary>
public class NestedOuter
{
public NestedInner Inner1;
public NestedInner Inner2;
}
/// <summary>
/// Nested inner object.
/// </summary>
public class NestedInner
{
public int Val;
}
/// <summary>
/// Outer object for handle migration test.
/// </summary>
public class MigrationOuter
{
public MigrationInner Inner1;
public MigrationInner Inner2;
}
/// <summary>
/// Inner object for handle migration test.
/// </summary>
public class MigrationInner
{
public int Val;
}
/// <summary>
/// Outer object for handle inversion test.
/// </summary>
public class InversionOuter
{
public InversionInner Inner;
}
/// <summary>
/// Inner object for handle inversion test.
/// </summary>
public class InversionInner
{
public InversionOuter Outer;
}
/// <summary>
/// Object for composite array tests.
/// </summary>
public class CompositeArray
{
public object[] InArr;
public object[] OutArr;
}
/// <summary>
/// Object for composite collection/dictionary tests.
/// </summary>
public class CompositeContainer
{
public ICollection Col;
public IDictionary Dict;
}
/// <summary>
/// OUter object for composite structures test.
/// </summary>
public class CompositeOuter
{
public CompositeInner Inner;
public CompositeOuter()
{
// No-op.
}
public CompositeOuter(CompositeInner inner)
{
Inner = inner;
}
}
/// <summary>
/// Inner object for composite structures test.
/// </summary>
public class CompositeInner
{
public int Val;
public CompositeInner()
{
// No-op.
}
public CompositeInner(int val)
{
Val = val;
}
}
/// <summary>
/// Type to test "ToBinary()" logic.
/// </summary>
public class ToBinary
{
public int Val;
public ToBinary(int val)
{
Val = val;
}
}
/// <summary>
/// Type to test removal.
/// </summary>
public class Remove
{
public object Val;
public RemoveInner Val2;
}
/// <summary>
/// Inner type to test removal.
/// </summary>
public class RemoveInner
{
/** */
public int Val;
/// <summary>
///
/// </summary>
/// <param name="val"></param>
public RemoveInner(int val)
{
Val = val;
}
}
/// <summary>
///
/// </summary>
public class BuilderInBuilderOuter
{
/** */
public BuilderInBuilderInner Inner;
/** */
public BuilderInBuilderInner Inner2;
}
/// <summary>
///
/// </summary>
public class BuilderInBuilderInner
{
/** */
public BuilderInBuilderOuter Outer;
}
/// <summary>
///
/// </summary>
public class BuilderCollection
{
/** */
public readonly ArrayList Col;
/// <summary>
///
/// </summary>
/// <param name="col"></param>
public BuilderCollection(ArrayList col)
{
Col = col;
}
}
/// <summary>
///
/// </summary>
public class BuilderCollectionItem
{
/** */
public int Val;
/// <summary>
///
/// </summary>
/// <param name="val"></param>
public BuilderCollectionItem(int val)
{
Val = val;
}
}
/// <summary>
///
/// </summary>
public class DecimalHolder
{
/** */
public decimal Val;
/** */
public decimal?[] ValArr;
}
/// <summary>
/// Test id mapper.
/// </summary>
public class IdMapper : IBinaryIdMapper
{
/** */
public const string TestTypeName = "IdMapperTestType";
/** */
public const int TestTypeId = -65537;
/** <inheritdoc /> */
public int GetTypeId(string typeName)
{
return typeName == TestTypeName ? TestTypeId : 0;
}
/** <inheritdoc /> */
public int GetFieldId(int typeId, string fieldName)
{
return 0;
}
}
/// <summary>
/// Test name mapper.
/// </summary>
public class NameMapper : IBinaryNameMapper
{
/** */
public const string TestTypeName = "NameMapperTestType";
/** */
public const string TestFieldName = "NameMapperTestField";
/** <inheritdoc /> */
public string GetTypeName(string name)
{
if (name == TestTypeName)
return name + "_";
return name;
}
/** <inheritdoc /> */
public string GetFieldName(string name)
{
if (name == TestFieldName)
return name + "_";
return name;
}
}
/// <summary>
/// Name mapper test type.
/// </summary>
public class NameMapperTestType
{
/** */
public int NameMapperTestField { get; set; }
}
}
| |
/*
* ResourceWriter.cs - Implementation of the
* "System.Resources.ResourceWriter" class.
*
* Copyright (C) 2002, 2003 Southern Storm Software, Pty Ltd.
*
* 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; either version 2 of the License, or
* (at your option) any later version.
*
* 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
namespace System.Resources
{
#if CONFIG_RUNTIME_INFRA
using System;
using System.IO;
using System.Collections;
using System.Globalization;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters;
using System.Runtime.Serialization.Formatters.Binary;
#if ECMA_COMPAT
internal
#else
public
#endif
sealed class ResourceWriter : IDisposable, IResourceWriter
{
// Internal state.
private Stream stream;
private bool generateDone;
private Hashtable table;
private Hashtable ignoreCaseNames;
private ArrayList types;
private TextInfo info;
// Constructors.
public ResourceWriter(Stream stream)
{
if(stream == null)
{
throw new ArgumentNullException("stream");
}
else if(!stream.CanWrite)
{
throw new ArgumentException
(_("IO_NotSupp_Write"), "stream");
}
this.stream = stream;
generateDone = false;
table = new Hashtable();
ignoreCaseNames = new Hashtable();
types = new ArrayList();
info = CultureInfo.InvariantCulture.TextInfo;
}
public ResourceWriter(String fileName)
: this(new FileStream(fileName, FileMode.Create,
FileAccess.Write))
{
// Nothing to do here.
}
// Add a value to this writer.
private void AddValue(String name, Object value)
{
// See if we already have the name.
String lowerName = info.ToLower(name);
if(ignoreCaseNames.Contains(lowerName))
{
throw new ArgumentException
(_("Arg_ResourceAlreadyPresent"), "value");
}
// Add the name to "table".
table.Add(name, value);
// Add the lower-case name to "ignoreCaseNames".
ignoreCaseNames.Add(lowerName, String.Empty);
// Add the value's type to the type list.
if(value != null && !types.Contains(value.GetType()))
{
types.Add(value.GetType());
}
}
// Implement the IDisposable interface.
public void Dispose()
{
Close();
}
// Implement the IResourceWriter interface.
public void AddResource(String name, byte[] value)
{
if(name == null)
{
throw new ArgumentNullException("name");
}
else if(generateDone)
{
throw new InvalidOperationException
(_("Invalid_ResourceWriterClosed"));
}
else
{
AddValue(name, value);
}
}
public void AddResource(String name, Object value)
{
if(name == null)
{
throw new ArgumentNullException("name");
}
else if(generateDone)
{
throw new InvalidOperationException
(_("Invalid_ResourceWriterClosed"));
}
else
{
AddValue(name, value);
}
}
public void AddResource(String name, String value)
{
if(name == null)
{
throw new ArgumentNullException("name");
}
else if(generateDone)
{
throw new InvalidOperationException
(_("Invalid_ResourceWriterClosed"));
}
else
{
AddValue(name, value);
}
}
public void Close()
{
if(stream != null)
{
if(!generateDone)
{
Generate();
}
stream.Close();
stream = null;
}
}
public void Generate()
{
if(generateDone)
{
throw new InvalidOperationException
(_("Invalid_ResourceWriterClosed"));
}
BinaryWriter bw = new BinaryWriter(stream);
try
{
// Write the resource file header.
bw.Write(ResourceManager.MagicNumber);
bw.Write(ResourceManager.HeaderVersionNumber);
MemoryStream mem = new MemoryStream();
BinaryWriter membw = new BinaryWriter(mem);
membw.Write("System.Resources.ResourceReader, mscorlib");
membw.Write
("System.Resources.RuntimeResourceSet, mscorlib");
membw.Flush();
bw.Write((int)(mem.Length));
bw.Write(mem.GetBuffer(), 0, (int)(mem.Length));
// Write the resource set header.
bw.Write(1); // Resource set version number.
bw.Write(table.Count); // Number of resources.
// Create streams for the name and value sections.
MemoryStream names = new MemoryStream();
BinaryWriter namesWriter = new BinaryWriter(names);
MemoryStream values = new MemoryStream();
BinaryWriter valuesWriter = new BinaryWriter(values);
int[] nameHash = new int [table.Count];
int[] namePosition = new int [table.Count];
int posn = 0;
// Process all values in the resource set.
IDictionaryEnumerator e = table.GetEnumerator();
while(e.MoveNext())
{
// Hash the name and record the name position.
nameHash[posn] = ResourceReader.Hash((String)(e.Key));
namePosition[posn] = (int)(names.Position);
++posn;
// Write out the name and value index.
WriteKey(namesWriter, (String)(e.Key));
namesWriter.Write((int)(values.Position));
// Write the type table index to the value section.
Object value = e.Value;
if(value == null)
{
valuesWriter.Write7BitEncoded(-1);
}
else
{
valuesWriter.Write7BitEncoded
(types.IndexOf(value.GetType()));
}
// Write the value to the value section.
if(value != null)
{
WriteValue(values, valuesWriter, value);
}
}
// Write the type table.
bw.Write(types.Count);
foreach(Type t in types)
{
bw.Write(t.AssemblyQualifiedName);
}
// Align on an 8-byte boundary.
bw.Flush();
while((bw.BaseStream.Position & 7) != 0)
{
bw.Write((byte)0);
bw.Flush();
}
// Sort the name hash and write it out.
Array.Sort(nameHash, namePosition);
foreach(int hash in nameHash)
{
bw.Write(hash);
}
foreach(int pos in namePosition)
{
bw.Write(pos);
}
// Write the offset of the value section.
bw.Flush();
namesWriter.Flush();
valuesWriter.Flush();
bw.Write((int)(bw.BaseStream.Position + names.Length + 4));
// Write the name and value sections.
bw.Write(names.GetBuffer(), 0, (int)(names.Length));
bw.Write(values.GetBuffer(), 0, (int)(values.Length));
names.Close();
values.Close();
}
finally
{
generateDone = true;
bw.Flush();
((IDisposable)bw).Dispose();
}
}
// Write a resource value to a stream.
private void WriteValue(MemoryStream stream, BinaryWriter writer,
Object value)
{
Type type = value.GetType();
if(type == typeof(String))
{
writer.Write((String)value);
}
else if(type == typeof(Byte))
{
writer.Write((byte)value);
}
else if(type == typeof(SByte))
{
writer.Write((sbyte)value);
}
else if(type == typeof(Int16))
{
writer.Write((short)value);
}
else if(type == typeof(UInt16))
{
writer.Write((ushort)value);
}
else if(type == typeof(Int32))
{
writer.Write((int)value);
}
else if(type == typeof(UInt32))
{
writer.Write((uint)value);
}
else if(type == typeof(Int64))
{
writer.Write((long)value);
}
else if(type == typeof(UInt64))
{
writer.Write((ulong)value);
}
#if CONFIG_EXTENDED_NUMERICS
else if(type == typeof(Single))
{
writer.Write((float)value);
}
else if(type == typeof(Double))
{
writer.Write((double)value);
}
else if(type == typeof(Decimal))
{
int[] bits = Decimal.GetBits((Decimal)value);
writer.Write(bits[0]);
writer.Write(bits[1]);
writer.Write(bits[2]);
writer.Write(bits[3]);
}
#endif
else if(type == typeof(DateTime))
{
writer.Write(((DateTime)value).Ticks);
}
else if(type == typeof(TimeSpan))
{
writer.Write(((TimeSpan)value).Ticks);
}
else
{
#if CONFIG_SERIALIZATION
// Serialize the value with a binary formatter.
writer.Flush();
BinaryFormatter formatter;
formatter = new BinaryFormatter
(null, new StreamingContext
(StreamingContextStates.File |
StreamingContextStates.Persistence));
formatter.Serialize(stream, value);
#endif
}
}
// Write a key value.
private static void WriteKey(BinaryWriter writer, String key)
{
writer.Write7BitEncoded(key.Length * 2);
foreach(char ch in key)
{
writer.Write((ushort)ch);
}
}
}; // class ResourceWriter
#endif // CONFIG_RUNTIME_INFRA
}; // namespace System.Resources
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace WebTestApp.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/spanner/v1/query_plan.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Google.Cloud.Spanner.V1 {
/// <summary>Holder for reflection information generated from google/spanner/v1/query_plan.proto</summary>
public static partial class QueryPlanReflection {
#region Descriptor
/// <summary>File descriptor for google/spanner/v1/query_plan.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static QueryPlanReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CiJnb29nbGUvc3Bhbm5lci92MS9xdWVyeV9wbGFuLnByb3RvEhFnb29nbGUu",
"c3Bhbm5lci52MRocZ29vZ2xlL2FwaS9hbm5vdGF0aW9ucy5wcm90bxocZ29v",
"Z2xlL3Byb3RvYnVmL3N0cnVjdC5wcm90byL4BAoIUGxhbk5vZGUSDQoFaW5k",
"ZXgYASABKAUSLgoEa2luZBgCIAEoDjIgLmdvb2dsZS5zcGFubmVyLnYxLlBs",
"YW5Ob2RlLktpbmQSFAoMZGlzcGxheV9uYW1lGAMgASgJEjoKC2NoaWxkX2xp",
"bmtzGAQgAygLMiUuZ29vZ2xlLnNwYW5uZXIudjEuUGxhbk5vZGUuQ2hpbGRM",
"aW5rEk0KFHNob3J0X3JlcHJlc2VudGF0aW9uGAUgASgLMi8uZ29vZ2xlLnNw",
"YW5uZXIudjEuUGxhbk5vZGUuU2hvcnRSZXByZXNlbnRhdGlvbhIpCghtZXRh",
"ZGF0YRgGIAEoCzIXLmdvb2dsZS5wcm90b2J1Zi5TdHJ1Y3QSMAoPZXhlY3V0",
"aW9uX3N0YXRzGAcgASgLMhcuZ29vZ2xlLnByb3RvYnVmLlN0cnVjdBpACglD",
"aGlsZExpbmsSEwoLY2hpbGRfaW5kZXgYASABKAUSDAoEdHlwZRgCIAEoCRIQ",
"Cgh2YXJpYWJsZRgDIAEoCRqyAQoTU2hvcnRSZXByZXNlbnRhdGlvbhITCgtk",
"ZXNjcmlwdGlvbhgBIAEoCRJTCgpzdWJxdWVyaWVzGAIgAygLMj8uZ29vZ2xl",
"LnNwYW5uZXIudjEuUGxhbk5vZGUuU2hvcnRSZXByZXNlbnRhdGlvbi5TdWJx",
"dWVyaWVzRW50cnkaMQoPU3VicXVlcmllc0VudHJ5EgsKA2tleRgBIAEoCRIN",
"CgV2YWx1ZRgCIAEoBToCOAEiOAoES2luZBIUChBLSU5EX1VOU1BFQ0lGSUVE",
"EAASDgoKUkVMQVRJT05BTBABEgoKBlNDQUxBUhACIjwKCVF1ZXJ5UGxhbhIv",
"CgpwbGFuX25vZGVzGAEgAygLMhsuZ29vZ2xlLnNwYW5uZXIudjEuUGxhbk5v",
"ZGVClwEKFWNvbS5nb29nbGUuc3Bhbm5lci52MUIOUXVlcnlQbGFuUHJvdG9Q",
"AVo4Z29vZ2xlLmdvbGFuZy5vcmcvZ2VucHJvdG8vZ29vZ2xlYXBpcy9zcGFu",
"bmVyL3YxO3NwYW5uZXKqAhdHb29nbGUuQ2xvdWQuU3Bhbm5lci5WMcoCF0dv",
"b2dsZVxDbG91ZFxTcGFubmVyXFYxYgZwcm90bzM="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::Google.Api.AnnotationsReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.StructReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Spanner.V1.PlanNode), global::Google.Cloud.Spanner.V1.PlanNode.Parser, new[]{ "Index", "Kind", "DisplayName", "ChildLinks", "ShortRepresentation", "Metadata", "ExecutionStats" }, null, new[]{ typeof(global::Google.Cloud.Spanner.V1.PlanNode.Types.Kind) }, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Spanner.V1.PlanNode.Types.ChildLink), global::Google.Cloud.Spanner.V1.PlanNode.Types.ChildLink.Parser, new[]{ "ChildIndex", "Type", "Variable" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Spanner.V1.PlanNode.Types.ShortRepresentation), global::Google.Cloud.Spanner.V1.PlanNode.Types.ShortRepresentation.Parser, new[]{ "Description", "Subqueries" }, null, null, new pbr::GeneratedClrTypeInfo[] { null, })}),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Spanner.V1.QueryPlan), global::Google.Cloud.Spanner.V1.QueryPlan.Parser, new[]{ "PlanNodes" }, null, null, null)
}));
}
#endregion
}
#region Messages
/// <summary>
/// Node information for nodes appearing in a [QueryPlan.plan_nodes][google.spanner.v1.QueryPlan.plan_nodes].
/// </summary>
public sealed partial class PlanNode : pb::IMessage<PlanNode> {
private static readonly pb::MessageParser<PlanNode> _parser = new pb::MessageParser<PlanNode>(() => new PlanNode());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<PlanNode> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Spanner.V1.QueryPlanReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PlanNode() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PlanNode(PlanNode other) : this() {
index_ = other.index_;
kind_ = other.kind_;
displayName_ = other.displayName_;
childLinks_ = other.childLinks_.Clone();
ShortRepresentation = other.shortRepresentation_ != null ? other.ShortRepresentation.Clone() : null;
Metadata = other.metadata_ != null ? other.Metadata.Clone() : null;
ExecutionStats = other.executionStats_ != null ? other.ExecutionStats.Clone() : null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public PlanNode Clone() {
return new PlanNode(this);
}
/// <summary>Field number for the "index" field.</summary>
public const int IndexFieldNumber = 1;
private int index_;
/// <summary>
/// The `PlanNode`'s index in [node list][google.spanner.v1.QueryPlan.plan_nodes].
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int Index {
get { return index_; }
set {
index_ = value;
}
}
/// <summary>Field number for the "kind" field.</summary>
public const int KindFieldNumber = 2;
private global::Google.Cloud.Spanner.V1.PlanNode.Types.Kind kind_ = 0;
/// <summary>
/// Used to determine the type of node. May be needed for visualizing
/// different kinds of nodes differently. For example, If the node is a
/// [SCALAR][google.spanner.v1.PlanNode.Kind.SCALAR] node, it will have a condensed representation
/// which can be used to directly embed a description of the node in its
/// parent.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Cloud.Spanner.V1.PlanNode.Types.Kind Kind {
get { return kind_; }
set {
kind_ = value;
}
}
/// <summary>Field number for the "display_name" field.</summary>
public const int DisplayNameFieldNumber = 3;
private string displayName_ = "";
/// <summary>
/// The display name for the node.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string DisplayName {
get { return displayName_; }
set {
displayName_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "child_links" field.</summary>
public const int ChildLinksFieldNumber = 4;
private static readonly pb::FieldCodec<global::Google.Cloud.Spanner.V1.PlanNode.Types.ChildLink> _repeated_childLinks_codec
= pb::FieldCodec.ForMessage(34, global::Google.Cloud.Spanner.V1.PlanNode.Types.ChildLink.Parser);
private readonly pbc::RepeatedField<global::Google.Cloud.Spanner.V1.PlanNode.Types.ChildLink> childLinks_ = new pbc::RepeatedField<global::Google.Cloud.Spanner.V1.PlanNode.Types.ChildLink>();
/// <summary>
/// List of child node `index`es and their relationship to this parent.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::Google.Cloud.Spanner.V1.PlanNode.Types.ChildLink> ChildLinks {
get { return childLinks_; }
}
/// <summary>Field number for the "short_representation" field.</summary>
public const int ShortRepresentationFieldNumber = 5;
private global::Google.Cloud.Spanner.V1.PlanNode.Types.ShortRepresentation shortRepresentation_;
/// <summary>
/// Condensed representation for [SCALAR][google.spanner.v1.PlanNode.Kind.SCALAR] nodes.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Cloud.Spanner.V1.PlanNode.Types.ShortRepresentation ShortRepresentation {
get { return shortRepresentation_; }
set {
shortRepresentation_ = value;
}
}
/// <summary>Field number for the "metadata" field.</summary>
public const int MetadataFieldNumber = 6;
private global::Google.Protobuf.WellKnownTypes.Struct metadata_;
/// <summary>
/// Attributes relevant to the node contained in a group of key-value pairs.
/// For example, a Parameter Reference node could have the following
/// information in its metadata:
///
/// {
/// "parameter_reference": "param1",
/// "parameter_type": "array"
/// }
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Protobuf.WellKnownTypes.Struct Metadata {
get { return metadata_; }
set {
metadata_ = value;
}
}
/// <summary>Field number for the "execution_stats" field.</summary>
public const int ExecutionStatsFieldNumber = 7;
private global::Google.Protobuf.WellKnownTypes.Struct executionStats_;
/// <summary>
/// The execution statistics associated with the node, contained in a group of
/// key-value pairs. Only present if the plan was returned as a result of a
/// profile query. For example, number of executions, number of rows/time per
/// execution etc.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Protobuf.WellKnownTypes.Struct ExecutionStats {
get { return executionStats_; }
set {
executionStats_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as PlanNode);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(PlanNode other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Index != other.Index) return false;
if (Kind != other.Kind) return false;
if (DisplayName != other.DisplayName) return false;
if(!childLinks_.Equals(other.childLinks_)) return false;
if (!object.Equals(ShortRepresentation, other.ShortRepresentation)) return false;
if (!object.Equals(Metadata, other.Metadata)) return false;
if (!object.Equals(ExecutionStats, other.ExecutionStats)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Index != 0) hash ^= Index.GetHashCode();
if (Kind != 0) hash ^= Kind.GetHashCode();
if (DisplayName.Length != 0) hash ^= DisplayName.GetHashCode();
hash ^= childLinks_.GetHashCode();
if (shortRepresentation_ != null) hash ^= ShortRepresentation.GetHashCode();
if (metadata_ != null) hash ^= Metadata.GetHashCode();
if (executionStats_ != null) hash ^= ExecutionStats.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Index != 0) {
output.WriteRawTag(8);
output.WriteInt32(Index);
}
if (Kind != 0) {
output.WriteRawTag(16);
output.WriteEnum((int) Kind);
}
if (DisplayName.Length != 0) {
output.WriteRawTag(26);
output.WriteString(DisplayName);
}
childLinks_.WriteTo(output, _repeated_childLinks_codec);
if (shortRepresentation_ != null) {
output.WriteRawTag(42);
output.WriteMessage(ShortRepresentation);
}
if (metadata_ != null) {
output.WriteRawTag(50);
output.WriteMessage(Metadata);
}
if (executionStats_ != null) {
output.WriteRawTag(58);
output.WriteMessage(ExecutionStats);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Index != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(Index);
}
if (Kind != 0) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Kind);
}
if (DisplayName.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(DisplayName);
}
size += childLinks_.CalculateSize(_repeated_childLinks_codec);
if (shortRepresentation_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(ShortRepresentation);
}
if (metadata_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Metadata);
}
if (executionStats_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(ExecutionStats);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(PlanNode other) {
if (other == null) {
return;
}
if (other.Index != 0) {
Index = other.Index;
}
if (other.Kind != 0) {
Kind = other.Kind;
}
if (other.DisplayName.Length != 0) {
DisplayName = other.DisplayName;
}
childLinks_.Add(other.childLinks_);
if (other.shortRepresentation_ != null) {
if (shortRepresentation_ == null) {
shortRepresentation_ = new global::Google.Cloud.Spanner.V1.PlanNode.Types.ShortRepresentation();
}
ShortRepresentation.MergeFrom(other.ShortRepresentation);
}
if (other.metadata_ != null) {
if (metadata_ == null) {
metadata_ = new global::Google.Protobuf.WellKnownTypes.Struct();
}
Metadata.MergeFrom(other.Metadata);
}
if (other.executionStats_ != null) {
if (executionStats_ == null) {
executionStats_ = new global::Google.Protobuf.WellKnownTypes.Struct();
}
ExecutionStats.MergeFrom(other.ExecutionStats);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
Index = input.ReadInt32();
break;
}
case 16: {
kind_ = (global::Google.Cloud.Spanner.V1.PlanNode.Types.Kind) input.ReadEnum();
break;
}
case 26: {
DisplayName = input.ReadString();
break;
}
case 34: {
childLinks_.AddEntriesFrom(input, _repeated_childLinks_codec);
break;
}
case 42: {
if (shortRepresentation_ == null) {
shortRepresentation_ = new global::Google.Cloud.Spanner.V1.PlanNode.Types.ShortRepresentation();
}
input.ReadMessage(shortRepresentation_);
break;
}
case 50: {
if (metadata_ == null) {
metadata_ = new global::Google.Protobuf.WellKnownTypes.Struct();
}
input.ReadMessage(metadata_);
break;
}
case 58: {
if (executionStats_ == null) {
executionStats_ = new global::Google.Protobuf.WellKnownTypes.Struct();
}
input.ReadMessage(executionStats_);
break;
}
}
}
}
#region Nested types
/// <summary>Container for nested types declared in the PlanNode message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static partial class Types {
/// <summary>
/// The kind of [PlanNode][google.spanner.v1.PlanNode]. Distinguishes between the two different kinds of
/// nodes that can appear in a query plan.
/// </summary>
public enum Kind {
/// <summary>
/// Not specified.
/// </summary>
[pbr::OriginalName("KIND_UNSPECIFIED")] Unspecified = 0,
/// <summary>
/// Denotes a Relational operator node in the expression tree. Relational
/// operators represent iterative processing of rows during query execution.
/// For example, a `TableScan` operation that reads rows from a table.
/// </summary>
[pbr::OriginalName("RELATIONAL")] Relational = 1,
/// <summary>
/// Denotes a Scalar node in the expression tree. Scalar nodes represent
/// non-iterable entities in the query plan. For example, constants or
/// arithmetic operators appearing inside predicate expressions or references
/// to column names.
/// </summary>
[pbr::OriginalName("SCALAR")] Scalar = 2,
}
/// <summary>
/// Metadata associated with a parent-child relationship appearing in a
/// [PlanNode][google.spanner.v1.PlanNode].
/// </summary>
public sealed partial class ChildLink : pb::IMessage<ChildLink> {
private static readonly pb::MessageParser<ChildLink> _parser = new pb::MessageParser<ChildLink>(() => new ChildLink());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<ChildLink> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Spanner.V1.PlanNode.Descriptor.NestedTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ChildLink() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ChildLink(ChildLink other) : this() {
childIndex_ = other.childIndex_;
type_ = other.type_;
variable_ = other.variable_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ChildLink Clone() {
return new ChildLink(this);
}
/// <summary>Field number for the "child_index" field.</summary>
public const int ChildIndexFieldNumber = 1;
private int childIndex_;
/// <summary>
/// The node to which the link points.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int ChildIndex {
get { return childIndex_; }
set {
childIndex_ = value;
}
}
/// <summary>Field number for the "type" field.</summary>
public const int TypeFieldNumber = 2;
private string type_ = "";
/// <summary>
/// The type of the link. For example, in Hash Joins this could be used to
/// distinguish between the build child and the probe child, or in the case
/// of the child being an output variable, to represent the tag associated
/// with the output variable.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Type {
get { return type_; }
set {
type_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "variable" field.</summary>
public const int VariableFieldNumber = 3;
private string variable_ = "";
/// <summary>
/// Only present if the child node is [SCALAR][google.spanner.v1.PlanNode.Kind.SCALAR] and corresponds
/// to an output variable of the parent node. The field carries the name of
/// the output variable.
/// For example, a `TableScan` operator that reads rows from a table will
/// have child links to the `SCALAR` nodes representing the output variables
/// created for each column that is read by the operator. The corresponding
/// `variable` fields will be set to the variable names assigned to the
/// columns.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Variable {
get { return variable_; }
set {
variable_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as ChildLink);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(ChildLink other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (ChildIndex != other.ChildIndex) return false;
if (Type != other.Type) return false;
if (Variable != other.Variable) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (ChildIndex != 0) hash ^= ChildIndex.GetHashCode();
if (Type.Length != 0) hash ^= Type.GetHashCode();
if (Variable.Length != 0) hash ^= Variable.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (ChildIndex != 0) {
output.WriteRawTag(8);
output.WriteInt32(ChildIndex);
}
if (Type.Length != 0) {
output.WriteRawTag(18);
output.WriteString(Type);
}
if (Variable.Length != 0) {
output.WriteRawTag(26);
output.WriteString(Variable);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (ChildIndex != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(ChildIndex);
}
if (Type.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Type);
}
if (Variable.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Variable);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(ChildLink other) {
if (other == null) {
return;
}
if (other.ChildIndex != 0) {
ChildIndex = other.ChildIndex;
}
if (other.Type.Length != 0) {
Type = other.Type;
}
if (other.Variable.Length != 0) {
Variable = other.Variable;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
ChildIndex = input.ReadInt32();
break;
}
case 18: {
Type = input.ReadString();
break;
}
case 26: {
Variable = input.ReadString();
break;
}
}
}
}
}
/// <summary>
/// Condensed representation of a node and its subtree. Only present for
/// `SCALAR` [PlanNode(s)][google.spanner.v1.PlanNode].
/// </summary>
public sealed partial class ShortRepresentation : pb::IMessage<ShortRepresentation> {
private static readonly pb::MessageParser<ShortRepresentation> _parser = new pb::MessageParser<ShortRepresentation>(() => new ShortRepresentation());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<ShortRepresentation> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Spanner.V1.PlanNode.Descriptor.NestedTypes[1]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ShortRepresentation() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ShortRepresentation(ShortRepresentation other) : this() {
description_ = other.description_;
subqueries_ = other.subqueries_.Clone();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ShortRepresentation Clone() {
return new ShortRepresentation(this);
}
/// <summary>Field number for the "description" field.</summary>
public const int DescriptionFieldNumber = 1;
private string description_ = "";
/// <summary>
/// A string representation of the expression subtree rooted at this node.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Description {
get { return description_; }
set {
description_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "subqueries" field.</summary>
public const int SubqueriesFieldNumber = 2;
private static readonly pbc::MapField<string, int>.Codec _map_subqueries_codec
= new pbc::MapField<string, int>.Codec(pb::FieldCodec.ForString(10), pb::FieldCodec.ForInt32(16), 18);
private readonly pbc::MapField<string, int> subqueries_ = new pbc::MapField<string, int>();
/// <summary>
/// A mapping of (subquery variable name) -> (subquery node id) for cases
/// where the `description` string of this node references a `SCALAR`
/// subquery contained in the expression subtree rooted at this node. The
/// referenced `SCALAR` subquery may not necessarily be a direct child of
/// this node.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::MapField<string, int> Subqueries {
get { return subqueries_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as ShortRepresentation);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(ShortRepresentation other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Description != other.Description) return false;
if (!Subqueries.Equals(other.Subqueries)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Description.Length != 0) hash ^= Description.GetHashCode();
hash ^= Subqueries.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Description.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Description);
}
subqueries_.WriteTo(output, _map_subqueries_codec);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Description.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Description);
}
size += subqueries_.CalculateSize(_map_subqueries_codec);
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(ShortRepresentation other) {
if (other == null) {
return;
}
if (other.Description.Length != 0) {
Description = other.Description;
}
subqueries_.Add(other.subqueries_);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
Description = input.ReadString();
break;
}
case 18: {
subqueries_.AddEntriesFrom(input, _map_subqueries_codec);
break;
}
}
}
}
}
}
#endregion
}
/// <summary>
/// Contains an ordered list of nodes appearing in the query plan.
/// </summary>
public sealed partial class QueryPlan : pb::IMessage<QueryPlan> {
private static readonly pb::MessageParser<QueryPlan> _parser = new pb::MessageParser<QueryPlan>(() => new QueryPlan());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<QueryPlan> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Spanner.V1.QueryPlanReflection.Descriptor.MessageTypes[1]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public QueryPlan() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public QueryPlan(QueryPlan other) : this() {
planNodes_ = other.planNodes_.Clone();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public QueryPlan Clone() {
return new QueryPlan(this);
}
/// <summary>Field number for the "plan_nodes" field.</summary>
public const int PlanNodesFieldNumber = 1;
private static readonly pb::FieldCodec<global::Google.Cloud.Spanner.V1.PlanNode> _repeated_planNodes_codec
= pb::FieldCodec.ForMessage(10, global::Google.Cloud.Spanner.V1.PlanNode.Parser);
private readonly pbc::RepeatedField<global::Google.Cloud.Spanner.V1.PlanNode> planNodes_ = new pbc::RepeatedField<global::Google.Cloud.Spanner.V1.PlanNode>();
/// <summary>
/// The nodes in the query plan. Plan nodes are returned in pre-order starting
/// with the plan root. Each [PlanNode][google.spanner.v1.PlanNode]'s `id` corresponds to its index in
/// `plan_nodes`.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::Google.Cloud.Spanner.V1.PlanNode> PlanNodes {
get { return planNodes_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as QueryPlan);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(QueryPlan other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if(!planNodes_.Equals(other.planNodes_)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
hash ^= planNodes_.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
planNodes_.WriteTo(output, _repeated_planNodes_codec);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
size += planNodes_.CalculateSize(_repeated_planNodes_codec);
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(QueryPlan other) {
if (other == null) {
return;
}
planNodes_.Add(other.planNodes_);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
planNodes_.AddEntriesFrom(input, _repeated_planNodes_codec);
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Entities.Blocks;
using Rynchodon.Settings;
using Rynchodon.Utility;
using Rynchodon.Utility.Network;
using Rynchodon.Utility.Vectors;
using Sandbox.Definitions;
using Sandbox.Game.Entities;
using Sandbox.Game.Gui;
using Sandbox.ModAPI;
using Sandbox.ModAPI.Interfaces.Terminal;
using VRage.Game;
using VRage.Game.Entity;
using VRage.Game.ModAPI;
using VRage.ModAPI;
using VRage.ObjectBuilders;
using VRage.Utils;
using VRageMath;
namespace Rynchodon.AntennaRelay
{
/// <summary>
/// Projects miniature ships. Could do asteroids / planets in the future or other entities.
/// </summary>
public class Projector
{
private enum Option : byte
{
None = 0,
Owner = ExtensionsRelations.Relations.Owner,
Faction = ExtensionsRelations.Relations.Faction,
Neutral = ExtensionsRelations.Relations.Neutral,
Enemy = ExtensionsRelations.Relations.Enemy,
ThisShip = 128,
OnOff = 16,
IntegrityColours = 32,
//ShowOffset = 64
}
private class StaticVariables
{
public readonly Vector3[] Directions = { Vector3.Zero, Vector3.Right, Vector3.Left, Vector3.Up, Vector3.Down, Vector3.Backward, Vector3.Forward };
/// <summary>Maximum time since detection for entity to be displayed.</summary>
public readonly TimeSpan displayAllowed = new TimeSpan(0, 0, 2);
/// <summary>Maximum time since detection for entity to be kept in cache.</summary>
public readonly TimeSpan keepInCache = new TimeSpan(0, 1, 0);
public readonly List<IMyTerminalControl> TermControls = new List<IMyTerminalControl>();
public readonly List<IMyTerminalControl> TermControls_Colours = new List<IMyTerminalControl>();
public readonly List<IMyTerminalControl> TermControls_Offset = new List<IMyTerminalControl>();
public bool MouseControls, ShowOffset;
public Color
value_IntegrityFull = new Color(UserSettings.GetSetting(UserSettings.IntSettingName.IntegrityFull)),
value_IntegrityFunctional = new Color(UserSettings.GetSetting(UserSettings.IntSettingName.IntegrityFunctional)),
value_IntegrityDamaged = new Color(UserSettings.GetSetting(UserSettings.IntSettingName.IntegrityDamaged)),
value_IntegrityZero = new Color(UserSettings.GetSetting(UserSettings.IntSettingName.IntegrityZero));
public StaticVariables()
{
Logger.DebugLog("entered", Logger.severity.TRACE);
MyAPIGateway.Session.DamageSystem.RegisterAfterDamageHandler((int)MyDamageSystemPriority.Low, AfterDamageHandler);
TerminalControlHelper.EnsureTerminalControlCreated<MySpaceProjector>();
TermControls.Add(new MyTerminalControlSeparator<MySpaceProjector>());
AddCheckbox("HoloDisplay", "Holographic Display", "Holographically display this ship and nearby detected ships", Option.OnOff);
AddCheckbox("HD_This_Ship", "This Ship", "Holographically display this ship", Option.ThisShip);
AddCheckbox("HD_Owner", "Owned Ships", "Holographically display ships owned by this block's owner", Option.Owner);
AddCheckbox("HD_Faction", "Faction Ships", "Holographically display faction owned ships", Option.Faction);
AddCheckbox("HD_Neutral", "Neutral Ships", "Holographically display neutral ships", Option.Neutral);
AddCheckbox("HD_Enemy", "Enemy Ships", "Holographically display enemy ships", Option.Enemy);
MyTerminalControlSlider<MySpaceProjector> slider = new MyTerminalControlSlider<MySpaceProjector>("HD_RangeDetection", MyStringId.GetOrCompute("Detection Range"), MyStringId.GetOrCompute("Maximum distance of detected entity"));
ValueSync<float, Projector> tvsRange = new ValueSync<float, Projector>(slider, (proj) => proj.m_rangeDetection, (proj, value) => proj.m_rangeDetection = value);
slider.DefaultValue = DefaultRangeDetection;
slider.Normalizer = (block, value) => Normalizer(MinRangeDetection, MaxRangeDetection, block, value);
slider.Denormalizer = (block, value) => Denormalizer(MinRangeDetection, MaxRangeDetection, block, value);
slider.Writer = (block, sb) => WriterMetres(tvsRange.GetValue(block), sb);
TermControls.Add(slider);
slider = new MyTerminalControlSlider<MySpaceProjector>("HD_RadiusHolo", MyStringId.GetOrCompute("Hologram Radius"), MyStringId.GetOrCompute("Maximum radius of hologram"));
ValueSync<float, Projector> tvsRadius = new ValueSync<float, Projector>(slider, (proj) => proj.m_radiusHolo, (proj, value) => proj.m_radiusHolo = value);
slider.DefaultValue = DefaultRadiusHolo;
slider.Normalizer = (block, value) => Normalizer(MinRadiusHolo, MaxRadiusHolo, block, value);
slider.Denormalizer = (block, value) => Denormalizer(MinRadiusHolo, MaxRadiusHolo, block, value);
slider.Writer = (block, sb) => WriterMetres(tvsRadius.GetValue(block), sb);
TermControls.Add(slider);
slider = new MyTerminalControlSlider<MySpaceProjector>("HD_EntitySizeScale", MyStringId.GetOrCompute("Entity Size Scale"), MyStringId.GetOrCompute("Larger value causes entities to appear larger"));
ValueSync<float, Projector> tvsScale = new ValueSync<float, Projector>(slider, (proj) => proj.m_sizeDistScale, (proj, value) => proj.m_sizeDistScale = value);
slider.DefaultValue = DefaultSizeScale;
slider.Normalizer = (block, value) => Normalizer(MinSizeScale, MaxSizeScale, block, value);
slider.Denormalizer = (block, value) => Denormalizer(MinSizeScale, MaxSizeScale, block, value);
slider.Writer = (block, sb) => sb.Append(tvsScale.GetValue(block));
TermControls.Add(slider);
TermControls.Add(new MyTerminalControlSeparator<MySpaceProjector>());
MyTerminalControlCheckbox<MySpaceProjector> control = new MyTerminalControlCheckbox<MySpaceProjector>("HD_MouseControls", MyStringId.GetOrCompute("Mouse Controls"),
MyStringId.GetOrCompute("Allow manipulation of hologram with mouse. User-specific setting."));
IMyTerminalValueControl<bool> valueControlBool = control;
valueControlBool.Getter = block => MouseControls;
valueControlBool.Setter = (block, value) => MouseControls = value;
TermControls.Add(control);
control = new MyTerminalControlCheckbox<MySpaceProjector>("HD_ShowBoundary", MyStringId.GetOrCompute("Show Boundary"), MyStringId.GetOrCompute("Show the boundaries of the hologram. User-specific setting."));
valueControlBool = control;
valueControlBool.Getter = block => ShowBoundary;
valueControlBool.Setter = (block, value) => ShowBoundary = value;
TermControls.Add(control);
control = new MyTerminalControlCheckbox<MySpaceProjector>("HD_ShowOffset", MyStringId.GetOrCompute("Show Offset Controls"), MyStringId.GetOrCompute("Display controls that can be used to adjust the position of the hologram. User-specific setting."));
control.Getter = block => ShowOffset;
control.Setter = (block, value) => {
ShowOffset = value;
block.RebuildControls();
};
TermControls.Add(control);
AddOffsetSlider("HD_OffsetX", "Right/Left Offset", "+ve moves hologram to the right, -ve moves hologram to the left", 0);
AddOffsetSlider("HD_OffsetY", "Up/Down Offset", "+ve moves hologram up, -ve moves hologram down", 1);
AddOffsetSlider("HD_OffsetZ", "Back/Fore Offset", "+ve moves hologram back, -ve moves hologram forward", 2);
TermControls_Offset.Add(new MyTerminalControlSeparator<MySpaceProjector>());
AddCheckbox("HD_IntegrityColour", "Colour by Integrity", "Colour blocks according to their integrities", Option.IntegrityColours);
IMyTerminalControlColor colour = MyAPIGateway.TerminalControls.CreateControl<IMyTerminalControlColor, IMyProjector>("HD_FullIntegriyColour");
colour.Title = MyStringId.GetOrCompute("Whole");
colour.Tooltip = MyStringId.GetOrCompute("Colour when block has full integrity. User-specific setting.");
colour.Getter = (block) => IntegrityFull;
colour.Setter = (block, value) => IntegrityFull = value;
TermControls_Colours.Add(colour);
colour = MyAPIGateway.TerminalControls.CreateControl<IMyTerminalControlColor, IMyProjector>("HD_CriticalIntegriyColour");
colour.Title = MyStringId.GetOrCompute("Func.");
colour.Tooltip = MyStringId.GetOrCompute("Colour when block is just above critical integrity. User-specific setting.");
colour.Getter = (block) => IntegrityFunctional;
colour.Setter = (block, value) => IntegrityFunctional = value;
TermControls_Colours.Add(colour);
colour = MyAPIGateway.TerminalControls.CreateControl<IMyTerminalControlColor, IMyProjector>("HD_CriticalIntegriyColour");
colour.Title = MyStringId.GetOrCompute("Broken");
colour.Tooltip = MyStringId.GetOrCompute("Colour when block is just below critical integrity. User-specific setting.");
colour.Getter = (block) => IntegrityDamaged;
colour.Setter = (block, value) => IntegrityDamaged = value;
TermControls_Colours.Add(colour);
colour = MyAPIGateway.TerminalControls.CreateControl<IMyTerminalControlColor, IMyProjector>("HD_ZeroIntegriyColour");
colour.Title = MyStringId.GetOrCompute("Razed");
colour.Tooltip = MyStringId.GetOrCompute("Colour when block has zero integrity. User-specific setting.");
colour.Getter = (block) => IntegrityZero;
colour.Setter = (block, value) => IntegrityZero = value;
TermControls_Colours.Add(colour);
new ValueSync<long, Projector>("CentreEntity",
(script) => script.m_centreEntityId,
(script, value) => {
script.m_centreEntityId = value;
script.m_centreEntityId_AfterValueChanged();
});
}
#region Terminal Controls
private void AddCheckbox(string id, string title, string toolTip, Option opt)
{
MyTerminalControlCheckbox<MySpaceProjector> control = new MyTerminalControlCheckbox<MySpaceProjector>(id, MyStringId.GetOrCompute(title), MyStringId.GetOrCompute(toolTip));
new ValueSync<bool, Projector>(control,
(proj) => (proj.m_options & opt) == opt,
(proj, value) => {
Logger.DebugLog("set option: " + opt + " to " + value + ", current options: " + proj.m_options);
if (value)
proj.m_options |= opt;
else
proj.m_options &= ~opt;
if (opt == Option.OnOff || opt == Option.IntegrityColours)
proj.m_block.RebuildControls();
});
TermControls.Add(control);
}
private void AddOffsetSlider(string id, string title, string toolTip, int dim)
{
MyTerminalControlSlider<MySpaceProjector> control = new MyTerminalControlSlider<MySpaceProjector>(id, MyStringId.GetOrCompute(title), MyStringId.GetOrCompute(toolTip));
ValueSync<float, Projector> tvs = new ValueSync<float, Projector>(control, (proj) => proj.m_offset_ev.GetDim(dim), (proj, value) => proj.m_offset_ev.SetDim(dim, value));
control.DefaultValue = dim == 1 ? 2.5f : 0f;
control.Normalizer = (block, value) => Normalizer(MinOffset, MaxOffset, block, value);
control.Denormalizer = (block, value) => Denormalizer(MinOffset, MaxOffset, block, value);
control.Writer = (block, sb) => WriterMetres(tvs.GetValue(block), sb);
TermControls_Offset.Add(control);
}
public void CustomControlGetter(IMyTerminalBlock block, List<IMyTerminalControl> controls)
{
if (!(block is IMyProjector))
return;
Projector instance;
if (!Registrar.TryGetValue(block, out instance))
{
if (!Globals.WorldClosed)
Logger.AlwaysLog("Failed to get block: " + block.nameWithId());
return;
}
controls.Add(TermControls[0]);
controls.Add(TermControls[1]);
if (instance.GetOption(Option.OnOff))
{
// find show on hud
int indexSOH = 0;
for (; indexSOH < controls.Count && controls[indexSOH].Id != "ShowOnHUD"; indexSOH++) ;
// remove all controls after ShowOnHUD and before separator
controls.RemoveRange(indexSOH + 1, controls.Count - indexSOH - 3);
bool showOffset = ShowOffset;
for (int index = 2; index < TermControls.Count; index++)
{
controls.Add(TermControls[index]);
if (showOffset && TermControls[index].Id == "HD_ShowOffset")
{
showOffset = false;
foreach (var offset in TermControls_Offset)
controls.Add(offset);
}
}
if (instance.GetOption(Option.IntegrityColours))
foreach (var colour in TermControls_Colours)
controls.Add(colour);
}
}
private float Normalizer(float min, float max, IMyTerminalBlock block, float value)
{
return (value - min) / (max - min);
}
private float Denormalizer(float min, float max, IMyTerminalBlock block, float value)
{
return min + value * (max - min);
}
private void WriterMetres(float value, StringBuilder stringBuilder)
{
stringBuilder.Append(PrettySI.makePretty(value));
stringBuilder.Append("m");
}
public void UpdateVisual()
{
foreach (var control in TermControls)
control.UpdateVisual();
}
#endregion Terminal Controls
}
public static Color IntegrityFull
{
get { return Static.value_IntegrityFull; }
set
{
Static.value_IntegrityFull = value;
UserSettings.SetSetting(UserSettings.IntSettingName.IntegrityFull, value.PackedValue);
}
}
public static Color IntegrityFunctional
{
get { return Static.value_IntegrityFunctional; }
set
{
Static.value_IntegrityFunctional = value;
UserSettings.SetSetting(UserSettings.IntSettingName.IntegrityFunctional, value.PackedValue);
}
}
public static Color IntegrityDamaged
{
get { return Static.value_IntegrityDamaged; }
set
{
Static.value_IntegrityDamaged = value;
UserSettings.SetSetting(UserSettings.IntSettingName.IntegrityDamaged, value.PackedValue);
}
}
public static Color IntegrityZero
{
get { return Static.value_IntegrityZero; }
set
{
Static.value_IntegrityZero = value;
UserSettings.SetSetting(UserSettings.IntSettingName.IntegrityZero, value.PackedValue);
}
}
public static bool ShowBoundary
{
get { return UserSettings.GetSetting(UserSettings.BoolSettingName.HologramShowBoundary); }
set { UserSettings.SetSetting(UserSettings.BoolSettingName.HologramShowBoundary, value); }
}
private class SeenHolo
{
public LastSeen Seen;
public MyEntity Holo;
public bool ColouredByIntegrity;
}
private const float InputScrollMulti = 1f / 120f, ScrollRangeMulti = 1.1f;
private const float MinRangeDetection = 1e2f, MaxRangeDetection = 1e5f, DefaultRangeDetection = 1e3f;
private const float MinRadiusHolo = 1f, MaxRadiusHolo = 10f, DefaultRadiusHolo = 2.5f;
private const float MinSizeScale = 1f, MaxSizeScale = 1e3f, DefaultSizeScale = 1f;
private const float MinOffset = -20f, MaxOffset = 20f;
private const double CrosshairRange = 20d;
private static StaticVariables Static;
[OnWorldLoad]
private static void Init()
{
Static = new StaticVariables();
MyTerminalControls.Static.CustomControlGetter += Static.CustomControlGetter;
}
[OnWorldClose]
private static void Unload()
{
MyTerminalControls.Static.CustomControlGetter -= Static.CustomControlGetter;
Static = null;
}
private static void AfterDamageHandler(object obj, MyDamageInformation damageInfo)
{
if (!(obj is IMySlimBlock))
return;
// grind damage is handled by OnBlockIntegrityChanged, which is faster
if (damageInfo.Type == MyDamageType.Grind)
return;
IMySlimBlock block = (IMySlimBlock)obj;
long gridId = block.CubeGrid.EntityId;
Registrar.ForEach((Projector proj) => {
SeenHolo sh;
if (!proj.m_holoEntities.TryGetValue(gridId, out sh) || !sh.Holo.Render.Visible || !sh.ColouredByIntegrity)
return;
ColourBlock(block, (IMyCubeGrid)sh.Holo);
});
}
/// <summary>
/// Prepare a projected entity by disabling physics, game logic, etc.
/// </summary>
private static void SetupProjection(IMyEntity entity)
{
//Static.logger.debugLog(entity is IMyCubeGrid, "setup: " + entity.nameWithId());
//if (entity is IMyCubeBlock)
//{
// IMyCubeBlock block2 = (IMyCubeBlock)entity;
// Static.logger.debugLog("setup: " + block2.nameWithId() + ", on " + block2.CubeGrid.nameWithId());
//}
if (entity.Physics != null && entity.Physics.Enabled)
entity.Physics.Enabled = false;
//Static.logger.debugLog("initial flags: " + entity.Flags);
entity.Flags &= ~EntityFlags.NeedsResolveCastShadow;
entity.Flags &= ~EntityFlags.Save;
entity.Flags &= ~EntityFlags.Sync;
entity.NeedsUpdate = MyEntityUpdateEnum.NONE;
entity.PersistentFlags &= ~MyPersistentEntityFlags2.CastShadows;
entity.Flags |= EntityFlags.SkipIfTooSmall;
((MyEntity)entity).IsPreview = true;
//Static.logger.debugLog("final flags: " + entity.Flags);
MyCubeBlock block = entity as MyCubeBlock;
if (block != null)
{
if (block.UseObjectsComponent.DetectorPhysics != null && block.UseObjectsComponent.DetectorPhysics.Enabled)
block.UseObjectsComponent.DetectorPhysics.Enabled = false;
//block.NeedsUpdate = MyEntityUpdateEnum.NONE;
//if (block is Ingame.IMyBeacon || block is Ingame.IMyRadioAntenna)
// ((IMyFunctionalBlock)block).RequestEnable(false);
}
foreach (var child in entity.Hierarchy.Children)
SetupProjection(child.Container.Entity);
}
/// <summary>
/// Colours a block according to its integrity.
/// </summary>
private static void ColourBlock(IMySlimBlock realBlock, IMyCubeGrid holoGrid)
{
Logger.DebugLog("realBlock == null", Logger.severity.FATAL, condition: realBlock == null);
float integrityRatio = (realBlock.BuildIntegrity - realBlock.CurrentDamage) / realBlock.MaxIntegrity;
float criticalRatio = ((MyCubeBlockDefinition)realBlock.BlockDefinition).CriticalIntegrityRatio;
float scaledRatio;
Color blockColour;
Logger.DebugLog("integrityRatio: " + integrityRatio + ", criticalRatio: " + criticalRatio + ", fatblock: " + realBlock.FatBlock.getBestName() + ", functional: " + (realBlock.FatBlock != null && realBlock.FatBlock.IsFunctional), condition: integrityRatio != 1f);
if (integrityRatio > criticalRatio && (realBlock.FatBlock == null || realBlock.FatBlock.IsFunctional))
{
scaledRatio = (integrityRatio - criticalRatio) / (1f - criticalRatio);
blockColour = IntegrityFull * scaledRatio + IntegrityFunctional * (1f - scaledRatio);
}
else
{
scaledRatio = integrityRatio / criticalRatio;
blockColour = IntegrityDamaged * scaledRatio + IntegrityZero * (1f - scaledRatio);
}
holoGrid.ColorBlocks(realBlock.Position, realBlock.Position, blockColour.ColorToHSVDX11());
}
/// <summary>
/// Updates the appearance of the block if the integrity has changed. Only used for welding/griding.
/// </summary>
private static void UpdateBlockModel(IMySlimBlock realBlock, IMyCubeGrid holoGrid)
{
IMySlimBlock holoBlock = holoGrid.GetCubeBlock(realBlock.Position);
Logger.DebugLog("holoBlock == null", Logger.severity.FATAL, condition: holoBlock == null);
float realIntegrityRatio = (realBlock.BuildIntegrity - realBlock.CurrentDamage) / realBlock.MaxIntegrity;
float holoIntegrityRatio = (holoBlock.BuildIntegrity - holoBlock.CurrentDamage) / holoBlock.MaxIntegrity;
if (realIntegrityRatio == holoIntegrityRatio)
return;
float min, max;
if (realIntegrityRatio > holoIntegrityRatio)
{
max = realIntegrityRatio;
min = holoIntegrityRatio;
}
else
{
max = holoIntegrityRatio;
min = realIntegrityRatio;
}
if (((MyCubeBlockDefinition)realBlock.BlockDefinition).ModelChangeIsNeeded(min, max))
{
holoGrid.RemoveBlock(holoBlock);
MyObjectBuilder_CubeBlock objBuilder = realBlock.GetObjectBuilder();
objBuilder.EntityId = 0L;
holoGrid.AddBlock(objBuilder, false);
IMyCubeBlock cubeBlock = holoGrid.GetCubeBlock(realBlock.Position).FatBlock;
if (cubeBlock != null)
SetupProjection(cubeBlock);
}
}
private readonly IMyProjector m_block;
private readonly RelayClient m_netClient;
private readonly Dictionary<long, SeenHolo> m_holoEntities = new Dictionary<long, SeenHolo>();
/// <summary>List of entities to remove holo entirely, it will have to be re-created to be displayed again</summary>
private readonly List<long> m_holoEntitiesRemove = new List<long>();
private Option m_options;
/// <summary>How close a detected entity needs to be to be placed inside the holographic area.</summary>
private float m_rangeDetection;
/// <summary>Maximum radius of holographic area, holo entities should fit inside a sphere of this size.</summary>
private float m_radiusHolo;
/// <summary>Size scale is distance scale * m_sizeDistScale</summary>
private float m_sizeDistScale;
/// <summary>Id of the real entity that is centred</summary>
private long m_centreEntityId;
private Vector3 m_offset_ev;
private DateTime m_clearAllAt = DateTime.UtcNow + Static.keepInCache;
/// <summary>The real entity that is centred</summary>
private IMyEntity value_centreEntity;
private bool m_playerCanSee;
private bool Enabled { get { return m_block.IsWorking && (m_options & Option.OnOff) != 0; } }
private IMyEntity m_centreEntity { get { return value_centreEntity ?? m_block; } }
private PositionBlock m_offset { get { return m_offset_ev; } }
private Logable Log { get { return new Logable(m_block); } }
public Projector(IMyCubeBlock block)
{
if (Static == null)
throw new Exception("StaticVariables not loaded");
this.m_block = (IMyProjector)block;
this.m_netClient = new RelayClient(block);
Registrar.Add(block, this);
}
/// <summary>
/// Check opts, load/unload
/// </summary>
public void Update100()
{
if (m_holoEntities.Count != 0 && DateTime.UtcNow >= m_clearAllAt)
{
Log.DebugLog("clearing all holo entities");
foreach (SeenHolo sh in m_holoEntities.Values)
{
Log.DebugLog("removing " + sh.Seen.Entity.EntityId + "from m_holoEntities (clear all)");
OnRemove(sh);
}
m_holoEntities.Clear();
}
if (!Enabled)
return;
Vector3D playerPos = MyAPIGateway.Session.Player.GetPosition(), holoCentre = m_offset.ToWorld(m_block);
double distSquared = Vector3D.DistanceSquared(playerPos, holoCentre);
m_playerCanSee = distSquared <= 1e4d;
if (m_playerCanSee && distSquared > 100d)
{
List<MyLineSegmentOverlapResult<MyEntity>> entitiesInRay = ResourcePool<List<MyLineSegmentOverlapResult<MyEntity>>>.Get();
m_playerCanSee = false;
MyEntity[] ignore = new MyEntity[] { (MyEntity)MyAPIGateway.Session.Player.Controller.ControlledEntity };
foreach (Vector3 vector in Static.Directions)
{
LineD ray = new LineD(playerPos, holoCentre + vector * m_radiusHolo);
MyGamePruningStructure.GetTopmostEntitiesOverlappingRay(ref ray, entitiesInRay);
if (!RayCast.Obstructed(ray, entitiesInRay.Select(overlap => overlap.Element), ignore))
{
m_playerCanSee = true;
entitiesInRay.Clear();
break;
}
entitiesInRay.Clear();
}
ResourcePool<List<MyLineSegmentOverlapResult<MyEntity>>>.Return(entitiesInRay);
}
if (!m_playerCanSee)
return;
RelayStorage storage = m_netClient.GetStorage();
if (storage == null)
{
((IMyTerminalBlock)m_block).AppendCustomInfo("No network connection");
return;
}
m_clearAllAt = DateTime.UtcNow + Static.keepInCache;
storage.ForEachLastSeen(CreateHolo);
foreach (SeenHolo sh in m_holoEntities.Values)
{
if (CanDisplay(sh.Seen))
{
if (!sh.Holo.Render.Visible)
{
Log.DebugLog("showing holo: " + sh.Seen.Entity.getBestName());
SetupProjection(sh.Holo);
SetVisible(sh.Holo, true);
}
if (sh.Seen.Entity is MyCubeGrid && sh.ColouredByIntegrity != ((m_options & Option.IntegrityColours) != 0))
{
if (sh.ColouredByIntegrity)
RestoreColour(sh);
else
ColourByIntegrity(sh);
}
}
else if (sh.Holo.Render.Visible)
{
Log.DebugLog("hiding holo: " + sh.Seen.Entity.getBestName());
SetVisible(sh.Holo, false);
}
}
if (m_holoEntitiesRemove.Count != 0)
{
foreach (long entityId in m_holoEntitiesRemove)
{
Log.DebugLog("removing " + entityId + "from m_holoEntities");
SeenHolo sh;
if (!m_holoEntities.TryGetValue(entityId, out sh))
{
// this may be normal
Log.DebugLog("not in m_holoEntities: " + entityId, Logger.severity.WARNING);
continue;
}
OnRemove(sh);
m_holoEntities.Remove(entityId);
}
m_holoEntitiesRemove.Clear();
}
}
/// <summary>
/// Updates positions & orientations
/// </summary>
public void Update1()
{
if (!Enabled || !m_playerCanSee)
{
foreach (SeenHolo sh in m_holoEntities.Values)
if (sh.Holo.Render.Visible)
{
Log.DebugLog("hiding holo: " + sh.Seen.Entity.getBestName());
SetVisible(sh.Holo, false);
}
return;
}
if (MyGuiScreenTerminal.GetCurrentScreen() == MyTerminalPageEnum.None && MyAPIGateway.Session.ControlledObject.Entity is IMyCharacter && Static.MouseControls)
CheckInput();
PositionWorld projectionCentre = m_offset.ToWorld(m_block);
float distanceScale = m_radiusHolo / m_rangeDetection;
float sizeScale = distanceScale * m_sizeDistScale;
foreach (SeenHolo sh in m_holoEntities.Values)
{
MatrixD worldMatrix = sh.Seen.Entity.WorldMatrix;
worldMatrix.Translation = projectionCentre + (sh.Seen.Entity.GetPosition() - m_centreEntity.GetPosition()) * distanceScale + (sh.Seen.Entity.GetPosition() - sh.Seen.Entity.GetCentre()) * (sizeScale - distanceScale);
Log.DebugLog("entity: " + sh.Seen.Entity.getBestName() + "(" + sh.Seen.Entity.EntityId + "), centre: " + projectionCentre + ", offset: " + (worldMatrix.Translation - projectionCentre) + ", position: " + worldMatrix.Translation);
sh.Holo.PositionComp.SetWorldMatrix(worldMatrix);
sh.Holo.PositionComp.Scale = sizeScale;
}
if (ShowBoundary)
{
MatrixD sphereMatrix = m_block.WorldMatrix;
sphereMatrix.Translation = projectionCentre;
Color c = Color.Yellow;
MySimpleObjectDraw.DrawTransparentSphere(ref sphereMatrix, m_radiusHolo, ref c, MySimpleObjectRasterizer.Wireframe, 8);
}
}
private void CheckInput()
{
MatrixD headMatrix = MyAPIGateway.Session.ControlledObject.GetHeadMatrix(true);
RayD ray = new RayD(headMatrix.Translation, headMatrix.Forward);
BoundingSphereD holoSphere = new BoundingSphereD(m_offset.ToWorld(m_block), m_radiusHolo);
double tmin, tmax;
if (!holoSphere.IntersectRaySphere(ray, out tmin, out tmax) || tmin > CrosshairRange)
return;
int scroll = MyAPIGateway.Input.DeltaMouseScrollWheelValue();
if (scroll != 0)
{
int scrollSteps = (int)Math.Round(scroll * InputScrollMulti);
float rangeMulti = 1f;
while (scrollSteps > 0)
{
rangeMulti *= ScrollRangeMulti;
scrollSteps--;
}
while (scrollSteps < 0)
{
rangeMulti /= ScrollRangeMulti;
scrollSteps++;
}
m_rangeDetection *= rangeMulti;
}
if (MyAPIGateway.Input.IsNewRightMousePressed())
{
m_centreEntityId = 0L;
}
else if (MyAPIGateway.Input.IsNewLeftMousePressed())
{
IMyEntity firstHit = null;
double firstHitDistance = CrosshairRange;
foreach (SeenHolo sh in m_holoEntities.Values)
if (sh.Holo.Render.Visible && sh.Holo.PositionComp.WorldAABB.Intersect(ref ray, out tmin, out tmax) && tmin < firstHitDistance)
{
firstHit = sh.Seen.Entity;
firstHitDistance = tmin;
}
if (firstHit != null)
m_centreEntityId = firstHit.EntityId;
}
}
private bool CanDisplay(LastSeen seen)
{
if (!CheckRelations(seen.Entity))
return false;
TimeSpan time = Globals.ElapsedTime - seen.RadarInfoTime();
if (time > Static.displayAllowed)
{
if (time > Static.keepInCache)
m_holoEntitiesRemove.Add(seen.Entity.EntityId);
return false;
}
float rangeDetection = m_rangeDetection; rangeDetection *= rangeDetection;
return Vector3D.DistanceSquared(m_centreEntity.GetPosition(), seen.Entity.GetCentre()) <= rangeDetection;
}
private bool CheckRelations(IMyEntity entity)
{
return entity == m_block.CubeGrid ? (m_options & Option.ThisShip) != 0 : (m_options & (Option)m_block.getRelationsTo(entity)) != 0;
}
private void CreateHolo(LastSeen seen)
{
if (!(seen.Entity is IMyCubeGrid))
return;
SeenHolo sh;
if (m_holoEntities.TryGetValue(seen.Entity.EntityId, out sh))
{
sh.Seen = seen;
return;
}
if (!CanDisplay(seen))
return;
Profiler.StartProfileBlock("CreateHolo.GetObjectBuilder");
MyObjectBuilder_CubeGrid builder = (MyObjectBuilder_CubeGrid)seen.Entity.GetObjectBuilder();
Profiler.EndProfileBlock();
MyEntities.RemapObjectBuilder(builder);
builder.IsStatic = false;
builder.CreatePhysics = false;
builder.EnableSmallToLargeConnections = false;
Profiler.StartProfileBlock("CreateHolo.CreateFromObjectBuilder");
MyCubeGrid holo = (MyCubeGrid)MyEntities.CreateFromObjectBuilder(builder);
Profiler.EndProfileBlock();
Profiler.StartProfileBlock("CreateHolo.SetupProjection");
SetupProjection(holo);
Profiler.EndProfileBlock();
Profiler.StartProfileBlock("CreateHolo.AddEntity");
MyAPIGateway.Entities.AddEntity(holo);
Profiler.EndProfileBlock();
Log.DebugLog("created holo for " + seen.Entity.nameWithId() + ", holo: " + holo.nameWithId());
m_holoEntities.Add(seen.Entity.EntityId, new SeenHolo() { Seen = seen, Holo = holo });
MyCubeGrid actual = (MyCubeGrid)seen.Entity;
actual.OnBlockAdded += Actual_OnBlockAdded;
actual.OnBlockRemoved += Actual_OnBlockRemoved;
actual.OnBlockIntegrityChanged += OnBlockIntegrityChanged;
}
/// <summary>
/// Actions that must be performed when removing an entry from m_holoEntities
/// </summary>
private void OnRemove(SeenHolo sh)
{
MyEntities.Remove(sh.Holo);
MyCubeGrid grid = sh.Seen.Entity as MyCubeGrid;
if (grid != null)
{
grid.OnBlockAdded -= Actual_OnBlockAdded;
grid.OnBlockRemoved -= Actual_OnBlockRemoved;
grid.OnBlockIntegrityChanged -= OnBlockIntegrityChanged;
}
}
private void Actual_OnBlockAdded(IMySlimBlock obj)
{
SeenHolo sh;
if (!m_holoEntities.TryGetValue(obj.CubeGrid.EntityId, out sh))
{
Log.DebugLog("failed lookup of grid: " + obj.CubeGrid.DisplayName, Logger.severity.ERROR);
obj.CubeGrid.OnBlockAdded -= Actual_OnBlockAdded;
obj.CubeGrid.OnBlockRemoved -= Actual_OnBlockRemoved;
return;
}
IMyCubeGrid holo = (IMyCubeGrid)sh.Holo;
MyObjectBuilder_CubeBlock objBuilder = obj.GetObjectBuilder();
objBuilder.EntityId = 0L;
holo.AddBlock(objBuilder, false);
IMyCubeBlock cubeBlock = holo.GetCubeBlock(obj.Position).FatBlock;
if (cubeBlock != null)
SetupProjection(cubeBlock);
}
private void Actual_OnBlockRemoved(IMySlimBlock obj)
{
SeenHolo sh;
if (!m_holoEntities.TryGetValue(obj.CubeGrid.EntityId, out sh))
{
Log.DebugLog("failed lookup of grid: " + obj.CubeGrid.DisplayName, Logger.severity.ERROR);
obj.CubeGrid.OnBlockAdded -= Actual_OnBlockAdded;
obj.CubeGrid.OnBlockRemoved -= Actual_OnBlockRemoved;
return;
}
Vector3I position = obj.Position;
IMyCubeGrid holo = (IMyCubeGrid)sh.Holo;
holo.RemoveBlock(holo.GetCubeBlock(position));
}
/// <summary>
/// Show or Hide a holo entity.
/// </summary>
/// <param name="entity">Entity to show/hide</param>
/// <param name="visible">Set Render.Visible to this bool</param>
private void SetVisible(IMyEntity entity, bool visible)
{
entity.Render.Visible = visible;
foreach (var child in entity.Hierarchy.Children)
SetVisible(child.Container.Entity, visible);
}
private void ColourByIntegrity(SeenHolo sh)
{
Log.DebugLog("colouring by integriy: " + sh.Seen.Entity.getBestName());
MyCubeGrid realGrid = (MyCubeGrid)sh.Seen.Entity;
IMyCubeGrid holoGrid = (IMyCubeGrid)sh.Holo;
foreach (IMySlimBlock block in realGrid.CubeBlocks)
ColourBlock(block, holoGrid);
sh.ColouredByIntegrity = true;
}
private void RestoreColour(SeenHolo sh)
{
Log.DebugLog("restoring original colour: " + sh.Seen.Entity.getBestName());
MyCubeGrid realGrid = (MyCubeGrid)sh.Seen.Entity;
MyCubeGrid holo = (MyCubeGrid)sh.Holo;
foreach (IMySlimBlock block in realGrid.CubeBlocks)
holo.ColorBlocks(block.Position, block.Position, block.GetColorMask(), false);
sh.ColouredByIntegrity = false;
}
private void OnBlockIntegrityChanged(IMySlimBlock block)
{
SeenHolo sh;
if (!m_holoEntities.TryGetValue(block.CubeGrid.EntityId, out sh))
{
Log.DebugLog("grid entity id lookup failed", Logger.severity.ERROR);
((MyCubeGrid)block.CubeGrid).OnBlockIntegrityChanged -= OnBlockIntegrityChanged;
return;
}
IMyCubeGrid grid = (IMyCubeGrid)sh.Holo;
if (sh.ColouredByIntegrity)
ColourBlock(block, grid);
UpdateBlockModel(block, grid);
}
private void m_centreEntityId_AfterValueChanged()
{
long entityId = m_centreEntityId;
if (entityId == 0L)
{
value_centreEntity = null;
}
else if (!MyAPIGateway.Entities.TryGetEntityById(entityId, out value_centreEntity))
{
Log.AlwaysLog("Failed to get entity for id: " + entityId, Logger.severity.WARNING);
value_centreEntity = null;
}
Log.DebugLog("centre entity is now " + m_centreEntity.getBestName() + "(" + entityId + ")");
}
private bool GetOption(Option opt)
{
return (m_options & opt) == opt;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.